An open source design system that's fully customizable and agent ready
TypeScript
docs(useMultiCombobox): add an issue labels example block (#9578)
홍규진62f5ebc5e4f8
diff --git a/.changeset/use-multi-combobox-issue-labels-example.md b/.changeset/use-multi-combobox-issue-labels-example.mdnew file mode 100644index 0000000000..3da79d329f--- /dev/null+++ b/.changeset/use-multi-combobox-issue-labels-example.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] A new `useMultiCombobox — Issue Labels` example block builds a Labels field on `useMultiCombobox`: typing filters the labels, the arrow keys move the active option while focus stays in the field, Enter or a click toggles a label and the list stays open, and selected labels show as removable tokens above the field. Copy it with `astryx template useMultiComboboxHookUsage <path>`.++@kyu-rongdiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex e1e8acb7b3..e9a26f3671 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -807,6 +807,7 @@"/templates/useListFocusHookUsage/","/templates/useLocaleHookUsage/","/templates/useMergedRefsHookUsage/",+ "/templates/useMultiComboboxHookUsage/","/templates/useOutlineFromMarkdownHookUsage/","/templates/useOverflowHookUsage/","/templates/useOverlayHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 6fdc13555e..60a7420693 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3786,6 +3786,11 @@"path": "examples/use-merged-refs/auto-grow-text-area","aliases": []},+ {+ "name": "example-use-multi-combobox-issue-labels",+ "path": "examples/use-multi-combobox/issue-labels",+ "aliases": []+ },{"name": "example-use-outline-from-markdown-docs-article","path": "examples/use-outline-from-markdown/docs-article",diff --git a/packages/cli/api/template/use-multi-combobox-hook-usage.test.tsx b/packages/cli/api/template/use-multi-combobox-hook-usage.test.tsxnew file mode 100644index 0000000000..44aea0a1c8--- /dev/null+++ b/packages/cli/api/template/use-multi-combobox-hook-usage.test.tsx@@ -0,0 +1,214 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useMultiCombobox example takes its keys and active option from the+ * hook: the arrow keys move the active option while focus stays in the field,+ * Enter toggles a label and the list stays open, and Escape closes the list.+ * Keys that compose a syllable stay with the input method, Enter with no+ * active option is left to the form, a new query announces its match count,+ * and a query with no match keeps the list shut.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, describe, expect, it, vi} from 'vitest';+import UseMultiComboboxHookUsage from '../../assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage';++(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(<UseMultiComboboxHookUsage />);+ });+ const input = container.querySelector<HTMLInputElement>('[role="combobox"]');+ if (input == null) {+ throw new Error('no combobox 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}));+ });+}++function listbox(): HTMLElement | null {+ return container.querySelector('[role="listbox"]');+}++function activeLabel(input: HTMLInputElement): string | null {+ const id = input.getAttribute('aria-activedescendant');+ return id == null ? null : (document.getElementById(id)?.textContent ?? '');+}++function selectedOptions(): string[] {+ return Array.from(+ container.querySelectorAll('[role="option"][aria-checked="true"]'),+ option => option.textContent ?? '',+ );+}++/** The remove buttons of the tokens above the field, one per selected label. */+function tokenRemoveLabels(): string[] {+ return Array.from(+ container.querySelectorAll('button[aria-label]'),+ button => button.getAttribute('aria-label') ?? '',+ );+}++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+});++describe('useMultiCombobox example', () => {+ it('moves the active option with the arrow keys while focus stays in the field', () => {+ const input = renderExample();+ press(input, 'ArrowDown');+ expect(listbox()).not.toBeNull();+ expect(activeLabel(input)).toBe('Bug');+ press(input, 'ArrowDown');+ expect(activeLabel(input)).toBe('Documentation');+ expect(document.activeElement).toBe(input);+ });++ it('toggles the active label with Enter and keeps the list open', () => {+ const input = renderExample();+ type(input, 'perf');+ expect(activeLabel(input)).toBe('Performance');+ press(input, 'Enter');+ expect(listbox()).not.toBeNull();+ expect(selectedOptions()).toEqual(['Performance']);+ expect(tokenRemoveLabels()).toHaveLength(2);+ press(input, 'Enter');+ expect(listbox()).not.toBeNull();+ expect(selectedOptions()).toEqual([]);+ expect(tokenRemoveLabels()).toHaveLength(1);+ });++ it('toggles a clicked label and keeps the list open', () => {+ const input = renderExample();+ press(input, 'ArrowDown');+ const option = Array.from(+ container.querySelectorAll<HTMLElement>('[role="option"]'),+ ).find(candidate => candidate.textContent === 'Accessibility');+ act(() => option?.click());+ expect(listbox()).not.toBeNull();+ expect(selectedOptions()).toEqual(['Bug', 'Accessibility']);+ });++ it('moves focus back to the field when a token is removed', () => {+ const input = renderExample();+ const remove = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Remove Bug"]',+ );+ act(() => remove?.focus());+ act(() => remove?.click());+ expect(tokenRemoveLabels()).toEqual([]);+ expect(document.activeElement).toBe(input);+ });++ it('leaves Home, End, PageUp and PageDown to the field', () => {+ const input = renderExample();+ press(input, 'ArrowDown');+ for (const key of ['Home', 'End', 'PageUp', 'PageDown']) {+ const event = new KeyboardEvent('keydown', {+ key,+ bubbles: true,+ cancelable: true,+ });+ act(() => {+ input.dispatchEvent(event);+ });+ expect(event.defaultPrevented, key).toBe(false);+ expect(activeLabel(input), key).toBe('Bug');+ }+ });++ it('closes the list on Escape', () => {+ const input = renderExample();+ press(input, 'ArrowDown');+ expect(listbox()).not.toBeNull();+ press(input, 'Escape');+ expect(listbox()).toBeNull();+ expect(input.getAttribute('aria-activedescendant')).toBeNull();+ });++ it('leaves keys that compose a syllable to the input method', () => {+ const input = renderExample();+ type(input, 'perf');+ expect(activeLabel(input)).toBe('Performance');+ act(() => {+ input.dispatchEvent(+ new KeyboardEvent('keydown', {+ key: 'Enter',+ isComposing: true,+ bubbles: true,+ }),+ );+ });+ expect(selectedOptions()).toEqual([]);+ });++ it('leaves Enter to the form while no option is active', () => {+ const input = renderExample();+ expect(input.getAttribute('aria-activedescendant')).toBeNull();+ const event = new KeyboardEvent('keydown', {+ key: 'Enter',+ bubbles: true,+ cancelable: true,+ });+ act(() => {+ input.dispatchEvent(event);+ });+ expect(event.defaultPrevented).toBe(false);+ });++ it('announces how many labels match a new query', async () => {+ const input = renderExample();+ // The live region is shared by the whole page, so a message an earlier+ // test left unexposed can still lead it: read the newest message.+ const lastSpoken = () =>+ document.querySelector('[data-astryx-live-region="polite"]')+ ?.textContent ?? '';+ type(input, 'o');+ await vi.waitFor(() => expect(lastSpoken()).toMatch(/(^| )3 labels$/));+ type(input, 'perf');+ await vi.waitFor(() => expect(lastSpoken()).toMatch(/(^| )1 label$/));+ type(input, 'zzz');+ await vi.waitFor(() =>+ expect(lastSpoken()).toMatch(/(^| )No labels match$/),+ );+ });++ it('keeps the list shut on ArrowDown when no label matches', () => {+ const input = renderExample();+ type(input, 'zzz');+ press(input, 'Escape');+ press(input, 'ArrowDown');+ expect(listbox()).toBeNull();+ expect(input.getAttribute('aria-activedescendant')).toBeNull();+ });+});diff --git a/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.doc.mjsnew file mode 100644index 0000000000..7e396f86fe--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.doc.mjs@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'useMultiCombobox',+ name: 'useMultiCombobox — Issue Labels',+ displayName: 'useMultiCombobox — Issue Labels',+ description:+ 'A Labels field built on useMultiCombobox: typing filters the labels, the arrow keys move the active option while focus stays in the field, Enter or a click toggles a label and the list stays open, and selected labels show as removable tokens above the field.',+ isReady: true,+ aspectRatio: 4 / 3,+ icons: {CheckIcon: 'check'},+ componentsUsed: [+ 'MultiSelector',+ 'Card',+ 'TextInput',+ 'Item',+ 'Icon',+ 'Token',+ 'Layout',+ ],+};diff --git a/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.tsx b/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.tsxnew file mode 100644index 0000000000..e5d9155d9a--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/MultiSelector/useMultiComboboxHookUsage.tsx@@ -0,0 +1,164 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useId, useRef, useState} from 'react';+import {CheckIcon} from '@heroicons/react/24/outline';+import {Card} from '@astryxdesign/core/Card';+import {useAnnounce} from '@astryxdesign/core/hooks';+import {Icon} from '@astryxdesign/core/Icon';+import {Item} from '@astryxdesign/core/Item';+import {HStack, VStack} from '@astryxdesign/core/Layout';+import {useMultiCombobox} from '@astryxdesign/core/MultiSelector';+import {TextInput} from '@astryxdesign/core/TextInput';+import {Token} from '@astryxdesign/core/Token';+import {isImeKeyEvent} from '@astryxdesign/core/utils';++const LABELS = [+ {value: 'bug', label: 'Bug'},+ {value: 'docs', label: 'Documentation'},+ {value: 'a11y', label: 'Accessibility'},+ {value: 'perf', label: 'Performance'},+ {value: 'good-first-issue', label: 'Good first issue'},+];++function filterLabels(query: string) {+ const needle = query.trim().toLowerCase();+ return LABELS.filter(item => item.label.toLowerCase().includes(needle));+}++export default function UseMultiComboboxHookUsage() {+ const listboxId = useId();+ const inputRef = useRef<HTMLInputElement>(null);+ const [query, setQuery] = useState('');+ const [isOpen, setIsOpen] = useState(false);+ const [selected, setSelected] = useState<string[]>(['bug']);+ const matches = filterLabels(query);+ const announce = useAnnounce({hasReplace: true});++ const toggle = (value: string) =>+ setSelected(current =>+ current.includes(value)+ ? current.filter(item => item !== value)+ : [...current, value],+ );++ const combobox = useMultiCombobox({+ selectableItems: matches,+ isOpen,+ hasSearch: true,+ // With no match there is no option to point at, so the list stays shut.+ onOpen: () => {+ if (matches.length === 0) {+ return false;+ }+ setIsOpen(true);+ },+ onClose: () => setIsOpen(false),+ onToggle: toggle,+ listboxId,+ });++ return (+ <Card width={360} padding={4}>+ <VStack gap={2}>+ <HStack gap={1} wrap="wrap">+ {LABELS.filter(item => selected.includes(item.value)).map(item => (+ <Token+ key={item.value}+ label={item.label}+ // The removed token's button unmounts, so focus goes back to+ // the field instead of the page.+ onRemove={() => {+ toggle(item.value);+ inputRef.current?.focus();+ }}+ />+ ))}+ </HStack>+ <TextInput+ ref={inputRef}+ label="Labels"+ placeholder="Filter labels"+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={isOpen}+ aria-controls={isOpen ? listboxId : undefined}+ aria-activedescendant={combobox.activeDescendantId}+ value={query}+ onChange={nextQuery => {+ const nextMatches = filterLabels(nextQuery);+ setQuery(nextQuery);+ setIsOpen(true);+ combobox.setHighlightedIndex(nextMatches.length > 0 ? 0 : -1);+ if (nextQuery.trim() !== query.trim()) {+ announce(+ nextMatches.length === 0+ ? 'No labels match'+ : nextMatches.length === 1+ ? '1 label'+ : `${nextMatches.length} labels`,+ );+ }+ }}+ onClick={combobox.onTriggerClick}+ onKeyDown={event => {+ // Keys that compose a Korean, Japanese or Chinese syllable belong+ // to the input method. Home, End, PageUp and PageDown keep their+ // text-field meaning.+ if (+ isImeKeyEvent(event.nativeEvent) ||+ ['Home', 'End', 'PageUp', 'PageDown'].includes(event.key)+ ) {+ return;+ }+ // With no active option, Enter submits a surrounding form.+ if (event.key === 'Enter' && combobox.activeDescendantId == null) {+ return;+ }+ combobox.onKeyDown(event);+ }}+ onBlur={() => {+ setIsOpen(false);+ combobox.setHighlightedIndex(-1);+ }}+ />+ {isOpen && (+ <VStack+ as="ul"+ gap={0}+ id={listboxId}+ role="listbox"+ aria-label="Labels"+ aria-multiselectable+ // Focus stays on the field when an option is pressed.+ onMouseDown={event => event.preventDefault()}>+ {matches.map((item, index) => (+ <Item+ key={item.value}+ as="li"+ id={combobox.getItemId(index)}+ role="option"+ // Selection is a check mark, so the highlight below stays the+ // only fill on the row and the active option is always visible.+ aria-checked={selected.includes(item.value)}+ density="compact"+ label={item.label}+ endContent={+ selected.includes(item.value) && (+ <Icon icon={CheckIcon} size="sm" />+ )+ }+ isHighlighted={index === combobox.highlightedIndex}+ onClick={() => toggle(item.value)}+ // Highlight follows pointer movement: a list that opens under+ // a resting pointer keeps the active option the keys set.+ onMouseMove={() => combobox.onItemMouseEnter(item, index)}+ />+ ))}+ </VStack>+ )}+ </VStack>+ </Card>+ );+}diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json b/packages/cli/test/__golden__/no-icon-set/search-icon-set.jsonindex 03ca4df764..dc92c0ee9a 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon set",- "matchCount": 385,+ "matchCount": 386,"results": [{"domain": "doc",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txtindex a9c6d55d79..86df267ce7 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon-set.txt@@ -1,4 +1,4 @@-Results for "icon set" (20 of 385)+Results for "icon set" (20 of 386)name: authoring/building-blocks/templates/build-the-template/template-assets/template-iconssection: use-astryx-icondomain: docdiff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.json b/packages/cli/test/__golden__/no-icon-set/search-icon.jsonindex 436b14bcc7..244adace8e 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon.json+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.json@@ -3,7 +3,7 @@"type": "search","data": {"query": "icon",- "matchCount": 231,+ "matchCount": 232,"results": [{"domain": "component",diff --git a/packages/cli/test/__golden__/no-icon-set/search-icon.txt b/packages/cli/test/__golden__/no-icon-set/search-icon.txtindex 4b88e33b26..569f4cc8b6 100644--- a/packages/cli/test/__golden__/no-icon-set/search-icon.txt+++ b/packages/cli/test/__golden__/no-icon-set/search-icon.txt@@ -1,4 +1,4 @@-Results for "icon" (20 of 231)+Results for "icon" (20 of 232)name: Icondomain: componentpackage: @astryxdesign/core