Akryum / floating-vue

💬 Easy tooltips, popovers, dropdown, menus... for Vue
https://floating-vue.starpad.dev/
MIT License
3.34k stars 336 forks source link

Re-focusing the trigger, when closing via `esc` key #1021

Closed dobromir-hristov closed 10 months ago

dobromir-hristov commented 10 months ago

Ideally for AX, the focus should go back to the trigger button when you close a dropdown via the esc key.

I tried capturing the esc keydown event in the popper slot, but that only works if I am focused on an item, inside the slot itself, not the outer v-popper__popper, which is focused when you open the dropdown for example.

If the hide event would specify the reason for closing, we could do the re-focusing on our end.

Akryum commented 10 months ago

What would be the use case for an additional parameter to hide? Doesn't it work if you just listen to hide and focus your button?

dobromir-hristov commented 10 months ago

That will focus if you click outside, or hide via some other mechanism, which is probably not correct 🤔 not exactly sure what is more correct, from an accessibility standpoint.

Akryum commented 10 months ago

Maybe you can do something similar to:

function onHide () {
  // Nothing is currently focused
  if (document.activeElement === document.body) {
    myButton.value.focus()
  }
}
dobromir-hristov commented 10 months ago

I'll see if always focusing on hide is a terrible idea. Will give feedback later.

dobromir-hristov commented 10 months ago

Right, that did the trick :)

  const el = document.activeElement
  const popperClass = 'v-popper__popper';
// if no active element, or its the body, or its the popper itself OR is still inside the popper
  if (!el || el === document.body || el.classList.contains(popperClass) || el.closest(`.${popperClass}`)) {
    // focus the trigger button
  }