WICG / close-watcher

A web API proposal for watching for close requests (e.g. Esc, Android back button, ...)
https://html.spec.whatwg.org/multipage/interaction.html#close-requests-and-close-watchers
71 stars 5 forks source link

Support blur as a close signal #25

Open tbondwilkinson opened 2 years ago

tbondwilkinson commented 2 years ago

When thinking about the new Popup API proposal, the close watcher currently supports a number of the close signals for a popup including esc and back button on certain UAs.

One of the new close signals however is focus leaving the popup.

Using keyboard or other navigation sources to move the focus off of the pop-up. When the focus changes, all pop-ups up to the "nearest open ancestral pop-up" for the newly-focused element will be hidden. Note that this includes subframes and the user changing windows (a window blur) - both will cause all open pop-ups to be closed.

I was thinking that it would be good if any new behavior provided automatically by the browser could be encapsulated in APIs that would allow component developers who could not use the popup API for one reason or another to still take advantage of the dismiss behavior.

Perhaps the API could be something like:

const hamburgerMenuButton = document.querySelector('#hamburger-menu-button');
const sidebar = document.querySelector('#sidebar');

hamburgerMenuButton.addEventListener('click', () => {
  const watcher = new CloseWatcher({element: sidebar, blur: true});

  sidebar.animate([{ transform: 'translateX(-200px)' }, { transform: 'translateX(0)' }]);

  watcher.onclose = () => {
    sidebar.animate([{ transform: 'translateX(0)' }, { transform: 'translateX(-200px)' }]);
  };