Overlays

FocusTrap

Headless focus-trap primitive that keeps Tab navigation within a container and restores focus on teardown.

import { FocusTrap } from '@lostgradient/cinder/focus-trap';
overlayaccessibility
01

Overview

Traps keyboard focus within a container and restores focus to the previously focused element when the trap deactivates.

Usage

svelte
<script lang="ts">
  import FocusTrap from '@lostgradient/cinder/focus-trap';
</script>

<FocusTrap>
  <button>First</button>
  <button>Second</button>
</FocusTrap>

initialFocus and fallbackFocus accept either selector strings or HTMLElement references. Invalid selectors are ignored so the trap can fall back to the next available focus target.

Live preview
02

When to use

Use when
  • Building non-native overlays or popovers that need contained keyboard focus.
  • Reusing the same focus-management behavior across custom floating surfaces.
Avoid when
  • The surface already uses native dialog focus trapping.
03

Examples

Basic focus trap

Keeps Tab navigation inside the rendered surface until the trap is removed.

04

Props

Props for focus-trap
Name Type Default Required Bindable Description
active boolean true
restoreFocus boolean true
initialFocus Exclude<FocusTargetInput, Function> null
fallbackFocus Exclude<FocusTargetInput, Function> null
children snippet req