Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

docs(useFocusTrap): add a quick edit panel example block (#9513)

Parman Mohammadalizadeh1404bf84e1ae
diff --git a/.changeset/use-focus-trap-quick-edit-example.md b/.changeset/use-focus-trap-quick-edit-example.md
new file mode 100644
index 0000000000..92781a5f50
--- /dev/null
+++ b/.changeset/use-focus-trap-quick-edit-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useFocusTrap — Quick Edit Panel` example block traps focus in a custom quick-edit panel that is not built on Dialog: `focusFirst` moves focus to its field on open, Tab and Shift+Tab stay inside it, Escape closes it through `onEscape`, and closing returns focus to the Quick edit button. Copy it with `astryx template useFocusTrapHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index bcc6510614..3055c02933 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -786,6 +786,7 @@
"/templates/useCollatorHookUsage/",
"/templates/useComboboxHookUsage/",
"/templates/useContainerRevealHookUsage/",
+ "/templates/useFocusTrapHookUsage/",
"/templates/useGridFocusHookUsage/",
"/templates/useKeyboardHintHookUsage/",
"/templates/useListFocusHookUsage/",
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index ef05dd9b96..f37c3d346c 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3671,6 +3671,11 @@
"path": "examples/use-container-reveal/reveal-on-hover-row-actions",
"aliases": []
},
+ {
+ "name": "example-use-focus-trap-quick-edit-panel",
+ "path": "examples/use-focus-trap/quick-edit-panel",
+ "aliases": []
+ },
{
"name": "example-use-grid-focus-color-swatch-grid",
"path": "examples/use-grid-focus/color-swatch-grid",
diff --git a/packages/cli/api/template/use-focus-trap-hook-usage.test.tsx b/packages/cli/api/template/use-focus-trap-hook-usage.test.tsx
new file mode 100644
index 0000000000..00f229f558
--- /dev/null
+++ b/packages/cli/api/template/use-focus-trap-hook-usage.test.tsx
@@ -0,0 +1,88 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useFocusTrap example traps focus in its quick-edit panel: opening it
+ * moves focus into the panel, Escape closes it, and closing returns focus to
+ * the Quick edit button. Which control focusFirst picks is not asserted here:
+ * this jsdom lists querySelectorAll matches by selector, not document order.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, describe, expect, it} from 'vitest';
+import UseFocusTrapHookUsage from '../../assets/templates/blocks/components/Hooks/useFocusTrapHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+function renderExample(): void {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseFocusTrapHookUsage />);
+ });
+}
+
+function button(label: string): HTMLButtonElement {
+ const match = Array.from(container.querySelectorAll('button')).find(
+ candidate => candidate.textContent === label,
+ );
+ if (match == null) {
+ throw new Error(`no "${label}" button rendered`);
+ }
+ return match;
+}
+
+function panel(): HTMLElement | null {
+ return container.querySelector('[role="dialog"]');
+}
+
+function openPanel(): HTMLButtonElement {
+ const opener = button('Quick edit');
+ act(() => {
+ opener.focus();
+ opener.click();
+ });
+ return opener;
+}
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+});
+
+describe('useFocusTrap example', () => {
+ it('moves focus into the panel when it opens', () => {
+ renderExample();
+ openPanel();
+ expect(panel()?.contains(document.activeElement)).toBe(true);
+ });
+
+ it('closes on Escape and returns focus to the Quick edit button', () => {
+ renderExample();
+ const opener = openPanel();
+ expect(panel()?.contains(document.activeElement)).toBe(true);
+ act(() => {
+ document.activeElement?.dispatchEvent(
+ new KeyboardEvent('keydown', {key: 'Escape', bubbles: true}),
+ );
+ });
+ expect(panel()).toBeNull();
+ expect(document.activeElement).toBe(opener);
+ });
+
+ it('returns focus to the Quick edit button after Cancel', () => {
+ renderExample();
+ const opener = openPanel();
+ expect(panel()?.contains(document.activeElement)).toBe(true);
+ act(() => button('Cancel').click());
+ expect(panel()).toBeNull();
+ expect(document.activeElement).toBe(opener);
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.doc.mjs
new file mode 100644
index 0000000000..daf497b677
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'useFocusTrap',
+ name: 'useFocusTrap — Quick Edit Panel',
+ displayName: 'useFocusTrap — Quick Edit Panel',
+ description:
+ 'A custom quick-edit panel, not built on Dialog, that traps focus with useFocusTrap: focusFirst moves focus to its field on open, Tab and Shift+Tab stay inside it, Escape closes it through onEscape, and closing returns focus to the Quick edit button.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Card', 'Button', 'TextInput', 'Text', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.tsx
new file mode 100644
index 0000000000..e95f5cd7da
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useFocusTrapHookUsage.tsx
@@ -0,0 +1,70 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useEffect, useState} from 'react';
+import {Button} from '@astryxdesign/core/Button';
+import {Card} from '@astryxdesign/core/Card';
+import {useFocusTrap} from '@astryxdesign/core/hooks';
+import {HStack, VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+
+export default function UseFocusTrapHookUsage() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [title, setTitle] = useState('Update onboarding guide');
+ const [draft, setDraft] = useState(title);
+ const close = () => setIsOpen(false);
+ const {containerRef, focusFirst} = useFocusTrap<HTMLDivElement>({
+ isActive: isOpen,
+ onEscape: close,
+ });
+
+ // Runs after commit, once the panel is mounted and useFocusTrap has recorded
+ // the opener, so closing the panel returns focus to it.
+ useEffect(() => {
+ if (isOpen) {
+ focusFirst();
+ }
+ }, [isOpen, focusFirst]);
+
+ return (
+ <HStack gap={4} vAlign="start">
+ <VStack gap={2}>
+ <Text type="body" weight="bold">
+ {title}
+ </Text>
+ <Button
+ label="Quick edit"
+ onClick={() => {
+ setDraft(title);
+ setIsOpen(true);
+ }}
+ />
+ </VStack>
+ {isOpen && (
+ <Card
+ ref={containerRef}
+ role="dialog"
+ aria-label="Quick edit"
+ width={280}
+ padding={4}>
+ <VStack gap={3}>
+ <TextInput label="Title" value={draft} onChange={setDraft} />
+ <HStack gap={2} hAlign="end">
+ <Button label="Cancel" variant="secondary" onClick={close} />
+ <Button
+ label="Save"
+ variant="primary"
+ onClick={() => {
+ setTitle(draft);
+ close();
+ }}
+ />
+ </HStack>
+ </VStack>
+ </Card>
+ )}
+ </HStack>
+ );
+}
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.json b/packages/cli/test/__golden__/no-icon-set/search-close.json
index 7f387aca0b..8093efa4d8 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.json
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.json
@@ -3,7 +3,7 @@
"type": "search",
"data": {
"query": "close",
- "matchCount": 46,
+ "matchCount": 47,
"results": [
{
"domain": "component",
diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.txt b/packages/cli/test/__golden__/no-icon-set/search-close.txt
index b3a0aca173..ec841a389e 100644
--- a/packages/cli/test/__golden__/no-icon-set/search-close.txt
+++ b/packages/cli/test/__golden__/no-icon-set/search-close.txt
@@ -1,4 +1,4 @@
-Results for "close" (20 of 46)
+Results for "close" (20 of 47)
name: AlertDialog
domain: component
package: @astryxdesign/core