Controllers FocusController
Focus controller
Lit reactive controller managing two keyboard-focus patterns: roving tabindex for composite widgets, and focus trapping for modal surfaces.
Roving tabindex
Tab moves into the toolbar once, then Arrow keys move between items. Only the active item is in the tab sequence.
Roving options
Roving usage
import {FocusController} from '@nathanmosher/design-system/controllers';
class DsToolbar extends LitElement {
private readonly focusController = new FocusController(this, {
roving: {
itemSelector: '.roving-item',
orientation: 'horizontal',
wrap: true,
direction: 'ltr',
onActiveItemChange: (item, index) => console.log(index),
},
});
}
Focus trap
While the panel is open, Tab and Shift+Tab cycle only through the fields inside it. The buttons outside stay unreachable until it closes.
Trap options
Trap usage
class DsDialog extends LitElement {
private readonly focusController = new FocusController(this, {
trap: {
active: false,
autoFocus: true,
restoreFocus: true,
container: () => this.renderRoot.querySelector('.panel'),
},
});
open() {
this.focusController.activateTrap();
}
}
Options reference
| Option | Type | Default | Description |
|---|---|---|---|
| roving.itemSelector | string | focusable children | Selector locating the items in the roving sequence. |
| roving.orientation | 'horizontal' | 'vertical' | 'both' | 'both' | Arrow key axes that move the active item. |
| roving.wrap | boolean | true | Whether moving past an end returns to the other end. |
| roving.direction | 'ltr' | 'rtl' | 'ltr' | Flips ArrowLeft and ArrowRight when set to 'rtl'. |
| roving.onActiveItemChange | (item, index) => void | undefined | Fires when the active roving item changes. |
| trap.active | boolean | false | Whether the trap holds focus from construction. |
| trap.autoFocus | boolean | true | Moves focus into the container on activation. |
| trap.restoreFocus | boolean | true | Returns focus to the prior element on deactivation. |
| trap.container | HTMLElement | ShadowRoot | getter | host | Boundary the trap cycles focus within. |
Methods reference
| Method | Returns | Description |
|---|---|---|
| activateTrap() | void | Starts trapping focus inside the container. |
| deactivateTrap() | void | Stops trapping and optionally restores focus. |
| setActiveRovingItem(index) | void | Moves the roving sequence to a specific index. |
| focusFirst() / focusLast() | boolean | Focuses the first or last focusable element. |
| getRovingItems() | HTMLElement[] | Returns the items currently in the roving sequence. |