Make popup close more generic, cleanup some code and added some tests.