(props: UseTrapFocusProps)
| 5 | } |
| 6 | |
| 7 | export function useTrapFocus(props: UseTrapFocusProps) { |
| 8 | useTask$(({ track }) => { |
| 9 | const container = track(() => props.containerRef.value) as HTMLElement; |
| 10 | if (!container) { |
| 11 | return undefined; |
| 12 | } |
| 13 | |
| 14 | const focusableElements = container.querySelectorAll<HTMLElement>( |
| 15 | 'a[href]:not([disabled]), button:not([disabled]), input:not([disabled])' |
| 16 | ); |
| 17 | const firstElement = focusableElements[0]; |
| 18 | const lastElement = focusableElements[focusableElements.length - 1]; |
| 19 | |
| 20 | function trapFocus(event: KeyboardEvent) { |
| 21 | if (event.key !== 'Tab') { |
| 22 | return; |
| 23 | } |
| 24 | |
| 25 | if (event.shiftKey) { |
| 26 | if (document.activeElement === firstElement) { |
| 27 | event.preventDefault(); |
| 28 | lastElement.focus(); |
| 29 | } |
| 30 | } else if (document.activeElement === lastElement) { |
| 31 | event.preventDefault(); |
| 32 | firstElement.focus(); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | container.addEventListener('keydown', trapFocus); |
| 37 | |
| 38 | return () => { |
| 39 | container.removeEventListener('keydown', trapFocus); |
| 40 | }; |
| 41 | }); |
| 42 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…