mantine icon indicating copy to clipboard operation
mantine copied to clipboard

Modal doesn't trap focus

Open ivanbrykov opened this issue 3 years ago • 2 comments

Hi. I stumbled upon a scenario when a modal can't trap focus. It goes like this:

  • Open a drawer
  • From the drawer open a modal
  • Hide the drawer immediately in the same callback

As a result, the modal is opened but it has no focus and doesn't close by pressing ESC.

The reason it happens is that the drawer is animated. If I wait for 300ms before opening the modal, everything works as expected.

I don't know what the fix here would be. Maybe I could tell the drawer to pass focus to the modal via ref in some callback?

ivanbrykov avatar Jan 30 '22 19:01 ivanbrykov

Thanks for reporting!

rtivital avatar Jan 30 '22 19:01 rtivital

I tried fix this bug. seems need change like 3 files. Drawer passRefModal, Modal pass modalRef and useFocusReturn pass the ref to trigger last active focus. but still not gonna work without setTimeout too. on useFocusReturn there race condition between focus lastActive on drawer when close and modal focusing

so I think use setTimeout on 1 line code it's not gonna hurt

auronsan avatar Apr 02 '22 03:04 auronsan

Fixed in 5.1.4, Modal and Drawer components now support withFocusReturn prop, set it to false to prevent the component from returning focus to previous active element after Modal/Drawer is closed.

rtivital avatar Aug 12 '22 07:08 rtivital

Hey @rtivital, would be awesome if withFocusReturn were dynamic.

My use case is under certain circumstances I do want the focus to return when I close the modal, but other time I don't.

In my modal there is an action that closes the modal and renders an input the main part of the app. This input should be focused after closing the modal. However, when the modal is closed without taking this action the focus should return to where it was before.

Could withFocusReturn accept a callback of signature () => boolean? Then I could set a ref to true / false in onClose.

adri1wald avatar Aug 22 '22 23:08 adri1wald

I'll make it dynamic without function in next patch

rtivital avatar Aug 23 '22 06:08 rtivital