An open source design system that's fully customizable and agent ready
TypeScript
docs(useCombobox): add an assign-to field example block (#9576)
홍규진637d2352c419
diff --git a/.changeset/use-combobox-assign-to-example.md b/.changeset/use-combobox-assign-to-example.mdnew file mode 100644index 0000000000..f3833d0e07--- /dev/null+++ b/.changeset/use-combobox-assign-to-example.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] A new `useCombobox — Assign To Field` example block spreads the field, listbox and option props from `useCombobox` onto a `TextInput` and a list of `Item` rows: typing filters a list of teammates, ArrowUp and ArrowDown move the active option while focus stays in the input, Enter or a press picks one, and Escape closes the list. Copy it with `astryx template useComboboxHookUsage <path>`.++@kyu-rongdiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex 37ed6942b0..6716cbcda9 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -781,6 +781,7 @@"/templates/table/","/templates/theme-showcase/","/templates/useCollatorHookUsage/",+ "/templates/useComboboxHookUsage/","/templates/useContainerRevealHookUsage/","/templates/useKeyboardHintHookUsage/","/templates/useListFocusHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex cf8945d5f4..0f6c619ccf 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3649,6 +3649,11 @@"path": "examples/use-collator/locale-aware-name-sort","aliases": []},+ {+ "name": "example-use-combobox-assign-to-field",+ "path": "examples/use-combobox/assign-to-field",+ "aliases": []+ },{"name": "example-use-container-reveal-reveal-on-hover-row-actions","path": "examples/use-container-reveal/reveal-on-hover-row-actions",diff --git a/packages/cli/api/template/use-combobox-hook-usage.test.tsx b/packages/cli/api/template/use-combobox-hook-usage.test.tsxnew file mode 100644index 0000000000..bdb01a415a--- /dev/null+++ b/packages/cli/api/template/use-combobox-hook-usage.test.tsx@@ -0,0 +1,138 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useCombobox example filters teammates as you type, moves the active+ * option with the arrows while focus stays in the input, picks with Enter or+ * a press, and closes the list with Escape.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, describe, expect, it} from 'vitest';+import UseComboboxHookUsage from '../../assets/templates/blocks/components/Selector/useComboboxHookUsage';++(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =+ true;++let root: Root | null = null;+let container: HTMLElement;++function renderExample(): HTMLInputElement {+ container = document.createElement('div');+ document.body.appendChild(container);+ act(() => {+ root = createRoot(container);+ root.render(<UseComboboxHookUsage />);+ });+ const input = container.querySelector('input');+ if (input == null) {+ throw new Error('no input rendered');+ }+ act(() => input.focus());+ return input;+}++function type(input: HTMLInputElement, text: string): void {+ const setValue = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ 'value',+ )?.set;+ act(() => {+ setValue?.call(input, text);+ input.dispatchEvent(new Event('input', {bubbles: true}));+ });+}++function press(input: HTMLInputElement, key: string): void {+ act(() => {+ input.dispatchEvent(+ new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}),+ );+ });+}++function options(): string[] {+ return Array.from(+ container.querySelectorAll('[role="option"]'),+ option => option.textContent ?? '',+ );+}++function activeOption(input: HTMLInputElement): string | null {+ const id = input.getAttribute('aria-activedescendant');+ return id == null ? null : (document.getElementById(id)?.textContent ?? null);+}++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+});++describe('useCombobox example', () => {+ it('filters teammates as you type and makes the first match active', () => {+ const input = renderExample();+ expect(input.getAttribute('role')).toBe('combobox');+ expect(input.getAttribute('aria-expanded')).toBe('false');+ type(input, 'ce');+ expect(options()).toEqual(['Ada Lovelace', 'Grace Hopper (away)']);+ expect(input.getAttribute('aria-expanded')).toBe('true');+ expect(activeOption(input)).toBe('Ada Lovelace');+ });++ it('moves the active option with the arrows while focus stays in the input', () => {+ const input = renderExample();+ press(input, 'ArrowDown');+ expect(activeOption(input)).toBe('Ada Lovelace');+ press(input, 'ArrowDown');+ press(input, 'ArrowDown');+ // Grace Hopper is away (disabled), so the arrows skip her.+ expect(activeOption(input)).toBe('Katherine Johnson');+ press(input, 'ArrowUp');+ expect(activeOption(input)).toBe('Alan Turing');+ expect(document.activeElement).toBe(input);+ expect(+ Array.from(+ container.querySelectorAll('[role="option"][aria-selected="true"]'),+ option => option.textContent,+ ),+ ).toEqual(['Alan Turing']);+ });++ it('picks the active option with Enter and closes the list', () => {+ const input = renderExample();+ type(input, 'mar');+ press(input, 'Enter');+ expect(container.textContent).toContain('Assigned to Margaret Hamilton');+ expect(options()).toEqual([]);+ expect(input.value).toBe('');+ expect(document.activeElement).toBe(input);+ });++ it('picks an option from a press while focus stays in the input', () => {+ const input = renderExample();+ type(input, 'a');+ const alan = Array.from(+ container.querySelectorAll<HTMLElement>('[role="option"]'),+ ).find(option => option.textContent === 'Alan Turing');+ act(() => {+ alan?.dispatchEvent(+ new MouseEvent('mousedown', {bubbles: true, cancelable: true}),+ );+ alan?.click();+ });+ expect(container.textContent).toContain('Assigned to Alan Turing');+ expect(document.activeElement).toBe(input);+ });++ it('closes the list with Escape', () => {+ const input = renderExample();+ type(input, 'a');+ expect(options()).not.toEqual([]);+ press(input, 'Escape');+ expect(options()).toEqual([]);+ expect(input.getAttribute('aria-expanded')).toBe('false');+ expect(container.textContent).toContain('Unassigned');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.doc.mjsnew file mode 100644index 0000000000..eb6cbe5b85--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.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: 'useCombobox',+ name: 'useCombobox — Assign To Field',+ displayName: 'useCombobox — Assign To Field',+ description:+ 'An "Assign to" TextInput and a list of Item rows, with the field, listbox and option props from useCombobox spread onto them: typing filters a list of teammates, ArrowUp and ArrowDown move the active option while focus stays in the input, Enter picks it and Escape closes the list.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['Card', 'TextInput', 'Item', 'Text', 'Layout'],+};diff --git a/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.tsxnew file mode 100644index 0000000000..5936e935b1--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Selector/useComboboxHookUsage.tsx@@ -0,0 +1,113 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useId, useState} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {useAnnounce} from '@astryxdesign/core/hooks';+import {Item} from '@astryxdesign/core/Item';+import {VStack} from '@astryxdesign/core/Layout';+import {useCombobox} from '@astryxdesign/core/Selector';+import {Text} from '@astryxdesign/core/Text';+import {TextInput} from '@astryxdesign/core/TextInput';++type Teammate = {value: string; label: string; disabled?: boolean};++const TEAMMATES: Teammate[] = [+ {value: 'ada', label: 'Ada Lovelace'},+ {value: 'alan', label: 'Alan Turing'},+ {value: 'grace', label: 'Grace Hopper (away)', disabled: true},+ {value: 'katherine', label: 'Katherine Johnson'},+ {value: 'margaret', label: 'Margaret Hamilton'},+];++function matching(query: string): Teammate[] {+ const needle = query.trim().toLowerCase();+ return TEAMMATES.filter(teammate =>+ teammate.label.toLowerCase().includes(needle),+ );+}++export default function UseComboboxHookUsage() {+ const listboxId = useId();+ const announce = useAnnounce({hasReplace: true});+ const [query, setQuery] = useState('');+ const [isOpen, setIsOpen] = useState(false);+ const [assignee, setAssignee] = useState<string>();+ const options = matching(query);++ const combobox = useCombobox({+ selectableItems: options,+ isOpen,+ onOpen: () => setIsOpen(true),+ onClose: () => setIsOpen(false),+ onSelect: value => {+ setAssignee(TEAMMATES.find(teammate => teammate.value === value)?.label);+ setQuery('');+ },+ listboxId,+ });++ return (+ <Card width={320} padding={4}>+ <VStack gap={2}>+ <TextInput+ label="Assign to"+ value={query}+ onChange={next => {+ const matches = matching(next);+ setQuery(next);+ setIsOpen(true);+ // A new query makes its first enabled match active, so Enter+ // picks it.+ combobox.setHighlightedIndex(+ matches.findIndex(teammate => !teammate.disabled),+ );+ if (next.trim() !== query.trim()) {+ announce(+ matches.length === 0+ ? 'No one matches'+ : matches.length === 1+ ? '1 teammate'+ : `${matches.length} teammates`,+ );+ }+ }}+ onBlur={() => {+ setIsOpen(false);+ combobox.setHighlightedIndex(-1);+ }}+ {...combobox.getFieldProps()}+ />+ {isOpen && options.length > 0 ? (+ <VStack+ as="ul"+ gap={0}+ aria-label="Teammates"+ {...combobox.getListboxProps()}>+ {options.map((teammate, index) => (+ <Item+ key={teammate.value}+ as="li"+ density="compact"+ label={teammate.label}+ isHighlighted={index === combobox.highlightedIndex}+ // Item writes aria-selected from isSelected, so the active+ // option has to be passed here to keep aria-selected="true".+ isSelected={index === combobox.highlightedIndex}+ isDisabled={teammate.disabled}+ {...combobox.getOptionProps(index)}+ />+ ))}+ </VStack>+ ) : null}+ {isOpen && options.length === 0 ? (+ <Text type="supporting">No one matches</Text>+ ) : null}+ <Text type="supporting">+ {assignee == null ? 'Unassigned' : `Assigned to ${assignee}`}+ </Text>+ </VStack>+ </Card>+ );+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-close.json b/packages/cli/test/__golden__/no-icon-set/search-close.jsonindex efdd97789c..7f387aca0b 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": 45,+ "matchCount": 46,"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.txtindex 414978469e..b3a0aca173 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 45)+Results for "close" (20 of 46)name: AlertDialogdomain: componentpackage: @astryxdesign/core