import { createSignal, onSettled, runWithOwner, Show } from "solid-js"; import preview from "../../../.storybook/preview.js"; import { autofocus, createAutofocus, createFocusSignal, makeFocusListener, createFocusTrap, createFocusGroup, } from "@solid-primitives/focus"; import readme from "../README.md?raw"; import { Badge, BoolRow, Button, ButtonRow, colors, Container, EventLog, font, inputStyle, Kbd, radii, StatRow, } from "../../../.storybook/ui/index.js"; const meta = preview.meta({ title: "Inputs/Focus", tags: ["autodocs"], parameters: { layout: "centered", docs: { description: { component: readme, }, }, }, }); export default meta; export const FocusOnRender = meta.story({ name: "Focus on render", parameters: { docs: { description: { story: "`autofocus()` is a ref callback factory that re-applies focus on every mount — the native `autofocus` attribute alone only fires on page load. Attach it via `ref={autofocus()}` alongside the `autofocus` HTML attribute. To opt out, remove the attribute — the primitive checks for it before focusing.", }, }, }, render: () => { const [mounted, setMounted] = createSignal(true); return (

Unmount and remount to see autofocus() fire again — the browser won't do this on its own.

); }, }); export const SignalDrivenFocus = meta.story({ name: "Signal-driven focus", parameters: { docs: { description: { story: "`createAutofocus(ref)` accepts a signal accessor — pass `ref={setRef}` on the element and hold the reference reactively. Focus re-fires whenever the accessor changes to a new element, making it easy to shift focus as the DOM updates.", }, }, }, render: () => { const [mounted, setMounted] = createSignal(true); const FocusedField = () => { const [ref, setRef] = createSignal(); createAutofocus(ref); return ; }; return (

The signal ref pattern is useful when the element reference needs to be passed up or shared — focus fires each time the signal resolves to a new element.

); }, }); export const LiveFocusState = meta.story({ name: "Live focus state", parameters: { docs: { description: { story: "`createFocusSignal(target)` returns a boolean signal that updates whenever the target element gains or loses focus. Accepts either a direct element reference or a reactive accessor.", }, }, }, render: () => { const FocusTracker = () => { let inputRef!: HTMLInputElement; const isFocused = createFocusSignal(() => inputRef); return (
Focus state {isFocused() ? "focused" : "blurred"}
); }; return ; }, }); export const FocusEventLog = meta.story({ name: "Imperative focus events", parameters: { docs: { description: { story: "`makeFocusListener(target, callback, useCapture?)` imperatively attaches `focus` and `blur` listeners to an element and returns a cleanup function. Useful in scenarios where you need to set up listeners outside a reactive scope or alongside other non-reactive setup.", }, }, }, render: () => { const [log, setLog] = createSignal<{ label: string; time: string }[]>([]); const addLog = (msg: string) => setLog(prev => [{ label: msg, time: new Date().toLocaleTimeString() }, ...prev].slice(0, 5)); let el1!: HTMLInputElement; let el2!: HTMLInputElement; onSettled(() => { // onSettled forbids onCleanup, which make* primitives register — so run them // ownerless and tear down manually via the returned cleanup. const [c1, c2] = runWithOwner(null, () => [ makeFocusListener(el1, focused => addLog(`Input A — ${focused ? "focused" : "blurred"}`)), makeFocusListener(el2, focused => addLog(`Input B — ${focused ? "focused" : "blurred"}`)), ])!; return () => { c1(); c2(); }; }); return ( ); }, }); export const TabWrapsInDialog = meta.story({ name: "Tab wraps in dialog", parameters: { docs: { description: { story: "`createFocusTrap({ element, enabled })` traps keyboard focus inside a container. Tab cycles forward through focusable children; Shift+Tab cycles backward. When the trap deactivates, focus is restored to the element that was focused before the trap activated.", }, }, }, render: () => { const [open, setOpen] = createSignal(false); const [trapRef, setTrapRef] = createSignal(); createFocusTrap({ element: trapRef, enabled: open }); return (

Dialog

Press Tab / Shift+Tab — focus wraps inside the dialog. Closing restores focus to the trigger button.

); }, }); export const CustomInitialFocus = meta.story({ name: "Custom initial focus", parameters: { docs: { description: { story: "Use `initialFocusElement` to override which element receives focus when the trap activates. Here the Cancel button receives initial focus instead of the first focusable element (the Name input). Also demonstrates `onInitialFocus` / `onFinalFocus` callbacks for observing focus moves.", }, }, }, render: () => { const [open, setOpen] = createSignal(false); const [trapRef, setTrapRef] = createSignal(); const [cancelRef, setCancelRef] = createSignal(); const [log, setLog] = createSignal<{ label: string; time: string }[]>([]); const addLog = (msg: string) => setLog(prev => [{ label: msg, time: new Date().toLocaleTimeString() }, ...prev].slice(0, 4)); createFocusTrap({ element: trapRef, enabled: open, initialFocusElement: cancelRef, onInitialFocus: () => addLog("onInitialFocus"), onFinalFocus: () => addLog("onFinalFocus"), }); return (

Dialog — Cancel focused first

); }, }); export const ArrowKeyNavigation = meta.story({ name: "Arrow-key focus navigation", parameters: { docs: { description: { story: "`createFocusGroup(ref)` creates a focus group that moves focus between the focusable children of the container — the building block for arrow-key navigation in menus, listboxes and toolbars. Keyboard navigation is enabled by default: the `keydown` listener is attached to the ref automatically, so no manual wiring is needed. Here ArrowDown/ArrowUp cycle with wrap, Home/End jump to the ends.", }, }, }, render: () => { const [ref, setRef] = createSignal(); const [focusedLabel, setFocusedLabel] = createSignal("One"); createFocusGroup(ref, () => ({ wrap: true })); return (
setFocusedLabel((event.target as HTMLElement).getAttribute("aria-label") ?? "Unknown") } role="listbox" aria-label="Focus group" style={{ display: "flex", "flex-direction": "column", gap: "0.5rem", background: "white", border: `1px solid ${colors.border}`, "border-radius": radii.lg, padding: "1rem", }} >

Focus an item, then use ArrowDown / ArrowUp to cycle with wrap,{" "} Home / End to jump.

); }, }); function MenuItem(props: { label: string }) { return ( ); }