An open source design system that's fully customizable and agent ready
TypeScript
fix(core): audit BaseTypeahead (#6179)
Cindy Zhang18781904cb07
diff --git a/.changeset/base-typeahead-audit-fixes.md b/.changeset/base-typeahead-audit-fixes.mdnew file mode 100644index 0000000000..04f66a8e15--- /dev/null+++ b/.changeset/base-typeahead-audit-fixes.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[fix] BaseTypeahead: preserve input props and keep results accessible in narrow layouts++BaseTypeahead now forwards its inherited DOM and styling props to the combobox input, preserves native input attributes unless a defined legacy alias overrides them, keeps empty result lists valid for assistive technology, counts visible characters for `minQueryLength`, and keeps both the popup and long result content within viewport gutters.++@cixzhangdiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex e26028fde0..7e3450816f 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -236,6 +236,17 @@"nextButton": ".astryx-tab-scroll-button"}},+ {+ "component": "BaseTypeahead",+ "storyId": "core-basetypeahead--logical-dropdown-placement",+ "dims": [+ "D4"+ ],+ "selectors": {+ "overlay": "[role=\"listbox\"]",+ "overlayRoot": "[data-base-typeahead-anchor=\"true\"]"+ }+ },{"component": "Typeahead","storyId": "core-typeahead--rtl-end-lane",diff --git a/apps/storybook/stories/BaseTypeahead.stories.tsx b/apps/storybook/stories/BaseTypeahead.stories.tsxnew file mode 100644index 0000000000..39ffcb0a1b--- /dev/null+++ b/apps/storybook/stories/BaseTypeahead.stories.tsx@@ -0,0 +1,278 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {useId, useRef, useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {expect, userEvent, waitFor, within} from 'storybook/test';+import * as stylex from '@stylexjs/stylex';+import {+ BaseTypeahead,+ createStaticSource,+ type BaseTypeaheadProps,+ type SearchableItem,+ type SearchSource,+} from '@astryxdesign/core/Typeahead';+import {+ borderVars,+ colorVars,+ focusVars,+ fontWeightVars,+ radiusVars,+ sizeVars,+ spacingVars,+ typeScaleVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const items: SearchableItem[] = [+ {id: 'react', label: 'React', auxiliaryData: {group: 'Libraries'}},+ {id: 'vue', label: 'Vue', auxiliaryData: {group: 'Libraries'}},+ {id: 'angular', label: 'Angular', auxiliaryData: {group: 'Frameworks'}},+ {id: 'svelte', label: 'Svelte', auxiliaryData: {group: 'Frameworks'}},+ {+ id: 'long',+ label:+ 'A deliberately long framework result that must stay inside the menu',+ auxiliaryData: {group: 'Frameworks'},+ },+];++const source = createStaticSource(items);+const emptySource = createStaticSource([]);+const pendingSource: SearchSource = {+ search: () => new Promise(() => {}),+ bootstrap: () => new Promise(() => {}),+};++const styles = stylex.create({+ stage: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-5'],+ maxWidth: '32rem',+ },+ fieldGroup: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-1'],+ },+ label: {+ color: colorVars['--color-text-primary'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-label-size'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ },+ field: {+ alignItems: 'center',+ backgroundColor: colorVars['--color-background-surface'],+ borderColor: colorVars['--color-border-emphasized'],+ borderRadius: radiusVars['--radius-element'],+ borderStyle: 'solid',+ borderWidth: borderVars['--border-width'],+ display: 'flex',+ minHeight: sizeVars['--size-element-md'],+ paddingInline: spacingVars['--spacing-2'],+ outlineColor: {+ default: 'transparent',+ ':has(input:focus-visible)': focusVars['--focus-outline-color'],+ },+ outlineOffset: focusVars['--focus-outline-offset'],+ outlineStyle: 'solid',+ outlineWidth: {+ default: '0',+ ':has(input:focus-visible)': focusVars['--focus-outline-width'],+ },+ width: '20rem',+ },+ narrowField: {+ maxWidth: '100%',+ width: '16rem',+ },+ customItem: {+ display: 'flex',+ flexDirection: 'column',+ minWidth: 0,+ },+ customItemLabel: {+ color: colorVars['--color-text-primary'],+ fontWeight: 500,+ },+ customItemGroup: {+ color: colorVars['--color-text-secondary'],+ fontSize: typeScaleVars['--text-supporting-size'],+ },+});++type DemoProps = Omit<+ BaseTypeaheadProps<SearchableItem>,+ 'searchSource' | 'value' | 'onChange'+> & {+ label?: string;+ source?: SearchSource<SearchableItem>;+ isNarrow?: boolean;+};++function Demo({+ label = 'Framework',+ source: searchSource = source,+ isNarrow = false,+ inputId: inputIdProp,+ ariaLabelledBy: ariaLabelledByProp,+ ...props+}: DemoProps) {+ const [value, setValue] = useState<SearchableItem | null>(null);+ const anchorRef = useRef<HTMLDivElement>(null);+ const generatedId = useId().replaceAll(':', '');+ const generatedInputId = `base-typeahead-${generatedId}`;+ const inputId = inputIdProp ?? generatedInputId;+ const labelId = `${inputId}-label`;++ return (+ <div {...stylex.props(styles.fieldGroup)}>+ <label id={labelId} htmlFor={inputId} {...stylex.props(styles.label)}>+ {label}+ </label>+ <div+ ref={anchorRef}+ data-base-typeahead-anchor="true"+ {...stylex.props(styles.field, isNarrow && styles.narrowField)}>+ <BaseTypeahead+ {...props}+ inputId={inputId}+ ariaLabelledBy={ariaLabelledByProp ?? labelId}+ anchorRef={anchorRef}+ searchSource={searchSource}+ value={value}+ onChange={setValue}+ />+ </div>+ </div>+ );+}++const meta: Meta<DemoProps> = {+ title: 'Core/BaseTypeahead',+ component: Demo,+ tags: ['autodocs'],+ parameters: {layout: 'centered'},+} satisfies Meta<DemoProps>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ render: () => <Demo placeholder="Search frameworks…" />,+};++export const LogicalDropdownPlacement: Story = {+ render: () => (+ <Demo+ hasEntriesOnFocus+ isNarrow+ menuWidth={320}+ placeholder="Focus to open results…"+ />+ ),+ play: async ({canvasElement}) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.click(input);+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));+ },+};++export const Loading: Story = {+ render: () => (+ <Demo+ source={pendingSource}+ debounceMs={0}+ placeholder="Type to start a pending search…"+ />+ ),+ play: async ({canvasElement}) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.type(input, 're');+ await waitFor(() => expect(input).toHaveAttribute('aria-busy', 'true'));+ },+};++export const EmptyResults: Story = {+ render: () => (+ <Demo+ source={emptySource}+ debounceMs={0}+ emptySearchResultsText="No matching frameworks"+ />+ ),+ play: async ({canvasElement}) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.type(input, 'none');+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));+ },+};++export const CustomRenderer: Story = {+ render: () => (+ <Demo+ hasEntriesOnFocus+ renderItem={item => (+ <span {...stylex.props(styles.customItem)}>+ <span {...stylex.props(styles.customItemLabel)}>{item.label}</span>+ <span {...stylex.props(styles.customItemGroup)}>+ {(item.auxiliaryData as {group?: string} | undefined)?.group}+ </span>+ </span>+ )}+ />+ ),+ play: async ({canvasElement}) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.click(input);+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));+ },+};++export const DisabledStates: Story = {+ render: () => (+ <div {...stylex.props(styles.stage)}>+ <Demo label="Native disabled" isDisabled />+ <Demo label="Focusable disabled" isDisabled isFocusableDisabled />+ </div>+ ),+};++export const SizeVariants: Story = {+ render: () => (+ <div {...stylex.props(styles.stage)}>+ <Demo label="Small" size="sm" hasEntriesOnFocus />+ <Demo label="Medium" size="md" hasEntriesOnFocus />+ <Demo label="Large" size="lg" hasEntriesOnFocus />+ </div>+ ),+};++export const NarrowLongResult: Story = {+ render: () => (+ <Demo isNarrow hasEntriesOnFocus label="Framework in a narrow container" />+ ),+ play: async ({canvasElement}) => {+ const input = within(canvasElement).getByRole('combobox');+ await userEvent.click(input);+ await waitFor(() => expect(input).toHaveAttribute('aria-expanded', 'true'));+ await waitFor(() => {+ const listbox = document.querySelector<HTMLElement>('[role="listbox"]');+ if (listbox == null) {+ throw new Error('Expected the BaseTypeahead listbox to be open');+ }+ const box = listbox.getBoundingClientRect();+ expect(+ box.left >= 16 &&+ box.right <= window.innerWidth - 16 &&+ listbox.scrollWidth <= listbox.clientWidth,+ ).toBe(true);+ expect(+ Array.from(+ listbox.querySelectorAll<HTMLElement>('[role="option"]'),+ ).every(option => option.scrollWidth <= option.clientWidth),+ ).toBe(true);+ });+ },+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 09710c3041..980194dd84 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -3835,6 +3835,11 @@"path": "showcases/banner/statuses","aliases": []},+ {+ "name": "showcase-base-typeahead-custom-search-bar",+ "path": "showcases/base-typeahead/custom-search-bar",+ "aliases": []+ },{"name": "showcase-blockquote-default","path": "showcases/blockquote/default",diff --git a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjsindex 38a2e1d1be..4b23438b3a 100644--- a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs+++ b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.doc.mjs@@ -7,8 +7,9 @@ export const doc = {name: 'BaseTypeahead — Custom Search Bar',displayName: 'BaseTypeahead — Custom Search Bar',description:- 'BaseTypeahead embedded inside a custom-styled wrapper. The wrapper provides its own border and icon chrome; anchorRef positions the dropdown relative to it. Use this pattern when Typeahead\'s built-in field layout does not fit your composition.',+ "BaseTypeahead embedded inside a custom-styled wrapper. The wrapper provides its own border and icon chrome; anchorRef positions the dropdown relative to it. Use this pattern when Typeahead's built-in field layout does not fit your composition.",isReady: true,+ isShowcase: true,aspectRatio: 16 / 9,componentsUsed: ['BaseTypeahead', 'Icon', 'Layout', 'Text'],};diff --git a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsx b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsxindex 4412ea42ee..2096eac7e3 100644--- a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsx+++ b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadCustomSearch.tsx@@ -3,11 +3,19 @@'use client';import {useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';import {BaseTypeahead, createStaticSource} from '@astryxdesign/core/Typeahead';import type {SearchableItem} from '@astryxdesign/core/Typeahead';import {Icon} from '@astryxdesign/core/Icon';import {HStack, VStack} from '@astryxdesign/core/Layout';import {Text} from '@astryxdesign/core/Text';+import {+ borderVars,+ colorVars,+ focusVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';import {MagnifyingGlassIcon} from '@heroicons/react/24/outline';const frameworks: SearchableItem[] = [@@ -23,24 +31,42 @@ const frameworks: SearchableItem[] = [const source = createStaticSource(frameworks);+const styles = stylex.create({+ root: {+ width: '100%',+ maxWidth: 360,+ },+ field: {+ backgroundColor: colorVars['--color-background-surface'],+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-element'],+ borderStyle: 'solid',+ borderWidth: borderVars['--border-width'],+ paddingBlock: spacingVars['--spacing-1-5'],+ paddingInline: spacingVars['--spacing-2'],+ outlineColor: {+ default: 'transparent',+ ':has(input:focus-visible)': focusVars['--focus-outline-color'],+ },+ outlineOffset: focusVars['--focus-outline-offset'],+ outlineStyle: 'solid',+ outlineWidth: {+ default: '0',+ ':has(input:focus-visible)': focusVars['--focus-outline-width'],+ },+ },+});+export default function BaseTypeaheadCustomSearch() {const [value, setValue] = useState<SearchableItem | null>(null);- const wrapperRef = useRef<HTMLElement>(null);+ const wrapperRef = useRef<HTMLDivElement>(null);return (- <VStack gap={3} style={{width: 320}}>- <HStack- ref={wrapperRef}- gap={2}- vAlign="center"- style={{- border: '1px solid var(--color-border)',- borderRadius: 'var(--radius-control)',- padding: '6px 10px',- background: 'var(--color-surface)',- }}>+ <VStack gap={3} xstyle={styles.root}>+ <HStack ref={wrapperRef} gap={2} vAlign="center" xstyle={styles.field}><Icon icon={MagnifyingGlassIcon} size="sm" color="secondary" /><BaseTypeahead+ aria-label="Search frameworks"searchSource={source}value={value}onChange={setValue}diff --git a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.doc.mjs b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.doc.mjsnew file mode 100644index 0000000000..65791ce63d--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.doc.mjs@@ -0,0 +1,15 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */+export const doc = {+ type: 'block',+ exampleFor: 'BaseTypeahead',+ name: 'BaseTypeahead',+ displayName: 'Base Typeahead',+ description:+ 'A custom result renderer that adds supporting metadata while BaseTypeahead retains option semantics and keyboard behavior.',+ registry: {slug: 'custom-search-bar'},+ isReady: true,+ aspectRatio: 16 / 9,+ componentsUsed: ['BaseTypeahead', 'Layout', 'Text'],+};diff --git a/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.tsx b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.tsxnew file mode 100644index 0000000000..6a5efcbd8f--- /dev/null+++ b/packages/cli/assets/templates/blocks/components/BaseTypeahead/BaseTypeaheadShowcase.tsx@@ -0,0 +1,87 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++import {useRef, useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {BaseTypeahead, createStaticSource} from '@astryxdesign/core/Typeahead';+import type {SearchableItem} from '@astryxdesign/core/Typeahead';+import {VStack} from '@astryxdesign/core/Layout';+import {Text} from '@astryxdesign/core/Text';+import {+ borderVars,+ colorVars,+ focusVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const frameworks: SearchableItem[] = [+ {id: 'react', label: 'React', auxiliaryData: {category: 'UI library'}},+ {id: 'remix', label: 'Remix', auxiliaryData: {category: 'Web framework'}},+ {id: 'next', label: 'Next.js', auxiliaryData: {category: 'Web framework'}},+];++const source = createStaticSource(frameworks);++const styles = stylex.create({+ root: {+ width: '100%',+ maxWidth: 360,+ },+ field: {+ backgroundColor: colorVars['--color-background-surface'],+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-element'],+ borderStyle: 'solid',+ borderWidth: borderVars['--border-width'],+ paddingBlock: spacingVars['--spacing-1-5'],+ paddingInline: spacingVars['--spacing-2'],+ outlineColor: {+ default: 'transparent',+ ':has(input:focus-visible)': focusVars['--focus-outline-color'],+ },+ outlineOffset: focusVars['--focus-outline-offset'],+ outlineStyle: 'solid',+ outlineWidth: {+ default: '0',+ ':has(input:focus-visible)': focusVars['--focus-outline-width'],+ },+ },+ result: {+ minWidth: 0,+ },+});++export default function BaseTypeaheadCustomResults() {+ const [value, setValue] = useState<SearchableItem | null>(null);+ const wrapperRef = useRef<HTMLDivElement>(null);++ return (+ <VStack gap={3} xstyle={styles.root}>+ <div ref={wrapperRef} {...stylex.props(styles.field)}>+ <BaseTypeahead+ aria-label="Search frameworks"+ searchSource={source}+ value={value}+ onChange={setValue}+ anchorRef={wrapperRef}+ placeholder="Search frameworks…"+ hasEntriesOnFocus+ debounceMs={0}+ renderItem={item => (+ <VStack gap={0} xstyle={styles.result}>+ <Text type="label">{item.label}</Text>+ <Text type="supporting" color="secondary">+ {+ (item.auxiliaryData as {category?: string} | undefined)+ ?.category+ }+ </Text>+ </VStack>+ )}+ />+ </div>+ </VStack>+ );+}diff --git a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs b/packages/core/src/Typeahead/BaseTypeahead.doc.mjsindex db1e091ea4..f05df6b3bc 100644--- a/packages/core/src/Typeahead/BaseTypeahead.doc.mjs+++ b/packages/core/src/Typeahead/BaseTypeahead.doc.mjs@@ -1,5 +1,62 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @type {import('@astryxdesign/cli/authoring').ComponentAnatomyElement[]} */+const anatomy = [+ {+ name: 'Input',+ required: true,+ description:+ 'Bare combobox input. The caller supplies its visible field chrome and accessible name.',+ },+ {+ name: 'Loading status',+ required: false,+ description:+ 'Named Spinner shown beside the input while an asynchronous source is pending, unless a composed owner takes over the busy indicator lane.',+ },+ {+ name: 'Dropdown',+ required: false,+ description:+ 'Anchored listbox surface containing current search or bootstrap results.',+ },+ {+ name: 'Empty state',+ required: false,+ description:+ 'Disabled listbox option shown after a completed search returns no results.',+ },+ {+ name: 'Result group heading',+ required: false,+ description: 'Visible label for a group of result options.',+ },+ {+ name: 'Result row',+ required: false,+ description:+ 'Option wrapper that owns highlight, selection, pointer, and keyboard behavior.',+ },+ {+ name: 'Default item content',+ required: false,+ description:+ 'TypeaheadItem label and optional supporting content rendered inside a result row.',+ },+ {+ name: 'Caller-rendered item content',+ required: false,+ description:+ 'Caller content supplied through renderItem or item.element inside the stable result row.',+ },+ {+ name: 'Selected result state',+ required: false,+ description:+ 'Selected row weight and trailing check shown when a result matches value.',+ },+];+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */export const docs = {@@ -7,15 +64,43 @@ export const docs = {subComponentOf: 'Typeahead',displayName: 'Base Typeahead',isHiddenFromOverview: true,- description: 'Unstyled combobox engine providing input, search, keyboard navigation, and dropdown. No wrapper div, no border styling, no token rendering. Used by Typeahead and Tokenizer for custom compositions.',+ description:+ 'Composable combobox engine providing a bare input, search, keyboard navigation, and a styled result dropdown. It renders no input wrapper, border, or selected-value token. Typeahead and Tokenizer compose it for standard fields.',usage: {- description: 'Unstyled combobox engine providing input, search, keyboard navigation, and dropdown. No wrapper div, no border styling, no token rendering. Used by Typeahead and Tokenizer for custom compositions.',+ anatomy,+ description:+ 'Composable combobox engine providing a bare input, search, keyboard navigation, and a styled result dropdown. It renders no input wrapper, border, or selected-value token. Typeahead and Tokenizer compose it for standard fields.',bestPractices: [- { guidance: true, description: 'Use Typeahead or Tokenizer for standard fields; they wrap BaseTypeahead with the wrapper div, border styling, and token rendering it intentionally omits.' },- { guidance: true, description: 'Provide your own wrapper div with border and layout when composing directly, since BaseTypeahead renders no visual chrome of its own.' },- { guidance: true, description: 'Pass anchorRef pointing to your wrapper so the dropdown positions against your custom input chrome, not just the bare input element.' },- { guidance: false, description: 'Expect a wrapper div, border, or token rendering. BaseTypeahead is an engine only; all visual chrome is the caller\'s responsibility.' },- { guidance: false, description: 'Use BaseTypeahead when Typeahead or Tokenizer would suffice; the extra wrapper and styling work is only justified for truly custom compositions.' },+ {+ guidance: true,+ description:+ 'Use Typeahead or Tokenizer for standard fields; they wrap BaseTypeahead with input chrome and selected-value rendering it intentionally omits.',+ },+ {+ guidance: true,+ description:+ 'Provide your own visible label or aria-label and custom input wrapper so the bare combobox has an accessible name, focus treatment, border, and layout.',+ },+ {+ guidance: true,+ description:+ 'Pass anchorRef pointing to your wrapper so the dropdown positions against your custom input chrome, not just the bare input element.',+ },+ {+ guidance: false,+ description:+ 'Expect input chrome or selected-value rendering. BaseTypeahead is an engine; the caller owns those visible parts.',+ },+ {+ guidance: false,+ description:+ 'Use BaseTypeahead when Typeahead or Tokenizer would suffice; the extra wrapper and styling work is only justified for truly custom compositions.',+ },+ {+ guidance: false,+ description:+ 'Treat Escape as cancellation of pending source work. It hides the current popup, but a late response can reopen it.',+ },],},props: [@@ -46,7 +131,7 @@ export const docs = {name: 'placeholder',type: 'string',description: 'Input placeholder text.',- default: "'Search...'",+ default: "'Search…'",},{name: 'hasEntriesOnFocus',@@ -63,12 +148,14 @@ export const docs = {{name: 'menuWidth',type: 'number',- description: 'Fixed dropdown width in pixels. The menu never shrinks below its anchor width.',+ description:+ 'Requested dropdown width in pixels before viewport clamping.',},{name: 'minQueryLength',type: 'number',- description: 'Minimum query length before the search source is queried. Below it no search runs and the menu stays closed.',+ description:+ 'Minimum query length before the search source is queried. Below it no search runs and the menu stays closed.',default: '1',},{@@ -83,6 +170,13 @@ export const docs = {description: 'Whether the input is disabled.',default: 'false',},+ {+ name: 'isFocusableDisabled',+ type: 'boolean',+ description:+ 'Keep a disabled input focusable with aria-disabled and readOnly so a caller-owned disabled reason remains discoverable. It blocks text entry, but when applied after results are already open, Enter can still select the highlighted option.',+ default: 'false',+ },{name: 'hasAutoFocus',type: 'boolean',@@ -92,23 +186,44 @@ export const docs = {{name: 'debounceMs',type: 'number',- description: 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',+ description:+ 'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',default: '150',},+ {+ name: 'size',+ type: "'sm' | 'md' | 'lg'",+ description: 'Size used to scale dropdown option padding.',+ default: "'md'",+ },{name: 'anchorRef',type: 'RefObject<HTMLElement | null>',- description: 'Ref to the anchor element for dropdown positioning. If not provided, the input itself is used.',+ description:+ 'Ref to the anchor element for dropdown positioning. If not provided, the input itself is used.',},{name: 'inputXStyle',type: 'StyleXStyles',description: 'Additional StyleX styles for the input element.',},+ {+ name: 'xstyle',+ type: 'StyleXStyles',+ description:+ 'Standard BaseProps StyleX styles applied to the input. Must be a stylex.create() value, not an inline style object.',+ },+ {+ name: 'inputTabIndex',+ type: 'number',+ description:+ 'Legacy input-specific alias for native tabIndex. When provided, it takes precedence; otherwise native tabIndex is preserved.',+ },{name: 'onKeyDown',type: '(e: React.KeyboardEvent<HTMLInputElement>) => void',- description: 'Additional keydown handler called before internal keyboard navigation. Call e.preventDefault() to skip internal handling.',+ description:+ 'Additional keydown handler called before internal keyboard navigation. Call e.preventDefault() to skip internal handling.',},{name: 'onChangeQuery',@@ -123,12 +238,20 @@ export const docs = {{name: 'inputId',type: 'string',- description: 'ID for the input element (for label association).',+ description:+ 'Legacy input-specific alias for native id. When provided, it takes precedence; otherwise native id is preserved.',},{name: 'ariaDescribedBy',type: 'string',- description: 'Additional aria-describedby IDs.',+ description:+ 'Legacy input-specific alias for native aria-describedby. When provided, it takes precedence; otherwise the native attribute is preserved.',+ },+ {+ name: 'ariaLabelledBy',+ type: 'string',+ description:+ 'Legacy input-specific alias for native aria-labelledby. When provided, it takes precedence; otherwise the native attribute is preserved.',},],};@@ -137,7 +260,8 @@ export const docsZh = {name: 'BaseTypeahead',isHiddenFromOverview: true,displayName: 'Base Typeahead',- description: '无样式的组合框引擎,提供输入、搜索、键盘导航和下拉列表。无包装 div,无边框样式,无标记渲染。由 Typeahead 和 Tokenizer 用于自定义组合。',+ description:+ '可组合的组合框引擎,提供裸输入框、搜索、键盘导航和带样式的结果下拉列表。它不渲染输入框包装、边框或已选值标记;Typeahead 和 Tokenizer 将其组合成标准字段。',props: [{name: 'searchSource',@@ -166,7 +290,7 @@ export const docsZh = {name: 'placeholder',type: 'string',description: '输入框占位文本。',- default: "'Search...'",+ default: "'Search…'",},{name: 'hasEntriesOnFocus',@@ -183,12 +307,13 @@ export const docsZh = {{name: 'menuWidth',type: 'number',- description: '下拉菜单的固定像素宽度。菜单不会小于其锚点宽度。',+ description: '视口限制前请求的下拉菜单像素宽度。',},{name: 'minQueryLength',type: 'number',- description: '查询搜索源前的最小查询长度。低于该长度不会发起搜索,菜单保持关闭。',+ description:+ '查询搜索源前的最小查询长度。低于该长度不会发起搜索,菜单保持关闭。',default: '1',},{@@ -203,6 +328,13 @@ export const docsZh = {description: '输入框是否被禁用。',default: 'false',},+ {+ name: 'isFocusableDisabled',+ type: 'boolean',+ description:+ '使用 aria-disabled 和只读状态保持禁用输入框可聚焦,以便访问调用方提供的禁用原因。它会阻止文本输入,但如果结果已打开,按 Enter 仍可选择高亮选项。',+ default: 'false',+ },{name: 'hasAutoFocus',type: 'boolean',@@ -215,6 +347,12 @@ export const docsZh = {description: '触发搜索前的防抖延迟(毫秒)。同步数据源设置为 0。',default: '150',},+ {+ name: 'size',+ type: "'sm' | 'md' | 'lg'",+ description: '用于调整下拉选项内边距的尺寸。',+ default: "'md'",+ },{name: 'anchorRef',type: 'RefObject<HTMLElement | null>',@@ -225,10 +363,22 @@ export const docsZh = {type: 'StyleXStyles',description: '输入元素的附加 StyleX 样式。',},+ {+ name: 'xstyle',+ type: 'StyleXStyles',+ description: '应用于输入元素的标准 BaseProps StyleX 样式。',+ },+ {+ name: 'inputTabIndex',+ type: 'number',+ description:+ '原生 tabIndex 的旧输入专用别名。提供时优先;未提供时保留原生属性。',+ },{name: 'onKeyDown',type: '(e: React.KeyboardEvent<HTMLInputElement>) => void',- description: '在内部键盘导航之前调用的附加 keydown 处理函数。调用 e.preventDefault() 可跳过内部处理。',+ description:+ '在内部键盘导航之前调用的附加 keydown 处理函数。调用 e.preventDefault() 可跳过内部处理。',},{name: 'onChangeQuery',@@ -243,12 +393,20 @@ export const docsZh = {{name: 'inputId',type: 'string',- description: '输入元素的 ID(用于标签关联)。',+ description:+ '原生 id 的旧输入专用别名。提供时优先;未提供时保留原生属性。',},{name: 'ariaDescribedBy',type: 'string',- description: '附加的 aria-describedby ID。',+ description:+ '原生 aria-describedby 的旧输入专用别名。提供时优先;未提供时保留原生属性。',+ },+ {+ name: 'ariaLabelledBy',+ type: 'string',+ description:+ '原生 aria-labelledby 的旧输入专用别名。提供时优先;未提供时保留原生属性。',},],};@@ -257,14 +415,40 @@ export const docsDense = {name: 'BaseTypeahead',isHiddenFromOverview: true,displayName: 'Base Typeahead',- description: 'Unstyled combobox engine; input+search+keyboard nav+dropdown. No wrapper/border/token. Used by Typeahead+Tokenizer.',+ description:+ 'Composable combobox engine providing a bare input and a styled result dropdown. Callers own input chrome and selected-value presentation.',usage: {bestPractices: [- { guidance: true, description: 'Use Typeahead or Tokenizer for standard fields; they add the wrapper, border, and token rendering BaseTypeahead omits.' },- { guidance: true, description: 'Provide your own wrapper div with border and layout when composing directly; BaseTypeahead renders no chrome.' },- { guidance: true, description: 'Pass anchorRef to your wrapper so the dropdown positions against your input chrome, not the bare input.' },- { guidance: false, description: 'Expect wrapper, border, or token rendering. Engine only; chrome is the caller\'s job.' },- { guidance: false, description: 'Use BaseTypeahead when Typeahead or Tokenizer suffice; extra work only pays off for custom compositions.' },+ {+ guidance: true,+ description:+ 'Use Typeahead or Tokenizer for standard fields; they add the input chrome and selected-value rendering BaseTypeahead omits.',+ },+ {+ guidance: true,+ description:+ 'Provide a visible label or aria-label plus a custom wrapper with focus treatment, border, and layout.',+ },+ {+ guidance: true,+ description:+ 'Pass anchorRef to your wrapper so the dropdown positions against your input chrome, not the bare input.',+ },+ {+ guidance: false,+ description:+ 'Expect input chrome or selected-value rendering. The caller owns those visible parts.',+ },+ {+ guidance: false,+ description:+ 'Use BaseTypeahead when Typeahead or Tokenizer suffice; extra work only pays off for custom compositions.',+ },+ {+ guidance: false,+ description:+ 'Treat Escape as pending-work cancellation. It hides the popup, but a late response can reopen it.',+ },],},propDescriptions: {@@ -275,18 +459,30 @@ export const docsDense = {placeholder: 'Input placeholder.',hasEntriesOnFocus: 'Bootstrap results on focus.',maxMenuItems: 'Max dropdown items.',- menuWidth: 'Fixed dropdown width in pixels.',- minQueryLength: 'Min query length before searching. Menu stays closed below it.',+ menuWidth: 'Requested px width before viewport clamping.',+ minQueryLength:+ 'Min query length before searching. Menu stays closed below it.',emptySearchResultsText: 'Text when no results.',isDisabled: 'Whether input disabled.',+ isFocusableDisabled:+ 'Keeps disabled input focusable and blocks text entry; an already-open highlight can still be selected with Enter.',hasAutoFocus: 'Auto-focus on mount.',debounceMs: 'Search debounce ms. 0 for sync.',+ size: 'Dropdown option padding size.',anchorRef: 'Anchor for dropdown positioning. Defaults to input.',inputXStyle: 'Additional StyleX styles for input.',- onKeyDown: 'Keydown before internal nav. preventDefault() skips internal handling.',+ xstyle: 'Standard BaseProps StyleX styles for input.',+ inputTabIndex:+ 'Legacy tabIndex alias; defined alias wins, otherwise native tabIndex passes through.',+ onKeyDown:+ 'Keydown before internal nav. preventDefault() skips internal handling.',onChangeQuery: 'Fired on query text change.',onOpenChange: 'Fired on dropdown open/close.',- inputId: 'Input ID for label association.',- ariaDescribedBy: 'Additional aria-describedby IDs.',+ inputId:+ 'Legacy id alias; defined alias wins, otherwise native id passes through.',+ ariaDescribedBy:+ 'Legacy aria-describedby alias; defined alias wins, otherwise native attribute passes through.',+ ariaLabelledBy:+ 'Legacy aria-labelledby alias; defined alias wins, otherwise native attribute passes through.',},};diff --git a/packages/core/src/Typeahead/BaseTypeahead.spec.md b/packages/core/src/Typeahead/BaseTypeahead.spec.mdnew file mode 100644index 0000000000..ed40aa26e3--- /dev/null+++ b/packages/core/src/Typeahead/BaseTypeahead.spec.md@@ -0,0 +1,269 @@+---+schema_version: 3+template_version: 4+kind: component+id: component:BaseTypeahead+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, layout, theming, accessibility]+verified_by:+ [+ packages/core/src/Typeahead/BaseTypeahead.test.tsx,+ packages/core/src/Typeahead/Typeahead.test.tsx,+ packages/core/src/Tokenizer/Tokenizer.test.tsx,+ packages/core/src/theme/themingTargets.test.ts,+ scripts/check-knowledge.mjs,+ ]+modules: []+families: [family:overlay-dismissal]+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:component-theming-surface,+ architecture:layer-runtime,+ ]+contributing: []+system_specs: []+---++# BaseTypeahead component contract++## Intent++BaseTypeahead is the exported combobox engine beneath Typeahead and Tokenizer. It+renders a bare input, search and bootstrap behavior, keyboard navigation, a+styled result listbox, loading feedback, and selection callbacks. A direct caller+supplies the visible input wrapper, accessible name, and selected-value+presentation.++This draft records verified shipped or audit-remediated behavior. It does not+approve a new prop, default, compatibility promise, visual treatment, or+ownership boundary.++## Compatibility and migration++- Released default preserved: `yes`+- Compatibility class: patch corrections preserve the existing public surface+- Controlled/uncontrolled behavior: controlled `value` remains unchanged+- Migration decision: none; unresolved public-surface cleanup requires a+ separate compatibility decision++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- Query text, search/bootstrap scheduling, stale-response rejection, result+ ordering, highlight, and selection callbacks.+- Combobox, listbox, option, busy, selected, and empty-result semantics.+- The anchored result popup and current dropdown/empty-state visual treatment.+- Direct-caller loading feedback when a composed wrapper does not take over the+ busy indicator lane.++**Does not own / non-goals**++- The visible input wrapper, label presentation, field border, or focus ring.+- Selected-value or token presentation in Typeahead and Tokenizer.+- Caller-rendered result content.+- Spinner presentation, owned by `component:Spinner`.+- Shared top-layer hosting, positioning, and dismissal behavior, owned by+ `architecture:layer-runtime` and `family:overlay-dismissal`.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by state | Default | Owner | Stability | Invalid-value behavior |+| --------------- | ---------------------------------------- | ------------------------------------------------------------ | -------------------------- | -------------------------------- | ---------------------------- | --------- | ---------------------------------------------------------------------------------------- |+| selection | `T` or `null` | Caller-controlled selected result | all states | required | `component:BaseTypeahead` | released | caller retains control |+| search source | `search`, `bootstrap`, optional `cancel` | Supplies query and focus results | enabled input | required | `component:BaseTypeahead` | released | rejected work clears current results |+| focus bootstrap | on or off | Offers bootstrap results before query input | empty focused input | off | `component:BaseTypeahead` | released | off keeps the menu closed |+| query threshold | non-negative number | Minimum visible-character count before search | non-empty query | `1` | `component:BaseTypeahead` | released | below threshold cancels work and closes results |+| debounce | milliseconds | Delays query search | typed query | `150` | `component:BaseTypeahead` | released | non-positive runs immediately |+| result cap | number | Limits fetched results shown | completed search/bootstrap | `10` | `component:BaseTypeahead` | released | source order is preserved |+| result content | default, `renderItem`, or `item.element` | Chooses content inside the stable option row | result present | default TypeaheadItem | caller and component | released | `item.element` takes precedence |+| disabled state | native or focusable-disabled | Blocks query mutation; native disabled blocks all activation | disabled | native disabled | component and caller wrapper | released | an already-open focusable-disabled list can still select with Enter (retained violation) |+| popup width | intrinsic or fixed pixels | Sets result popup width before viewport clamping | popup present | intrinsic, at least anchor width | `component:BaseTypeahead` | released | viewport fit wins |+| size | `sm`, `md`, `lg` | Selects option-row padding | popup options | `md` | `component:BaseTypeahead` | released | TypeScript rejects other values |++## Behavioral and layout contract++Draft requirements identify their observational or current-authority basis.++| ID | Candidate invariant | Basis | Draft review state |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------- |+| FR1 | The input is controlled by internal query state while `value` is caller-controlled; selecting a result calls `onChange(item)`, clears query/results, closes the popup, and returns focus to the input. | Current source and tests | verified shipped behavior |+| FR2 | Search starts only at the grapheme-count threshold, uses the configured debounce, and never presents an empty result for a query that was not searched. | Public API, current i18n character utility, tests | verified audit remediation |+| FR3 | A newer query, selection, clear, or unmount invalidates stale asynchronous work. Escape hides the current popup but does not invalidate pending work, so a late response currently reopens it (retained violation). | Current source, focused retained-red probe, and tests | verified shipped behavior |+| FR4 | The popup is a named listbox whose result rows are options. A completed empty search renders one disabled option so the listbox retains a valid owned child. | APG combobox pattern, axe, tests | verified audit remediation |+| FR5 | Arrow keys wrap the highlight; Home/End move to the first/last option; Enter selects; Escape and Tab hide the current popup; IME-owned key events do not activate combobox commands. Escape dismissal is not durable while source work remains pending (FR3). | Current source and tests | verified shipped behavior; Escape gap retained |+| FR6 | Pending asynchronous source work sets `aria-busy` and renders one named Spinner unless the composed wrapper owns the busy indicator lane. | Current source, input-family FR7, tests | verified shipped behavior |+| FR7 | Supported BaseProps DOM, ARIA, data, class, style, event, and `xstyle` inputs reach the combobox input while component-owned role, state, value, and behavior remain authoritative. | `architecture:public-component-api/INV5–INV7`, tests | verified audit remediation |+| FR8 | The popup remains within the inline viewport at 320 CSS px, including long default results and a requested width larger than the available viewport. | WCAG 1.4.10, real Chromium | verified audit remediation |+| FR9 | Native disabled removes ordinary focus and activation. Focusable-disabled uses `aria-disabled` plus `readOnly` and blocks text/query mutation, but applying it after the popup opens does not currently block Enter selection (retained violation). | Current source, tests, and focused retained-red probe | verified shipped behavior |++### Allowed variation++- Search and bootstrap may complete synchronously or asynchronously.+- Results may be grouped or ungrouped and may use default or caller-rendered+ content.+- A direct caller may anchor the popup to the input or to its own wrapper.+- Typeahead and Tokenizer may own the visible wrapper and busy-indicator lane.++### Representative states++| State | Required invariant | Allowed variation |+| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |+| rest | named combobox is closed and not busy | caller-owned wrapper and label |+| focused bootstrap | popup opens only when enabled and results exist | synchronous or asynchronous source |+| query pending | combobox is busy and duplicate stale work is rejected | direct or wrapper-owned Spinner |+| results | one highlighted option and valid active descendant | grouped/default/custom content |+| completed empty | one disabled empty option; no active descendant | caller-supplied empty text |+| selected result | matching option exposes `aria-selected=true` | generic check presentation |+| disabled | native disabled blocks activation; focusable-disabled blocks query mutation but can still select an already-open highlight with Enter | native or focusable-disabled semantics |+| dismissed pending | Escape hides the popup; a late pending response currently reopens it | source completion timing |+| narrow viewport | popup and result content remain inside two viewport gutters | intrinsic or requested width |++### Transformation and precedence order++- **ORD1 — Result content.** `item.element` → caller `renderItem` →+ TypeaheadItem.+- **ORD2 — Input props.** Consumer rest props → defined legacy aliases (`inputId`,+ `ariaDescribedBy`, `ariaLabelledBy`, `inputTabIndex`) → component-owned+ semantics and handlers → component styles → consumer class/style escape+ hatches. An omitted legacy alias preserves its equivalent native BaseProp.++### Performance and resources++- **PR1 — Search lifetime.** One generation counter rejects stale responses;+ debounce timers and optional source cancellation are cleared on replacement and+ unmount.++## Accessibility contract++- **AR1 — Combobox pattern.** DOM focus stays on the input while+ `aria-activedescendant` identifies the highlighted option in the named listbox.+- **AR2 — Accessible name.** A direct caller supplies `aria-label` or a valid+ `aria-labelledby` relationship; composed owners supply their visible label ID.+- **AR3 — State.** Expanded, busy, disabled, active-descendant, and selected+ states are exposed programmatically.+- **AR4 — Result feedback.** Active queries announce the localized result count+ or empty-result message through the shared announcer.+- **AR5 — Input method.** IME composition commands remain with the candidate+ window; ordinary keyboard and pointer selection remain equivalent.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| -------------------- | ----------------------------------------------- | -------------------------------- | ----------------- | ------------------ |+| Input | caller-owned visible chrome and focus treatment | unsettled ownership for bare use | prominent | AR2 |+| Loading status | shared Spinner | `component:Spinner` | supporting | FR6 |+| Dropdown | Popover surface with bounded listbox | current source and layer runtime | prominent | FR4, FR8 |+| Highlighted result | overlay plus forced-color outline | objective accessibility standard | prominent | FR5 |+| Empty state | disabled option message | APG/axe | supporting | FR4 |+| Default item content | TypeaheadItem | `component:Typeahead` | prominent | ORD1 |+| Caller item content | caller-owned | caller | context-dependent | ORD1 |++### Theming anatomy++<!-- anatomy-theming:v1 -->++```json+{+ "Input": {+ "none": {+ "reason": "intentional: The direct caller owns the bare input chrome and styles it through supported input styling props."+ }+ },+ "Loading status": {+ "delegatesTo": {"owner": "component:Spinner", "target": "spinner"}+ },+ "Dropdown": {+ "delegatesTo": {+ "owner": "component:Typeahead",+ "target": "typeahead-dropdown"+ }+ },+ "Empty state": {+ "delegatesTo": {+ "owner": "component:Typeahead",+ "target": "typeahead-empty-state"+ }+ },+ "Result group heading": {+ "none": {+ "reason": "reachability-gap: No current public target reaches the visible group heading."+ }+ },+ "Result row": {+ "none": {+ "reason": "reachability-gap: The stable option row owns highlight and selection but has no current target."+ }+ },+ "Default item content": {+ "delegatesTo": {+ "owner": "component:Typeahead",+ "target": "typeahead-item"+ }+ },+ "Caller-rendered item content": {+ "none": {+ "reason": "intentional: Caller-rendered result content remains caller-owned."+ }+ },+ "Selected result state": {+ "none": {+ "reason": "reachability-gap: No current Typeahead target or state reaches the outer selected option."+ }+ }+}+```++## Family and system relationships++- `family:overlay-dismissal` owns Escape and platform-close ordering while the+ popup is present.+- `architecture:layer-runtime` owns top-layer hosting, anchoring, viewport+ positioning, and native light dismissal.+- `architecture:public-component-api` owns reachable exports and BaseProps+ passthrough semantics.+- `architecture:component-theming-surface` owns anatomy qualification and target+ disposition.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| --------------- | ------------------------------------------------------ | ------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------- |+| FR1–FR2 | BaseTypeahead and Typeahead tests | query, overlap, select, clear | current work replaces newer results or selection does not close | `audit:BaseTypeahead/behavior` |+| FR3 | shared stale-response tests plus retained-red probe | newer query, clear, unmount, Escape while pending | late work replaces current results or reopens after explicit dismissal | `audit:BaseTypeahead/a11y` |+| FR4, AR1–AR4 | focused tests, component-scoped axe, live-region tests | results, empty, busy, selected | invalid listbox ownership or state/announcement disappears | `audit:BaseTypeahead/a11y` |+| FR5, AR5 | keyboard, focus-out, IME, and retained-red tests | arrows, Home/End, Enter, Escape, Tab, composition | command selects or dismisses at the wrong time | `audit:BaseTypeahead/a11y` |+| FR6 | busy-lane tests | direct and composed pending source | duplicate/missing Spinner or stale busy state | `audit:BaseTypeahead/a11y` |+| FR7 | focused passthrough tests and strict lint | native-only, alias collisions, DOM/style/events | supported consumer input is dropped or owned semantics are replaced | `audit:BaseTypeahead/api` |+| FR8 | real-Chromium 320px sensor receipt | long result, wide request, LTR/RTL | popup or its content crosses either viewport gutter | `audit:BaseTypeahead/responsive` |+| FR9 | shared disabled tests plus retained-red probe | native disabled, focusable-disabled after open | disabled mode mutates query or accepts an already-open selection | `audit:BaseTypeahead/a11y` |+| Theming anatomy | knowledge and theming-target checks | all mapped parts | target inventory or disposition drifts | `audit:BaseTypeahead/theming` |++## Decision log++None. This draft records current or objectively remediated behavior and makes no+component-local API, design, compatibility, or ownership decision.++## Open questions++- **OQ1 — How should the released public props type remove package-internal+ composition knobs such as `__queryEntries`, `isFocusableDisabled`, and+ `inputTabIndex`?** (`human-api`)+- **OQ2 — Should `inputXStyle` be deprecated now that the inherited `xstyle`+ contract correctly reaches the same input?** (`human-api`)+- **OQ3 — Does bare BaseTypeahead own a default focus-visible ring, or must every+ direct caller provide the ring on its wrapper?** (`human-design`)++## Content boundary++This file does not duplicate the prop reference, examples, current audit score,+shared layer mechanics, or shared accessibility and theming rules.diff --git a/packages/core/src/Typeahead/BaseTypeahead.test.tsx b/packages/core/src/Typeahead/BaseTypeahead.test.tsxnew file mode 100644index 0000000000..0a094a1337--- /dev/null+++ b/packages/core/src/Typeahead/BaseTypeahead.test.tsx@@ -0,0 +1,200 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file BaseTypeahead.test.tsx+ * @input BaseTypeahead public props and a synchronous SearchSource+ * @output Focused contract tests for the public combobox engine+ * @position Colocated verification for BaseTypeahead+ */++import {afterAll, beforeAll, describe, expect, it, vi} from 'vitest';+import {fireEvent, render, screen, waitFor} from '@testing-library/react';+import * as stylex from '@stylexjs/stylex';+import {BaseTypeahead} from './BaseTypeahead';+import type {SearchSource, SearchableItem} from './types';++const popoverOpenState = new WeakMap<HTMLElement, boolean>();+const originalMatchesDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'matches',+);+const originalMatches = HTMLElement.prototype.matches;++beforeAll(() => {+ HTMLElement.prototype.showPopover = function () {+ popoverOpenState.set(this, true);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'open'});+ this.dispatchEvent(event);+ };+ HTMLElement.prototype.hidePopover = function () {+ popoverOpenState.set(this, false);+ const event = new Event('toggle');+ Object.defineProperty(event, 'newState', {value: 'closed'});+ this.dispatchEvent(event);+ };+ Object.defineProperty(HTMLElement.prototype, 'matches', {+ ...originalMatchesDescriptor,+ value(this: HTMLElement, selector: string) {+ if (selector === ':popover-open') {+ return popoverOpenState.get(this) ?? false;+ }+ return originalMatches.call(this, selector);+ },+ });+});++afterAll(() => {+ if (originalMatchesDescriptor) {+ Object.defineProperty(+ HTMLElement.prototype,+ 'matches',+ originalMatchesDescriptor,+ );+ }+});++const emptySource: SearchSource<SearchableItem> = {+ search: () => [],+ bootstrap: () => [],+};++const resultItem: SearchableItem = {id: '1', label: 'Result'};++const testStyles = stylex.create({+ input: {textTransform: 'uppercase'},+});++describe('BaseTypeahead', () => {+ it('forwards supported DOM, styling, and event props to the combobox input', () => {+ const onBlur = vi.fn();+ const onFocus = vi.fn();+ const onPointerDown = vi.fn();++ render(+ <BaseTypeahead+ searchSource={emptySource}+ value={null}+ onChange={() => {}}+ aria-label="Find a framework"+ aria-expanded="true"+ className="consumer-input"+ data-audit-state="forwarded"+ onBlur={onBlur}+ onFocus={onFocus}+ onPointerDown={onPointerDown}+ style={{letterSpacing: '0.08em'}}+ xstyle={testStyles.input}+ />,+ );++ const input = screen.getByRole('combobox', {name: 'Find a framework'});+ expect(input).toHaveAttribute('aria-expanded', 'false');+ expect(input).toHaveAttribute('data-audit-state', 'forwarded');+ expect(input).toHaveClass('consumer-input');+ expect(input).toHaveStyle({letterSpacing: '0.08em'});+ expect(getComputedStyle(input).textTransform).toBe('uppercase');++ fireEvent.pointerDown(input);+ fireEvent.focus(input);+ fireEvent.blur(input);+ expect(onPointerDown).toHaveBeenCalledOnce();+ expect(onFocus).toHaveBeenCalledOnce();+ expect(onBlur).toHaveBeenCalledOnce();+ });++ it('preserves native input attributes when legacy aliases are undefined', () => {+ render(+ <BaseTypeahead+ searchSource={emptySource}+ value={null}+ onChange={() => {}}+ id="native-input"+ aria-describedby="native-description"+ aria-labelledby="native-label"+ tabIndex={3}+ inputId={undefined}+ ariaDescribedBy={undefined}+ ariaLabelledBy={undefined}+ inputTabIndex={undefined}+ />,+ );++ const input = screen.getByRole('combobox');+ expect(input).toHaveAttribute('id', 'native-input');+ expect(input).toHaveAttribute('aria-describedby', 'native-description');+ expect(input).toHaveAttribute('aria-labelledby', 'native-label');+ expect(input).toHaveAttribute('tabindex', '3');+ });++ it('lets defined legacy aliases override their native equivalents', () => {+ render(+ <BaseTypeahead+ searchSource={emptySource}+ value={null}+ onChange={() => {}}+ id="native-input"+ aria-describedby="native-description"+ aria-labelledby="native-label"+ tabIndex={3}+ inputId="legacy-input"+ ariaDescribedBy="legacy-description"+ ariaLabelledBy="legacy-label"+ inputTabIndex={-1}+ />,+ );++ const input = screen.getByRole('combobox');+ expect(input).toHaveAttribute('id', 'legacy-input');+ expect(input).toHaveAttribute('aria-describedby', 'legacy-description');+ expect(input).toHaveAttribute('aria-labelledby', 'legacy-label');+ expect(input).toHaveAttribute('tabindex', '-1');+ });++ it('counts grapheme clusters when enforcing minQueryLength', async () => {+ const search = vi.fn(() => [resultItem]);+ render(+ <BaseTypeahead+ searchSource={{search, bootstrap: () => []}}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ minQueryLength={2}+ />,+ );++ const input = screen.getByRole('combobox');+ fireEvent.change(input, {target: {value: '😀'}});+ await Promise.resolve();+ expect(search).not.toHaveBeenCalled();+ expect(input).toHaveAttribute('aria-expanded', 'false');++ fireEvent.change(input, {target: {value: '😀a'}});+ await waitFor(() => expect(search).toHaveBeenCalledExactlyOnceWith('😀a'));+ });++ it('exposes a completed empty search as a disabled listbox option', async () => {+ render(+ <BaseTypeahead+ searchSource={emptySource}+ value={null}+ onChange={() => {}}+ debounceMs={0}+ emptySearchResultsText="No matching frameworks"+ />,+ );++ fireEvent.change(screen.getByRole('combobox'), {+ target: {value: 'none'},+ });++ await waitFor(() => {+ expect(+ screen.getByRole('option', {+ hidden: true,+ name: 'No matching frameworks',+ }),+ ).toHaveAttribute('aria-disabled', 'true');+ });+ });+});diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex b7099461d4..a9445ac3ca 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -38,6 +38,7 @@ import {TypeaheadItem} from './TypeaheadItem';import {Icon} from '../Icon';import {Spinner} from '../Spinner';import {+ borderVars,colorVars,spacingVars,radiusVars,@@ -45,7 +46,13 @@ import {fontWeightVars,typeScaleVars,} from '../theme/tokens.stylex';-import {getKey, groupItems, mergeProps} from '../utils';+import {+ characterCount,+ composeEventHandlers,+ getKey,+ groupItems,+ mergeProps,+} from '../utils';import type {BaseProps} from '../BaseProps';import type {SearchableItem, SearchSource} from './types';import {themeProps} from '../utils/themeProps';@@ -98,7 +105,7 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<*/maxMenuItems?: number;- /** Fixed dropdown width in pixels. Never shrinks below the anchor width. */+ /** Requested dropdown width in pixels before viewport clamping. */menuWidth?: number;/**@@ -107,8 +114,8 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<* for a result set that cannot be meaningful yet — and the user does not* see "no results" for a query that was never searched.*- * Measured with `String.length` (UTF-16 code units), like every other- * length check in the library.+ * Measured by grapheme cluster, so one visible character counts once even+ * when JavaScript represents it with multiple UTF-16 code units.** @default 1 — every non-empty query is searched.*/@@ -130,8 +137,10 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<* When disabled with a reason, keeps the input focusable via `aria-disabled`* (instead of the native `disabled` attribute) and `readOnly` so an* associated disabled-reason tooltip stays discoverable by keyboard and- * assistive technology. Value mutation is still blocked by the `isDisabled`- * guards. Consumers (Typeahead) own the tooltip and wrapper.+ * assistive technology. Query and text mutation are blocked, but an+ * already-open highlighted option can still be selected with Enter after a+ * transition into this state. Consumers (Typeahead) own the tooltip and+ * wrapper.* @default false*/isFocusableDisabled?: boolean;@@ -182,17 +191,20 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<debounceMs?: number;/**- * ID for the input element (for label association).+ * Legacy input-specific alias for the native `id` prop. When provided, this+ * alias takes precedence; otherwise the native prop is preserved.*/inputId?: string;/**- * Additional aria-describedby IDs.+ * Legacy input-specific alias for native `aria-describedby`. When provided,+ * this alias takes precedence; otherwise the native prop is preserved.*/ariaDescribedBy?: string;/**- * Additional aria-labelledby IDs.+ * Legacy input-specific alias for native `aria-labelledby`. When provided,+ * this alias takes precedence; otherwise the native prop is preserved.*/ariaLabelledBy?: string;@@ -202,12 +214,13 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<inputXStyle?: StyleXStyles;/**- * Tab-order override for the input element. Typeahead passes `-1` while- * its selected-value token is shown: the input is visually collapsed- * (width 0 / opacity 0) but must stay programmatically focusable for- * token edit/clear interactions, so removing it from the Tab order is- * what prevents an invisible tab stop (WCAG 2.4.3 / 2.4.7). The input- * remains focusable via `.focus()` regardless of this value.+ * Legacy input-specific alias for native `tabIndex`. When provided, this+ * alias takes precedence; otherwise the native prop is preserved. Typeahead+ * passes `-1` while its selected-value token is shown: the input is visually+ * collapsed (width 0 / opacity 0) but must stay programmatically focusable+ * for token edit/clear interactions, so removing it from the Tab order is+ * what prevents an invisible tab stop (WCAG 2.4.3 / 2.4.7). The input remains+ * focusable via `.focus()` regardless of this value.*/inputTabIndex?: number;@@ -236,6 +249,10 @@ export interface BaseTypeaheadProps<T extends SearchableItem> extends Omit<// Styles// =============================================================================+const TYPEAHEAD_VIEWPORT_GUTTER = spacingVars['--spacing-4'];+const TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE = `calc(100% - max(${TYPEAHEAD_VIEWPORT_GUTTER}, env(safe-area-inset-left, 0px), env(safe-area-inset-right, 0px)))`;+const TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK = `calc(100% - ${TYPEAHEAD_VIEWPORT_GUTTER})`;+const styles = stylex.create({input: {display: 'block',@@ -267,7 +284,12 @@ const styles = stylex.create({padding: spacingVars['--spacing-1'],},popover: {+ boxSizing: 'border-box',minWidth: 'anchor-size(width)',+ maxInlineSize: stylex.firstThatWorks(+ TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE,+ TYPEAHEAD_POSITION_AREA_MAX_INLINE_SIZE_FALLBACK,+ ),},popoverCustomWidth: (width: number) => ({width: `${width}px`,@@ -299,6 +321,18 @@ const styles = stylex.create({},itemHighlighted: {backgroundColor: colorVars['--color-overlay-hover'],+ outlineColor: {+ default: null,+ '@media (forced-colors: active)': 'Highlight',+ },+ outlineStyle: {+ default: null,+ '@media (forced-colors: active)': 'solid',+ },+ outlineWidth: {+ default: null,+ '@media (forced-colors: active)': borderVars['--border-width'],+ },},itemSelected: {fontWeight: fontWeightVars['--font-weight-medium'],@@ -307,6 +341,11 @@ const styles = stylex.create({display: 'flex',flex: 1,minWidth: 0,+ overflow: 'hidden',+ },+ defaultItem: {+ minWidth: 0,+ width: '100%',},emptyState: {padding: spacingVars['--spacing-3'],@@ -355,7 +394,8 @@ const itemSizeStyles = stylex.create({* untouched state, and `hasEntriesOnFocus` owns what happens there.*/function isBelowMinQueryLength(query: string, minQueryLength: number): boolean {- return query.length > 0 && query.length < minQueryLength;+ const length = characterCount(query);+ return length > 0 && length < minQueryLength;}// =============================================================================@@ -376,6 +416,7 @@ function isBelowMinQueryLength(query: string, minQueryLength: number): boolean {* searchSource={source}* value={selected}* onChange={setSelected}+ * aria-label="Search frameworks"* anchorRef={wrapperRef}* placeholder="Search..."* />@@ -407,7 +448,18 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({onKeyDown: externalOnKeyDown,debounceMs = 150,size = 'md',+ xstyle,+ className,+ style,+ onPointerDown: onPointerDownProp,+ onFocus: onFocusProp,+ onBlur: onBlurProp,+ id: nativeInputId,+ 'aria-describedby': nativeAriaDescribedBy,+ 'aria-labelledby': nativeAriaLabelledBy,+ tabIndex: nativeInputTabIndex,ref,+ ...rest}: BaseTypeaheadProps<T>) {const t = useTranslator();const placeholder =@@ -416,7 +468,12 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({emptySearchResultsTextFromProps ??t('@astryx.typeahead.emptySearchResults');const generatedId = useId();- const inputId = externalInputId ?? generatedId;+ // Keep the released input-specific aliases authoritative when a caller uses+ // them, but do not let an omitted alias erase the equivalent native BaseProp.+ const inputId = externalInputId ?? nativeInputId ?? generatedId;+ const inputAriaDescribedBy = ariaDescribedBy ?? nativeAriaDescribedBy;+ const inputAriaLabelledBy = ariaLabelledBy ?? nativeAriaLabelledBy;+ const resolvedInputTabIndex = inputTabIndex ?? nativeInputTabIndex;const listboxId = useId();const inputRef = useRef<HTMLInputElement>(null);@@ -943,6 +1000,7 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({return (<><input+ {...rest}ref={useMergedRefs(ref, inputRef, fallbackAnchorRef)}id={inputId}type="text"@@ -958,13 +1016,13 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({}aria-autocomplete="list"aria-busy={isLoading || undefined}- aria-describedby={ariaDescribedBy}- aria-labelledby={ariaLabelledBy}+ aria-describedby={inputAriaDescribedBy}+ aria-labelledby={inputAriaLabelledBy}aria-disabled={isFocusableDisabled ? 'true' : undefined}- tabIndex={inputTabIndex}+ tabIndex={resolvedInputTabIndex}value={query}onChange={handleInputChange}- onPointerDown={() => {+ onPointerDown={composeEventHandlers(() => {pointerActiveRef.current = true;document.addEventListener('click',@@ -973,23 +1031,29 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({},{once: true},);- }}- onFocus={handleFocus}- onBlur={handleBlur}+ }, onPointerDownProp)}+ onFocus={composeEventHandlers(handleFocus, onFocusProp)}+ onBlur={composeEventHandlers(handleBlur, onBlurProp)}onKeyDown={handleKeyDown}placeholder={placeholder}// When a disabled-reason tooltip is shown the input keeps focusability// via aria-disabled + readOnly instead of the native disabled- // attribute; value mutation stays blocked by the isDisabled guards.+ // attribute. Query and text mutation are blocked, but an already-open+ // highlighted option can still be selected with Enter after transition.disabled={isDisabled && !isFocusableDisabled}readOnly={isFocusableDisabled || undefined}autoFocus={hasAutoFocus}data-autofocus={hasAutoFocus || undefined}autoComplete="off"- {...stylex.props(- styles.input,- isDisabled && styles.inputDisabled,- inputXStyle,+ {...mergeProps(+ stylex.props(+ styles.input,+ isDisabled && styles.inputDisabled,+ inputXStyle,+ xstyle,+ ),+ className,+ style,)}/>{isLoading && busyLane == null && (@@ -1008,6 +1072,8 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({)}>{results.length === 0 && hasSearched ? (<div+ role="option"+ aria-disabled="true"{...mergeProps(themeProps('typeahead-empty-state'),stylex.props(styles.emptyState),@@ -1040,7 +1106,10 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({{renderItem ? (renderItem(item)) : (- <TypeaheadItem item={item} />+ <TypeaheadItem+ item={item}+ xstyle={styles.defaultItem}+ />)}</span>{isSelected && (