theKashey / react-focus-lock

It is a trap! A lock for a Focus. 🔓
MIT License
1.27k stars 67 forks source link

Trap loosing focus in case focusable is portaled, within shards, and the last child of the body #225

Closed yakunins closed 1 year ago

yakunins commented 2 years ago

Steps to reproduce the issue:

  1. visit standalone sandbox https://5l92ir.csb.app/
  2. press Enable button
  3. press Tab several times (and watch trap loosing focus)
  4. press Shift+Tab several times (and watch trap doing its job well)

Comments:

  1. When running not in standalone sandbox, trap is working: https://codesandbox.io/s/react-focus-lock-forked-5l92ir
  2. There is a piece of CSS in this file, which removes focusable iframe with a link to Codesandbox. If this CSS removed, trap start working.
theKashey commented 2 years ago

This is more about feature rather a bug because frankly speaking being able to leave to the browser interface is often correct behavior.

The expected solution for this is to wrap portalled content with InFocusGuard, that should provide the original behavior. But it's not working. Even if I have a test for it 🙄

Leave this to me...

yakunins commented 2 years ago

Greetings, Anton! Thank you for this tool :)

The main problem here is that usually createPortal mounts sharded node as last child of body. In my case this is a dropdown of a Select, and the Select is inside a focus-trap. And even a dropdown is within trap's shard, it won't work... :(

leave to the browser interface is often correct behavior

Here is what happening:

  1. if there is a focusble between sharded focusable and body boundary, focus is trapped
  2. if there is no focusable in between, focus isn't trapped and leave to the browser interface
  3. such inconsistentcy/misbehavior of programming tool often called bug

BTW same behavior happens with having shard as first focusable child of the body, revealing itself on Shift+Tab.

yakunins commented 2 years ago

to wrap portalled content with InFocusGuard, but it's not working

Yes. I tried FocusGuard too. They are not working, but might be improved to bugfix in this way:

image

Underlined attributes is obligatory to make it work.

Check this out: https://8247h3.csb.app/ https://codesandbox.io/s/react-focus-lock-forked-8247h3

theKashey commented 2 years ago

So there is a special component with roving tab index over focus guards, which makes them safe and easy to put where needed - https://github.com/theKashey/react-focus-lock/blob/master/src/FocusGuard.js#L18

They are not activating on time 🤷‍♂️

stale[bot] commented 1 year ago

This issue has been marked as "stale" because there has been no activity for 2 months. If you have any new information or would like to continue the discussion, please feel free to do so. If this issue got buried among other tasks, maybe this message will reignite the conversation. Otherwise, this issue will be closed in 7 days. Thank you for your contributions so far.