An open source design system that's fully customizable and agent ready
TypeScript
docs(useGridFocus): add a color swatch grid example block (#9574)
홍규진559b0054f995
diff --git a/.changeset/use-grid-focus-swatch-grid-example.md b/.changeset/use-grid-focus-swatch-grid-example.mdnew file mode 100644index 0000000000..d4cca88d70--- /dev/null+++ b/.changeset/use-grid-focus-swatch-grid-example.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] A new `useGridFocus — Color Swatch Grid` example block wires `useGridFocus` to a color swatch picker in rows of eight: the grid has one Tab stop, the arrow keys move focus cell to cell, Home and End jump within a row, Ctrl+Home and Ctrl+End jump to the corners. Each swatch is a button, so Enter or a click picks it. Copy it with `astryx template useGridFocusHookUsage <path>`.++@kyu-rongdiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 364a0ca267..33b2d9dc0d 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -783,6 +783,7 @@"/templates/useCollatorHookUsage/","/templates/useComboboxHookUsage/","/templates/useContainerRevealHookUsage/",+ "/templates/useGridFocusHookUsage/","/templates/useKeyboardHintHookUsage/","/templates/useListFocusHookUsage/","/templates/useOverflowHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 75187ca89a..1d4aafeacb 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3661,6 +3661,11 @@"path": "examples/use-container-reveal/reveal-on-hover-row-actions","aliases": []},+ {+ "name": "example-use-grid-focus-color-swatch-grid",+ "path": "examples/use-grid-focus/color-swatch-grid",+ "aliases": []+ },{"name": "example-use-hover-card-profile-preview","path": "examples/use-hover-card/profile-preview",diff --git a/packages/cli/api/template/use-grid-focus-hook-usage.test.tsx b/packages/cli/api/template/use-grid-focus-hook-usage.test.tsxnew file mode 100644index 0000000000..ebffe4607a--- /dev/null+++ b/packages/cli/api/template/use-grid-focus-hook-usage.test.tsx@@ -0,0 +1,124 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useGridFocus example moves focus through its swatch grid with the+ * keyboard and keeps one Tab stop, which moves with that focus.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, describe, expect, it} from 'vitest';+import UseGridFocusHookUsage from '../../assets/templates/blocks/components/Hooks/useGridFocusHookUsage';++(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(<UseGridFocusHookUsage />);+ });+}++function swatch(name: string): HTMLButtonElement {+ const match = container.querySelector<HTMLButtonElement>(+ `button[aria-label="${name}"]`,+ );+ if (match == null) {+ throw new Error(`no "${name}" swatch rendered`);+ }+ return match;+}++function focused(): string | null {+ return document.activeElement?.getAttribute('aria-label') ?? null;+}++function press(key: string, init: KeyboardEventInit = {}): void {+ act(() => {+ document.activeElement?.dispatchEvent(+ new KeyboardEvent('keydown', {key, bubbles: true, ...init}),+ );+ });+}++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+});++describe('useGridFocus example', () => {+ it('keeps one Tab stop in the grid', () => {+ renderExample();+ const tabbable = container.querySelectorAll('button[tabindex="0"]');+ expect(+ Array.from(tabbable, cell => cell.getAttribute('aria-label')),+ ).toEqual(['Red']);+ expect(container.querySelectorAll('button[tabindex="-1"]')).toHaveLength(+ 15,+ );+ });++ it('moves focus with the arrow keys and moves the Tab stop with it', () => {+ renderExample();+ act(() => swatch('Red').focus());+ press('ArrowRight');+ expect(focused()).toBe('Tomato');+ press('ArrowDown');+ expect(focused()).toBe('Violet');+ press('ArrowLeft');+ expect(focused()).toBe('Indigo');+ press('ArrowUp');+ expect(focused()).toBe('Red');+ press('ArrowDown');+ expect(swatch('Indigo').getAttribute('tabindex')).toBe('0');+ expect(swatch('Red').getAttribute('tabindex')).toBe('-1');+ });++ it('jumps within a row with Home and End, and to the corners with Ctrl', () => {+ renderExample();+ act(() => swatch('Violet').focus());+ press('End');+ expect(focused()).toBe('Black');+ press('Home');+ expect(focused()).toBe('Indigo');+ press('Home', {ctrlKey: true});+ expect(focused()).toBe('Red');+ press('End', {ctrlKey: true});+ expect(focused()).toBe('Black');+ });++ it('picks the swatch that is clicked and exposes it on the focused button', () => {+ renderExample();+ expect(swatch('Red').getAttribute('aria-pressed')).toBe('true');+ act(() => swatch('Teal').click());+ expect(container.textContent).toContain('Selected: Teal');+ expect(+ swatch('Teal')+ .closest('[role="gridcell"]')+ ?.getAttribute('aria-selected'),+ ).toBe('true');+ expect(swatch('Teal').getAttribute('aria-pressed')).toBe('true');+ expect(swatch('Red').getAttribute('aria-pressed')).toBe('false');+ });++ it('exposes the swatch picked from the keyboard on its button', () => {+ renderExample();+ act(() => swatch('Red').focus());+ press('ArrowRight');+ press('ArrowRight');+ // jsdom does not turn Enter on a button into a click, so this does it the+ // way the browser does for the focused swatch.+ act(() => (document.activeElement as HTMLButtonElement).click());+ expect(focused()).toBe('Amber');+ expect(swatch('Amber').getAttribute('aria-pressed')).toBe('true');+ expect(swatch('Red').getAttribute('aria-pressed')).toBe('false');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.doc.mjsnew file mode 100644index 0000000000..ccd28db42c--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.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: 'useGridFocus',+ name: 'useGridFocus — Color Swatch Grid',+ displayName: 'useGridFocus — Color Swatch Grid',+ description:+ 'A color swatch picker in rows of eight with one Tab stop. useGridFocus moves focus with the arrow keys, Home and End, and Ctrl+Home and Ctrl+End. Each swatch is a button, so Enter or a click picks it.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['Card', 'Text', 'Layout'],+};diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.tsxnew file mode 100644index 0000000000..62a15cd43f--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useGridFocusHookUsage.tsx@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useState} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {useGridFocus} from '@astryxdesign/core/hooks';+import {VStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';++const COLUMNS = 8;++const SWATCHES = [+ {name: 'Red', value: '#e5484d'},+ {name: 'Tomato', value: '#f76b15'},+ {name: 'Amber', value: '#ffc53d'},+ {name: 'Lime', value: '#bdee63'},+ {name: 'Green', value: '#30a46c'},+ {name: 'Teal', value: '#12a594'},+ {name: 'Cyan', value: '#00a2c7'},+ {name: 'Blue', value: '#0090ff'},+ {name: 'Indigo', value: '#3e63dd'},+ {name: 'Violet', value: '#6e56cf'},+ {name: 'Purple', value: '#8e4ec6'},+ {name: 'Plum', value: '#ab4aba'},+ {name: 'Pink', value: '#d6409f'},+ {name: 'Brown', value: '#ad7f58'},+ {name: 'Gray', value: '#8d8d8d'},+ {name: 'Black', value: '#111111'},+];++const ROWS = Array.from({length: SWATCHES.length / COLUMNS}, (_, row) =>+ SWATCHES.slice(row * COLUMNS, (row + 1) * COLUMNS),+);++export default function UseGridFocusHookUsage() {+ const [selected, setSelected] = useState(SWATCHES[0].name);+ const {gridRef, handleKeyDown, handleFocus} = useGridFocus<HTMLDivElement>({+ columns: COLUMNS,+ cellSelector: '[role="gridcell"]',+ getFocusTarget: cell => cell.querySelector('button'),+ hasRovingTabIndex: true,+ });++ return (+ <Card padding={4}>+ <VStack gap={3}>+ <Text type="body">Selected: {selected}</Text>+ <div+ ref={gridRef}+ role="grid"+ aria-label="Colors"+ onKeyDown={handleKeyDown}+ onFocus={handleFocus}+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>+ {ROWS.map((row, index) => (+ <div key={index} role="row" style={{display: 'flex', gap: 4}}>+ {row.map(swatch => (+ <div+ key={swatch.name}+ role="gridcell"+ aria-selected={swatch.name === selected}>+ <button+ type="button"+ aria-label={swatch.name}+ aria-pressed={swatch.name === selected}+ onClick={() => setSelected(swatch.name)}+ style={{+ width: 28,+ height: 28,+ border: 'none',+ boxShadow:+ 'inset 0 0 0 1px var(--color-border-emphasized)',+ borderRadius: 4,+ background: swatch.value,+ }}+ />+ </div>+ ))}+ </div>+ ))}+ </div>+ </VStack>+ </Card>+ );+}