useFocusTrap @astryx-svelte/core v0.3.0 · hooks
Usage
Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. When the trap deactivates or unmounts, focus is restored to the element that was focused before activation, unless focus was already moved elsewhere. Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.tsimport { hooks } from '@astryx-svelte/core/hooks';
Best practices
| Guidance | Practices |
|---|---|
| Do | Call focusFirst() when opening a dialog/modal to move focus into the trapped region. |
| Do | Provide an onEscape callback to close the dialog when Escape is pressed. |
| Do | Rely on the built-in focus restoration on close; only add your own onHide focus handling when you need to send focus somewhere other than the previously-focused element. |
| Don't | Use on non-modal content like tooltips or dropdowns; those need light-dismiss, not focus trapping. |
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
options Required | () => UseFocusTrapOptions | — | Configuration object for the focus trap. |
options.isActive Required | boolean | — | Whether the focus trap is currently active. |
options.onEscape | () => void | — | Callback when Escape key is pressed inside the trapped container. |
Returns
| Field | Type | Default | Description |
|---|---|---|---|
containerRef | HTMLElement | null | — | Ref to attach to the container element that should trap focus. Element references are attachments here. The port returns an |
focusFirst | () => void | — | Focuses the first focusable element inside the container. |