Hopefully fixes trigger focus restoration on modal close

Fixes #12364? I admit this is not my forte, but this explanation for the cause of the bug seems to make sense, and the new unit tests pass, so...

* register the callback before invoking the toggling
* listen for `hidden` instead of `hide`
* account for the possibility of the associated `show` event being preventDefault-ed

Adds relevant unit tests.

To: @fat for review