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.
ts
import { hooks } from '@astryx-svelte/core/hooks';

Best practices

GuidancePractices
DoCall focusFirst() when opening a dialog/modal to move focus into the trapped region.
DoProvide an onEscape callback to close the dialog when Escape is pressed.
DoRely 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'tUse on non-modal content like tooltips or dropdowns; those need light-dismiss, not focus trapping.

Parameters

ParameterTypeDefaultDescription
options Required () => UseFocusTrapOptionsConfiguration object for the focus trap.
options.isActive Required booleanWhether the focus trap is currently active.
options.onEscape () => voidCallback when Escape key is pressed inside the trapped container.

Returns

FieldTypeDefaultDescription
containerRef HTMLElement | nullRef to attach to the container element that should trap focus.

Element references are attachments here. The port returns an Attachment<HTMLElement> named attach…; spread it onto the element instead of assigning a ref.Upstream declares React.RefObject<HTMLElement | null>.

focusFirst () => voidFocuses the first focusable element inside the container.