Skip to content

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

TypeScript

docs(useTypeahead): add a type-to-focus country list example block (#9614)

Parman Mohammadalizadehad27496be43c
diff --git a/.changeset/use-typeahead-country-list-example.md b/.changeset/use-typeahead-country-list-example.md
new file mode 100644
index 0000000000..dec6efbf05
--- /dev/null
+++ b/.changeset/use-typeahead-country-list-example.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] A new `useTypeahead — Type to Focus a Country` example block adds type-to-focus to a country list of buttons. Typing "can" focuses Canada, pressing "b" again and again cycles through Belgium, Brazil and Bulgaria, and "e" finds Éire with the accent ignored. `useTypeahead` reports each match through `onMatch`, and `useListFocus` moves focus. Copy it with `astryx template useTypeaheadHookUsage <path>`.
+
+@MannXo
diff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.json
index 1042802df8..40a51cca8b 100644
--- a/apps/sandbox/scripts/next-export-routes.json
+++ b/apps/sandbox/scripts/next-export-routes.json
@@ -798,6 +798,7 @@
"/templates/useThemeHookUsage/",
"/templates/useToastHookUsage/",
"/templates/useTranslatorHookUsage/",
+ "/templates/useTypeaheadHookUsage/",
"/templates/work-item-detail/",
"/themes/",
"/tools/"
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index 8bc50afd3e..45dbdc8b56 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -3791,6 +3791,11 @@
"path": "examples/use-translator/load-more-footer",
"aliases": []
},
+ {
+ "name": "example-use-typeahead-type-to-focus-a-country",
+ "path": "examples/use-typeahead/type-to-focus-a-country",
+ "aliases": []
+ },
{
"name": "example-v-stack-basic",
"path": "examples/v-stack/basic",
diff --git a/packages/cli/api/template/use-typeahead-hook-usage.test.tsx b/packages/cli/api/template/use-typeahead-hook-usage.test.tsx
new file mode 100644
index 0000000000..1612fa8a97
--- /dev/null
+++ b/packages/cli/api/template/use-typeahead-hook-usage.test.tsx
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+// @vitest-environment jsdom
+
+/**
+ * The useTypeahead example moves focus in its country list to the item whose
+ * name starts with the typed letters. A repeated letter cycles through its
+ * matches, accents are ignored, and arrow keys still reach useListFocus.
+ */
+
+import {act} from 'react';
+import {createRoot, type Root} from 'react-dom/client';
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import UseTypeaheadHookUsage from '../../assets/templates/blocks/components/Hooks/useTypeaheadHookUsage';
+
+(globalThis as {IS_REACT_ACT_ENVIRONMENT?: boolean}).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let root: Root | null = null;
+let container: HTMLElement;
+
+function country(name: string): HTMLButtonElement {
+ const match = Array.from(container.querySelectorAll('button')).find(
+ candidate => candidate.textContent === name,
+ );
+ if (match == null) {
+ throw new Error(`no "${name}" button rendered`);
+ }
+ return match;
+}
+
+function focused(): string | null | undefined {
+ return document.activeElement?.textContent;
+}
+
+function type(keys: string): void {
+ for (const key of keys) {
+ press(key);
+ }
+}
+
+function press(key: string): void {
+ act(() => {
+ document.activeElement?.dispatchEvent(
+ new KeyboardEvent('keydown', {key, bubbles: true, cancelable: true}),
+ );
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ act(() => {
+ root = createRoot(container);
+ root.render(<UseTypeaheadHookUsage />);
+ });
+ act(() => country('Belgium').focus());
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('useTypeahead example', () => {
+ it('focuses the country that starts with the typed letters', () => {
+ type('can');
+ expect(focused()).toBe('Canada');
+
+ act(() => vi.advanceTimersByTime(750));
+ type('ch');
+ expect(focused()).toBe('Chile');
+ });
+
+ it('cycles through the matches when one letter is pressed again', () => {
+ act(() => country('Canada').focus());
+ type('b');
+ expect(focused()).toBe('Belgium');
+ type('b');
+ expect(focused()).toBe('Brazil');
+ type('b');
+ expect(focused()).toBe('Bulgaria');
+ });
+
+ it('ignores accents when it matches', () => {
+ type('e');
+ expect(focused()).toBe('Éire');
+ });
+
+ it('leaves arrow keys to the list focus manager', () => {
+ press('ArrowDown');
+ expect(focused()).toBe('Brazil');
+ });
+});
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.doc.mjs
new file mode 100644
index 0000000000..5257149119
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.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: 'useTypeahead',
+ name: 'useTypeahead — Type to Focus a Country',
+ displayName: 'useTypeahead — Type to Focus a Country',
+ description:
+ 'A country list of buttons with useListFocus arrow keys and useTypeahead type-to-focus. Typing "can" focuses Canada, pressing "b" again and again cycles through Belgium, Brazil and Bulgaria, and "e" finds Éire with the accent ignored. The hook only reports the match through onMatch, and useListFocus moves focus.',
+ isReady: true,
+ aspectRatio: 4 / 3,
+ componentsUsed: ['Button', 'Text', 'Layout'],
+};
diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.tsx
new file mode 100644
index 0000000000..663fcef53b
--- /dev/null
+++ b/packages/cli/assets/templates/blocks/components/Hooks/useTypeaheadHookUsage.tsx
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {useState} from 'react';
+import {Button} from '@astryxdesign/core/Button';
+import {useListFocus, useTypeahead} from '@astryxdesign/core/hooks';
+import {VStack} from '@astryxdesign/core/Layout';
+import {Text} from '@astryxdesign/core/Text';
+
+const COUNTRIES = [
+ 'Belgium',
+ 'Brazil',
+ 'Bulgaria',
+ 'Canada',
+ 'Chile',
+ 'Denmark',
+ 'Éire',
+ 'Finland',
+];
+
+export default function UseTypeaheadHookUsage() {
+ const [country, setCountry] = useState<string | null>(null);
+ const {listRef, handleKeyDown, handleFocus, focusItem, getItems} =
+ useListFocus({itemSelector: 'button', hasRovingTabIndex: true});
+ const typeahead = useTypeahead({
+ getItemLabels: () => getItems().map(item => item.textContent),
+ onMatch: focusItem,
+ getCurrentIndex: () =>
+ getItems().findIndex(item => item === document.activeElement),
+ });
+
+ return (
+ <VStack gap={3} hAlign="start">
+ <VStack
+ ref={listRef}
+ role="group"
+ aria-label="Country"
+ hAlign="start"
+ onFocus={handleFocus}
+ onBlur={event => {
+ if (!event.currentTarget.contains(event.relatedTarget)) {
+ typeahead.reset();
+ }
+ }}
+ onKeyDown={event => {
+ if (typeahead.onKeyDown(event)) {
+ event.preventDefault();
+ } else {
+ handleKeyDown(event);
+ }
+ }}>
+ {COUNTRIES.map(name => (
+ <Button
+ key={name}
+ label={name}
+ variant="ghost"
+ aria-pressed={country === name}
+ onClick={() => setCountry(name)}
+ />
+ ))}
+ </VStack>
+ <Text type="supporting">Selected: {country ?? 'none'}</Text>
+ </VStack>
+ );
+}