Focus engine

Keep the keyboard inside a part of the page while it is open, like a modal or a sidebar, so Tab never runs behind it.

What it does
Keeps the keyboard inside a part of the page while it is open, and gives the focus back when it closes.
Exported from the package?
Yes. Import focusTrap from @davidnet-net/svelte-ui. Pair it with shortcutTrap of the Shortcut engine.

focusTrap

typescript
typescript
function focusTrap(node: HTMLElement, active?: boolean): ActionReturn

focusTrap is an action: use:focusTrap on an element moves the focus into it (the first thing that can take focus, or the element itself when it has nothing), and lets Tab and Shift+Tab go around inside it. When it becomes inactive or the element goes away, the focus goes back to where it was.

When to use

Use it on anything that sits on top of the page and asks for attention: a modal, a drawer, a menu that opens over the content. Pair it with shortcutTrap.

When not to use, and what to use instead

Do not trap focus on content that is part of the page: people would get stuck. Components like Modal already use it: you do not add it again. It listens for Tab on the whole window, so only one trap should be active at a time.

Live example

Result Focus trap: off Focus is inside the box: no

While the box is trapped, press Tab and Shift+Tab: the focus stays in the box. Use Release the box to let go.

svelte
svelte
{#if open}
	<div role="dialog" aria-modal="true" use:focusTrap use:shortcutTrap>
		<!-- Tab and Shift+Tab stay in here, and the shortcuts of the page are quiet -->
		<button onclick={() => (open = false)}>Close</button>
	</div>
{/if}