Skip to content

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

TypeScript

Document the seven core hooks missing from the CLI hook index, and fail the build when it goes stale (#5109)

Cindy Zhangd88306a55312
diff --git a/.changeset/document-the-seven-core-hooks-that-were-missing--sr6p.md b/.changeset/document-the-seven-core-hooks-that-were-missing--sr6p.md
new file mode 100644
index 0000000000..f03369b55f
--- /dev/null
+++ b/.changeset/document-the-seven-core-hooks-that-were-missing--sr6p.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/cli': patch
+'@astryxdesign/core': patch
+---
+
+[docs] `useAnnounce`, `useTypeahead`, `useInteractiveRole`, `useLongPress`, `useInputStatusIcon`, `useDevWarning` and `useIndicatorFocusRing` are now discoverable. The CLI's hook index is built from the `.doc.mjs` files next to each hook, and these seven shipped without one; so `astryx hook <name>` answered "No hook named", `astryx hook` omitted them and `astryx search` never returned them, while the package exported them with full TSDoc. Agents following the documented discovery workflow concluded the primitives did not exist and hand-rolled replacements; for `useAnnounce` that means a hand-built `aria-live` region, which usually does not announce at all. A test now fails when a hook is exported from the barrel without a doc, so the index cannot silently go stale again.
+
+@cixzhang
diff --git a/packages/cli/foundation/discovery/hook-discovery.test.mjs b/packages/cli/foundation/discovery/hook-discovery.test.mjs
index 048ad62c7f..711224ae1c 100644
--- a/packages/cli/foundation/discovery/hook-discovery.test.mjs
+++ b/packages/cli/foundation/discovery/hook-discovery.test.mjs
@@ -5,16 +5,25 @@
* @astryxdesign/core source tree plus throwaway fixtures. Pins the
* category grouping, the missing-src guarding (which differs from
* component-discovery), and the Levenshtein fuzzy-fallback in findHookDoc.
+ * Also gates the index against the hooks barrel: every hook the built barrel
+ * exports must be discoverable, so adding a hook without a doc fails here.
*/
import {describe, it, expect, afterAll} from 'vitest';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {discoverHooks, findHookDoc, getAllHookNames} from './hook-discovery.mjs';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {
+ discoverHooks,
+ findHookDoc,
+ getAllHookNames,
+} from './hook-discovery.mjs';
-const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+const REPO = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../../../..',
+);
const CORE = path.join(REPO, 'packages', 'core');
const SLOW = 30_000;
@@ -29,35 +38,53 @@ afterAll(() => {
});
describe('discoverHooks (real core)', () => {
- it('discovers real hooks grouped by category', () => {
- const hooks = discoverHooks(CORE);
- const cats = Object.keys(hooks);
- expect(cats.length).toBeGreaterThan(1);
- if (cats.includes('Other')) expect(cats[cats.length - 1]).toBe('Other');
- const nonOther = cats.filter(c => c !== 'Other');
- expect([...nonOther].sort((a, b) => a.localeCompare(b))).toEqual(nonOther);
- for (const members of Object.values(hooks)) {
- expect([...members].sort()).toEqual(members);
- }
- const all = getAllHookNames(CORE);
- expect(all).toContain('useMediaQuery');
- expect(all.length).toBeGreaterThan(10);
- }, SLOW);
+ it(
+ 'discovers real hooks grouped by category',
+ () => {
+ const hooks = discoverHooks(CORE);
+ const cats = Object.keys(hooks);
+ expect(cats.length).toBeGreaterThan(1);
+ if (cats.includes('Other')) expect(cats[cats.length - 1]).toBe('Other');
+ const nonOther = cats.filter(c => c !== 'Other');
+ expect([...nonOther].sort((a, b) => a.localeCompare(b))).toEqual(
+ nonOther,
+ );
+ for (const members of Object.values(hooks)) {
+ expect([...members].sort()).toEqual(members);
+ }
+ const all = getAllHookNames(CORE);
+ expect(all).toContain('useMediaQuery');
+ expect(all.length).toBeGreaterThan(10);
+ },
+ SLOW,
+ );
it('capitalizes categories and buckets category-less docs into Other', () => {
const core = mkTmp('as-hd-cat-');
const hooksDir = path.join(core, 'src', 'hooks');
fs.mkdirSync(hooksDir, {recursive: true});
- fs.writeFileSync(path.join(hooksDir, 'useThing.doc.mjs'), "export default {\n category: 'layout',\n};\n");
- fs.writeFileSync(path.join(hooksDir, 'useOrphan.doc.mjs'), 'export default {};\n');
- expect(discoverHooks(core)).toEqual({Layout: ['useThing'], Other: ['useOrphan']});
+ fs.writeFileSync(
+ path.join(hooksDir, 'useThing.doc.mjs'),
+ "export default {\n category: 'layout',\n};\n",
+ );
+ fs.writeFileSync(
+ path.join(hooksDir, 'useOrphan.doc.mjs'),
+ 'export default {};\n',
+ );
+ expect(discoverHooks(core)).toEqual({
+ Layout: ['useThing'],
+ Other: ['useOrphan'],
+ });
});
it('discovers use*.doc.mjs colocated in component directories', () => {
const core = mkTmp('as-hd-colo-');
const compDir = path.join(core, 'src', 'Resizable');
fs.mkdirSync(compDir, {recursive: true});
- fs.writeFileSync(path.join(compDir, 'useResizable.doc.mjs'), "export default {\n category: 'interaction',\n};\n");
+ fs.writeFileSync(
+ path.join(compDir, 'useResizable.doc.mjs'),
+ "export default {\n category: 'interaction',\n};\n",
+ );
expect(discoverHooks(core)).toEqual({Interaction: ['useResizable']});
});
@@ -69,13 +96,25 @@ describe('discoverHooks (real core)', () => {
});
describe('findHookDoc (real core)', () => {
- it('resolves an exact hook name', () => {
- expect(findHookDoc(CORE, 'useMediaQuery')).toMatch(/useMediaQuery\.doc\.mjs$/);
- }, SLOW);
+ it(
+ 'resolves an exact hook name',
+ () => {
+ expect(findHookDoc(CORE, 'useMediaQuery')).toMatch(
+ /useMediaQuery\.doc\.mjs$/,
+ );
+ },
+ SLOW,
+ );
- it('resolves a bare (use-prefix-stripped, case-insensitive) name', () => {
- expect(findHookDoc(CORE, 'mediaquery')).toMatch(/useMediaQuery\.doc\.mjs$/);
- }, SLOW);
+ it(
+ 'resolves a bare (use-prefix-stripped, case-insensitive) name',
+ () => {
+ expect(findHookDoc(CORE, 'mediaquery')).toMatch(
+ /useMediaQuery\.doc\.mjs$/,
+ );
+ },
+ SLOW,
+ );
it('returns null when src/ is missing (guarded)', () => {
const core = mkTmp('as-fhd-nosrc-');
@@ -84,14 +123,94 @@ describe('findHookDoc (real core)', () => {
});
describe('findHookDoc fuzzy Levenshtein fallback (pinned current behavior)', () => {
- it('auto-resolves a typo within edit distance 3', () => {
- expect(getAllHookNames(CORE)).not.toContain('useLayers');
- expect(getAllHookNames(CORE)).toContain('useLayer');
- expect(findHookDoc(CORE, 'useLayers')).toMatch(/useLayer\.doc\.mjs$/);
- }, SLOW);
-
- it('returns null when the closest hook is farther than distance 3', () => {
- expect(findHookDoc(CORE, 'useZzzzzz')).toBeNull();
- expect(findHookDoc(CORE, 'zzzzzzzzzz')).toBeNull();
- }, SLOW);
+ it(
+ 'auto-resolves a typo within edit distance 3',
+ () => {
+ expect(getAllHookNames(CORE)).not.toContain('useLayers');
+ expect(getAllHookNames(CORE)).toContain('useLayer');
+ expect(findHookDoc(CORE, 'useLayers')).toMatch(/useLayer\.doc\.mjs$/);
+ },
+ SLOW,
+ );
+
+ it(
+ 'returns null when the closest hook is farther than distance 3',
+ () => {
+ expect(findHookDoc(CORE, 'useZzzzzz')).toBeNull();
+ expect(findHookDoc(CORE, 'zzzzzzzzzz')).toBeNull();
+ },
+ SLOW,
+ );
+});
+
+/**
+ * The set of hooks a barrel actually exports, read from the module itself
+ * rather than from its text. Importing is what makes this a derivation: it sees
+ * `export * from` re-exports, aliases and any other form the language allows,
+ * and type-only exports have already been erased. A regex over the source can
+ * only see the spellings someone thought to write a pattern for.
+ * @param {string} entry absolute path to a built ESM barrel
+ */
+async function exportedHookNames(entry) {
+ const mod = await import(pathToFileURL(entry).href);
+ return new Set(Object.keys(mod).filter(name => /^use[A-Z]/.test(name)));
+}
+
+describe('core hooks barrel coverage (real core)', () => {
+ // Discovery is filesystem-driven: a hook is only reachable from `astryx hook`
+ // and `astryx search` if it ships a .doc.mjs. Nothing about adding a hook
+ // forces one, so the index silently goes stale; seven exported hooks,
+ // useAnnounce among them, were invisible until this check existed.
+ //
+ // Only the standalone hooks in src/hooks/ are in scope. Hooks that belong to
+ // a component's API (useDialog, useToast, ...) are documented in that
+ // component's directory and deliberately never enter this barrel, so their
+ // absence from it is not a defect.
+ it(
+ 'every hook exported from the barrel has a doc and is discoverable',
+ async () => {
+ // The built barrel, not src/hooks/index.ts: this suite runs in the `node`
+ // project, which has no StyleX babel transform, so importing core's TS
+ // source throws on the first stylex.defineVars it reaches. dist is present
+ // because the project's globalSetup builds core before any worker forks.
+ const exported = await exportedHookNames(
+ path.join(CORE, 'dist', 'hooks', 'index.js'),
+ );
+ expect(exported.size).toBeGreaterThan(10);
+
+ const discovered = new Set(getAllHookNames(CORE));
+ const missing = [...exported]
+ .filter(name => !discovered.has(name))
+ .sort();
+ if (missing.length) {
+ throw new Error(
+ `${missing.length} exported hook(s) are missing from the CLI hook index, so ` +
+ `\`astryx hook <name>\` and \`astryx search\` deny they exist. Add a ` +
+ `<hook>.doc.mjs next to each hook in packages/core/src/hooks/:\n ${missing.join('\n ')}`,
+ );
+ }
+ expect(missing).toEqual([]);
+ },
+ SLOW,
+ );
+
+ it('sees hooks re-exported with `export *`, which a regex over `export {…}` misses', async () => {
+ const dir = mkTmp('as-hd-star-');
+ fs.writeFileSync(
+ path.join(dir, 'useStarred.mjs'),
+ 'export function useStarred() {}\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'useNamed.mjs'),
+ 'export function useNamed() {}\n',
+ );
+ fs.writeFileSync(
+ path.join(dir, 'index.mjs'),
+ "export * from './useStarred.mjs';\nexport {useNamed} from './useNamed.mjs';\n",
+ );
+
+ expect(await exportedHookNames(path.join(dir, 'index.mjs'))).toEqual(
+ new Set(['useStarred', 'useNamed']),
+ );
+ });
});
diff --git a/packages/core/src/hooks/useAnnounce.doc.mjs b/packages/core/src/hooks/useAnnounce.doc.mjs
new file mode 100644
index 0000000000..34dd31529d
--- /dev/null
+++ b/packages/core/src/hooks/useAnnounce.doc.mjs
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useAnnounce',
+ displayName: 'useAnnounce',
+ keywords: [
+ 'announce',
+ 'live region',
+ 'aria-live',
+ 'screen reader',
+ 'accessibility',
+ 'a11y',
+ 'status',
+ 'alert',
+ 'polite',
+ 'assertive',
+ 'visually hidden',
+ 'wcag',
+ ],
+ params: [],
+ returns: [
+ {
+ name: 'announce',
+ type: '(message: string, politeness?: "polite" | "assertive") => void',
+ description:
+ 'Speaks a message through the shared live region. Politeness defaults to "polite"; an empty message clears any lingering status instead of announcing.',
+ },
+ ],
+ usage: {
+ description:
+ 'Imperatively announces a message to screen readers through a visually-hidden live region. Use it for state that is only conveyed visually; search result counts, "no results", loading and saved confirmations, validation errors (WCAG 4.1.3 Status Messages). The polite and assertive regions are created empty on first use and stay mounted, which is what makes announcements reliable: most screen readers ignore a live region that is inserted together with its content. Each message is cleared a couple of seconds after it is announced so stale status does not linger in the accessibility tree.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Reach for this instead of hand-rolling an aria-live div; a region rendered with its content usually does not announce at all.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Keep "polite" for status and result counts; reserve "assertive" for errors and time-sensitive alerts, since it interrupts whatever the screen reader is saying.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Announce the outcome, not the interaction; "12 results" rather than "search ran".',
+ },
+ {
+ guidance: false,
+ description:
+ 'Announce content that is already visible and correctly labeled in the DOM; that doubles up for screen reader users.',
+ },
+ ],
+ },
+ relatedComponents: ['VisuallyHidden', 'Toast'],
+ relatedHooks: ['useClipboard'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'accessibility',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Imperative screen-reader announcements via a visually-hidden live region. Polite + assertive regions created empty on first use + kept mounted, so announcements are reliable (most AT ignore a live region inserted together w/ its content). Messages auto-clear after ~2s.',
+ returnDescriptions: {
+ announce:
+ 'speaks message through shared live region. politeness defaults "polite"; empty message clears lingering status.',
+ },
+ usage: {
+ description:
+ 'Announces visual-only state to screen readers: result counts, "no results", loading / saved confirmations, validation errors (WCAG 4.1.3). Regions mounted empty up front, so updates announce; text auto-clears so stale status does not linger in a11y tree.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use instead of hand-rolled aria-live div; region rendered w/ its content usually does not announce.',
+ },
+ {
+ guidance: true,
+ description:
+ '"polite" for status / counts; "assertive" only for errors + time-sensitive alerts (it interrupts).',
+ },
+ {
+ guidance: true,
+ description:
+ 'Announce outcome, not interaction; "12 results", not "search ran".',
+ },
+ {
+ guidance: false,
+ description:
+ 'Announce content already visible + labeled in DOM; doubles up for AT users.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useDevWarning.doc.mjs b/packages/core/src/hooks/useDevWarning.doc.mjs
new file mode 100644
index 0000000000..89f3830557
--- /dev/null
+++ b/packages/core/src/hooks/useDevWarning.doc.mjs
@@ -0,0 +1,96 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useDevWarning',
+ displayName: 'useDevWarning',
+ keywords: [
+ 'warning',
+ 'dev',
+ 'development',
+ 'console',
+ 'guardrail',
+ 'misuse',
+ 'invariant',
+ 'debug',
+ 'devWarn',
+ ],
+ params: [
+ {
+ name: 'component',
+ type: 'string',
+ description: 'Component or hook name, used as the message prefix.',
+ required: true,
+ },
+ {
+ name: 'message',
+ type: 'string',
+ description: 'What went wrong and how to fix it.',
+ required: true,
+ },
+ {
+ name: 'condition',
+ type: 'boolean',
+ description: 'Whether to warn.',
+ default: 'true',
+ },
+ ],
+ returns: [],
+ usage: {
+ description:
+ 'Fires a dev-only "Component: message" console warning once per mount while the condition holds. It is the render-safe way for a component to flag misuse: warning straight from the render body repeats on every render, and gating it with state adds a re-render, so this uses a ref and an effect instead. For a warning outside a component, use the imperative devWarn utility.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Say what is wrong and what the builder should do instead; the message is the whole value of the warning.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Warn about combinations the types cannot express, such as two mutually exclusive props being set together.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use it for anything a user could see or for runtime error handling; it is stripped from production builds.',
+ },
+ ],
+ },
+ relatedComponents: [],
+ relatedHooks: [],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'utility',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Dev-only "Component: message" console warning, once per mount while condition holds. Ref + effect, so it never repeats per render nor causes a re-render. Outside a component, use the imperative devWarn utility.',
+ paramDescriptions: {
+ component: 'component / hook name, used as message prefix.',
+ message: 'what went wrong + how to fix it.',
+ condition: 'whether to warn.',
+ },
+ usage: {
+ description:
+ 'Render-safe guardrail warning from inside a component. Stripped from production builds.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Say what is wrong + what to do instead; the message is the value.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Warn about combinations types cannot express (mutually exclusive props set together).',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for user-visible problems / runtime error handling; it is dev-only.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useIndicatorFocusRing.doc.mjs b/packages/core/src/hooks/useIndicatorFocusRing.doc.mjs
new file mode 100644
index 0000000000..46b9dd75a1
--- /dev/null
+++ b/packages/core/src/hooks/useIndicatorFocusRing.doc.mjs
@@ -0,0 +1,104 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useIndicatorFocusRing',
+ displayName: 'useIndicatorFocusRing',
+ keywords: [
+ 'focus ring',
+ 'focus',
+ 'focus-visible',
+ 'outline',
+ 'indicator',
+ 'checkbox',
+ 'radio',
+ 'visually hidden input',
+ 'keyboard',
+ 'accessibility',
+ 'a11y',
+ 'wcag',
+ ],
+ params: [
+ {
+ name: 'containerRef',
+ type: 'RefObject<HTMLElement | null>',
+ description:
+ 'Ref to an element wrapping only the indicator, so its single element child is unambiguously the thing to ring.',
+ required: true,
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: 'Skip the ring; a disabled control is not focusable.',
+ default: 'false',
+ },
+ ],
+ returns: [
+ {
+ name: 'focusProps',
+ type: '{onFocus: (event: FocusEvent<HTMLElement>) => void; onBlur: () => void}',
+ description: 'Spread onto the element that owns the focusable input.',
+ },
+ ],
+ usage: {
+ description:
+ "Draws the standard focus ring on the indicator of a control whose real input is visually hidden; a checkbox or radio focuses an opacity-0 input, so the ring has to appear on the picture beside it. The ring is painted imperatively on the indicator's own element, which is the only element whose border-radius can shape it, and only on :focus-visible, so pointer clicks stay quiet. Owning it here means a theme-supplied indicator cannot ship a control with no visible focus (WCAG 2.4.7) by ignoring a prop.",
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ "Wrap only the indicator in the ref'd element; a wrapper holding label text would ring the whole row.",
+ },
+ {
+ guidance: true,
+ description:
+ 'Spread focusProps on the element that contains the hidden input, not on the input itself.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Ask a themeable indicator to draw its own focus ring; a replacement that ignores the prop leaves the control with no visible focus.',
+ },
+ ],
+ },
+ relatedComponents: ['CheckboxInput', 'RadioList', 'Selector'],
+ relatedHooks: ['useFocusTrap'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'focus',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Draws the standard focus ring on the indicator of a control whose input is visually hidden (checkbox / radio). Painted imperatively on the indicator element (only element whose border-radius shapes the outline), on :focus-visible only.',
+ paramDescriptions: {
+ containerRef:
+ 'ref to element wrapping ONLY the indicator; its single element child gets the ring.',
+ isDisabled: 'skip the ring; disabled control is not focusable.',
+ },
+ returnDescriptions: {
+ focusProps:
+ 'onFocus / onBlur to spread onto the element owning the focusable input.',
+ },
+ usage: {
+ description:
+ 'Owner draws the ring so a theme-supplied indicator cannot ship a control w/ no visible focus (WCAG 2.4.7).',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ "Wrap only the indicator in the ref'd element; a wrapper w/ label text rings the whole row.",
+ },
+ {
+ guidance: true,
+ description:
+ 'Spread focusProps on the element containing the hidden input, not the input.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Delegate the ring to a themeable indicator; a replacement that ignores it loses visible focus.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useInputStatusIcon.doc.mjs b/packages/core/src/hooks/useInputStatusIcon.doc.mjs
new file mode 100644
index 0000000000..3819718973
--- /dev/null
+++ b/packages/core/src/hooks/useInputStatusIcon.doc.mjs
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useInputStatusIcon',
+ displayName: 'useInputStatusIcon',
+ keywords: [
+ 'input',
+ 'status',
+ 'icon',
+ 'error',
+ 'warning',
+ 'success',
+ 'validation',
+ 'tooltip',
+ 'info tip',
+ 'field',
+ 'describedby',
+ 'accessibility',
+ 'a11y',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseInputStatusIconOptions',
+ description: 'Configuration object.',
+ required: true,
+ },
+ {
+ name: 'options.status',
+ type: 'InputStatus',
+ description:
+ "The input's status (type plus message), or undefined when there is none.",
+ },
+ {
+ name: 'options.statusVariant',
+ type: "'attached' | 'detached' | 'tooltip'",
+ description: 'How the status is presented relative to the input.',
+ default: "'attached'",
+ },
+ {
+ name: 'options.isInGroup',
+ type: 'boolean',
+ description:
+ 'Whether the input sits inside an InputGroup, which owns status rendering itself.',
+ default: 'false',
+ },
+ {
+ name: 'options.size',
+ type: 'IconSize',
+ description: 'Size of the on-field icon.',
+ default: "'md'",
+ },
+ ],
+ returns: [
+ {
+ name: 'statusIcon',
+ type: 'ReactNode',
+ description:
+ 'The affordance to render inside the input container: a plain icon, or a focusable info-tip button with its tooltip. Null when no icon should render.',
+ },
+ {
+ name: 'describedBy',
+ type: 'string | undefined',
+ description:
+ "ID to add to the input's aria-describedby, present exactly when a tooltip element is in the DOM, so there is never a dangling reference.",
+ },
+ ],
+ usage: {
+ description:
+ 'Builds the on-field status affordance for a bordered input and its accessibility wiring, so every input in the family behaves the same for a given status. The attached variant renders a plain glyph and leaves the text to the message box; the detached variant renders nothing here, because the message box already carries its own icon; the tooltip variant renders a real focusable button whose tooltip is reachable by keyboard, pointer, touch and assistive tech. Use it when building a bordered input, not for field-level messaging.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ "Render statusIcon inside the input container and merge describedBy into the control's aria-describedby list.",
+ },
+ {
+ guidance: true,
+ description:
+ 'Let it decide when nothing should render; pass isInGroup and the variant through rather than branching at the call site.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use it to convey the status by icon alone; the tooltip variant is the only one that carries the message, so the others still need a message box.',
+ },
+ ],
+ },
+ relatedComponents: [
+ 'TextInput',
+ 'TextArea',
+ 'NumberInput',
+ 'DateInput',
+ 'FileInput',
+ 'FieldStatus',
+ 'InputGroup',
+ ],
+ relatedHooks: ['useInputContainer'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'On-field status affordance + a11y wiring for bordered inputs. attached = plain glyph (message box carries text); detached = nothing (box has own icon); tooltip = focusable info-tip button reachable by keyboard / pointer / touch / AT.',
+ paramDescriptions: {
+ options: 'config.',
+ 'options.status': 'input status (type + message), or undefined.',
+ 'options.statusVariant': 'how status is presented relative to input.',
+ 'options.isInGroup': 'inside InputGroup, which owns status rendering.',
+ 'options.size': 'on-field icon size.',
+ },
+ returnDescriptions: {
+ statusIcon:
+ 'node to render inside input container; null when nothing should render.',
+ describedBy:
+ 'id for aria-describedby, present exactly when the tooltip element is in the DOM.',
+ },
+ usage: {
+ description:
+ 'Use when building a bordered input so all inputs behave the same per status; not for field-level messaging.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Render statusIcon in the input container; merge describedBy into aria-describedby.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass isInGroup + variant through; let the hook decide when nothing renders.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Rely on the icon alone for meaning; only the tooltip variant carries the message.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useInteractiveRole.doc.mjs b/packages/core/src/hooks/useInteractiveRole.doc.mjs
new file mode 100644
index 0000000000..5285ab79ac
--- /dev/null
+++ b/packages/core/src/hooks/useInteractiveRole.doc.mjs
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useInteractiveRole',
+ displayName: 'useInteractiveRole',
+ keywords: [
+ 'role',
+ 'polymorphic',
+ 'link',
+ 'button',
+ 'inert',
+ 'href',
+ 'onClick',
+ 'element type',
+ 'as',
+ 'trigger',
+ 'semantics',
+ 'accessibility',
+ 'a11y',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseInteractiveRoleOptions',
+ description: 'The interactivity inputs the component received.',
+ required: true,
+ },
+ {
+ name: 'options.href',
+ type: 'string',
+ description:
+ 'URL for navigation. Highest priority: with an href the component is a link.',
+ },
+ {
+ name: 'options.onClick',
+ type: '((...args: never[]) => unknown) | null',
+ description:
+ 'Click handler. Resolves to a button, ahead of any context-provided role.',
+ },
+ {
+ name: 'options.isDisabled',
+ type: 'boolean',
+ description:
+ 'When true, href is ignored for role resolution (a disabled link is an anti-pattern), so the role comes from onClick, then context, then inert.',
+ default: 'false',
+ },
+ ],
+ returns: [
+ {
+ name: 'role',
+ type: "'link' | 'button' | 'inert'",
+ description:
+ 'The element the component should render: an anchor, a button, or a non-interactive span/div.',
+ },
+ ],
+ usage: {
+ description:
+ 'Resolves what a polymorphic component should render as, in one place: href wins, then onClick, then an interactive trigger context supplied by a parent (Popover, DropdownMenu and friends), then inert. Use it in any component that is sometimes a link, sometimes a button, and sometimes plain content; Token, Thumbnail, Item and ClickableCard all do. Because context is part of the resolution, a component built on it becomes a valid trigger for new surfaces without changing.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Switch on the returned role to pick the element, and render an anchor only for "link" so keyboard and middle-click behavior come from the platform.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass isDisabled through rather than dropping the href yourself; the hook already keeps disabled links out of the tab order.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Add another ad-hoc href/onClick precedence check in a component; new trigger contexts are added here so every consumer inherits them.',
+ },
+ ],
+ },
+ relatedComponents: ['Token', 'Thumbnail', 'Item', 'ClickableCard'],
+ relatedHooks: ['useClickableContainer'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Resolves what a polymorphic component renders as: href -> link, onClick -> button, interactive trigger context -> its role, else inert. Single place the precedence lives.',
+ paramDescriptions: {
+ options: 'interactivity inputs the component received.',
+ 'options.href': 'navigation URL; highest priority.',
+ 'options.onClick': 'click handler; button, ahead of context role.',
+ 'options.isDisabled':
+ 'true = href ignored for resolution (disabled link is anti-pattern); falls to onClick / context / inert.',
+ },
+ returnDescriptions: {
+ role: "element to render: 'link' (anchor), 'button', or 'inert' (span/div).",
+ },
+ usage: {
+ description:
+ 'For components that are sometimes link, sometimes button, sometimes plain content (Token, Thumbnail, Item, ClickableCard). Context-aware, so consumers become valid triggers for new surfaces w/o changing.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Switch on returned role; render a real anchor for "link" so platform keyboard / middle-click behavior applies.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass isDisabled through instead of dropping href yourself.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Re-implement href/onClick precedence per component; new trigger contexts are added here.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useLongPress.doc.mjs b/packages/core/src/hooks/useLongPress.doc.mjs
new file mode 100644
index 0000000000..1d502878a9
--- /dev/null
+++ b/packages/core/src/hooks/useLongPress.doc.mjs
@@ -0,0 +1,123 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useLongPress',
+ displayName: 'useLongPress',
+ keywords: [
+ 'long press',
+ 'touch',
+ 'press and hold',
+ 'context menu',
+ 'mobile',
+ 'ios',
+ 'safari',
+ 'gesture',
+ 'tap',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseLongPressOptions',
+ description: 'Configuration object.',
+ required: true,
+ },
+ {
+ name: 'options.onLongPress',
+ type: '(point: {x: number; y: number}) => void',
+ description:
+ 'Fired with the touch start point once the press is held for delayMs.',
+ required: true,
+ },
+ {
+ name: 'options.disabled',
+ type: 'boolean',
+ description: 'When true, the returned touch handlers are inert.',
+ default: 'false',
+ },
+ {
+ name: 'options.delayMs',
+ type: 'number',
+ description: 'Hold duration before the press fires, in milliseconds.',
+ default: '500',
+ },
+ {
+ name: 'options.moveCancelPx',
+ type: 'number',
+ description:
+ 'Movement past this distance on either axis cancels the press, treating it as a scroll or drag.',
+ default: '10',
+ },
+ ],
+ returns: [
+ {
+ name: 'handlers',
+ type: 'UseLongPressHandlers',
+ description:
+ 'onTouchStart, onTouchMove, onTouchEnd and onTouchCancel to spread onto the target element.',
+ },
+ ],
+ usage: {
+ description:
+ 'Detects a single-finger press-and-hold and reports where it happened, so touch users can reach affordances that a pointer gets from right-click. iOS Safari never synthesizes a contextmenu event on long-press, which makes this the only touch route into a cursor-positioned surface such as ContextMenu. The press cancels on movement, lift, multi-touch or unmount.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use the reported point to position the surface you open, so it appears under the finger.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pair it with the pointer contextmenu handler rather than replacing it; this hook only covers touch.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use it for the primary action of a control; press-and-hold is undiscoverable as the only way to do something.',
+ },
+ ],
+ },
+ relatedComponents: ['ContextMenu'],
+ relatedHooks: ['useClickableContainer', 'useHotkeys'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'interaction',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'Single-finger press-and-hold detection reporting the touch point. iOS Safari never fires contextmenu on long-press, so this is the only touch route to cursor-positioned surfaces. Cancels on move / lift / multi-touch / unmount.',
+ paramDescriptions: {
+ options: 'config.',
+ 'options.onLongPress': 'fired w/ touch start point after delayMs.',
+ 'options.disabled': 'true = handlers inert.',
+ 'options.delayMs': 'hold duration before firing, ms.',
+ 'options.moveCancelPx':
+ 'movement past this (px, either axis) cancels as scroll / drag.',
+ },
+ returnDescriptions: {
+ handlers:
+ 'onTouchStart / onTouchMove / onTouchEnd / onTouchCancel to spread onto the element.',
+ },
+ usage: {
+ description:
+ 'Touch press-and-hold for affordances a pointer reaches by right-click (e.g. ContextMenu). Reports the point so the surface opens under the finger.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Position the opened surface at the reported point.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pair w/ pointer contextmenu handler; this covers touch only.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Make press-and-hold the only way to reach an action; it is undiscoverable.',
+ },
+ ],
+ },
+};
diff --git a/packages/core/src/hooks/useTypeahead.doc.mjs b/packages/core/src/hooks/useTypeahead.doc.mjs
new file mode 100644
index 0000000000..1d016b8c9b
--- /dev/null
+++ b/packages/core/src/hooks/useTypeahead.doc.mjs
@@ -0,0 +1,153 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ name: 'useTypeahead',
+ displayName: 'useTypeahead',
+ keywords: [
+ 'typeahead',
+ 'type to focus',
+ 'first character',
+ 'keyboard',
+ 'search',
+ 'jump',
+ 'menu',
+ 'listbox',
+ 'select',
+ 'apg',
+ 'accessibility',
+ 'a11y',
+ ],
+ params: [
+ {
+ name: 'options',
+ type: 'UseTypeaheadOptions',
+ description: 'Configuration object.',
+ required: true,
+ },
+ {
+ name: 'options.getItemLabels',
+ type: '() => ReadonlyArray<string | null | undefined>',
+ description:
+ "Returns the item labels in DOM order. A null or empty entry marks a non-matchable slot and keeps indices aligned with the caller's items.",
+ required: true,
+ },
+ {
+ name: 'options.onMatch',
+ type: '(index: number) => void',
+ description:
+ "Called with the index of the matched item so the caller can focus or select it; typically useListFocus's focusItem.",
+ required: true,
+ },
+ {
+ name: 'options.getCurrentIndex',
+ type: '() => number',
+ description:
+ 'The index to search from, usually the focused item, so repeated presses of one letter cycle through matches. A negative value means nothing is current.',
+ default: '() => -1',
+ },
+ {
+ name: 'options.resetMs',
+ type: 'number',
+ description:
+ 'Milliseconds of inactivity after which the typed buffer resets.',
+ default: '750',
+ },
+ {
+ name: 'options.isDisabled',
+ type: '(index: number) => boolean',
+ description: 'Whether an index should be skipped, e.g. disabled items.',
+ },
+ ],
+ returns: [
+ {
+ name: 'onKeyDown',
+ type: '(e: React.KeyboardEvent | KeyboardEvent) => boolean',
+ description:
+ 'Keydown handler. Returns true when it consumed a printable character, so the caller can stop its own key handling.',
+ },
+ {
+ name: 'reset',
+ type: '() => void',
+ description:
+ 'Clears the pending buffer, e.g. when the collection closes.',
+ },
+ ],
+ usage: {
+ description:
+ "Adds APG type-to-focus search to a collection: printable keystrokes are buffered (resetting after a pause), and the first item whose label starts with the buffer is reported through onMatch. Pressing the same letter repeatedly cycles through the matches rather than filtering deeper. It moves nothing itself; pair it with the collection's own focus management, most often useListFocus or useGridFocus.",
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Wire onMatch to the focus manager you already have (useListFocus.focusItem) instead of moving focus yourself.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Let it see the key event first and fall through to arrow-key navigation only when it returns false.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass getCurrentIndex so repeated presses of one letter walk through matches instead of sticking on the first.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use it on a text input; the field already receives the characters, and typeahead would fight the value.',
+ },
+ ],
+ },
+ relatedComponents: ['DropdownMenu', 'Selector', 'TreeList'],
+ relatedHooks: ['useListFocus', 'useGridFocus', 'useTreeFocus'],
+ importPath: '@astryxdesign/core/hooks',
+ category: 'focus',
+};
+
+/** @type {import('@astryxdesign/cli/authoring').HookTranslationDoc} */
+export const docsDense = {
+ description:
+ 'APG type-to-focus search for a collection. Buffers printable keys (resets after pause), matches labels by prefix, reports index via onMatch. Same letter pressed repeatedly cycles matches. Moves nothing itself; pair w/ useListFocus / useGridFocus.',
+ paramDescriptions: {
+ options: 'config.',
+ 'options.getItemLabels':
+ 'item labels in DOM order; null / empty = non-matchable slot, indices stay aligned.',
+ 'options.onMatch':
+ 'called w/ matched index so caller focuses / selects (e.g. useListFocus focusItem).',
+ 'options.getCurrentIndex':
+ 'index to search from (usually focused item) so repeat presses cycle. negative = nothing current.',
+ 'options.resetMs': 'ms of inactivity before typed buffer resets.',
+ 'options.isDisabled': 'whether an index is skipped (e.g. disabled items).',
+ },
+ returnDescriptions: {
+ onKeyDown:
+ 'keydown handler; true = consumed a printable char, caller can stop its own handling.',
+ reset: 'clears pending buffer (e.g. on close).',
+ },
+ usage: {
+ description:
+ 'Type-to-jump for menus / listboxes / trees. Buffered prefix match w/ APG same-letter cycling; reports index, caller owns focus.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Wire onMatch to existing focus manager (useListFocus.focusItem), do not move focus yourself.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Give it the key event first; fall through to arrow navigation when it returns false.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass getCurrentIndex so repeat presses walk matches instead of sticking on first.',
+ },
+ {
+ guidance: false,
+ description: 'Use on a text input; field already gets the characters.',
+ },
+ ],
+ },
+};