An open source design system that's fully customizable and agent ready
TypeScript
docs(useAnnounce): add a filter result count example block (#9509)
Parman Mohammadalizadehdc90b5031909
diff --git a/.changeset/use-announce-filter-count-example.md b/.changeset/use-announce-filter-count-example.mdnew file mode 100644index 0000000000..4197016185--- /dev/null+++ b/.changeset/use-announce-filter-count-example.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[docs] A new `useAnnounce — Filter Result Count` example block shows the hook on a product filter: once typing pauses for 500 ms, a screen reader hears the result count ("3 results", or "No results"). The count has its own `hasReplace` instance, as the hook's docs advise for a changing value. Copy it with `astryx template useAnnounceHookUsage <path>`.++@MannXodiff --git a/apps/sandbox/scripts/next-export-routes.json b/apps/sandbox/scripts/next-export-routes.jsonindex b209db8755..bcc6510614 100644--- a/apps/sandbox/scripts/next-export-routes.json+++ b/apps/sandbox/scripts/next-export-routes.json@@ -782,6 +782,7 @@"/templates/table-tree/","/templates/table/","/templates/theme-showcase/",+ "/templates/useAnnounceHookUsage/","/templates/useCollatorHookUsage/","/templates/useComboboxHookUsage/","/templates/useContainerRevealHookUsage/",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex f9d2ebbbb3..ef05dd9b96 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3641,6 +3641,11 @@"path": "examples/use-animator/playing-cards","aliases": []},+ {+ "name": "example-use-announce-filter-result-count",+ "path": "examples/use-announce/filter-result-count",+ "aliases": []+ },{"name": "example-use-app-shell-mobile-custom-mobile-trigger","path": "examples/use-app-shell-mobile/custom-mobile-trigger",diff --git a/packages/cli/api/template/use-announce-hook-usage.test.tsx b/packages/cli/api/template/use-announce-hook-usage.test.tsxnew file mode 100644index 0000000000..37c9f0c4b9--- /dev/null+++ b/packages/cli/api/template/use-announce-hook-usage.test.tsx@@ -0,0 +1,89 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @vitest-environment jsdom++/**+ * The useAnnounce example announces the filter's result count once typing+ * pauses, not on every keystroke, and says "No results" when nothing matches.+ */++import {act} from 'react';+import {createRoot, type Root} from 'react-dom/client';+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import UseAnnounceHookUsage from '../../assets/templates/blocks/components/Hooks/useAnnounceHookUsage';++(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(<UseAnnounceHookUsage />);+ });+}++/** Type a value into the controlled filter field. */+function type(value: string): void {+ const input = container.querySelector('input');+ if (input == null) {+ throw new Error('no filter field rendered');+ }+ const setValue = Object.getOwnPropertyDescriptor(+ HTMLInputElement.prototype,+ 'value',+ )?.set;+ act(() => {+ setValue?.call(input, value);+ input.dispatchEvent(new Event('input', {bubbles: true}));+ });+}++function wait(ms: number): void {+ act(() => {+ vi.advanceTimersByTime(ms);+ vi.advanceTimersToNextFrame();+ });+}++function spoken(): string | null | undefined {+ return document.querySelector('[data-astryx-live-region="polite"]')+ ?.textContent;+}++beforeEach(() => {+ vi.useFakeTimers();+});++afterEach(() => {+ act(() => root?.unmount());+ root = null;+ container.remove();+ vi.useRealTimers();+});++describe('useAnnounce example', () => {+ it('announces the count once typing pauses', () => {+ renderExample();+ type('d');+ wait(200);+ type('de');+ wait(200);+ type('desk');+ wait(200);+ expect(spoken() ?? '').toBe('');+ wait(300);+ expect(spoken()).toBe('3 results');+ expect(container.querySelectorAll('li')).toHaveLength(3);+ });++ it('announces "No results" when nothing matches', () => {+ renderExample();+ type('sofa');+ wait(500);+ expect(spoken()).toBe('No results');+ });+});diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.doc.mjs b/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.doc.mjsnew file mode 100644index 0000000000..5556f287c0--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.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: 'useAnnounce',+ name: 'useAnnounce — Filter Result Count',+ displayName: 'useAnnounce — Filter Result Count',+ description:+ 'A product filter that announces its result count with useAnnounce: once typing pauses for 500 ms, a screen reader hears "3 results" or "No results". The count has its own hasReplace instance, as the hook\'s docs advise for a changing value.',+ isReady: true,+ aspectRatio: 4 / 3,+ componentsUsed: ['Card', 'TextInput', 'List', 'Text', 'Layout'],+};diff --git a/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.tsx b/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.tsxnew file mode 100644index 0000000000..f3618312f5--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/Hooks/useAnnounceHookUsage.tsx@@ -0,0 +1,90 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useEffect, useRef, useState} from 'react';+import {Card} from '@astryxdesign/core/Card';+import {useAnnounce} from '@astryxdesign/core/hooks';+import {VStack} from '@astryxdesign/core/Layout';+import {List, ListItem} from '@astryxdesign/core/List';+import {Text} from '@astryxdesign/core/Text';+import {TextInput} from '@astryxdesign/core/TextInput';++const PRODUCTS = [+ 'Desk lamp',+ 'Desk organizer',+ 'Standing desk',+ 'Office chair',+ 'Chair mat',+ 'Monitor arm',+ 'Monitor stand',+ 'Keyboard tray',+];++const ANNOUNCE_DELAY_MS = 500;++function filterProducts(query: string): string[] {+ const needle = query.trim().toLowerCase();+ return PRODUCTS.filter(product => product.toLowerCase().includes(needle));+}++export default function UseAnnounceHookUsage() {+ const announce = useAnnounce({hasReplace: true});+ const [query, setQuery] = useState('');+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const matches = filterProducts(query);+ const count = matches.length;++ const handleChange = (value: string) => {+ setQuery(value);+ if (timerRef.current != null) {+ clearTimeout(timerRef.current);+ timerRef.current = null;+ }+ if (value === '') {+ return;+ }+ const nextCount = filterProducts(value).length;+ timerRef.current = setTimeout(() => {+ timerRef.current = null;+ announce(+ nextCount === 0+ ? 'No results'+ : `${nextCount} ${nextCount === 1 ? 'result' : 'results'}`,+ );+ }, ANNOUNCE_DELAY_MS);+ };++ // A count still pending at unmount would be spoken for a filter that is gone.+ useEffect(() => {+ return () => {+ if (timerRef.current != null) {+ clearTimeout(timerRef.current);+ }+ };+ }, []);++ return (+ <Card width={360} padding={4}>+ <VStack gap={3}>+ <TextInput+ label="Filter products"+ value={query}+ onChange={handleChange}+ hasClear+ />+ {count === 0 ? (+ <Text type="body" color="secondary">+ No results+ </Text>+ ) : (+ <List density="compact">+ {matches.map(product => (+ <ListItem key={product} label={product} />+ ))}+ </List>+ )}+ </VStack>+ </Card>+ );+}