Skip to content

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

TypeScript

feat(core): Tokenizer touch sheet behind experimental.presentation (#7977)

Xinzi Zhou54fbccb27c01
diff --git a/.changeset/tokenizer-experimental-bottom-sheet.md b/.changeset/tokenizer-experimental-bottom-sheet.md
new file mode 100644
index 0000000000..21be220b8d
--- /dev/null
+++ b/.changeset/tokenizer-experimental-bottom-sheet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[experimental] Tokenizer gains a touch surface behind `experimental={{presentation: 'bottom-sheet' | 'adaptive'}}`. `bottom-sheet` replaces the inline combobox with a trigger that shows the selected tokens and opens one tall modal sheet: a search row on top, full-width checkbox rows that keep their place while the sheet is open and regroup selected-first on the next open, 50-row progressive rendering for long lists, a `Create "…"` row with a trailing Add action under `hasCreate`, and a footer with a confirmed Clear all and Done. `adaptive` uses the sheet on compact coarse-pointer screens and the popover otherwise, resolved the same way Selector resolves it. The sheet surface loads on demand, so a Tokenizer that does not opt in does not carry it. The trigger describes its selected tokens to assistive technology, announcements made while the sheet is open reach assistive technology through a live region inside the sheet, with `experimental` passed the component also accepts a `Ref<HTMLInputElement | HTMLButtonElement>` because `ref` reaches the trigger in the sheet presentation (the exported `TokenizerProps` interface is unchanged), and in development the field warns once about props that have no surface in the sheet presentation (`renderItem`, `renderToken`, `endContent`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`, `tokenOverflowBehavior`, `hasAutoFocus`). New `@astryx.tokenizer.*` catalog keys for the sheet's strings; the sheet's parts expose no theming targets while the option is experimental. Anything inside Tokenizer's `experimental` prop may change or be removed in a patch release; omitting it keeps the stable behavior.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsx
index d85226ab45..d4f1e8c239 100644
--- a/apps/storybook/stories/Tokenizer.stories.tsx
+++ b/apps/storybook/stories/Tokenizer.stories.tsx
@@ -798,3 +798,143 @@ export const CaretPlacement: Story = {
}
},
};
+// A long, searchable dataset for the sheet presentation: enough entries to
+// see the 50-row batches of progressive rendering.
+const sheetTags: SearchableItem[] = Array.from({length: 1000}, (_, index) => {
+ const number = index + 1;
+ return {
+ id: `tag-${number}`,
+ label:
+ number === 1
+ ? 'Design'
+ : number === 2
+ ? 'Eng'
+ : `Tag ${String(number).padStart(2, '0')}`,
+ };
+});
+
+const sheetTagSource: SearchSource = {
+ search: (query: string) =>
+ sheetTags.filter(tag =>
+ tag.label.toLowerCase().includes(query.toLowerCase()),
+ ),
+ bootstrap: () => sheetTags,
+};
+
+/**
+ * The experimental touch surface, forced on every device so it is reviewable
+ * on a laptop: `experimental.presentation="bottom-sheet"`. The trigger shows
+ * the selected tokens; tapping it opens one tall sheet with the search row on
+ * top, checkbox rows that keep their place while the sheet is open, a Create
+ * row for typed text, and a confirmed Clear all beside Done.
+ */
+export const ExperimentalBottomSheet: Story = {
+ render: args => {
+ const [value, setValue] = useState<SearchableItem[]>([
+ sheetTags[0],
+ sheetTags[1],
+ ]);
+ return (
+ <Tokenizer
+ {...args}
+ searchSource={sheetTagSource}
+ value={value}
+ onChange={items => setValue(items)}
+ hasCreate
+ maxMenuItems={1000}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ },
+ args: {
+ label: 'Tags',
+ placeholder: 'Add tags',
+ },
+ name: 'Experimental: bottom sheet',
+};
+
+/**
+ * `experimental.presentation="adaptive"`: the sheet on a compact
+ * coarse-pointer screen (narrow the viewport and emulate touch), otherwise the
+ * inline combobox — the same resolution Selector uses.
+ */
+export const ExperimentalAdaptive: Story = {
+ render: args => {
+ // Enough tokens to wrap the inline field's row on a phone, so the box
+ // the trigger keeps at the swap is the wrapped one (FR16, FR17).
+ const [value, setValue] = useState<SearchableItem[]>([
+ sheetTags[0],
+ sheetTags[1],
+ sheetTags[2],
+ sheetTags[3],
+ sheetTags[4],
+ ]);
+ return (
+ <Tokenizer
+ {...args}
+ searchSource={sheetTagSource}
+ value={value}
+ onChange={items => setValue(items)}
+ maxMenuItems={1000}
+ debounceMs={0}
+ experimental={{presentation: 'adaptive'}}
+ />
+ );
+ },
+ args: {
+ label: 'Tags',
+ placeholder: 'Add tags',
+ },
+ name: 'Experimental: adaptive',
+};
+
+/**
+ * Disabled and at-limit states of the sheet presentation: the disabled
+ * trigger stays focusable and does not open; at `maxEntries` the sheet's
+ * unchecked rows are inert while checked rows still toggle.
+ */
+export const ExperimentalBottomSheetStates: Story = {
+ render: args => {
+ const [value, setValue] = useState<SearchableItem[]>([
+ sheetTags[0],
+ sheetTags[1],
+ ]);
+ return (
+ <div style={{display: 'grid', gap: 16}}>
+ <Tokenizer
+ {...args}
+ label="Disabled"
+ searchSource={sheetTagSource}
+ value={[sheetTags[0], sheetTags[1]]}
+ onChange={() => {}}
+ isDisabled
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <Tokenizer
+ {...args}
+ label="Disabled and empty"
+ searchSource={sheetTagSource}
+ value={[]}
+ onChange={() => {}}
+ isDisabled
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <Tokenizer
+ {...args}
+ label="At the limit"
+ searchSource={sheetTagSource}
+ value={value}
+ onChange={items => setValue(items)}
+ maxEntries={2}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </div>
+ );
+ },
+ args: {
+ placeholder: 'Add tags',
+ },
+ name: 'Experimental: bottom sheet states',
+};
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index a3aa68558d..fe0d6d5437 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1599,6 +1599,58 @@
"defaultMessage": "Removed {label}",
"description": "Polite screen-reader announcement after a token is removed from a Tokenizer, by its × button or by Backspace. Live-region text, never shown on screen; `{label}` is the token's visible text."
},
+ "@astryx.tokenizer.search": {
+ "defaultMessage": "Search {label}",
+ "description": "Accessible name of the search field at the top of a Tokenizer's bottom sheet (the touch presentation). `{label}` is the field's own label, e.g. `Search Tags`. Not shown on screen."
+ },
+ "@astryx.tokenizer.searchPlaceholder": {
+ "defaultMessage": "Search…",
+ "description": "Placeholder inside the search field at the top of a Tokenizer's bottom sheet, shown while the query is empty. Single word plus ellipsis."
+ },
+ "@astryx.tokenizer.noResultsDescription": {
+ "defaultMessage": "Try a different search.",
+ "description": "Supporting sentence under the no-results empty-state title inside a Tokenizer's bottom sheet, suggesting the person change the query."
+ },
+ "@astryx.tokenizer.create": {
+ "defaultMessage": "Create \"{value}\"",
+ "description": "Label of the create row inside a Tokenizer's bottom sheet when `hasCreate` is set and the typed text matches no existing item. `{value}` is the typed text, e.g. `Create \"Marketing\"`."
+ },
+ "@astryx.tokenizer.add": {
+ "defaultMessage": "Add",
+ "description": "Visible label of the button at the end of the create row inside a Tokenizer's bottom sheet; pressing it adds the typed text as a new token. Imperative verb; short."
+ },
+ "@astryx.tokenizer.addValue": {
+ "defaultMessage": "Add {value}",
+ "description": "Screen-reader-only name of the create row's Add button inside a Tokenizer's bottom sheet. `{value}` is the typed text, e.g. `Add Marketing`."
+ },
+ "@astryx.tokenizer.done": {
+ "defaultMessage": "Done",
+ "description": "Label of the primary footer button inside a Tokenizer's bottom sheet; pressing it closes the sheet. Selections are already applied, so this is not a confirm."
+ },
+ "@astryx.tokenizer.clearAllTitle": {
+ "defaultMessage": "Clear all selected items?",
+ "description": "Title of the confirmation dialog shown when the person presses Clear all inside a Tokenizer's bottom sheet. A question."
+ },
+ "@astryx.tokenizer.clearAllDescription": {
+ "defaultMessage": "This removes all selected items from {label}.",
+ "description": "Body of the Clear all confirmation dialog inside a Tokenizer's bottom sheet. `{label}` is the field's own label, e.g. `This removes all selected items from Tags.`"
+ },
+ "@astryx.tokenizer.nothingToClear": {
+ "defaultMessage": "Nothing selected",
+ "description": "Tooltip on the disabled Clear all action in a Tokenizer's bottom sheet while no item is selected; keeps the action focusable and says why it does nothing."
+ },
+ "@astryx.tokenizer.allRemoved": {
+ "defaultMessage": "All items removed",
+ "description": "Polite screen-reader announcement after a confirmed Clear all in a Tokenizer's bottom sheet has removed every selected item. Live-region text, never shown on screen."
+ },
+ "@astryx.tokenizer.selectedCount": {
+ "defaultMessage": "{count, number} selected",
+ "description": "Screen-reader-only lead-in of the description on a Tokenizer's bottom-sheet trigger (the touch presentation), followed by the selected token labels. `{count}` is how many tokens are selected, e.g. `2 selected`. Not shown on screen."
+ },
+ "@astryx.tokenizer.clearSelection": {
+ "defaultMessage": "Clear selection",
+ "description": "Label of the destructive action button in the Clear all confirmation dialog inside a Tokenizer's bottom sheet. Imperative verb phrase; confirms removing every token."
+ },
"@astryx.lightbox.imagePosition": {
"defaultMessage": "Image {index, number} of {total, number}",
"description": "Polite screen-reader announcement when a Lightbox moves to a media item that has no alt text. Live-region text, never shown on screen; `{index}` is 1-based, example: `Image 3 of 12`."
diff --git a/packages/core/src/AlertDialog/AlertDialog.tsx b/packages/core/src/AlertDialog/AlertDialog.tsx
index 838e3b6fb1..9553b3bc91 100644
--- a/packages/core/src/AlertDialog/AlertDialog.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.tsx
@@ -30,7 +30,7 @@ import type {BaseProps} from '../BaseProps';
import {mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
-import {useMediaQuery} from '../hooks';
+import {useMediaQuery} from '../hooks/useMediaQuery';
const SMALL_SCREEN_QUERY = '(max-width: 640px)';
diff --git a/packages/core/src/BottomSheet/BottomSheet.tsx b/packages/core/src/BottomSheet/BottomSheet.tsx
index d7c2911a88..bffdec2657 100644
--- a/packages/core/src/BottomSheet/BottomSheet.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.tsx
@@ -97,7 +97,8 @@ import {
easeVars,
spacingVars,
} from '../theme/tokens.stylex';
-import {useDevWarning, useScrollLock} from '../hooks';
+import {useDevWarning} from '../hooks/useDevWarning';
+import {useScrollLock} from '../hooks/useScrollLock';
import {mergeProps} from '../utils';
import {LayerDepthProvider} from '../Layer/LayerDepthContext';
import {ModalAnnounceProvider} from '../hooks/ModalAnnounceProvider';
diff --git a/packages/core/src/BottomSheet/BottomSheetPanel.tsx b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
index 7af3b3273d..502210f2d1 100644
--- a/packages/core/src/BottomSheet/BottomSheetPanel.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetPanel.tsx
@@ -34,7 +34,8 @@ import {
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
-import {useDevWarning, useMediaQuery} from '../hooks';
+import {useDevWarning} from '../hooks/useDevWarning';
+import {useMediaQuery} from '../hooks/useMediaQuery';
import {useScrollableArea} from '../hooks/useScrollableArea';
import {
borderVars,
diff --git a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
index 83ae1ff1b2..0a1b5eea7d 100644
--- a/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
+++ b/packages/core/src/BottomSheet/BottomSheetSwitcher.tsx
@@ -90,7 +90,7 @@ import {
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '../BaseProps';
import type {DialogPurpose} from '../Dialog';
-import {useScrollLock} from '../hooks';
+import {useScrollLock} from '../hooks/useScrollLock';
import {useFocusTrapEscapeCompatibilitySignal} from '../hooks/useFocusTrap';
import {dispatchLayerEscapeKeyDown} from '../Layer/layerStack';
import {useLayerDismissal} from '../Layer/useLayerDismissal';
diff --git a/packages/core/src/Field/Field.tsx b/packages/core/src/Field/Field.tsx
index 420a8d259d..fe9790fbfa 100644
--- a/packages/core/src/Field/Field.tsx
+++ b/packages/core/src/Field/Field.tsx
@@ -29,7 +29,7 @@ import type {IconType} from '../Icon';
import {mergeProps} from '../utils';
import {useDevWarning} from '../hooks/useDevWarning';
import {FormLayoutContext} from '../FormLayout/FormLayoutContext';
-import {Text} from '../Text';
+import {Text} from '../Text/Text';
import {VisuallyHidden} from '../VisuallyHidden';
import {themeProps} from '../utils/themeProps';
diff --git a/packages/core/src/Field/FieldLabel.tsx b/packages/core/src/Field/FieldLabel.tsx
index b0ff1eb64a..6cac00136f 100644
--- a/packages/core/src/Field/FieldLabel.tsx
+++ b/packages/core/src/Field/FieldLabel.tsx
@@ -32,7 +32,7 @@ import {Icon, renderIconSlot, type IconType} from '../Icon';
import {Tooltip} from '../Tooltip';
import {useTranslator} from '../i18n';
import {themeProps} from '../utils/themeProps';
-import {useInputContainer} from '../hooks';
+import {useInputContainer} from '../hooks/useInputContainer';
import {FormLayoutContext} from '../FormLayout/FormLayoutContext';
const styles = stylex.create({
diff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsx
index db80f72646..caa4c9aa12 100644
--- a/packages/core/src/Field/PanelSearchInput.tsx
+++ b/packages/core/src/Field/PanelSearchInput.tsx
@@ -41,6 +41,7 @@
import {useCallback, useState, type Ref} from 'react';
import * as stylex from '@stylexjs/stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
import {Icon} from '../Icon';
import {InputClearButton} from './InputClearButton';
import {mergeProps} from '../utils';
@@ -177,6 +178,14 @@ export interface PanelSearchInputProps extends Omit<
* handler of its own.
*/
onContainerKeyDown?: React.KeyboardEventHandler<HTMLDivElement>;
+
+ /**
+ * Styles for the field box itself (the rounded row that draws the focus
+ * ring), as opposed to `xstyle`, which lands on the outer gutter. A panel
+ * whose rows are taller than a dropdown's — a touch sheet — uses it to grow
+ * the field to the same height as its rows.
+ */
+ fieldXstyle?: StyleXStyles;
}
/**
@@ -199,6 +208,7 @@ export function PanelSearchInput({
onFocus,
onBlur,
onContainerKeyDown,
+ fieldXstyle,
xstyle,
className,
style,
@@ -258,6 +268,7 @@ export function PanelSearchInput({
{...stylex.props(
styles.field,
isKeyboardFocus && styles.fieldKeyboardFocus,
+ fieldXstyle,
)}>
<Icon icon="search" size="sm" color="secondary" xstyle={styles.icon} />
<input
diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
index b393882d80..b2201899bb 100644
--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs
+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
@@ -289,6 +289,13 @@ export const docs = {
type: 'CSSProperties',
description: 'Inline styles for the visual control box.',
},
+ {
+ name: 'experimental',
+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",
+ stability: 'experimental',
+ description:
+ "Experimental options: anything in this object may change or be removed in a patch release, and omitting it keeps the stable behavior. presentation (default 'popover') chooses how the field presents its choices. popover is the inline combobox with its anchored suggestion menu. bottom-sheet replaces it with a trigger showing the selected tokens that opens one tall modal sheet: a search row on top, full-width checkbox rows that keep their place while the sheet is open, a Create row with hasCreate, and a footer with a confirmed Clear all and Done. adaptive uses the bottom sheet on compact touch screens and the popover otherwise, resolved the same way Selector resolves it. In the sheet presentation the trigger is the control (ref, id, aria-* and data-* reach it; with experimental passed, ref also accepts a Ref<HTMLInputElement | HTMLButtonElement> — an input-only ref still type-checks against that wider type, but with adaptive or bottom-sheet it receives the trigger button at runtime, so type the ref for both elements; the exported TokenizerProps interface is unchanged), and renderItem, renderToken, endContent, hasClear, hasEntriesOnFocus, menuWidth, tokenOverflowBehavior and hasAutoFocus have no surface to act on; the field warns once in development when they are passed. For example: <Tokenizer label=\"Tags\" searchSource={tagSource} value={tags} onChange={setTags} hasCreate experimental={{presentation: 'adaptive'}} />.",
+ },
],
theming: {
targets: [
@@ -628,6 +635,13 @@ export const docsZh = {
type: 'CSSProperties',
description: '可视控件框的内联样式。',
},
+ {
+ name: 'experimental',
+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",
+ stability: 'experimental',
+ description:
+ "实验性选项:此对象中的任何内容都可能在补丁版本中更改或移除;省略它即保持稳定行为。presentation(默认 'popover')决定字段如何呈现选项:popover 为内联组合框及其锚定建议菜单;bottom-sheet 改为一个显示已选标记的触发按钮,点按后打开一个高的模态底部面板——顶部为搜索行,下方为整行复选框行(面板打开期间位置保持不变),hasCreate 时有「创建」行,底部为需确认的「全部清除」和「完成」;adaptive 在紧凑触摸屏上使用底部面板,其他情况使用 popover,解析方式与 Selector 相同。在底部面板呈现中,触发按钮即为控件(ref、id、aria-* 和 data-* 都作用于它;传入 experimental 后,ref 也接受 Ref<HTMLInputElement | HTMLButtonElement>——仅为输入框类型的 ref 在这个更宽的类型下仍能通过类型检查,但在 adaptive 或 bottom-sheet 下运行时收到的是触发按钮,因此请为两种元素声明 ref 的类型;导出的 TokenizerProps 接口不变);renderItem、renderToken、endContent、hasClear、hasEntriesOnFocus、menuWidth、tokenOverflowBehavior 和 hasAutoFocus 没有作用对象,传入时开发模式下会警告一次。例如:<Tokenizer label=\"标签\" searchSource={tagSource} value={tags} onChange={setTags} hasCreate experimental={{presentation: 'adaptive'}} />。",
+ },
],
theming: {
targets: [
@@ -825,5 +839,7 @@ export const docsDense = {
'Icon at input start, before tokens. Icon name, SVG component, or ReactNode.',
endContent: 'Content at input row end. For buttons, counts, controls.',
handleRef: 'Imperative handle for focus() and blur() control.',
+ experimental:
+ "Experimental; may change in a patch. presentation: 'popover' (default, inline combobox) | 'bottom-sheet' (trigger + one searchable modal sheet of checkbox rows) | 'adaptive' (sheet on compact touch, else popover).",
},
};
diff --git a/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx b/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx
new file mode 100644
index 0000000000..5e7ca712b5
--- /dev/null
+++ b/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Tokenizer.props-type.test.tsx
+ * @input Uses vitest, TokenizerProps and Tokenizer
+ * @output Type-level proof that the exported `TokenizerProps` stays an
+ * interface callers can extend and `Omit` (its `ref` typed for the combobox
+ * input as released), and that only the experimental opt-in admits a `ref`
+ * that also accepts the sheet presentation's trigger button
+ * @position Core type tests; checked by `tsc`, with `@ts-expect-error`
+ * marking the shapes that must keep failing
+ */
+import {createRef, type ComponentProps} from 'react';
+import {describe, it, expect} from 'vitest';
+import type {SearchableItem} from '../Typeahead/types';
+import {Tokenizer, type TokenizerProps} from './Tokenizer';
+
+type Item = SearchableItem;
+const source = {search: () => [], bootstrap: () => []};
+
+// A consumer's props interface extends the exported one, as before.
+interface TagsFieldProps extends TokenizerProps<Item> {
+ helpUrl?: string;
+}
+
+// A wrapper narrows the exported props with Omit and spreads the rest.
+function TagsField({helpUrl, ...rest}: Omit<TagsFieldProps, 'label'>) {
+ void helpUrl;
+ return <Tokenizer label="Tags" {...rest} />;
+}
+
+// The component's declared props resolve to the stable interface, so the
+// same two consumer shapes work through ComponentProps.
+type FromComponent = ComponentProps<typeof Tokenizer>;
+interface FromComponentProps extends FromComponent {
+ helpUrl?: string;
+}
+function FromComponentField({
+ helpUrl,
+ ...rest
+}: Omit<FromComponentProps, 'label'>) {
+ void helpUrl;
+ return <Tokenizer label="Tags" {...rest} />;
+}
+// And it is exactly TokenizerProps, in both directions.
+const same: FromComponent extends TokenizerProps<Item>
+ ? TokenizerProps<Item> extends FromComponent
+ ? true
+ : never
+ : never = true;
+void same;
+
+const inputRef = createRef<HTMLInputElement>();
+const wideRef = createRef<HTMLInputElement | HTMLButtonElement>();
+
+export function compiles() {
+ return (
+ <>
+ <TagsField searchSource={source} value={[]} onChange={() => {}} />
+ <FromComponentField
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={inputRef}
+ />
+ <TagsField
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={inputRef}
+ experimental={{presentation: 'adaptive'}}
+ />
+ {/* The stable shape: ref is the combobox input's. */}
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={inputRef}
+ />
+ {/* The experimental opt-in admits the wider ref. */}
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={wideRef}
+ experimental={{presentation: 'adaptive'}}
+ />
+ {/* An input-typed ref is still fine with the opt-in. */}
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={inputRef}
+ experimental={{}}
+ />
+ {/* @ts-expect-error -- without experimental, ref keeps the released input-only type */}
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={wideRef}
+ />
+ </>
+ );
+}
+
+describe('Tokenizer props type', () => {
+ it('keeps TokenizerProps an interface that extends and Omit-wraps (type-checked above)', () => {
+ expect(typeof compiles).toBe('function');
+ });
+});
diff --git a/packages/core/src/Tokenizer/Tokenizer.spec.md b/packages/core/src/Tokenizer/Tokenizer.spec.md
index 4bad54c7e2..9a535ff763 100644
--- a/packages/core/src/Tokenizer/Tokenizer.spec.md
+++ b/packages/core/src/Tokenizer/Tokenizer.spec.md
@@ -13,6 +13,8 @@ review_triggers: [public-api, behavior, layout, accessibility]
verified_by:
[
packages/core/src/Tokenizer/Tokenizer.test.tsx,
+ packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx,
+ packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx,
packages/core/src/Typeahead/Typeahead.test.tsx,
packages/core/src/Layer/useLayer.test.tsx,
scripts/check-knowledge.mjs,
@@ -54,7 +56,7 @@ system_specs:
| Behavior | A committed empty-query bootstrap choice keeps remaining eligible loaded choices open, filters committed IDs, and advances the active option; terminal states close safely. The `bottom-sheet` presentation replaces the inline combobox with a trigger that opens one searchable modal sheet of checkbox rows (FR16–FR24). |
| End-user impact | People selecting several loaded values can continue without reopening the menu, while disabled, loading, exhausted, and dismissed states remain non-interactive. On a compact touch screen, an opted-in field offers thumb-sized rows and a search field the keyboard does not cover. |
| Builder impact | None for existing callers. A caller opts into the touch surface with `experimental={{presentation: 'adaptive'}}` or `'bottom-sheet'`, accepting that the option may change or be removed in a patch release. |
-| Compatibility/readiness | Omitting `experimental`, and the default `hasEntriesOnFocus={false}` path, keep today's inline combobox and direct single-select BaseTypeahead unchanged. DEC-2 is current and owner-approved with implementation and exact-head evidence pending; DEC-3 is current with the implementation gap recorded on its rows. |
+| Compatibility/readiness | Omitting `experimental`, and the default `hasEntriesOnFocus={false}` path, keep today's inline combobox and direct single-select BaseTypeahead unchanged. DEC-2 is current and owner-approved with implementation and exact-head evidence pending; DEC-3 is current and implemented. |
| Review checks | Reject implementations that filter by label instead of ID, reorder eligible choices, lose focus or a valid active descendant, refetch unnecessarily, or let disabled, exhausted, dismissed, or stale-loading states remain interactive or reopen. Reject a sheet presentation that switches without `experimental`, moves an existing row on toggle, or clears every token without confirmation. |
| Governing rules | This canonical `component:Tokenizer` record: [FR13–FR24](#behavioral-and-layout-contract), [AR5–AR6](#accessibility-contract), [DEC-2](#dec-2--focus-bootstrap-supports-consecutive-committed-selections), and [DEC-3](#dec-3--the-touch-sheet-presentation-is-an-experimental-option). |
@@ -74,9 +76,6 @@ exposing DOM refs, pointer coordinates, or width policy to consumers. The
dependent [PowerSearch draft](https://github.com/facebook/astryx/pull/5804)
remains evidence for the need, not authority for this record.
-Where the shipped Tokenizer does not yet meet a requirement, the row carries a
-present-tense implementation gap note.
-
## Compatibility and migration
- The stable public API and the default `hasEntriesOnFocus={false}` path are
@@ -167,8 +166,7 @@ X extends TokenizerProps<T>` and `Omit<TokenizerProps<T>, …>` wrappers keep
compiling; the component's own parameter type is where the widening lives:
with `experimental` passed, `ref` accepts `Ref<HTMLInputElement |
HTMLButtonElement>` and receives the trigger button in the sheet presentation
-and the combobox input otherwise. Implementation gap: `ref` is typed
-`Ref<HTMLInputElement>` whether or not `experimental` is passed. The
+and the combobox input otherwise. The
props that describe the inline combobox have no surface in the sheet
presentation: `renderItem`, `renderToken`, `endContent`, `hasClear` (the
sheet's own Clear all replaces it), `hasEntriesOnFocus` (the sheet always
@@ -191,32 +189,32 @@ pending. FR1–FR15 describe the `popover` presentation, the inline combobox;
FR16–FR24 describe the `experimental.presentation` option and its sheet
presentation, which has no inline combobox, suggestion menu, or end lane.
-| ID | Invariant | Basis | Status |
-| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1 | Tokenizer MUST keep one native combobox input mounted across token addition, removal, clear, ordinary wrapping, and maximum-entry states. Reaching `maxEntries` may make the input zero-width, transparent, and out of flow, but MUST NOT replace its identity. | Current source and tests | Verified current behavior |
-| FR2 | Tokenizer's suggestion menu MUST remain associated with the outer field/control surface. Existing `menuWidth` behavior remains an exact preferred pixel width plus the outer field's minimum width; it is not a maximum. | Current BaseTypeahead/Tokenizer source and docs | Verified current behavior; preserve |
-| FR3 | `unfocusedInline` MAY replace direct token layout with OverflowList while blurred. `unfocusedLayer` MAY keep the real wrapper/input mounted in a context layer while an ordinary-flow placeholder represents the collapsed field. | Current source, tests, and stories | Verified current behavior |
-| FR4 | Tokenizer MUST provide Core peers one package-internal descriptor with stable identities for its outer field/control surface and active opening control. Layer consumes the descriptor; public consumers cannot observe or configure it. | Approved package-internal contract; #5804 evidence; `spec:AST-002/DEC-1` | Current contract; implementation pending |
-| FR5 | Add/search opens MUST identify the stable inner input as the opening control before the result row disappears. Selection, query clearing, result removal, refocus, or later input collapse MUST NOT substitute the transient result row or a pointer coordinate. | Current selection order plus approved descriptor contract | Current contract; implementation pending |
-| FR6 | Edit opens MUST capture the actual activated token/control before state removes or replaces it. The Tokenizer-owned capture path MUST include custom `renderToken` output when activation originates from an identifiable descendant control; it MUST NOT require a new public ref contract. | Current owned wrapper plus approved capture contract | Current contract; implementation pending |
-| FR7 | A non-null element is usable only while connected, rendered, and geometrically meaningful for the open being prepared. A disconnected, stale, hidden-layer, zero-width, or otherwise unusable opening control MUST fall back safely to the outer field at logical start before show. | Current max/overflow states plus approved safety rule | Current contract; implementation pending |
-| FR8 | The descriptor MUST remain valid across focus movement, token add/remove/clear, wrapping, and `unfocusedLayer` reparenting. It MUST clear on unmount, perform no DOM work during SSR, and never retain an element beyond the open preparation that uses it. | Approved identity/lifetime contract | Current contract; implementation pending |
-| FR9 | A consuming surface MUST resolve its preferred width before choosing horizontal placement. A surface at least as wide as the outer field MUST use outer-field logical-start alignment. Only a surface narrower than the outer field may use opening-control geometry. | Approved conditional-placement contract | Current contract; implementation pending |
-| FR10 | For a narrower surface, Layer MUST compare the opening control with the outer field's physical start/end geometry, choose the nearer physical edge, map that result to logical start/end, and use logical start on a tie. Viewport collision runs last. | Approved Layer-consumer contract | Current contract; implementation pending |
-| FR11 | Opening placement MUST be modality-neutral and latched for one open lifetime. Pointer, keyboard, touch, and programmatic activation of the same control MUST produce the same preferred edge. Pointer movement, later focus movement, resize, or target collapse MUST NOT recompute it. | `architecture:interaction-modality` plus approved stability contract | Current contract; implementation pending |
-| FR12 | Placement state MUST commit while the surface is hidden, and Layer MUST show it on the next animation frame only after anchor, alignment, and width styles exist. A stale or invalid descriptor MUST never cause a visible wrong-position or first-frame flash. | Approved no-flash contract | Current contract; implementation pending |
-| FR13 | Tokenizer MUST exclude every choice whose `SearchableItem.id` is already present in its committed `value` from displayed bootstrap and search cohorts, including results that settle after the controlled value changes. A caller-rejected proposed value remains eligible because it was not committed. Distinct IDs remain eligible even when their labels match. | Approved Tokenizer multi-selection contract | Current contract; implementation and verification pending |
-| FR14 | With `hasEntriesOnFocus` enabled, committing a choice from the current settled empty-query bootstrap cohort MUST keep the input focused and the popup open when another eligible loaded choice remains. The active option advances to the next remaining choice in displayed order; when the committed choice was last, the nearest preceding choice becomes active. `aria-activedescendant` MUST reference that rendered option. | Approved rapid multi-select lifecycle | Current contract; implementation and verification pending |
-| FR15 | The retained popup MUST close and clear its active descendant when no eligible loaded choice remains, `maxEntries` is reached, the control becomes disabled, focus leaves, or the person dismisses it. Disabled Tokenizer remains non-interactive. Pending or stale source work MUST NOT reopen a terminal popup or expose stale choices; loading has no selectable placeholder and its busy state clears when work is cancelled or settles. | Approved terminal-state safety boundary | Current contract; implementation and verification pending |
-| FR16 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the inline combobox with its anchored suggestion menu, unchanged. `bottom-sheet` is the trigger and modal sheet of FR17–FR24 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the one touch-presentation rule `spec:AST-094/FR13` owns, as the selection controls do. `adaptive` renders on the server, and hydrates, as the inline field, because the resolver answers `popover` where there is no `matchMedia` and in the hydrating render; on a compact coarse-pointer client the field swaps to the trigger in the first render after hydration; nothing is focused before interaction, so focus is undisturbed (`document.activeElement` stays the body), except with `hasAutoFocus`, whose server-rendered `autofocus` focuses the inline input on load: then the swap moves that focus to the trigger — the same element and visit for the caller, so no `onBlur`/`onFocus` pair is reported. The trigger keeps the field's box — the same width, top, label, and `size` block size — except the inline input's own row: when the tokens leave the input no room on their row, the inline field wraps the input onto a row of its own, and the trigger, which has no input, drops that row (one `md` row, 27px, on a 390 and a 414px phone with five tokens); with room for the input beside the tokens, nothing shifts. A resolution change while the sheet is open takes effect after it closes and focus has returned to the trigger — the presentation hold `architecture:layer-runtime/INV14` assigns to the layer runtime; INV14 gap: the runtime does not yet provide one (its record names INV14 as ownership not yet met), so until it does the field keeps its own hold, to be replaced by the runtime's when it exists. Whenever the presentation changes while its control holds focus — then, or while the sheet is closed — focus moves to the new presentation's control, the combobox input or the trigger, so it never lands on the page body (`spec:AST-085/FR4`). | DEC-3; touch-flow evidence from the Lab prototype | Current contract. Implementation gap: the shipped Tokenizer has no `experimental` prop and renders the inline combobox on every device. |
-| FR17 | In the sheet presentation the control surface is one button, named by the field label, with `aria-haspopup="dialog"` and `aria-expanded`. It shows the selected tokens without remove controls, or the placeholder when empty, wraps tokens onto further lines, and keeps the inline field's block size for its `size` step. Activating it opens one tall modal BottomSheet named by the field label; the suggestion popover, inline input, and end lane do not render. While disabled the trigger stays focusable with `aria-disabled="true"`, does not open, and shows `disabledMessage` as the inline field does (`spec:AST-085/FR1`); a field that becomes disabled while its sheet is open closes the sheet and returns focus to the trigger (`spec:AST-085/FR2`). | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Current contract. Implementation gap: no trigger exists. |
-| FR18 | The sheet is a single surface: a search row at the top using the panel search field the selection controls share, a scrolling list of rows, and, while the query is empty, a footer with Clear all and Done. There is no second sheet. On open, focus moves to the sheet's panel, not the search field, so the reading order starts at the top of the sheet and the on-screen keyboard rises only when the person reaches for the search (WCAG 2.2 SC 2.4.3 Focus Order and 3.2.1 On Focus through `spec:AST-020/FR1`). Done closes the sheet; swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"`; each of those closes clears the query and reports it through `onChangeQuery`, so the next open lists the bootstrap set, while a close the field forces (becoming disabled, FR17) keeps the query, since nothing the person did changed it; focus returns to the trigger after the sheet closes. | DEC-3; Lab touch-flow evidence; `component:BottomSheet` | Current contract. Implementation gap: no sheet exists. |
-| FR19 | Each row is a `checkbox` named by the item label whose `aria-checked` mirrors membership in `value`. Activating an unchecked row commits an `add` change; a checked row commits a `remove` change; both apply immediately and are announced with the inline field's words through the sheet's own live region (AR6). Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then selected items absent from the results, then the results in source order; a toggle never moves an existing row. The next open takes a fresh snapshot. The query filters the selected rows by case-insensitive label substring. A row renders an item without its `action` and warns once in development that the sheet does not render it, as the inline panel does (`spec:AST-058/FR9`). | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no rows exist. |
-| FR20 | An empty query lists the source's bootstrap set, capped at `maxMenuItems` as the inline field caps its focus bootstrap (the prop keeps its meaning in the sheet), requested at once on open and on clearing the query, so an instant source shows no busy feedback and announces no busy start; a query shorter than `minQueryLength` is not searched: it lists only the selected rows it matches and, with `hasCreate`, the create row, with no busy feedback, no empty state, and no outcome announcement, as the inline field shows nothing for such a query; otherwise the source is searched `debounceMs` after the query change and the results are capped at `maxMenuItems`. `onChangeQuery` fires on every query change. From open, and from each query change, until that search settles, the list is pending: it shows named busy feedback above any rows still listed from the previous search, the list element carries the busy semantics (`aria-busy`), since the sheet has no combobox (`family:input-fields/FR7`, which places busy semantics on the list a presentation without a combobox updates), and no empty state shows; when the settled search removes the row that holds focus, focus moves to the search field (`spec:AST-085/FR4`). Once settled, the outcome is announced through the sheet's live region (AR6): the result count for a searched query, or the rendered text of the empty state when it shows (`spec:AST-056/FR3`). A source that rejects settles the search to no results, as the inline field does. With no rows and no create row, a searched query shows the `emptySearchText` empty state (its default message when omitted); an empty query shows no list, no message, and announces nothing — only the search field, above the footer — as the inline field opens no menu and reports nothing for a bootstrap set that is empty: nothing has failed, and typing is what finds items (a search-only source, `bootstrap: () => []`, is such a source). | DEC-3; Lab touch-flow evidence; `family:input-fields` | Current contract. Implementation gap: no sheet search exists. |
-| FR21 | Long lists render progressively: 50 rows at a time, the next batch when the list scrolls within 200px of its end, with the window reset to the first batch on open and on each query change. The rendered and total counts are exposed as `data-rendered-count` and `data-total-count` on the list, and the rows sit in a `list` whose `listitem` wrappers carry `aria-setsize` with the total and `aria-posinset` with the row's position — the `checkbox` role itself admits neither — so a person moving through the rows can learn that more exist before the list has scrolled; whether a screen reader speaks the position ("n of total") from the focused checkbox depends on the screen reader (`spec:AST-009/FR8`), and the accessibility tree proves the `list`, `listitem`, `aria-setsize`, and `aria-posinset` exposure; focus reaching the last rendered row renders the next batch (WCAG 2.2 SC 1.3.1 Info and Relationships and 4.1.2 Name, Role, Value through `spec:AST-020/FR1`). | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no list exists. |
-| FR22 | With `hasCreate`, a non-empty trimmed query that matches no selected id, no selected label, and no result label (case-insensitive) adds a create row above the list showing `Create "{text}"` with a trailing Add action named `Add {text}`. Activating it commits a `create` change whose item has the text as both id and label, clears the query, and moves focus to the sheet's search field, since the row it was on is gone. The create row is absent at `maxEntries`. | DEC-3; Lab touch-flow evidence; `hasCreate` contract of the inline field | Current contract. Implementation gap: no create row exists. |
-| FR23 | At `maxEntries`, unchecked rows carry `aria-disabled="true"`, stay focusable, and ignore activation; checked rows remain toggleable so the person can make room (`spec:AST-085/FR1`). | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Current contract. Implementation gap: no rows exist. |
-| FR24 | Clear all is disabled while `value` is empty: `aria-disabled`, still in the focus order, with a tooltip saying nothing is selected, and a click opens nothing (`spec:AST-085/FR1`). Otherwise it opens an AlertDialog confirmation naming the field; confirming commits `[]` with a `remove` change naming the last selected item, closes the confirmation, and — once the confirmation has closed — moves focus to the sheet's search field, the destination this record names (`spec:AST-085/FR4`): the clear is spent, and the search field is where the next selection starts (WCAG 2.2 SC 2.4.3 through `spec:AST-020/FR1`), and announces "All items removed" inside the sheet (AR6); cancelling changes nothing and focus returns to Clear all. | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no footer exists. |
+| ID | Invariant | Basis | Status |
+| ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------- |
+| FR1 | Tokenizer MUST keep one native combobox input mounted across token addition, removal, clear, ordinary wrapping, and maximum-entry states. Reaching `maxEntries` may make the input zero-width, transparent, and out of flow, but MUST NOT replace its identity. | Current source and tests | Verified current behavior |
+| FR2 | Tokenizer's suggestion menu MUST remain associated with the outer field/control surface. Existing `menuWidth` behavior remains an exact preferred pixel width plus the outer field's minimum width; it is not a maximum. | Current BaseTypeahead/Tokenizer source and docs | Verified current behavior; preserve |
+| FR3 | `unfocusedInline` MAY replace direct token layout with OverflowList while blurred. `unfocusedLayer` MAY keep the real wrapper/input mounted in a context layer while an ordinary-flow placeholder represents the collapsed field. | Current source, tests, and stories | Verified current behavior |
+| FR4 | Tokenizer MUST provide Core peers one package-internal descriptor with stable identities for its outer field/control surface and active opening control. Layer consumes the descriptor; public consumers cannot observe or configure it. | Approved package-internal contract; #5804 evidence; `spec:AST-002/DEC-1` | Current contract; implementation pending |
+| FR5 | Add/search opens MUST identify the stable inner input as the opening control before the result row disappears. Selection, query clearing, result removal, refocus, or later input collapse MUST NOT substitute the transient result row or a pointer coordinate. | Current selection order plus approved descriptor contract | Current contract; implementation pending |
+| FR6 | Edit opens MUST capture the actual activated token/control before state removes or replaces it. The Tokenizer-owned capture path MUST include custom `renderToken` output when activation originates from an identifiable descendant control; it MUST NOT require a new public ref contract. | Current owned wrapper plus approved capture contract | Current contract; implementation pending |
+| FR7 | A non-null element is usable only while connected, rendered, and geometrically meaningful for the open being prepared. A disconnected, stale, hidden-layer, zero-width, or otherwise unusable opening control MUST fall back safely to the outer field at logical start before show. | Current max/overflow states plus approved safety rule | Current contract; implementation pending |
+| FR8 | The descriptor MUST remain valid across focus movement, token add/remove/clear, wrapping, and `unfocusedLayer` reparenting. It MUST clear on unmount, perform no DOM work during SSR, and never retain an element beyond the open preparation that uses it. | Approved identity/lifetime contract | Current contract; implementation pending |
+| FR9 | A consuming surface MUST resolve its preferred width before choosing horizontal placement. A surface at least as wide as the outer field MUST use outer-field logical-start alignment. Only a surface narrower than the outer field may use opening-control geometry. | Approved conditional-placement contract | Current contract; implementation pending |
+| FR10 | For a narrower surface, Layer MUST compare the opening control with the outer field's physical start/end geometry, choose the nearer physical edge, map that result to logical start/end, and use logical start on a tie. Viewport collision runs last. | Approved Layer-consumer contract | Current contract; implementation pending |
+| FR11 | Opening placement MUST be modality-neutral and latched for one open lifetime. Pointer, keyboard, touch, and programmatic activation of the same control MUST produce the same preferred edge. Pointer movement, later focus movement, resize, or target collapse MUST NOT recompute it. | `architecture:interaction-modality` plus approved stability contract | Current contract; implementation pending |
+| FR12 | Placement state MUST commit while the surface is hidden, and Layer MUST show it on the next animation frame only after anchor, alignment, and width styles exist. A stale or invalid descriptor MUST never cause a visible wrong-position or first-frame flash. | Approved no-flash contract | Current contract; implementation pending |
+| FR13 | Tokenizer MUST exclude every choice whose `SearchableItem.id` is already present in its committed `value` from displayed bootstrap and search cohorts, including results that settle after the controlled value changes. A caller-rejected proposed value remains eligible because it was not committed. Distinct IDs remain eligible even when their labels match. | Approved Tokenizer multi-selection contract | Current contract; implementation and verification pending |
+| FR14 | With `hasEntriesOnFocus` enabled, committing a choice from the current settled empty-query bootstrap cohort MUST keep the input focused and the popup open when another eligible loaded choice remains. The active option advances to the next remaining choice in displayed order; when the committed choice was last, the nearest preceding choice becomes active. `aria-activedescendant` MUST reference that rendered option. | Approved rapid multi-select lifecycle | Current contract; implementation and verification pending |
+| FR15 | The retained popup MUST close and clear its active descendant when no eligible loaded choice remains, `maxEntries` is reached, the control becomes disabled, focus leaves, or the person dismisses it. Disabled Tokenizer remains non-interactive. Pending or stale source work MUST NOT reopen a terminal popup or expose stale choices; loading has no selectable placeholder and its busy state clears when work is cancelled or settles. | Approved terminal-state safety boundary | Current contract; implementation and verification pending |
+| FR16 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the inline combobox with its anchored suggestion menu, unchanged. `bottom-sheet` is the trigger and modal sheet of FR17–FR24 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the one touch-presentation rule `spec:AST-094/FR13` owns, as the selection controls do. `adaptive` renders on the server, and hydrates, as the inline field, because the resolver answers `popover` where there is no `matchMedia` and in the hydrating render; on a compact coarse-pointer client the field swaps to the trigger in the first render after hydration; nothing is focused before interaction, so focus is undisturbed (`document.activeElement` stays the body), except with `hasAutoFocus`, whose server-rendered `autofocus` focuses the inline input on load: then the swap moves that focus to the trigger — the same element and visit for the caller, so no `onBlur`/`onFocus` pair is reported. The trigger keeps the field's box — the same width, top, label, and `size` block size — except the inline input's own row: when the tokens leave the input no room on their row, the inline field wraps the input onto a row of its own, and the trigger, which has no input, drops that row (one `md` row, 27px, on a 390 and a 414px phone with five tokens); with room for the input beside the tokens, nothing shifts. A resolution change while the sheet is open takes effect after it closes and focus has returned to the trigger — the presentation hold `architecture:layer-runtime/INV14` assigns to the layer runtime; INV14 gap: the runtime does not yet provide one (its record names INV14 as ownership not yet met), so until it does the field keeps its own hold, to be replaced by the runtime's when it exists. Whenever the presentation changes while its control holds focus — then, or while the sheet is closed — focus moves to the new presentation's control, the combobox input or the trigger, so it never lands on the page body (`spec:AST-085/FR4`). | DEC-3; touch-flow evidence from the Lab prototype | Verified current behavior |
+| FR17 | In the sheet presentation the control surface is one button, named by the field label, with `aria-haspopup="dialog"` and `aria-expanded`. It shows the selected tokens without remove controls, or the placeholder when empty, wraps tokens onto further lines, and keeps the inline field's block size for its `size` step. Activating it opens one tall modal BottomSheet named by the field label; the suggestion popover, inline input, and end lane do not render. While disabled the trigger stays focusable with `aria-disabled="true"`, does not open, and shows `disabledMessage` as the inline field does (`spec:AST-085/FR1`); a field that becomes disabled while its sheet is open closes the sheet and returns focus to the trigger (`spec:AST-085/FR2`). | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Verified current behavior |
+| FR18 | The sheet is a single surface: a search row at the top using the panel search field the selection controls share, a scrolling list of rows, and, while the query is empty, a footer with Clear all and Done. There is no second sheet. On open, focus moves to the sheet's panel, not the search field, so the reading order starts at the top of the sheet and the on-screen keyboard rises only when the person reaches for the search (WCAG 2.2 SC 2.4.3 Focus Order and 3.2.1 On Focus through `spec:AST-020/FR1`). Done closes the sheet; swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"`; each of those closes clears the query and reports it through `onChangeQuery`, so the next open lists the bootstrap set, while a close the field forces (becoming disabled, FR17) keeps the query, since nothing the person did changed it; focus returns to the trigger after the sheet closes. | DEC-3; Lab touch-flow evidence; `component:BottomSheet` | Verified current behavior |
+| FR19 | Each row is a `checkbox` named by the item label whose `aria-checked` mirrors membership in `value`. Activating an unchecked row commits an `add` change; a checked row commits a `remove` change; both apply immediately and are announced with the inline field's words through the sheet's own live region (AR6). Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then selected items absent from the results, then the results in source order; a toggle never moves an existing row. The next open takes a fresh snapshot. The query filters the selected rows by case-insensitive label substring. A row renders an item without its `action` and warns once in development that the sheet does not render it, as the inline panel does (`spec:AST-058/FR9`). | DEC-3; Lab touch-flow evidence | Verified current behavior |
+| FR20 | An empty query lists the source's bootstrap set, capped at `maxMenuItems` as the inline field caps its focus bootstrap (the prop keeps its meaning in the sheet), requested at once on open and on clearing the query, so an instant source shows no busy feedback and announces no busy start; a query shorter than `minQueryLength` is not searched: it lists only the selected rows it matches and, with `hasCreate`, the create row, with no busy feedback, no empty state, and no outcome announcement, as the inline field shows nothing for such a query; otherwise the source is searched `debounceMs` after the query change and the results are capped at `maxMenuItems`. `onChangeQuery` fires on every query change. From open, and from each query change, until that search settles, the list is pending: it shows named busy feedback above any rows still listed from the previous search, the list element carries the busy semantics (`aria-busy`), since the sheet has no combobox (`family:input-fields/FR7`, which places busy semantics on the list a presentation without a combobox updates), and no empty state shows; when the settled search removes the row that holds focus, focus moves to the search field (`spec:AST-085/FR4`). Once settled, the outcome is announced through the sheet's live region (AR6): the result count for a searched query, or the rendered text of the empty state when it shows (`spec:AST-056/FR3`). A source that rejects settles the search to no results, as the inline field does. With no rows and no create row, a searched query shows the `emptySearchText` empty state (its default message when omitted); an empty query shows no list, no message, and announces nothing — only the search field, above the footer — as the inline field opens no menu and reports nothing for a bootstrap set that is empty: nothing has failed, and typing is what finds items (a search-only source, `bootstrap: () => []`, is such a source). | DEC-3; Lab touch-flow evidence; `family:input-fields` | Verified current behavior |
+| FR21 | Long lists render progressively: 50 rows at a time, the next batch when the list scrolls within 200px of its end, with the window reset to the first batch on open and on each query change. The rendered and total counts are exposed as `data-rendered-count` and `data-total-count` on the list, and the rows sit in a `list` whose `listitem` wrappers carry `aria-setsize` with the total and `aria-posinset` with the row's position — the `checkbox` role itself admits neither — so a person moving through the rows can learn that more exist before the list has scrolled; whether a screen reader speaks the position ("n of total") from the focused checkbox depends on the screen reader (`spec:AST-009/FR8`), and the accessibility tree proves the `list`, `listitem`, `aria-setsize`, and `aria-posinset` exposure; focus reaching the last rendered row renders the next batch (WCAG 2.2 SC 1.3.1 Info and Relationships and 4.1.2 Name, Role, Value through `spec:AST-020/FR1`). | DEC-3; Lab touch-flow evidence | Verified current behavior |
+| FR22 | With `hasCreate`, a non-empty trimmed query that matches no selected id, no selected label, and no result label (case-insensitive) adds a create row above the list showing `Create "{text}"` with a trailing Add action named `Add {text}`. Activating it commits a `create` change whose item has the text as both id and label, clears the query, and moves focus to the sheet's search field, since the row it was on is gone. The create row is absent at `maxEntries`. | DEC-3; Lab touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior |
+| FR23 | At `maxEntries`, unchecked rows carry `aria-disabled="true"`, stay focusable, and ignore activation; checked rows remain toggleable so the person can make room (`spec:AST-085/FR1`). | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Verified current behavior |
+| FR24 | Clear all is disabled while `value` is empty: `aria-disabled`, still in the focus order, with a tooltip saying nothing is selected, and a click opens nothing (`spec:AST-085/FR1`). Otherwise it opens an AlertDialog confirmation naming the field; confirming commits `[]` with a `remove` change naming the last selected item, closes the confirmation, and — once the confirmation has closed — moves focus to the sheet's search field, the destination this record names (`spec:AST-085/FR4`): the clear is spent, and the search field is where the next selection starts (WCAG 2.2 SC 2.4.3 through `spec:AST-020/FR1`), and announces "All items removed" inside the sheet (AR6); cancelling changes nothing and focus returns to Clear all. | DEC-3; Lab touch-flow evidence | Verified current behavior |
### Allowed variation
@@ -316,7 +314,7 @@ presentation, which has no inline combobox, suggestion menu, or end lane.
presentation does not load the sheet surface's code; the surface loads on
demand only while a field resolves to `bottom-sheet`, renders nothing on the
server or during the hydrating render, and renders its long lists in batches
- (FR21). Implementation gap: no sheet surface exists.
+ (FR21).
## Accessibility contract
@@ -375,7 +373,6 @@ presentation.
through `spec:AST-020/FR1`). After the sheet closes focus returns to the
trigger and the field's announcements follow the same FR14 route from
wherever the field renders.
- Implementation gap: no sheet exists.
## Design relationships
@@ -448,16 +445,16 @@ become Tokenizer policy.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| FR1–FR3 | Existing Tokenizer/BaseTypeahead unit tests plus source inspection | empty, tokens, remove, clear, max, wrapping, both overflow modes | Input remounts, suggestion menu changes anchor/width semantics, or overflow ownership is misstated. | `audit:Tokenizer/current` |
-| FR4–FR8 | Focused descriptor identity/capture tests when implemented | add, default/custom token edit, max, hidden layer, reparent, stale node, unmount, SSR | Descriptor leaks publicly, captures a transient result/pointer, misses custom controls, or uses unusable geometry. | `audit:Tokenizer/opening-anchor` |
-| FR9–FR12 | Layer unit tests and real-Chromium geometry checks when implemented | full/equal/narrow surface, start/end/tie, LTR/RTL, collision, stale fallback | Full-width follows inner input, tie is physical, collision runs early, or stale identity flashes. | `audit:Tokenizer/placement` |
-| FR13–FR15, AR5 | Focused Tokenizer/BaseTypeahead tests and exact-head Chromium interaction evidence | pointer/keyboard commit, first/middle/last choice, rejected/deferred control, loading, disabled, max, exhaustion, Escape, Tab, outside focus | Selected values remain available, order changes, focus leaves the combobox, active descendant names no option, stale work reopens, or a terminal state stays interactive. | `audit:Tokenizer/multi-select` |
-| PR1–PR5 | Instrumented reads, pending-frame cleanup tests, and first-frame Chromium capture | open, close before frame, reopen opposite side, resize while open | Render-time/repeated reads, observer/pointer tracking, uncancelled frame, or first-frame jump occurs. | `audit:Tokenizer/performance` |
-| AR1–AR5 | Existing interaction suites plus focused pointer/keyboard/browser checks; native-disabled assertions pending conformance (`spec:AST-085`) | add/edit, focus/refocus, overflow, disabled, dismissal, retained bootstrap selection | Modality changes placement, semantics/focus regress, active descendant becomes invalid, or visible placement is wrong before fallback. | `audit:Tokenizer/accessibility` |
-| FR16–FR24, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, plus real-engine touch evidence (implementation gap: not yet in the tree) | default popover, forced sheet, adaptive both ways, `adaptive` server-rendered as the combobox and hydrated without a recoverable error, then the trigger on a coarse-pointer client with the body still active, with `hasAutoFocus` the autofocused input's focus on the trigger after the swap and no `onBlur`/`onFocus` reported, the trigger's box against the hydrating field's at 390 and 414px, base props and ref on the trigger, the trigger's description in the inline input's order — a disabled trigger with `disabledMessage`, `description` and a status exposing the caller's ids, the description, the status message and the reason before the count and the tokens —, inert-prop warning, pending search, in-sheet announcements of toggles, busy start, result count and the rendered empty outcome, the confirmed Clear all announced once the confirmation has closed, a below-threshold query, a rejecting source, focus on the panel at open, the query cleared by a swipe, scrim, or Escape close, focus after a presentation change with the sheet closed, focus after the create row, focus after a confirmed Clear all, a spent Clear all focusable with `aria-disabled` and no action, focus after a settled search removes the focused row, no busy feedback or busy-start announcement on open with an instant source, only the search field — no list, no message, no announcement — for an empty query with nothing to list (a search-only source, nothing selected), and the list once a query finds items, element counts under a fine and a coarse pointer at rest and open (Chromium, Experimental stories: adaptive 154/120 at rest — the closed trigger in place of the inline field, a different element that stays under the fine count — and 157/165 open at the query "e" with no footer, the coarse total reconciled as rest − the re-hosted surfaces host + the dialog of 47 by part, forced sheet 114/114 and 165/165; the two owner exceptions DEC-3 records beyond the FR60 allowance, with before and after counts), no confirmation dialog in the DOM while none is pending, the query kept across a disabled-forced close, `aria-setsize`/`aria-posinset` on each row's `listitem` and the next batch on focus reaching the last rendered row, open/toggle/reopen order, create, batches, limit, Clear all, disabled while open, focus return | A field without `experimental` changes, a toggle moves a row, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |
-| Record structure | `scripts/check-knowledge.mjs` | Template-v3 current record and current-only frontmatter links | Invalid metadata, authority, or relationship references fail repository validation. | `audit:Tokenizer/knowledge` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| FR1–FR3 | Existing Tokenizer/BaseTypeahead unit tests plus source inspection | empty, tokens, remove, clear, max, wrapping, both overflow modes | Input remounts, suggestion menu changes anchor/width semantics, or overflow ownership is misstated. | `audit:Tokenizer/current` |
+| FR4–FR8 | Focused descriptor identity/capture tests when implemented | add, default/custom token edit, max, hidden layer, reparent, stale node, unmount, SSR | Descriptor leaks publicly, captures a transient result/pointer, misses custom controls, or uses unusable geometry. | `audit:Tokenizer/opening-anchor` |
+| FR9–FR12 | Layer unit tests and real-Chromium geometry checks when implemented | full/equal/narrow surface, start/end/tie, LTR/RTL, collision, stale fallback | Full-width follows inner input, tie is physical, collision runs early, or stale identity flashes. | `audit:Tokenizer/placement` |
+| FR13–FR15, AR5 | Focused Tokenizer/BaseTypeahead tests and exact-head Chromium interaction evidence | pointer/keyboard commit, first/middle/last choice, rejected/deferred control, loading, disabled, max, exhaustion, Escape, Tab, outside focus | Selected values remain available, order changes, focus leaves the combobox, active descendant names no option, stale work reopens, or a terminal state stays interactive. | `audit:Tokenizer/multi-select` |
+| PR1–PR5 | Instrumented reads, pending-frame cleanup tests, and first-frame Chromium capture | open, close before frame, reopen opposite side, resize while open | Render-time/repeated reads, observer/pointer tracking, uncancelled frame, or first-frame jump occurs. | `audit:Tokenizer/performance` |
+| AR1–AR5 | Existing interaction suites plus focused pointer/keyboard/browser checks; native-disabled assertions pending conformance (`spec:AST-085`) | add/edit, focus/refocus, overflow, disabled, dismissal, retained bootstrap selection | Modality changes placement, semantics/focus regress, active descendant becomes invalid, or visible placement is wrong before fallback. | `audit:Tokenizer/accessibility` |
+| FR16–FR24, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, plus real-engine touch evidence | default popover, forced sheet, adaptive both ways, `adaptive` server-rendered as the combobox and hydrated without a recoverable error, then the trigger on a coarse-pointer client with the body still active, with `hasAutoFocus` the autofocused input's focus on the trigger after the swap and no `onBlur`/`onFocus` reported, the trigger's box against the hydrating field's at 390 and 414px, base props and ref on the trigger, the trigger's description in the inline input's order — a disabled trigger with `disabledMessage`, `description` and a status exposing the caller's ids, the description, the status message and the reason before the count and the tokens —, inert-prop warning, pending search, in-sheet announcements of toggles, busy start, result count and the rendered empty outcome, the confirmed Clear all announced once the confirmation has closed, a below-threshold query, a rejecting source, focus on the panel at open, the query cleared by a swipe, scrim, or Escape close, focus after a presentation change with the sheet closed, focus after the create row, focus after a confirmed Clear all, a spent Clear all focusable with `aria-disabled` and no action, focus after a settled search removes the focused row, no busy feedback or busy-start announcement on open with an instant source, only the search field — no list, no message, no announcement — for an empty query with nothing to list (a search-only source, nothing selected), and the list once a query finds items, element counts under a fine and a coarse pointer at rest and open (Chromium, Experimental stories: adaptive 154/120 at rest — the closed trigger in place of the inline field, a different element that stays under the fine count — and 157/165 open at the query "e" with no footer, the coarse total reconciled as rest − the re-hosted surfaces host + the dialog of 47 by part, forced sheet 114/114 and 165/165; the two owner exceptions DEC-3 records beyond the FR60 allowance, with before and after counts), no confirmation dialog in the DOM while none is pending, the query kept across a disabled-forced close, `aria-setsize`/`aria-posinset` on each row's `listitem` and the next batch on focus reaching the last rendered row, open/toggle/reopen order, create, batches, limit, Clear all, disabled while open, focus return | A field without `experimental` changes, a toggle moves a row, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |
+| Record structure | `scripts/check-knowledge.mjs` | Template-v3 current record and current-only frontmatter links | Invalid metadata, authority, or relationship references fail repository validation. | `audit:Tokenizer/knowledge` |
## Decision log
diff --git a/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx b/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx
new file mode 100644
index 0000000000..8b85074fa0
--- /dev/null
+++ b/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx
@@ -0,0 +1,145 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file Tokenizer.ssr.test.tsx
+ * @input Uses vitest, react-dom/server, react-dom/client, Tokenizer
+ * @output Proof of component:Tokenizer FR16's server and hydration path for
+ * `adaptive`: the server renders the inline combobox, the client hydrates
+ * it without a recoverable error, a coarse-pointer client swaps to the
+ * trigger in the first post-hydration render, and focus is undisturbed
+ * @position Core Tokenizer tests
+ */
+import {act} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import type {SearchableItem, SearchSource} from '../Typeahead/types';
+
+const ITEMS: SearchableItem[] = [
+ {id: 'design', label: 'Design'},
+ {id: 'eng', label: 'Eng'},
+];
+const source: SearchSource<SearchableItem> = {
+ search: q =>
+ ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
+ bootstrap: () => ITEMS,
+};
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+function stubCoarsePointer(matches: boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: matches && query.includes('pointer: coarse'),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+async function serverRenderThenHydrate(
+ isCoarsePointer: boolean,
+ options: {
+ hasAutoFocus?: boolean;
+ onFocus?: () => void;
+ onBlur?: () => void;
+ } = {},
+) {
+ vi.resetModules();
+ const {Tokenizer} = await import('./Tokenizer');
+ const tree = (
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ hasAutoFocus={options.hasAutoFocus}
+ onFocus={options.onFocus}
+ onBlur={options.onBlur}
+ experimental={{presentation: 'adaptive'}}
+ />
+ );
+ // The server has no matchMedia: the resolver answers `popover`.
+ const html = renderToString(tree);
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ // The browser honours the server markup's `autofocus` on load, before any
+ // script runs; jsdom does not, so stand in for it.
+ if (options.hasAutoFocus) {
+ container.querySelector<HTMLElement>('[autofocus]')?.focus();
+ }
+
+ stubCoarsePointer(isCoarsePointer);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const recoverableErrors: unknown[] = [];
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, tree, {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+ const result = {
+ html,
+ recoverableErrors,
+ combobox: container.querySelector('[role="combobox"]'),
+ trigger: container.querySelector('button[aria-haspopup="dialog"]'),
+ activeElement: document.activeElement,
+ };
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+ return result;
+}
+
+describe('Tokenizer — SSR with experimental.presentation: adaptive (FR16)', () => {
+ it('server-renders the inline combobox, hydrates it without a recoverable error, and swaps to the trigger on a coarse-pointer client with focus undisturbed', async () => {
+ const result = await serverRenderThenHydrate(true);
+ // The server markup is the inline field: a combobox input, no trigger.
+ expect(result.html).toContain('role="combobox"');
+ expect(result.html).not.toContain('aria-haspopup="dialog"');
+ // Hydration matches that markup, then the first client render after it
+ // resolves `bottom-sheet` and renders the trigger in the field's place.
+ expect(result.recoverableErrors).toEqual([]);
+ expect(result.trigger).not.toBeNull();
+ expect(result.combobox).toBeNull();
+ // Nothing was focused before interaction, and the swap moves no focus.
+ expect(result.activeElement).toBe(document.body);
+ }, 30000);
+
+ it("with hasAutoFocus, moves the autofocused inline input's focus to the trigger at the swap, reporting no onBlur/onFocus pair", async () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ const result = await serverRenderThenHydrate(true, {
+ hasAutoFocus: true,
+ onFocus,
+ onBlur,
+ });
+ expect(result.html).toContain('autofocus=""');
+ expect(result.recoverableErrors).toEqual([]);
+ expect(result.trigger).not.toBeNull();
+ expect(result.combobox).toBeNull();
+ // The same element and visit: the trigger holds the focus the input had.
+ expect(result.activeElement).toBe(result.trigger);
+ expect(onBlur).not.toHaveBeenCalled();
+ expect(onFocus).not.toHaveBeenCalled();
+ }, 30000);
+
+ it('keeps the inline combobox after hydration on a fine-pointer client', async () => {
+ const result = await serverRenderThenHydrate(false);
+ expect(result.recoverableErrors).toEqual([]);
+ expect(result.combobox).not.toBeNull();
+ expect(result.trigger).toBeNull();
+ expect(result.activeElement).toBe(document.body);
+ }, 30000);
+});
diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsx
index 22465af668..082b132e72 100644
--- a/packages/core/src/Tokenizer/Tokenizer.tsx
+++ b/packages/core/src/Tokenizer/Tokenizer.tsx
@@ -4,24 +4,31 @@
/**
* @file Tokenizer.tsx
- * @input Uses React, BaseTypeahead, Field, Token, useAnnounce
+ * @input Uses React, BaseTypeahead, Field, Token, useAnnounce,
+ * useAdaptivePresentation, and TokenizerBottomSheet (lazy)
* @output Exports Tokenizer multi-select typeahead component
* @position Composed component; forwards DOM ref and exposes focus control via
- * handleRef
+ * handleRef. The experimental `presentation` option swaps the inline
+ * combobox for a trigger that opens TokenizerBottomSheet.
*
* SYNC: When modified, update:
* - /packages/core/src/Tokenizer/index.ts
+ * - /packages/core/src/Tokenizer/TokenizerBottomSheet.tsx (sheet presentation)
* - /apps/storybook/stories/Tokenizer.stories.tsx
* - /packages/cli/assets/templates/blocks/components/Tokenizer/ (showcase blocks)
*/
import React, {
+ lazy,
+ Suspense,
useCallback,
+ useEffect,
useId,
useImperativeHandle,
useMemo,
useRef,
useState,
+ type ComponentType,
type ReactNode,
type RefObject,
} from 'react';
@@ -39,6 +46,10 @@ import {
} from '../Field/fieldParts';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
+import {useAdaptivePresentation} from '../hooks/useAdaptivePresentation';
+import {useIsHydrating} from '../hooks/useIsHydrating';
+import {VisuallyHidden} from '../VisuallyHidden';
+import {warnOnce} from '../utils/devWarning';
import type {SizeValue} from '../utils/types';
import {BaseTypeahead} from '../Typeahead/BaseTypeahead';
import {useSize} from '../SizeContext/SizeContext';
@@ -67,9 +78,10 @@ import {
typeScaleVars,
} from '../theme/tokens.stylex';
import type {SearchableItem, SearchSource} from '../Typeahead/types';
-import {mergeProps} from '../utils';
+import {composeEventHandlers, mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+import type {TokenizerBottomSheetProps} from './TokenizerBottomSheet';
// Re-export status types for convenience
export type {
@@ -111,6 +123,36 @@ export interface TokenizerHandle {
blur(): void;
}
+/**
+ * Experimental options, outside the stable compatibility promise: anything in
+ * this object may change or be removed in a patch release.
+ * @experimental
+ */
+interface TokenizerExperimentalOptions {
+ /**
+ * How the field presents its choices.
+ * - `'popover'`: the inline combobox with its anchored suggestion menu —
+ * the stable behavior.
+ * - `'bottom-sheet'`: a trigger showing the selected tokens that opens one
+ * tall modal sheet: a search row on top, full-width checkbox rows that
+ * keep their place while the sheet is open, a create row with
+ * `hasCreate`, and a footer with a confirmed Clear all and Done. Suited
+ * to compact touch screens, where the inline combobox competes with the
+ * software keyboard.
+ * - `'adaptive'`: the bottom sheet on compact coarse-pointer screens,
+ * otherwise the popover — the same resolution Selector uses.
+ *
+ * In the sheet presentation the trigger is the control: `ref`, `id`,
+ * `aria-*`, and `data-*` reach it. `renderItem`, `renderToken`,
+ * `endContent`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`,
+ * `tokenOverflowBehavior`, and `hasAutoFocus` have no surface to act on
+ * and warn once in development.
+ * @experimental
+ * @default 'popover'
+ */
+ presentation?: 'popover' | 'bottom-sheet' | 'adaptive';
+}
+
export interface TokenizerProps<T extends SearchableItem> extends Omit<
FieldInputBaseProps<HTMLInputElement>,
'onChange' | 'onFocus' | 'onBlur' | 'onKeyDown'
@@ -262,8 +304,38 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<
ref?: React.Ref<HTMLInputElement>;
/** Imperative handle ref for focus/blur control. */
handleRef?: React.Ref<TokenizerHandle>;
+ /**
+ * Experimental options, outside the stable compatibility promise: anything
+ * in this object may change or be removed in a patch release. Omit it for
+ * the stable behavior.
+ * @experimental
+ */
+ experimental?: TokenizerExperimentalOptions;
}
+/**
+ * The props the experimental opt-in admits: `TokenizerProps` with
+ * `experimental` present and a `ref` that also accepts the sheet
+ * presentation's trigger button, the control it stands for there. Reached
+ * only through the overload below; `TokenizerProps` — an interface, so
+ * `interface X extends TokenizerProps<T>`, `Omit<TokenizerProps<T>, …>` and
+ * `ComponentProps<typeof Tokenizer>` keep their released shapes — stays the
+ * component's declared props type.
+ */
+type TokenizerExperimentalProps<T extends SearchableItem> = Omit<
+ TokenizerProps<T>,
+ 'ref' | 'experimental'
+> & {
+ /** @experimental */
+ experimental: TokenizerExperimentalOptions;
+ /**
+ * Ref forwarded to the control: the combobox input in the popover
+ * presentation, the trigger button in the sheet presentation.
+ * @experimental
+ */
+ ref?: React.Ref<HTMLInputElement | HTMLButtonElement>;
+};
+
// =============================================================================
// Styles
// =============================================================================
@@ -394,6 +466,55 @@ const styles = stylex.create({
color: colorVars['--color-text-secondary'],
paddingInline: spacingVars['--spacing-1'],
},
+ // The sheet presentation's trigger: the field's own control box, as a
+ // button. It wraps tokens like the inline field, but there is no input to
+ // type into, so the cursor says "press".
+ sheetTrigger: {
+ width: '100%',
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ color: 'inherit',
+ textAlign: 'start',
+ appearance: 'none',
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ },
+ // An aria-disabled button gets no system disabled paint in forced colors;
+ // GrayText is the platform's disabled affordance there. Defaults repeat the
+ // base values, since StyleX merges per property.
+ sheetTriggerDisabled: {
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ color: {
+ default: null,
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ sheetTriggerPlaceholder: {
+ color: colorVars['--color-text-secondary'],
+ // Match the input's text inset so the placeholder sits where the typed
+ // query would.
+ paddingInline: spacingVars['--spacing-1'],
+ },
+ sheetTriggerPlaceholderDisabled: {
+ color: {
+ default: colorVars['--color-text-secondary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ // A Token authors its own color, which forced colors replace with
+ // CanvasText; GrayText marks the tokens of a disabled trigger as disabled.
+ // The default repeats Token's own default color.
+ sheetTokenDisabled: {
+ color: {
+ default: colorVars['--color-text-primary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
});
const sizeStyles = stylex.create({
@@ -437,6 +558,46 @@ const layerPlaceholderSizeStyles = stylex.create({
// "Create: X" suggestions from real search results.
const CREATABLE_ID_PREFIX = '__xds_create__';
+// The touch sheet (BottomSheet, its gestures, the confirmation dialog, and
+// the empty state) only renders for the bottom-sheet presentation. Loading it
+// on demand keeps it out of pages whose tokenizers stay inline combobox fields
+// (`component:Tokenizer` PR6).
+// One import promise, shared by the preload and the lazy element: the sheet
+// presentation loads its chunk as soon as it is active, so the first press
+// does not wait for the network, while nothing of the sheet is rendered until
+// a press (`architecture:component-style-authoring` INV7).
+const loadTokenizerBottomSheet = async () => import('./TokenizerBottomSheet');
+const LazyTokenizerBottomSheet = lazy(async () =>
+ loadTokenizerBottomSheet().then(module => ({
+ default: module.TokenizerBottomSheet,
+ })),
+);
+
+/**
+ * Hosts the lazily loaded sheet. Renders nothing on the server or in the
+ * render that hydrates server HTML: a lazy component that has not loaded yet
+ * would leave server markup incomplete and abort hydration. The closed sheet
+ * has no visible markup, so it first renders right after hydration.
+ */
+function TokenizerSheetHost<T extends SearchableItem>(
+ props: TokenizerBottomSheetProps<T>,
+) {
+ const isHydrating = useIsHydrating();
+ if (isHydrating) {
+ return null;
+ }
+ // `lazy` erases the component's type parameter; the module exports the
+ // generic component this props type belongs to.
+ const Sheet = LazyTokenizerBottomSheet as unknown as ComponentType<
+ TokenizerBottomSheetProps<T>
+ >;
+ return (
+ <Suspense fallback={null}>
+ <Sheet {...props} />
+ </Suspense>
+ );
+}
+
/**
* Multi-select input with token chips and typeahead search.
*
@@ -540,6 +701,16 @@ function EndLane({
);
}
+// The experimental arm first: TypeScript resolves `ComponentProps<typeof
+// Tokenizer>` and a call without `experimental` against the last overload, the
+// stable signature, while a call that passes `experimental` matches this one
+// and may pass the wider `ref`.
+export function Tokenizer<T extends SearchableItem>(
+ props: TokenizerExperimentalProps<T>,
+): React.JSX.Element;
+export function Tokenizer<T extends SearchableItem>(
+ props: TokenizerProps<T>,
+): React.JSX.Element;
export function Tokenizer<T extends SearchableItem>({
label,
isLabelHidden = false,
@@ -585,15 +756,19 @@ export function Tokenizer<T extends SearchableItem>({
ref,
handleRef,
onKeyDown,
+ experimental,
id: idProp,
'aria-describedby': ariaDescribedByProp,
...restProps
-}: TokenizerProps<T>) {
+}: TokenizerProps<T> | TokenizerExperimentalProps<T>): React.JSX.Element {
const {rest, container} = useFieldInputStyling('Tokenizer', restProps, {
containerXstyle,
containerClassName,
containerStyle,
});
+ // A caller's onClick arrives through the base props; the sheet trigger
+ // composes it with its own open handler rather than letting either win.
+ const {onClick: callerOnClick, ...restWithoutClick} = rest;
const t = useTranslator();
const size = useSize(sizeProp, 'md');
const generatedInputId = useId();
@@ -603,6 +778,155 @@ export function Tokenizer<T extends SearchableItem>({
const inputRef = useRef<HTMLInputElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
+ // Experimental presentation (`component:Tokenizer` DEC-3). `adaptive`
+ // resolves through the policy the selection controls share; an open sheet
+ // keeps its presentation until it closes, so a resolution change mid-task
+ // cannot pull the surface out from under the person.
+ const presentation = experimental?.presentation ?? 'popover';
+ const resolvedPresentation = useAdaptivePresentation(presentation);
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ // Latched for the sheet's lifetime: a sheet stays presented after it closes
+ // until BottomSheet has run its exit and handed focus back to the trigger.
+ // Without the latch, `adaptive` resolving to `popover` mid-session (a phone
+ // turned to landscape) would unmount the sheet and the trigger it returns
+ // focus to in the same render, dropping focus to the page body
+ // (`component:Tokenizer` FR16).
+ const [isSheetPresented, setIsSheetPresented] = useState(false);
+ const isSheetPresentation =
+ isSheetOpen || isSheetPresented || resolvedPresentation === 'bottom-sheet';
+ // Preload the sheet's chunk while the sheet presentation is active, so the
+ // first press opens without waiting for the network; nothing renders.
+ useEffect(() => {
+ if (isSheetPresentation) {
+ void loadTokenizerBottomSheet();
+ }
+ }, [isSheetPresentation]);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ // The sheet's query between presentations: the sheet is in the DOM only
+ // from a press until its exit completes, and a close the field forces
+ // keeps the query (FR18). The ref follows every report; the press
+ // snapshots it into the state the next presentation starts from.
+ const sheetQueryRef = useRef('');
+ const [sheetInitialQuery, setSheetInitialQuery] = useState('');
+ const handleSheetQueryChange = useCallback(
+ (query: string) => {
+ sheetQueryRef.current = query;
+ onChangeQuery?.(query);
+ },
+ [onChangeQuery],
+ );
+ // Whether the field's control — the inline input or the trigger — holds
+ // focus. Kept in a ref by the focus and blur handlers of both, because a
+ // control unmounted while focused fires no blur: when a presentation swap
+ // removes the focused control (the latch releasing into the popover, or
+ // `adaptive` changing while the sheet is closed), the new presentation's
+ // control takes the focus over once it has mounted, so focus never lands on
+ // the page body (`component:Tokenizer` FR16, `spec:AST-085` FR4).
+ const isControlFocusedRef = useRef(false);
+ // Set around a focus move the field makes itself — a presentation swap
+ // handing focus from one control to the other — so the receiving control
+ // does not report it as focus entering from outside.
+ const isHandingOffFocusRef = useRef(false);
+ // Whether the caller has been told focus entered the field in this visit,
+ // so `onBlur` is never reported without its `onFocus`: in Safari a click
+ // or tap does not focus a button, so a pointer-opened sheet reports no
+ // entry, and the one focus the trigger then gets — BottomSheet's return
+ // focus — is the entry to report.
+ const hasReportedFocusRef = useRef(false);
+ // A control can hold focus without the field having seen a focus event:
+ // the inline input server-rendered with `autofocus` (`hasAutoFocus`) is
+ // focused before hydration, and the swap to the trigger in the first
+ // render after it removes that input. React detaches the old control
+ // before any effect of the swapping commit runs, so the live focus is
+ // read during that render, while the control is still in the document —
+ // a read of `document.activeElement` only, with no update made in render.
+ const previousPresentationRef = useRef(isSheetPresentation);
+ if (previousPresentationRef.current !== isSheetPresentation) {
+ previousPresentationRef.current = isSheetPresentation;
+ if (typeof document !== 'undefined') {
+ const active = document.activeElement;
+ if (
+ active != null &&
+ (active === inputRef.current || active === triggerRef.current)
+ ) {
+ isControlFocusedRef.current = true;
+ }
+ }
+ }
+ useEffect(() => {
+ if (!isControlFocusedRef.current) {
+ return;
+ }
+ const active = document.activeElement;
+ if (active != null && active !== document.body) {
+ return;
+ }
+ isHandingOffFocusRef.current = true;
+ (isSheetPresentation ? triggerRef.current : inputRef.current)?.focus();
+ isHandingOffFocusRef.current = false;
+ }, [isSheetPresentation]);
+ // The trigger's accessible description names the selected tokens: the
+ // button's children are tokens whose own content assistive technology
+ // leaves out of a button's name (`spec:AST-020` FR1).
+ const triggerTokensId = useId();
+ // Each rendered token's id, for the trigger's description; the item id is
+ // an arbitrary string, so it is encoded rather than used as is.
+ const tokenElementId = (itemId: string) =>
+ `${triggerTokensId}-${encodeURIComponent(itemId)}`;
+ // Props that describe the inline combobox have no surface in the sheet
+ // presentation. Say so once in development rather than dropping them
+ // silently (`architecture:public-component-api` INV3).
+ const inertSheetProps = isSheetPresentation
+ ? (
+ [
+ ['renderItem', renderItem],
+ ['renderToken', renderToken],
+ ['endContent', endContent],
+ ['hasClear', hasClear || undefined],
+ ['hasEntriesOnFocus', hasEntriesOnFocus || undefined],
+ ['menuWidth', menuWidth],
+ ['tokenOverflowBehavior', tokenOverflowBehavior],
+ ['hasAutoFocus', hasAutoFocus || undefined],
+ ] as const
+ )
+ .filter(([, v]) => v !== undefined && v !== 'none')
+ .map(([name]) => name)
+ : [];
+ const inertSheetPropsKey = inertSheetProps.join(',');
+ useEffect(() => {
+ if (inertSheetPropsKey === '') {
+ return;
+ }
+ warnOnce(
+ `tokenizer:sheet-inert:${inertSheetPropsKey}`,
+ 'Tokenizer',
+ `\`${inertSheetProps.join('`, `')}\` ${
+ inertSheetProps.length === 1 ? 'has' : 'have'
+ } no surface in the bottom-sheet presentation and ${
+ inertSheetProps.length === 1 ? 'is' : 'are'
+ } not rendered there.`,
+ );
+ // eslint-disable-next-line @eslint-react/exhaustive-deps -- keyed by the joined names
+ }, [inertSheetPropsKey]);
+ // A field that becomes disabled cannot keep its sheet open, and must not
+ // reopen it when re-enabled (`component:Tokenizer` FR17). Adjusted in the
+ // render that sees the change, not an effect, so no frame shows both.
+ const [wasDisabled, setWasDisabled] = useState(isDisabled);
+ // A sheet that was open when the field became disabled stays mounted,
+ // closed, so it runs its exit and hands focus back to the trigger; a field
+ // that is disabled from the start mounts no sheet.
+ const [keepsSheetWhileDisabled, setKeepsSheetWhileDisabled] = useState(false);
+ if (isDisabled !== wasDisabled) {
+ setWasDisabled(isDisabled);
+ if (isDisabled && isSheetOpen) {
+ setIsSheetOpen(false);
+ setKeepsSheetWhileDisabled(true);
+ }
+ if (!isDisabled) {
+ setKeepsSheetWhileDisabled(false);
+ }
+ }
+
// Disabled-reason tooltip. The tooltip listeners attach to the input wrapper
// and the typeahead input stays perceivable via aria-disabled instead of the
// disabled attribute. Input is blocked by the isDisabled guards in
@@ -616,12 +940,20 @@ export function Tokenizer<T extends SearchableItem>({
isEnabled: showsDisabledMessage,
});
+ // The sheet presentation has no input; the public ref reaches the trigger,
+ // the control it stands for (`family:input-fields` FR10).
+ const triggerMergedRef = useMergedRefs<HTMLButtonElement>(
+ triggerRef,
+ ref as React.Ref<HTMLButtonElement> | undefined,
+ disabledMessageTooltip.ref,
+ );
+
useImperativeHandle(handleRef, () => ({
focus() {
- inputRef.current?.focus();
+ (isSheetPresentation ? triggerRef : inputRef).current?.focus();
},
blur() {
- inputRef.current?.blur();
+ (isSheetPresentation ? triggerRef : inputRef).current?.blur();
},
}));
@@ -694,7 +1026,11 @@ export function Tokenizer<T extends SearchableItem>({
layer.show();
}
if (comingFromOutside) {
- onFocus?.(e);
+ isControlFocusedRef.current = true;
+ if (!isHandingOffFocusRef.current) {
+ hasReportedFocusRef.current = true;
+ onFocus?.(e);
+ }
// Redirect to the input so the user doesn't have to tab through
// every token remove button.
if (e.target !== inputRef.current) {
@@ -708,6 +1044,8 @@ export function Tokenizer<T extends SearchableItem>({
const handleBlurCapture = useCallback(
(e: React.FocusEvent) => {
if (!isFocusInTokenizer(e.relatedTarget)) {
+ isControlFocusedRef.current = false;
+ hasReportedFocusRef.current = false;
setIsFocusedWithin(false);
onBlur?.(e);
if (isLayerMode) {
@@ -794,20 +1132,22 @@ export function Tokenizer<T extends SearchableItem>({
[],
);
- // Announce token add/remove politely via the persistent live region.
- // Tokens previously appeared and disappeared silently — Backspace on an
- // empty input removes the trailing token, and the per-token remove buttons
- // gave no audible feedback either.
+ // Announce token add/remove politely via a persistent live region.
+ // Announce token add/remove politely. `useAnnounce` follows where this
+ // call is made (`spec:AST-086` FR14): the inline field's words go to the
+ // shared channel, or into the modal that encloses the field. The sheet's
+ // own changes are announced from inside the sheet, where FR14 routes them
+ // into the sheet's dialog; the handlers below stay silent for those.
const announce = useAnnounce();
// Handle adding an item — detect creatable synthetic items
const handleAdd = useCallback(
- (item: T | null) => {
+ (item: T | null, options?: {silent?: boolean}): boolean => {
if (isDisabled || !item) {
- return;
+ return false;
}
if (isAtMax) {
- return;
+ return false;
}
// Detect "Create: X" synthetic items from the creatable source
@@ -824,22 +1164,27 @@ export function Tokenizer<T extends SearchableItem>({
selectedIds.has(createdValue) ||
selectedLabels.has(createdValue.toLowerCase())
) {
- return;
+ return false;
}
const base = {id: createdValue, label: createdValue};
const realItem = base as T;
const newItems = [...value, realItem];
onChange(newItems, {item: realItem, type: 'create'});
- announce(t('@astryx.tokenizer.tokenAdded', {label: createdValue}));
- return;
+ if (!options?.silent) {
+ announce(t('@astryx.tokenizer.tokenAdded', {label: createdValue}));
+ }
+ return true;
}
if (selectedIds.has(item.id)) {
- return;
+ return false;
}
const newItems = [...value, item];
onChange(newItems, {item, type: 'add'});
- announce(t('@astryx.tokenizer.tokenAdded', {label: item.label}));
+ if (!options?.silent) {
+ announce(t('@astryx.tokenizer.tokenAdded', {label: item.label}));
+ }
+ return true;
},
[
value,
@@ -858,14 +1203,17 @@ export function Tokenizer<T extends SearchableItem>({
// input and the per-token remove buttons route through here, so the
// announcement covers both.
const handleRemove = useCallback(
- (item: T) => {
+ (item: T, options?: {silent?: boolean}): boolean => {
if (isDisabled) {
- return;
+ return false;
}
const newItems = value.filter(v => v.id !== item.id);
onChange(newItems, {item, type: 'remove'});
- announce(t('@astryx.tokenizer.tokenRemoved', {label: item.label}));
+ if (!options?.silent) {
+ announce(t('@astryx.tokenizer.tokenRemoved', {label: item.label}));
+ }
inputRef.current?.focus();
+ return true;
},
[value, onChange, isDisabled, announce, t],
);
@@ -1026,7 +1374,12 @@ export function Tokenizer<T extends SearchableItem>({
<TrailingKeyDownContext value={onKeyDown}>
<BaseTypeahead
{...rest}
- ref={useMergedRefs(inputRef, ref)}
+ ref={useMergedRefs(
+ inputRef,
+ // With `experimental`, the ref type admits the trigger too; in
+ // this presentation it receives the input.
+ ref as React.Ref<HTMLInputElement> | undefined,
+ )}
searchSource={isAtMax ? emptySource : filteredSource}
value={null}
onChange={handleAdd}
@@ -1099,7 +1452,191 @@ export function Tokenizer<T extends SearchableItem>({
);
let tokenizerContent: ReactNode;
- if (isLayerMode) {
+ if (isSheetPresentation) {
+ tokenizerContent = (
+ <>
+ <button
+ // The field-level pass-through props (`data-*`, `aria-*`) were typed
+ // for the inline input; here the control is a button.
+ {...(restWithoutClick as React.ButtonHTMLAttributes<HTMLButtonElement>)}
+ ref={triggerMergedRef}
+ type="button"
+ id={inputId}
+ aria-haspopup="dialog"
+ aria-expanded={isSheetOpen}
+ aria-disabled={isDisabled || undefined}
+ // The description is what the inline input's is, in its order —
+ // the caller's ids, the field description, the status message, the
+ // disabled reason (`spec:AST-085` FR5: a disabled control exposes
+ // its description and reason on itself) — then the hidden count and
+ // the rendered tokens themselves, each by id: the
+ // accessible-description algorithm reads the referenced elements in
+ // order and separates them, so every label renders once
+ // (`architecture:component-style-authoring` INV7) and no locale's
+ // list punctuation is written here (AR6).
+ aria-describedby={
+ [
+ ariaDescribedByProp,
+ ariaDescribedBy,
+ value.length > 0 ? triggerTokensId : null,
+ ...value.map(item => tokenElementId(item.id)),
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined
+ }
+ // The open runs first and the caller's onClick after it, as the
+ // inline input composes its click: a caller observes the click but
+ // cannot cancel the field's own handling
+ // (`family:input-fields` FR10).
+ onClick={composeEventHandlers<React.MouseEvent<HTMLButtonElement>>(
+ () => {
+ if (isDisabled) {
+ return;
+ }
+ setIsSheetPresented(true);
+ setSheetInitialQuery(sheetQueryRef.current);
+ setIsSheetOpen(true);
+ },
+ // Typed for the input by the base props; here the control is the
+ // trigger button, and the handler only reads the event.
+ callerOnClick as unknown as
+ React.MouseEventHandler<HTMLButtonElement> | undefined,
+ )}
+ onFocus={event => {
+ isControlFocusedRef.current = true;
+ // BottomSheet focuses the trigger only after its exit completes;
+ // that focus is the signal that the retained sheet can leave. If
+ // the resolution moved to the popover meanwhile, the inline input
+ // takes the focus over once it mounts. The field's own sheet is
+ // part of the field: focus coming back from it, or handed over by
+ // a presentation swap, is not focus entering from outside, so the
+ // caller's onFocus — "when focus enters the tokenizer from
+ // outside" — stays quiet for it (`family:input-fields` FR10).
+ const isReturningFromSheet = !isSheetOpen && isSheetPresented;
+ if (isReturningFromSheet) {
+ setIsSheetPresented(false);
+ }
+ const isInsideTheField =
+ (isReturningFromSheet && hasReportedFocusRef.current) ||
+ isHandingOffFocusRef.current;
+ if (!isInsideTheField) {
+ hasReportedFocusRef.current = true;
+ onFocus?.(event);
+ }
+ }}
+ onBlur={event => {
+ // Focus moving into the sheet is still the field's: the flag
+ // stays, and the caller's onBlur — "when focus leaves the
+ // tokenizer entirely" — stays quiet. Only a blur to somewhere
+ // else reports.
+ if (isSheetOpen) {
+ return;
+ }
+ isControlFocusedRef.current = false;
+ hasReportedFocusRef.current = false;
+ onBlur?.(event);
+ }}
+ onKeyDown={onKeyDown}
+ {...mergeProps(
+ themeProps('tokenizer', {
+ size,
+ status: status?.type,
+ disabled: isDisabled ? 'disabled' : null,
+ }),
+ stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ styles.sheetTrigger,
+ // The trigger keeps the inline field's height for its size step,
+ // as Selector's bottom-sheet trigger does; the sheet's own rows
+ // and search field carry the touch-sized targets.
+ sizeStyles[size],
+ value.length > 0 && styles.wrapperWithTokens,
+ isDisabled && inputWrapperStyles.disabled,
+ isDisabled && styles.sheetTriggerDisabled,
+ status && inputStatusBorderStyles[status.type],
+ status &&
+ !isDisabled &&
+ inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ controlXstyle,
+ ),
+ controlClassName,
+ controlStyle,
+ )}>
+ {startIcon && (
+ <span
+ {...stylex.props(value.length > 0 && styles.startIconWithTokens)}>
+ {renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
+ </span>
+ )}
+ {value.length > 0 ? (
+ value.map(item => (
+ <Token
+ key={item.id}
+ id={tokenElementId(item.id)}
+ label={item.label}
+ size={size}
+ isDisabled={isDisabled}
+ xstyle={isDisabled ? styles.sheetTokenDisabled : undefined}
+ />
+ ))
+ ) : (
+ <span
+ {...stylex.props(
+ styles.sheetTriggerPlaceholder,
+ isDisabled && styles.sheetTriggerPlaceholderDisabled,
+ )}>
+ {placeholder ?? ''}
+ </span>
+ )}
+ </button>
+ {value.length > 0 && (
+ <VisuallyHidden id={triggerTokensId}>
+ {t('@astryx.tokenizer.selectedCount', {count: value.length})}
+ </VisuallyHidden>
+ )}
+ {/* Form carriers, gated exactly as the inline branch gates its own: a
+ disabled field submits nothing. */}
+ {htmlName != null &&
+ !isDisabled &&
+ value.map(item => (
+ <input
+ key={item.id}
+ type="hidden"
+ name={htmlName}
+ value={item.id}
+ />
+ ))}
+ {/* Mounted from the press until the sheet's exit has completed and
+ focus is back on the trigger (`isSheetPresented`): at rest the
+ field renders its trigger alone — no closed dialog, rows, search
+ field or confirmation in the DOM (INV7). */}
+ {(isSheetOpen || isSheetPresented) &&
+ (!isDisabled || keepsSheetWhileDisabled) && (
+ <TokenizerSheetHost
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ finalFocusRef={triggerRef}
+ initialQuery={sheetInitialQuery}
+ label={label}
+ searchSource={searchSource}
+ value={value}
+ isAtMax={isAtMax}
+ hasCreate={hasCreate}
+ maxMenuItems={maxMenuItems ?? 10}
+ minQueryLength={minQueryLength ?? 1}
+ debounceMs={debounceMs ?? 150}
+ emptySearchText={emptySearchText}
+ onAdd={handleAdd}
+ onRemove={handleRemove}
+ onClearAll={handleClearAll}
+ onChangeQuery={handleSheetQueryChange}
+ />
+ )}
+ </>
+ );
+ } else if (isLayerMode) {
const placeholderSizeStyle = layerPlaceholderSizeStyles[size];
tokenizerContent = (
<>
diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx
new file mode 100644
index 0000000000..cb21c299e5
--- /dev/null
+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx
@@ -0,0 +1,2718 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file TokenizerBottomSheet.test.tsx
+ * @input Uses vitest, Testing Library, Tokenizer with
+ * `experimental.presentation`
+ * @output Tests for the experimental sheet presentation: the presentation
+ * resolution (`component:Tokenizer` FR16) and the single-sheet touch flow
+ * (FR17–FR24, AR6)
+ * @position Core tests; validates Tokenizer.tsx and TokenizerBottomSheet.tsx
+ */
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import {createRef, useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Tokenizer, type TokenizerChange} from './Tokenizer';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import {__resetDevWarnings} from '../utils/devWarning';
+import {colorVars} from '../theme/tokens.stylex';
+import type {SearchSource, SearchableItem} from '../Typeahead/types';
+
+import {COMPACT_TOUCH_PRESENTATION_QUERY as COMPACT_TOUCH_QUERY} from '../hooks/useAdaptivePresentation';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {
+ getBottomSheetStackForTests,
+ resetBottomSheetStackForTests,
+} from '../BottomSheet/bottomSheetStack';
+import {getActiveModalOutlet} from '../Layer/modalOutlet';
+
+const ITEMS: SearchableItem[] = [
+ {id: 'design', label: 'Design'},
+ {id: 'eng', label: 'Eng'},
+ {id: 'engineer', label: 'Engineer'},
+ {id: 'energizer', label: 'Energizer'},
+];
+const source: SearchSource<SearchableItem> = {
+ search: q =>
+ ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
+ bootstrap: () => ITEMS,
+};
+
+type Presentation = 'popover' | 'bottom-sheet' | 'adaptive';
+
+const DEFAULT_INITIAL = [ITEMS[0], ITEMS[1]];
+
+function Harness({
+ spy,
+ presentation = 'bottom-sheet',
+ initial = DEFAULT_INITIAL,
+ ...props
+}: {
+ spy?: (
+ items: SearchableItem[],
+ change: TokenizerChange<SearchableItem>,
+ ) => void;
+ presentation?: Presentation;
+ initial?: SearchableItem[];
+ hasCreate?: boolean;
+ maxEntries?: number;
+ isDisabled?: boolean;
+ disabledMessage?: string;
+ debounceMs?: number;
+ onFocus?: (event: React.FocusEvent) => void;
+ onBlur?: (event: React.FocusEvent) => void;
+}) {
+ const [value, setValue] = useState<SearchableItem[]>(initial);
+ return (
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={value}
+ debounceMs={0}
+ placeholder="Add tags"
+ onChange={(items, change) => {
+ setValue(items);
+ spy?.(items, change);
+ }}
+ experimental={{presentation}}
+ {...props}
+ />
+ );
+}
+
+function stubMatchMedia(matcher: (query: string) => boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: matcher(query),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+function stubEnvironment() {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ if (!Element.prototype.setPointerCapture) {
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ }
+ stubMatchMedia(() => false);
+ window.scrollTo = vi.fn();
+}
+
+const openTrigger = () => screen.getByRole('button', {name: 'Tags'});
+// The row list carries the progressive-rendering counters (FR21).
+const list = () => document.querySelector<HTMLElement>('[data-total-count]')!;
+
+// The sheet surface is loaded with React.lazy, so the first sheet renders a
+// tick after it opens. Open one up front so the module is cached and every
+// later sheet renders synchronously.
+beforeAll(async () => {
+ stubEnvironment();
+ try {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ await screen.findByLabelText('Search Tags', undefined, {timeout: 15000});
+ } finally {
+ cleanup();
+ vi.unstubAllGlobals();
+ }
+}, 20000);
+
+beforeEach(() => {
+ __resetLiveRegionsForTest();
+ resetBottomSheetStackForTests();
+ stubEnvironment();
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe('Tokenizer experimental.presentation (FR16)', () => {
+ it('keeps the inline combobox when experimental is omitted', () => {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Tags'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('keeps the inline combobox for an empty experimental object and for popover', () => {
+ const {unmount} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ experimental={{}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ unmount();
+ render(<Harness presentation="popover" />);
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Tags'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('forces the sheet trigger for bottom-sheet on every device', async () => {
+ render(<Harness presentation="bottom-sheet" />);
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
+ const trigger = openTrigger();
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(trigger).toHaveTextContent('Design');
+ expect(trigger).toHaveTextContent('Eng');
+ // Tokens in the trigger are display-only (FR17).
+ expect(within(trigger).queryAllByRole('button')).toHaveLength(0);
+
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ expect(sheet).toBeInTheDocument();
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalled();
+ });
+
+ it('uses the sheet for adaptive presentation on compact touch', async () => {
+ stubMatchMedia(query => query === COMPACT_TOUCH_QUERY);
+ render(<Harness presentation="adaptive" />);
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
+ fireEvent.click(openTrigger());
+ expect(
+ await screen.findByRole('dialog', {name: 'Tags'}),
+ ).toBeInTheDocument();
+ });
+
+ it('keeps adaptive presentation inline without compact touch', () => {
+ render(<Harness presentation="adaptive" />);
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Tags'}),
+ ).not.toBeInTheDocument();
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ });
+
+ it('shows the trigger placeholder when nothing is selected', () => {
+ render(<Harness initial={[]} />);
+ expect(openTrigger()).toHaveTextContent('Add tags');
+ });
+});
+
+describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {
+ it('keeps rows stable while open and applies selected-first order on reopen (FR19)', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ const trigger = openTrigger();
+ fireEvent.click(trigger);
+
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+ const checkboxLabels = () =>
+ within(list())
+ .getAllByRole('checkbox')
+ .map(row => row.getAttribute('aria-label'));
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+ expect(screen.getByLabelText('Search Tags')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Add item'}),
+ ).not.toBeInTheDocument();
+ const design = screen.getByRole('checkbox', {name: 'Design'});
+ expect(design).toBeChecked();
+ expect(design.lastElementChild).toHaveAttribute('aria-hidden', 'true');
+ expect(design.lastElementChild).toHaveAttribute('data-size', 'md');
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
+ expect(spy).toHaveBeenCalledWith(
+ [ITEMS[0], ITEMS[1], ITEMS[3]],
+ expect.objectContaining({type: 'add'}),
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Energizer'})).toBeChecked(),
+ );
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ expect(spy).toHaveBeenLastCalledWith(
+ [ITEMS[0], ITEMS[3]],
+ expect.objectContaining({type: 'remove'}),
+ );
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ await act(async () => {
+ fireEvent.click(trigger);
+ });
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Energizer',
+ 'Eng',
+ 'Engineer',
+ ]);
+ });
+
+ it('announces additions, removals, and the busy start inside the open modal sheet, not on the page body (AR6; AST-086 FR14)', async () => {
+ // jsdom has no showModal(), so an open dialog never matches `:modal`;
+ // stand in for the sheet the browser presents modally.
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ // A real debounce, so a typed query has a busy window to announce.
+ render(<Harness debounceMs={50} />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ const shared = () =>
+ document.querySelector('[data-astryx-live-region="polite"]');
+ // An instant bootstrap announces no busy start; a debounced typed
+ // query does, in the sheet, before its results land.
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+ expect(region()).toBeNull();
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'E'},
+ });
+ await waitFor(() => expect(region()).toHaveTextContent('Loading'));
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: ''},
+ });
+ fireEvent.click(await screen.findByRole('checkbox', {name: 'Energizer'}));
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('Added Energizer'),
+ );
+ expect(region()).toHaveAttribute('role', 'status');
+ expect(dialog.contains(region())).toBe(true);
+ expect(shared()?.textContent ?? '').toBe('');
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ await waitFor(() => expect(region()).toHaveTextContent('Removed Design'));
+ expect(shared()?.textContent ?? '').toBe('');
+ // How a search ended: the result count for a typed query …
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ await waitFor(() => expect(region()).toHaveTextContent('3 results'));
+ // … and the empty state's words when it shows.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'zzz'},
+ });
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('No results found'),
+ );
+ expect(shared()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('keeps the inline popover presentation on the shared live region', async () => {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ // Backspace on the empty input removes the last token through the
+ // same path the sheet's rows use.
+ const input = screen.getByRole('combobox');
+ input.focus();
+ fireEvent.keyDown(input, {key: 'Backspace'});
+ await waitFor(() =>
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]'),
+ ).toHaveTextContent('Removed Eng'),
+ );
+ expect(
+ document.querySelector('[data-astryx-modal-live-region]'),
+ ).toBeNull();
+ });
+
+ it('creates a custom entry with a trailing Add action and announces the created value (FR22)', async () => {
+ // jsdom has no showModal(); stand in for the sheet presented modally so
+ // the announcement takes the in-dialog route.
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ const spy = vi.fn();
+ render(<Harness spy={spy} hasCreate initial={[]} />);
+ const trigger = openTrigger();
+ fireEvent.click(trigger);
+ const search = await screen.findByLabelText('Search Tags');
+ fireEvent.change(search, {target: {value: 'Custom'}});
+
+ expect(
+ screen.queryByRole('checkbox', {name: 'Create "Custom"'}),
+ ).not.toBeInTheDocument();
+ const create = await screen.findByRole('button', {name: 'Add Custom'});
+ expect(
+ screen.queryByRole('button', {name: 'Clear all'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Done'}),
+ ).not.toBeInTheDocument();
+ expect(create).toHaveAttribute('data-size', 'lg');
+ expect(screen.getByText('Create "Custom"')).toBeInTheDocument();
+ await act(async () => {
+ fireEvent.click(create);
+ });
+ expect(spy).toHaveBeenCalledWith(
+ [{id: 'Custom', label: 'Custom'}],
+ expect.objectContaining({type: 'create'}),
+ );
+ await waitFor(() => expect(trigger).toHaveTextContent('Custom'));
+ expect(search).toHaveValue('');
+ const custom = await screen.findByRole('checkbox', {name: 'Custom'});
+ expect(custom).toBeChecked();
+ // Announced inside the sheet as the created value, not the row's
+ // caption ("Create …"), as the inline field announces it.
+ const dialog = screen.getByRole('dialog', {name: 'Tags'});
+ await waitFor(() =>
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('Added Custom'),
+ );
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).not.toHaveTextContent('Create');
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+ it('offers no create row for text that matches a selected label or a result', async () => {
+ render(<Harness hasCreate />);
+ fireEvent.click(openTrigger());
+ const search = await screen.findByLabelText('Search Tags');
+ fireEvent.change(search, {target: {value: 'design'}});
+ await screen.findByRole('checkbox', {name: 'Design'});
+ expect(
+ screen.queryByRole('button', {name: /^Add /}),
+ ).not.toBeInTheDocument();
+ fireEvent.change(search, {target: {value: 'ENGINEER'}});
+ await screen.findByRole('checkbox', {name: 'Engineer'});
+ expect(
+ screen.queryByRole('button', {name: /^Add /}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('renders long lists in 50-item batches and resets the window for search (FR21)', async () => {
+ const longItems: SearchableItem[] = Array.from(
+ {length: 120},
+ (_, index) => ({
+ id: `item-${index + 1}`,
+ label: `Item ${String(index + 1).padStart(3, '0')}`,
+ }),
+ );
+ const longSource: SearchSource<SearchableItem> = {
+ bootstrap: () => longItems,
+ search: query =>
+ longItems.filter(item =>
+ item.label.toLowerCase().includes(query.toLowerCase()),
+ ),
+ };
+ render(
+ <Tokenizer
+ label="Items"
+ searchSource={longSource}
+ value={[]}
+ onChange={() => {}}
+ maxMenuItems={120}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Items'}));
+ await screen.findByRole('checkbox', {name: 'Item 001'});
+ const items = list();
+ await waitFor(() => {
+ expect(items).toHaveAttribute('data-rendered-count', '50');
+ expect(items).toHaveAttribute('data-total-count', '120');
+ });
+ expect(screen.getAllByRole('checkbox')).toHaveLength(50);
+ expect(
+ screen.queryByRole('checkbox', {name: 'Item 051'}),
+ ).not.toBeInTheDocument();
+ // Every row's listitem names its place in the whole set, not the
+ // rendered window; `checkbox` does not admit the position attributes,
+ // so they sit on the listitem that wraps each row.
+ const rowList = within(items).getByRole('list');
+ const listItems = within(rowList).getAllByRole('listitem');
+ expect(listItems).toHaveLength(50);
+ expect(listItems[0]).toHaveAttribute('aria-setsize', '120');
+ expect(listItems[0]).toHaveAttribute('aria-posinset', '1');
+ expect(
+ within(listItems[0]).getByRole('checkbox', {name: 'Item 001'}),
+ ).toBeInTheDocument();
+ expect(listItems[49]).toHaveAttribute('aria-setsize', '120');
+ expect(listItems[49]).toHaveAttribute('aria-posinset', '50');
+ const first = screen.getByRole('checkbox', {name: 'Item 001'});
+ expect(first).not.toHaveAttribute('aria-setsize');
+ expect(first).not.toHaveAttribute('aria-posinset');
+ const fiftieth = screen.getByRole('checkbox', {name: 'Item 050'});
+ // Focus reaching the last rendered row renders the next batch, so a
+ // keyboard user reaches every row without scrolling.
+ fiftieth.focus();
+ await waitFor(() =>
+ expect(items).toHaveAttribute('data-rendered-count', '100'),
+ );
+ expect(
+ screen
+ .getByRole('checkbox', {name: 'Item 051'})
+ .closest('[role="listitem"]'),
+ ).toHaveAttribute('aria-posinset', '51');
+ screen.getByRole('checkbox', {name: 'Item 100'}).focus();
+ await waitFor(() =>
+ expect(items).toHaveAttribute('data-rendered-count', '120'),
+ );
+ // The window is back to one batch for the scroll part of the test.
+ fireEvent.change(screen.getByLabelText('Search Items'), {
+ target: {value: 'Item'},
+ });
+ await waitFor(() =>
+ expect(items).toHaveAttribute('data-rendered-count', '50'),
+ );
+ fireEvent.change(screen.getByLabelText('Search Items'), {
+ target: {value: ''},
+ });
+ await waitFor(() =>
+ expect(items).toHaveAttribute('data-rendered-count', '50'),
+ );
+
+ Object.defineProperties(items, {
+ clientHeight: {configurable: true, value: 600},
+ scrollHeight: {configurable: true, value: 2400},
+ scrollTop: {configurable: true, value: 1700, writable: true},
+ });
+ fireEvent.scroll(items);
+ expect(items).toHaveAttribute('data-rendered-count', '100');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(100);
+ expect(
+ screen.getByRole('checkbox', {name: 'Item 100'}),
+ ).toBeInTheDocument();
+
+ Object.defineProperties(items, {
+ scrollHeight: {configurable: true, value: 4400},
+ scrollTop: {configurable: true, value: 3600, writable: true},
+ });
+ fireEvent.scroll(items);
+ expect(items).toHaveAttribute('data-rendered-count', '120');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(120);
+
+ fireEvent.change(screen.getByLabelText('Search Items'), {
+ target: {value: 'Item'},
+ });
+ await waitFor(() =>
+ expect(items).toHaveAttribute('data-rendered-count', '50'),
+ );
+ expect(screen.getAllByRole('checkbox')).toHaveLength(50);
+
+ fireEvent.scroll(items);
+ expect(items).toHaveAttribute('data-rendered-count', '100');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(100);
+ });
+
+ it('searches within the same sheet and shows the no-results state (FR18, FR20)', async () => {
+ const onChangeQuery = vi.fn();
+ const {rerender} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ onChangeQuery={onChangeQuery}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const search = await screen.findByLabelText('Search Tags');
+ fireEvent.change(search, {target: {value: 'zzz'}});
+ expect(onChangeQuery).toHaveBeenCalledWith('zzz');
+
+ const title = await screen.findByRole('heading', {
+ name: 'No results found',
+ });
+ // EmptyState is not a live region (it announces itself once when it
+ // appears); locate it by its own root.
+ const emptyState = title.closest('.astryx-empty-state');
+ expect(emptyState).toHaveTextContent('Try a different search.');
+ expect(emptyState?.querySelector('.astryx-icon')).toHaveAttribute(
+ 'data-size',
+ 'lg',
+ );
+ // Only one dialog: the sheet searches in place (FR18).
+ expect(screen.getAllByRole('dialog')).toHaveLength(1);
+
+ // A string emptySearchText becomes the empty state's title.
+ rerender(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ emptySearchText="Nothing here"
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(
+ await screen.findByRole('heading', {name: 'Nothing here'}),
+ ).toBeInTheDocument();
+ });
+
+ it('shows only the search field for an empty query with nothing to list, as the inline field does — no list, no message, no announcement (FR20)', async () => {
+ // A search-only source: typing finds items, the bootstrap set is empty.
+ const searchOnly: SearchSource<SearchableItem> = {
+ search: (q: string) =>
+ ITEMS.filter(item =>
+ item.label.toLowerCase().includes(q.toLowerCase()),
+ ),
+ bootstrap: () => [],
+ };
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={searchOnly}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const search = screen.getByLabelText('Search Tags');
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(within(dialog).queryByRole('list')).not.toBeInTheDocument();
+ expect(within(dialog).queryByRole('heading')).not.toBeInTheDocument();
+ expect(screen.queryByText('No items available')).not.toBeInTheDocument();
+ expect(dialog.querySelector('.astryx-empty-state')).toBeNull();
+ expect(
+ within(dialog).queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ // Nothing is announced for a bootstrap that returned nothing: not in
+ // the sheet's region, not on the page body.
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ )?.textContent ?? '',
+ ).toBe('');
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]')
+ ?.textContent ?? '',
+ ).toBe('');
+ // The footer still closes the sheet (FR18); Clear all is spent.
+ expect(within(dialog).getByRole('button', {name: 'Done'})).toBeVisible();
+ expect(
+ within(dialog).getByRole('button', {name: 'Clear all'}),
+ ).toHaveAttribute('aria-disabled', 'true');
+ // Typing is what finds items.
+ fireEvent.change(search, {target: {value: 'En'}});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ expect(within(dialog).getByRole('list')).toBeInTheDocument();
+ // Clearing returns to the search-only state, silently.
+ fireEvent.change(search, {target: {value: ''}});
+ await waitFor(() =>
+ expect(within(dialog).queryByRole('list')).not.toBeInTheDocument(),
+ );
+ expect(dialog.querySelector('.astryx-empty-state')).toBeNull();
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('renders nothing of the sheet at rest: the DOM holds the trigger alone until a press, and again once the exit has completed (INV7)', async () => {
+ render(<Harness />);
+ const trigger = openTrigger();
+ // The lazy chunk may load; give it a tick, then check nothing rendered.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 20));
+ });
+ const sheetDom = () => ({
+ dialog: document.querySelector('dialog'),
+ sheet: document.querySelector('.astryx-bottom-sheet'),
+ checkboxes: screen.queryAllByRole('checkbox').length,
+ search: screen.queryByLabelText('Search Tags'),
+ confirmation: screen.queryByRole('alertdialog'),
+ });
+ expect(sheetDom()).toEqual({
+ dialog: null,
+ sheet: null,
+ checkboxes: 0,
+ search: null,
+ confirmation: null,
+ });
+ // Each selected label is in the DOM once: the trigger's token.
+ expect(screen.getAllByText('Design')).toHaveLength(1);
+
+ fireEvent.click(trigger);
+ await screen.findByRole('dialog', {name: 'Tags'});
+ expect(sheetDom().dialog).not.toBeNull();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ await waitFor(() => expect(trigger).toHaveFocus());
+ await waitFor(() => expect(sheetDom().dialog).toBeNull());
+ expect(sheetDom()).toEqual({
+ dialog: null,
+ sheet: null,
+ checkboxes: 0,
+ search: null,
+ confirmation: null,
+ });
+ expect(screen.getAllByText('Design')).toHaveLength(1);
+ });
+
+ it('mounts the Clear all confirmation only from the press until it closes: no alertdialog while none is pending, focus placed on cancel and on confirm (FR24; INV7)', async () => {
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ const noConfirmation = () => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
+ expect(sheet.querySelectorAll('dialog')).toHaveLength(0);
+ };
+ noConfirmation();
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+
+ // Cancel: the confirmation goes, focus is back on Clear all, nothing
+ // changed, nothing announced.
+ clearAll.focus();
+ fireEvent.click(clearAll);
+ const first = await screen.findByRole('alertdialog');
+ expect(sheet.contains(first)).toBe(true);
+ fireEvent.click(within(first).getByRole('button', {name: 'Cancel'}));
+ await waitFor(noConfirmation);
+ expect(clearAll).toHaveFocus();
+ expect(screen.getByRole('checkbox', {name: 'Design'})).toBeChecked();
+
+ // Confirm: the confirmation goes, the search field takes focus, the
+ // clear is announced inside the sheet.
+ fireEvent.click(clearAll);
+ const second = await screen.findByRole('alertdialog');
+ fireEvent.click(
+ within(second).getByRole('button', {name: 'Clear selection'}),
+ );
+ await waitFor(noConfirmation);
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ await waitFor(() =>
+ expect(
+ sheet.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('All items removed'),
+ );
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('keeps large equal-width Clear all and Done footer actions while guarding the bulk clear (FR24)', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+ const done = screen.getByRole('button', {name: 'Done'});
+ expect(clearAll).toHaveAttribute('data-size', 'lg');
+ expect(clearAll).toHaveAttribute('data-variant', 'secondary');
+ expect(done).toHaveAttribute('data-size', 'lg');
+ expect(list().compareDocumentPosition(clearAll)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ expect(list().compareDocumentPosition(done)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ fireEvent.click(clearAll);
+ const confirmation = screen.getByRole('alertdialog');
+ expect(confirmation).toHaveTextContent('Clear all selected items?');
+ expect(confirmation).toHaveTextContent(
+ 'This removes all selected items from Tags.',
+ );
+ expect(spy).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
+ );
+ expect(spy).toHaveBeenLastCalledWith(
+ [],
+ expect.objectContaining({type: 'remove', item: ITEMS[1]}),
+ );
+ await waitFor(() =>
+ expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ ),
+ );
+ });
+
+ it('keeps a disabled trigger focusable without opening the sheet (FR17; AST-085 FR1, FR2)', () => {
+ render(<Harness isDisabled initial={[ITEMS[0]]} />);
+ const trigger = openTrigger();
+ expect(trigger).not.toHaveAttribute('disabled');
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ trigger.focus();
+ expect(trigger).toHaveFocus();
+ fireEvent.click(trigger);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ // A field disabled from the start mounts no sheet at all.
+ expect(document.querySelector('dialog')).toBeNull();
+ expect(document.querySelector('[data-total-count]')).toBeNull();
+ });
+
+ it('moves focus to the search field after a confirmed Clear all, since Clear all is disabled by then (FR24; AST-085 FR4)', async () => {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+ clearAll.focus();
+ fireEvent.click(clearAll);
+ const confirmation = await screen.findByRole('alertdialog');
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ const clearAllAfter = screen.getByRole('button', {name: 'Clear all'});
+ expect(clearAllAfter).toHaveAttribute('aria-disabled', 'true');
+ expect(clearAllAfter).not.toBeDisabled();
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ expect(document.activeElement).not.toBe(document.body);
+ });
+
+ it('caps the empty-query bootstrap set at maxMenuItems, as the inline field caps its focus bootstrap (FR20)', async () => {
+ // Twenty bootstrap items, two selected (one of them outside the capped
+ // window): the sheet lists the selected rows plus the first maxMenuItems
+ // bootstrap rows, not the whole set.
+ const many = Array.from({length: 20}, (_, i) => ({
+ id: `t${String(i).padStart(2, '0')}`,
+ label: `Tag ${String(i).padStart(2, '0')}`,
+ }));
+ const manySource = {
+ search: (q: string) =>
+ many.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
+ bootstrap: () => many,
+ };
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={manySource}
+ value={[many[1], many[15]]}
+ onChange={() => {}}
+ debounceMs={0}
+ maxMenuItems={5}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Tag 00'});
+ const rows = within(dialog)
+ .getAllByRole('checkbox')
+ .map(row => row.getAttribute('aria-label'));
+ // Selected first (Tag 01, Tag 15), then the capped bootstrap window's
+ // remaining rows (Tag 00, 02, 03, 04): five bootstrap rows in all.
+ expect(rows).toEqual([
+ 'Tag 01',
+ 'Tag 15',
+ 'Tag 00',
+ 'Tag 02',
+ 'Tag 03',
+ 'Tag 04',
+ ]);
+ expect(dialog.querySelector('[data-total-count]')).toHaveAttribute(
+ 'data-total-count',
+ '6',
+ );
+ });
+
+ it('announces the rows it lists, not the source count: a created value and a maxMenuItems cap (FR20; AR6)', async () => {
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ // "Enzo" is a created value the source never returns; the source has
+ // three "en" matches (Eng, Engineer, Energizer), capped to two rows.
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[{id: 'Enzo', label: 'Enzo'}]}
+ onChange={() => {}}
+ debounceMs={0}
+ maxMenuItems={2}
+ hasCreate
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ // Part of the created value: the source returns nothing, but the
+ // checked row for Enzo is listed, and the sheet offers a create row
+ // for "enz" — two entries, not "0 results".
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'enz'},
+ });
+ await screen.findByRole('checkbox', {name: 'Enzo'});
+ await screen.findByRole('button', {name: 'Add enz'});
+ await waitFor(() => expect(region()).toHaveTextContent('2 results'));
+ expect(region()).not.toHaveTextContent('0 results');
+ // A query the cap applies to: the source has three matches, capped to
+ // two rows, plus the created value's checked row, plus the create row
+ // the sheet offers for "en" — four entries listed, four announced (the
+ // source count would say two, or three uncapped).
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'en'},
+ });
+ await screen.findByRole('button', {name: 'Add en'});
+ await waitFor(() => expect(region()).toHaveTextContent('4 results'));
+ expect(screen.getAllByRole('checkbox')).toHaveLength(3);
+ expect(
+ screen.queryByRole('checkbox', {name: 'Energizer'}),
+ ).not.toBeInTheDocument();
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('counts the create row it offers, as the inline field counts its create entry (FR20, FR22; AR6)', async () => {
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(<Harness hasCreate initial={[]} />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ // Nothing from the source, one create row offered: "1 result", not
+ // "0 results" over a row the person can act on.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Custom'},
+ });
+ await screen.findByRole('button', {name: 'Add Custom'});
+ await waitFor(() => expect(region()).toHaveTextContent('1 result'));
+ expect(region()).not.toHaveTextContent('0 results');
+ // An exact source match offers no create row: the one row counts.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Design'},
+ });
+ await screen.findByRole('checkbox', {name: 'Design'});
+ expect(
+ screen.queryByRole('button', {name: 'Add Design'}),
+ ).not.toBeInTheDocument();
+ await waitFor(() => expect(region()).toHaveTextContent('1 result'));
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('keeps a spent Clear all focusable with aria-disabled and no action, instead of native disabled (FR24; AST-085 FR1)', async () => {
+ render(<Harness initial={[]} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+ expect(clearAll).toHaveAttribute('aria-disabled', 'true');
+ expect(clearAll).not.toHaveAttribute('disabled');
+ // In the tab order, and it says why it does nothing.
+ clearAll.focus();
+ expect(clearAll).toHaveFocus();
+ expect(clearAll).toHaveAccessibleDescription('Nothing selected');
+ // A click opens no confirmation.
+ fireEvent.click(clearAll);
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
+ });
+
+ it('asks a source rebuilt in render only on open, on a query change, and on clearing — not on a row toggle (FR20)', async () => {
+ const search = vi.fn((q: string) =>
+ ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
+ );
+ const bootstrap = vi.fn(() => ITEMS);
+ function InlineSourceHarness() {
+ const [value, setValue] = useState<SearchableItem[]>([ITEMS[0]]);
+ return (
+ <Tokenizer
+ label="Tags"
+ // A new object every render, as a caller writing the source inline
+ // produces; the selection change on each toggle re-renders.
+ searchSource={{search, bootstrap}}
+ value={value}
+ onChange={items => setValue(items)}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<InlineSourceHarness />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ expect(search).not.toHaveBeenCalled();
+ // Row toggles re-render with a fresh source object: no new request.
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Eng'})).toBeChecked(),
+ );
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Engineer'}));
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Engineer'})).toBeChecked(),
+ );
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Eng'})).not.toBeChecked(),
+ );
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ expect(search).not.toHaveBeenCalled();
+ // A query change asks the source once; clearing asks for the bootstrap
+ // set once more.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'en'},
+ });
+ await waitFor(() => expect(search).toHaveBeenCalledTimes(1));
+ expect(search).toHaveBeenLastCalledWith('en');
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: ''},
+ });
+ await waitFor(() => expect(bootstrap).toHaveBeenCalledTimes(2));
+ expect(search).toHaveBeenCalledTimes(1);
+ });
+
+ it('announces a confirmed Clear all inside the sheet (AR6; AST-086 FR14)', async () => {
+ // jsdom has no showModal(); stand in for the sheet presented modally so
+ // the announcement takes the in-dialog route.
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.click(screen.getByRole('button', {name: 'Clear all'}));
+ const confirmation = await screen.findByRole('alertdialog');
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ await waitFor(() =>
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('All items removed'),
+ );
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('keeps and does not report the query when the field is disabled while the sheet is open (FR18)', async () => {
+ const onChangeQuery = vi.fn();
+ const props = {
+ label: 'Tags',
+ searchSource: source,
+ value: [ITEMS[0]],
+ onChange: () => {},
+ onChangeQuery,
+ debounceMs: 0,
+ experimental: {presentation: 'bottom-sheet' as const},
+ };
+ const {rerender} = render(<Tokenizer {...props} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ onChangeQuery.mockClear();
+ rerender(<Tokenizer {...props} isDisabled />);
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ // Nothing the person did changed the query, so nothing is reported, and
+ // the caller's mirror and the sheet agree on the next open.
+ expect(onChangeQuery).not.toHaveBeenCalled();
+ rerender(<Tokenizer {...props} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ expect(screen.getByLabelText('Search Tags')).toHaveValue('En');
+ expect(onChangeQuery).not.toHaveBeenCalled();
+ });
+
+ it('reopens settled, not pending, after a forced close kept a query shorter than minQueryLength (FR18, FR20)', async () => {
+ const props = {
+ label: 'Tags',
+ searchSource: source,
+ value: [ITEMS[0]],
+ onChange: () => {},
+ debounceMs: 0,
+ minQueryLength: 3,
+ experimental: {presentation: 'bottom-sheet' as const},
+ };
+ const {rerender} = render(<Tokenizer {...props} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ // Two characters: below the threshold, so nothing is searched.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ // The field becomes disabled: the sheet closes, keeping the query.
+ rerender(<Tokenizer {...props} isDisabled />);
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ await waitFor(() => expect(openTrigger()).toHaveFocus());
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),
+ );
+ rerender(<Tokenizer {...props} />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ expect(screen.getByLabelText('Search Tags')).toHaveValue('En');
+ // Mounted open with a query no search runs for: settled at once — no
+ // busy feedback, no aria-busy, only the selected rows the query matches
+ // (none: "Design" does not contain "En"), no empty state, and nothing
+ // announced.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 20));
+ });
+ expect(
+ within(dialog).queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ expect(dialog.querySelector('[data-total-count]')).not.toHaveAttribute(
+ 'aria-busy',
+ );
+ expect(within(dialog).queryAllByRole('checkbox')).toHaveLength(0);
+ expect(dialog.querySelector('.astryx-empty-state')).toBeNull();
+ expect(
+ dialog.querySelector(':scope > [data-astryx-modal-live-region="polite"]')
+ ?.textContent ?? '',
+ ).toBe('');
+ // Typing on past the threshold searches as usual.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Eng'},
+ });
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ });
+
+ it('closes the sheet and returns focus to the trigger when the field becomes disabled (FR17; AST-085 FR2)', async () => {
+ const {rerender} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ const trigger = openTrigger();
+ fireEvent.click(trigger);
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const search = screen.getByLabelText('Search Tags');
+ search.focus();
+ expect(search).toHaveFocus();
+
+ rerender(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ isDisabled
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(dialog).toHaveAttribute('aria-hidden', 'true');
+ // BottomSheet hands focus back after its exit motion.
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ expect(trigger).toHaveFocus();
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ // Re-enabling does not reopen it.
+ rerender(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+ });
+
+ it("exposes the caller's ids, the field description, the status and the disabled reason on a disabled trigger, in the inline field's order, before the count and tokens (AR6; AST-085 FR5)", () => {
+ render(
+ <>
+ <span id="hint">Up to five</span>
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ aria-describedby="hint"
+ description="Pick some"
+ status={{type: 'error', message: 'Pick at least three'}}
+ isDisabled
+ disabledMessage="Locked while syncing"
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </>,
+ );
+ const trigger = openTrigger();
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ const ids = trigger.getAttribute('aria-describedby')!.split(' ');
+ const texts = ids.map(id => document.getElementById(id)?.textContent);
+ expect(texts).toEqual([
+ 'Up to five',
+ 'Pick some',
+ 'Pick at least three',
+ 'Locked while syncing',
+ '2 selected',
+ 'Design',
+ 'Eng',
+ ]);
+ expect(trigger).toHaveAccessibleDescription(
+ 'Up to five Pick some Pick at least three Locked while syncing 2 selected Design Eng',
+ );
+ });
+
+ it('describes the trigger with the selected token labels for assistive technology (AR6; AST-020 FR1)', () => {
+ const {unmount} = render(<Harness />);
+ const trigger = openTrigger();
+ expect(trigger).toHaveAccessibleName('Tags');
+ // A catalog count, then each label; the separator is the accessible-name
+ // algorithm's, not a literal (i18n INV1a).
+ expect(trigger).toHaveAccessibleDescription('2 selected Design Eng');
+ // The labels come from the rendered tokens themselves, referenced by id:
+ // in the trigger and its description, each label is in the DOM once
+ // (component-style-authoring INV7); the only hidden text is the count.
+ const ids = trigger.getAttribute('aria-describedby')!.split(' ');
+ expect(ids).toHaveLength(3);
+ const described = ids.map(id => document.getElementById(id)!);
+ expect(described[0]).toHaveTextContent('2 selected');
+ expect(described[1]).toBe(
+ within(trigger).getByText('Design').closest('.astryx-token'),
+ );
+ expect(described[2]).toBe(
+ within(trigger).getByText('Eng').closest('.astryx-token'),
+ );
+ const leaves = (root: Element) =>
+ Array.from(root.querySelectorAll('*')).filter(
+ el => el.children.length === 0 && el.textContent?.trim() !== '',
+ );
+ const texts = [...leaves(trigger), ...leaves(described[0])].map(
+ el => el.textContent,
+ );
+ expect(texts.filter(text => text === 'Design')).toHaveLength(1);
+ expect(texts.filter(text => text === 'Eng')).toHaveLength(1);
+ unmount();
+ render(<Harness initial={[]} />);
+ expect(openTrigger()).not.toHaveAttribute('aria-describedby');
+ });
+
+ it('sends base props and ref to the trigger in the sheet presentation (FR10, INV8)', () => {
+ const ref = createRef<HTMLInputElement>();
+ const onFocus = vi.fn();
+ const onKeyDown = vi.fn();
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ id="tags-field"
+ data-testid="tags"
+ aria-describedby="hint"
+ description="Pick some"
+ ref={ref}
+ onFocus={onFocus}
+ onKeyDown={onKeyDown}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ const trigger = openTrigger();
+ expect(trigger).toHaveAttribute('id', 'tags-field');
+ expect(trigger).toHaveAttribute('data-testid', 'tags');
+ expect(trigger.getAttribute('aria-describedby')).toContain('hint');
+ expect(trigger).toHaveAccessibleDescription(/Pick some/);
+ expect(ref.current).toBe(trigger);
+ // The label points at the trigger.
+ expect(screen.getByText('Tags', {selector: 'label'})).toHaveAttribute(
+ 'for',
+ 'tags-field',
+ );
+ fireEvent.focus(trigger);
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ fireEvent.keyDown(trigger, {key: 'ArrowDown'});
+ expect(onKeyDown).toHaveBeenCalledTimes(1);
+ });
+
+ it('treats the sheet as part of the field: no onBlur on open, no onFocus on return, both on a real exit (FR10)', async () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ render(
+ <>
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ const trigger = openTrigger();
+ // Entering the field from outside reports once.
+ trigger.focus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // Open: focus moves into the field's own sheet, not out of the field.
+ fireEvent.click(trigger);
+ await screen.findByRole('dialog', {name: 'Tags'});
+ screen.getByLabelText('Search Tags').focus();
+ expect(onBlur).not.toHaveBeenCalled();
+ // Done: focus returns from the sheet, not from outside.
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ expect(trigger).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).not.toHaveBeenCalled();
+ // A real exit, from the trigger to elsewhere, reports.
+ screen.getByRole('button', {name: 'Elsewhere'}).focus();
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ // And a second open-and-close cycle from outside reports the entry once.
+ trigger.focus();
+ expect(onFocus).toHaveBeenCalledTimes(2);
+ fireEvent.click(trigger);
+ await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ expect(onFocus).toHaveBeenCalledTimes(2);
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports the entry on the return focus when the open came from a click that did not focus the trigger (Safari), so onBlur never comes alone (FR10)', async () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ render(
+ <>
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <button type="button">Elsewhere</button>
+ </>,
+ );
+ const trigger = openTrigger();
+ // A click with no focus first, as Safari delivers a pointer press on a
+ // button: no entry has been reported when the sheet opens.
+ fireEvent.click(trigger);
+ await screen.findByRole('dialog', {name: 'Tags'});
+ expect(onFocus).not.toHaveBeenCalled();
+ expect(onBlur).not.toHaveBeenCalled();
+ // Done: BottomSheet's return focus is the one focus the trigger gets in
+ // this visit, so it is the entry, and is reported.
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ expect(trigger).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).not.toHaveBeenCalled();
+ // Leaving reports the exit: one onFocus, one onBlur.
+ screen.getByRole('button', {name: 'Elsewhere'}).focus();
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs the open first and then the caller onClick, which cannot cancel it (FR10)', async () => {
+ const order: string[] = [];
+ const onClick = vi.fn((event: React.MouseEvent) => {
+ order.push(
+ (event.currentTarget as HTMLElement).getAttribute('aria-expanded') ??
+ '',
+ );
+ event.preventDefault();
+ });
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ onClick={onClick}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ const trigger = openTrigger();
+ fireEvent.click(trigger);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ // The caller's preventDefault() does not keep the sheet closed, as the
+ // inline field's own click handling runs first and is not cancelable.
+ expect(
+ await screen.findByRole('dialog', {name: 'Tags'}),
+ ).toBeInTheDocument();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ // The caller saw the click on the trigger (its pre-open state in the same
+ // event, since the open commits after the handler).
+ expect(order).toEqual(['false']);
+ });
+
+ it('warns once in development about props with no sheet surface (INV3)', () => {
+ __resetDevWarnings();
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {rerender} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ hasClear
+ menuWidth={320}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toMatch(/Tokenizer/);
+ expect(warn.mock.calls[0][0]).toMatch(/`hasClear`, `menuWidth`/);
+ expect(warn.mock.calls[0][0]).toMatch(/bottom-sheet presentation/);
+ rerender(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ hasClear
+ menuWidth={320}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(warn).toHaveBeenCalledTimes(1);
+ warn.mockClear();
+ render(
+ <Tokenizer
+ label="Other"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ hasClear
+ menuWidth={320}
+ />,
+ );
+ // The inline presentation renders them, so nothing to say.
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('is busy, not empty, from open and from each query change until the search settles (FR20)', async () => {
+ vi.useFakeTimers();
+ try {
+ const slow: SearchSource<SearchableItem> = {
+ bootstrap: async () =>
+ new Promise(resolve => setTimeout(() => resolve(ITEMS), 50)),
+ search: async q =>
+ new Promise(resolve =>
+ setTimeout(
+ () =>
+ resolve(
+ ITEMS.filter(item =>
+ item.label.toLowerCase().includes(q.toLowerCase()),
+ ),
+ ),
+ 50,
+ ),
+ ),
+ };
+ // Default debounceMs (150), so the debounce window is under test too.
+ // hasCreate, so the create row's timing is under test as well.
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={slow}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const list = () => document.querySelector('[data-total-count]')!;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(list()).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('img', {name: 'Loading'})).toBeInTheDocument();
+ expect(
+ screen.queryByRole('heading', {name: 'No items available'}),
+ ).not.toBeInTheDocument();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(250);
+ });
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.getByRole('checkbox', {name: 'Design'}),
+ ).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'zzz'},
+ });
+ // Inside the debounce window: busy, no "No results found", no create
+ // row (the previous query's results cannot judge a duplicate), and the
+ // named Loading row sits above the rows still listed from before, so
+ // the person sees that those rows are not the answer yet.
+ expect(
+ screen.queryByRole('button', {name: /^Add /}),
+ ).not.toBeInTheDocument();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(100);
+ });
+ expect(list()).toHaveAttribute('aria-busy', 'true');
+ const loading = screen.getByRole('img', {name: 'Loading'});
+ const staleRow = screen.getByRole('checkbox', {name: 'Design'});
+ expect(staleRow).toBeInTheDocument();
+ expect(loading.compareDocumentPosition(staleRow)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ expect(
+ screen.queryByRole('heading', {name: 'No results found'}),
+ ).not.toBeInTheDocument();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(200);
+ });
+ expect(list()).not.toHaveAttribute('aria-busy');
+ // Settled with no match: the create row is offered now, against this
+ // query's own results, and no empty state shows beside it.
+ expect(screen.getByRole('button', {name: 'Add zzz'})).toBeInTheDocument();
+ expect(
+ screen.queryByRole('heading', {name: 'No results found'}),
+ ).not.toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('describes a disabled trigger with disabledMessage', async () => {
+ render(
+ <Harness isDisabled disabledMessage="Pick a team first" initial={[]} />,
+ );
+ const trigger = openTrigger();
+ fireEvent.focus(trigger);
+ expect(await screen.findByText('Pick a team first')).toBeInTheDocument();
+ });
+
+ it('keeps an unselectable row at the limit focusable but inert (FR23; AST-085 FR1, FR2)', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} initial={[ITEMS[0]]} maxEntries={1} />);
+ fireEvent.click(openTrigger());
+ const row = await screen.findByRole('checkbox', {name: 'Energizer'});
+ expect(row).not.toHaveAttribute('disabled');
+ expect(row).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.click(row);
+ expect(spy).not.toHaveBeenCalled();
+ expect(row).toHaveAttribute('aria-checked', 'false');
+ // In forced colors its indicator border takes GrayText (AST-085 FR6).
+ const indicatorClasses = stylex
+ .props(
+ stylex.create({
+ indicatorBorder: {
+ borderColor: {
+ default: colorVars['--color-border'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ }).indicatorBorder,
+ )
+ .className!.split(' ')
+ .filter(name => !name.includes('__'));
+ const indicator = row.querySelector('.astryx-checkbox-indicator')!;
+ for (const name of indicatorClasses) {
+ expect(indicator).toHaveClass(name);
+ }
+ // The checked row still toggles, making room (FR23).
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ expect(spy).toHaveBeenLastCalledWith(
+ [],
+ expect.objectContaining({type: 'remove'}),
+ );
+ });
+
+ it('paints a disabled trigger, its placeholder, and its tokens GrayText in forced colors (AST-085 FR6)', () => {
+ const atoms = (style: stylex.StyleXStyles) =>
+ stylex
+ .props(style)
+ .className!.split(' ')
+ .filter(name => !name.includes('__'));
+ const forced = stylex.create({
+ trigger: {
+ borderColor: {
+ default: colorVars['--color-border-emphasized'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ color: {default: null, '@media (forced-colors: active)': 'GrayText'},
+ },
+ token: {
+ color: {
+ default: colorVars['--color-text-primary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ placeholder: {
+ color: {
+ default: colorVars['--color-text-secondary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ });
+ const {unmount} = render(<Harness isDisabled />);
+ const trigger = openTrigger();
+ for (const name of atoms(forced.trigger)) {
+ expect(trigger).toHaveClass(name);
+ }
+ const tokens = trigger.querySelectorAll('.astryx-token');
+ expect(tokens).toHaveLength(2);
+ for (const token of tokens) {
+ for (const name of atoms(forced.token)) {
+ expect(token).toHaveClass(name);
+ }
+ }
+ unmount();
+ render(<Harness isDisabled initial={[]} />);
+ const placeholder = screen.getByText('Add tags');
+ for (const name of atoms(forced.placeholder)) {
+ expect(placeholder).toHaveClass(name);
+ }
+ });
+
+ it('renders a row without its action and warns once in development (FR19; AST-058 FR9)', async () => {
+ __resetDevWarnings();
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const withAction: SearchSource<SearchableItem> = {
+ search: () => [],
+ bootstrap: () => [
+ {
+ id: 'design',
+ label: 'Design',
+ action: <button type="button">Go</button>,
+ },
+ {id: 'eng', label: 'Eng'},
+ ],
+ };
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={withAction}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const row = await screen.findByRole('checkbox', {name: 'Design'});
+ expect(within(row).queryByRole('button')).not.toBeInTheDocument();
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
+ expect(warn.mock.calls[0][0]).toMatch(/`action`/);
+ expect(warn.mock.calls[0][0]).toMatch(/bottom-sheet rows/);
+ warn.mockRestore();
+ });
+
+ it('keeps focus when adaptive stops resolving to the sheet while it is open (FR16)', async () => {
+ // A matchMedia stub whose match can flip, with a change listener the
+ // test fires, as a phone turned to landscape would.
+ let compact = true;
+ const listeners = new Set<() => void>();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ get matches() {
+ return query === COMPACT_TOUCH_QUERY ? compact : false;
+ },
+ media: query,
+ onchange: null,
+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),
+ removeEventListener: (_: string, cb: () => void) =>
+ listeners.delete(cb),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ render(<Harness presentation="adaptive" />);
+ const trigger = openTrigger();
+ fireEvent.click(trigger);
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ screen.getByLabelText('Search Tags').focus();
+
+ // The viewport stops being compact while the sheet is open: nothing
+ // changes until the sheet closes.
+ compact = false;
+ act(() => {
+ for (const cb of listeners) cb();
+ });
+ expect(screen.getByRole('dialog', {name: 'Tags'})).toBe(dialog);
+ expect(trigger).toBeInTheDocument();
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // The sheet is closing; the trigger stays mounted to take focus back,
+ // and the inline input does not appear yet.
+ expect(trigger).toBeInTheDocument();
+ expect(screen.queryByRole('combobox')).not.toBeInTheDocument();
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ // Focus came back to the trigger, the latch released into the popover
+ // presentation, and the inline input took the focus over.
+ await waitFor(() =>
+ expect(screen.getByRole('combobox')).toBeInTheDocument(),
+ );
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ expect(
+ screen.queryByRole('button', {name: 'Tags'}),
+ ).not.toBeInTheDocument();
+ });
+
+ it('types ref for the control it reaches: the input without experimental, input or trigger with it', () => {
+ const inputRef = createRef<HTMLInputElement>();
+ const {unmount} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={inputRef}
+ />,
+ );
+ expect(inputRef.current).toBe(screen.getByRole('combobox'));
+ unmount();
+ const wideRef = createRef<HTMLInputElement | HTMLButtonElement>();
+ const {rerender} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={wideRef}
+ experimental={{presentation: 'popover'}}
+ />,
+ );
+ expect(wideRef.current).toBe(screen.getByRole('combobox'));
+ rerender(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ ref={wideRef}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(wideRef.current).toBe(openTrigger());
+ });
+
+ it('does not search, wait, empty out, or announce for a query below minQueryLength (FR20)', async () => {
+ const search = vi.fn(source.search);
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{...source, search}}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ minQueryLength={3}
+ hasCreate
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ search.mockClear();
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'De'},
+ });
+ // Only the selected row it matches, and the create row; nothing searched,
+ // nothing pending, no empty state.
+ expect(screen.getByRole('checkbox', {name: 'Design'})).toBeInTheDocument();
+ expect(
+ screen.queryByRole('checkbox', {name: 'Eng'}),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Add De'})).toBeInTheDocument();
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('heading', {name: 'No results found'}),
+ ).not.toBeInTheDocument();
+ expect(search).not.toHaveBeenCalled();
+ // One more character crosses the threshold and searches.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Des'},
+ });
+ await waitFor(() => expect(search).toHaveBeenCalledWith('Des'));
+ spy.mockRestore();
+ });
+
+ it('announces the rendered empty state when emptySearchText is an element (FR20; AST-056 FR3)', async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ emptySearchText={
+ <p>
+ Nothing called <strong>that</strong>
+ <span aria-hidden="true"> (decorative)</span>
+ </p>
+ }
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'zzz'},
+ });
+ await waitFor(() =>
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).toHaveTextContent('Nothing called that'),
+ );
+ expect(
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ ),
+ ).not.toHaveTextContent('decorative');
+ expect(screen.getByText('that')).toBeInTheDocument();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('announces the default empty state exactly once inside the sheet (FR20; AST-086 FR6)', async () => {
+ const matches = Element.prototype.matches;
+ const modalSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'zzz'},
+ });
+ await screen.findByRole('heading', {name: 'No results found'});
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('No results found'),
+ );
+ // Spoken by EmptyState itself, once: the sheet adds no second copy of
+ // the title or description, joined or otherwise.
+ const text = region()?.textContent ?? '';
+ expect(text.match(/No results found/g)).toHaveLength(1);
+ expect(text.match(/Try a different search\./g)).toHaveLength(1);
+ expect(
+ document.querySelector('[data-astryx-live-region="polite"]')
+ ?.textContent ?? '',
+ ).toBe('');
+ } finally {
+ modalSpy.mockRestore();
+ }
+ });
+
+ it('settles a rejecting source to no results without an unhandled rejection (FR20)', async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ const rejected = vi.fn();
+ const onRejection = (event: PromiseRejectionEvent) => {
+ rejected(event.reason);
+ event.preventDefault();
+ };
+ window.addEventListener('unhandledrejection', onRejection);
+ try {
+ const flaky: SearchSource<SearchableItem> = {
+ bootstrap: () => ITEMS,
+ search: async q => {
+ if (q === 'boom') {
+ throw new Error('source down');
+ }
+ return source.search(q);
+ },
+ };
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={flaky}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+ await waitFor(() => expect(region()).toHaveTextContent('3 results'));
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'boom'},
+ });
+ // Settled: no stale rows, busy cleared, the empty state announced
+ // rather than the old count.
+ await waitFor(() =>
+ expect(
+ screen.getByRole('heading', {name: 'No results found'}),
+ ).toBeInTheDocument(),
+ );
+ expect(
+ screen.queryByRole('checkbox', {name: 'Energizer'}),
+ ).not.toBeInTheDocument();
+ expect(list()).not.toHaveAttribute('aria-busy');
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('No results found'),
+ );
+ expect(region()).not.toHaveTextContent('3 results');
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(rejected).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('unhandledrejection', onRejection);
+ spy.mockRestore();
+ }
+ });
+
+ it('retires an unsettled search when a query below minQueryLength follows it, announcing nothing (FR20)', async () => {
+ vi.useFakeTimers();
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ const slow: SearchSource<SearchableItem> = {
+ bootstrap: () => ITEMS,
+ search: async q =>
+ new Promise(resolve =>
+ setTimeout(() => resolve(source.search(q)), 300),
+ ),
+ };
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={slow}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ minQueryLength={3}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10);
+ });
+ const dialog = screen.getByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ const search = screen.getByLabelText('Search Tags');
+ // "Eng" searches; before it settles, backspace to "En", below the
+ // threshold: nothing pending, and when the old search returns its rows
+ // do not land and no count is announced.
+ fireEvent.change(search, {target: {value: 'Eng'}});
+ expect(list()).toHaveAttribute('aria-busy', 'true');
+ fireEvent.change(search, {target: {value: 'En'}});
+ expect(list()).not.toHaveAttribute('aria-busy');
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ expect(
+ screen.queryByRole('checkbox', {name: 'Eng'}),
+ ).not.toBeInTheDocument();
+ expect(region()?.textContent ?? '').not.toMatch(/results?/);
+ // A searched query afterwards announces as usual.
+ fireEvent.change(search, {target: {value: 'Ener'}});
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ expect(
+ screen.getByRole('checkbox', {name: 'Energizer'}),
+ ).toBeInTheDocument();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(50);
+ });
+ expect(region()).toHaveTextContent('1 result');
+ } finally {
+ spy.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('marks the list pending while the bootstrap set reloads after the create row (FR20, FR22)', async () => {
+ vi.useFakeTimers();
+ try {
+ const onChangeQuery = vi.fn();
+ const slow: SearchSource<SearchableItem> = {
+ bootstrap: async () =>
+ new Promise(resolve => setTimeout(() => resolve(ITEMS), 300)),
+ search: async q =>
+ new Promise(resolve =>
+ setTimeout(() => resolve(source.search(q)), 300),
+ ),
+ };
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={slow}
+ value={[]}
+ onChange={() => {}}
+ onChangeQuery={onChangeQuery}
+ debounceMs={0}
+ hasCreate
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Ops'},
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ onChangeQuery.mockClear();
+ fireEvent.click(screen.getByRole('button', {name: 'Add Ops'}));
+ // The query is cleared through the same path a typed change takes:
+ // the bootstrap reload is pending and the change is reported.
+ expect(list()).toHaveAttribute('aria-busy', 'true');
+ expect(screen.getByRole('img', {name: 'Loading'})).toBeInTheDocument();
+ expect(onChangeQuery).toHaveBeenCalledWith('');
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(400);
+ });
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.getByRole('checkbox', {name: 'Design'}),
+ ).toBeInTheDocument();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('joins two announcements from one change inside the sheet (AST-086 FR14)', async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ render(<Harness hasCreate maxEntries={2} initial={[ITEMS[0]]} />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ const region = () =>
+ dialog.querySelector(
+ ':scope > [data-astryx-modal-live-region="polite"]',
+ );
+ // Typing a query that both searches (its count is announced on settle)
+ // and, here with an instant source, settles in the same frame as the
+ // create row appears: the count includes the create row the sheet
+ // offers, as the inline field counts its create entry.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Ops'},
+ });
+ await waitFor(() => expect(region()).toHaveTextContent('1 result'));
+ // Two selection changes in one frame: neither is dropped.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: ''},
+ });
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ await act(async () => {
+ await new Promise(resolve =>
+ requestAnimationFrame(() => resolve(null)),
+ );
+ await new Promise(resolve =>
+ requestAnimationFrame(() => resolve(null)),
+ );
+ });
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('Added Eng Removed Design'),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('clears the query on Escape dismissal, so the next open lists the bootstrap set and settles (FR18, FR20)', async () => {
+ const onChangeQuery = vi.fn();
+ const search = vi.fn(source.search);
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={{...source, search}}
+ value={[]}
+ onChange={() => {}}
+ onChangeQuery={onChangeQuery}
+ debounceMs={0}
+ minQueryLength={3}
+ hasCreate
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Design'});
+ // A query below the threshold, then an Escape dismissal: the query does
+ // not survive the close.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'De'},
+ });
+ expect(screen.getByRole('button', {name: 'Add De'})).toBeInTheDocument();
+ onChangeQuery.mockClear();
+ search.mockClear();
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ await waitFor(() =>
+ expect(openTrigger()).toHaveAttribute('aria-expanded', 'false'),
+ );
+ expect(onChangeQuery).toHaveBeenCalledWith('');
+ fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {
+ propertyName: 'transform',
+ });
+ // Reopened: the search field is empty, the bootstrap set loads and
+ // settles — no list left pending for a search that never runs.
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ expect(screen.getByLabelText('Search Tags')).toHaveValue('');
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: /^Add /}),
+ ).not.toBeInTheDocument();
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('reports the cleared query from the close handler, not during render (FR18; runtime INV2)', async () => {
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ // A caller that mirrors the query into its own state: a render-phase
+ // report would be a cross-component update React warns about.
+ function Mirror() {
+ const [query, setQuery] = useState('');
+ return (
+ <>
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ onChangeQuery={setQuery}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <output data-testid="mirror">{query}</output>
+ </>
+ );
+ }
+ render(<Mirror />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ expect(screen.getByTestId('mirror')).toHaveTextContent('En');
+ fireEvent.keyDown(dialog, {key: 'Escape'});
+ await waitFor(() =>
+ expect(openTrigger()).toHaveAttribute('aria-expanded', 'false'),
+ );
+ expect(screen.getByTestId('mirror')).toHaveTextContent('');
+ const renderPhase = errors.mock.calls.filter(call =>
+ String(call[0]).includes('Cannot update a component'),
+ );
+ expect(renderPhase).toEqual([]);
+ } finally {
+ errors.mockRestore();
+ }
+ });
+
+ it('loads the bootstrap set at once on open: an instant source shows no Loading row and announces nothing (FR20)', async () => {
+ const matches = Element.prototype.matches;
+ const spy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ try {
+ // Default debounceMs (150): the open must not wait for it.
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(
+ screen.queryByRole('img', {name: 'Loading'}),
+ ).not.toBeInTheDocument();
+ // Nothing was announced for the open: no region was ever needed.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 50));
+ });
+ expect(
+ dialog.querySelector('[data-astryx-modal-live-region]'),
+ ).toBeNull();
+ // A typed query still waits for the debounce (busy meanwhile), and
+ // clearing it reloads the bootstrap set at once.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ expect(list()).toHaveAttribute('aria-busy', 'true');
+ await waitFor(() => expect(list()).not.toHaveAttribute('aria-busy'));
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: ''},
+ });
+ await screen.findByRole('checkbox', {name: 'Design'});
+ expect(list()).not.toHaveAttribute('aria-busy');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('moves focus to the search field when a settled search removes the focused row (FR20; AST-085 FR4)', async () => {
+ render(<Harness initial={[]} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ const design = await screen.findByRole('checkbox', {name: 'Design'});
+ design.focus();
+ expect(design).toHaveFocus();
+ // A query Design does not match: the settled search removes the focused
+ // row, and focus lands on the search field, not the page body.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'En'},
+ });
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('checkbox', {name: 'Design'}),
+ ).not.toBeInTheDocument(),
+ );
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ expect(document.activeElement).not.toBe(document.body);
+ });
+
+ it('awaits a non-native thenable from the source, as the inline field does (FR20)', async () => {
+ // A thenable that is not a native Promise: a library promise, or one
+ // from another realm. Typed as what the source contract names so the
+ // source is a plain object of synchronous functions returning it.
+ const asThenable = (items: SearchableItem[]) =>
+ ({
+ then: (resolve: (items: SearchableItem[]) => void) => {
+ resolve(items);
+ },
+ }) as unknown as SearchableItem[];
+ const thenable: SearchSource<SearchableItem> = {
+ bootstrap: () => asThenable(ITEMS),
+ search: q => asThenable(source.search(q) as SearchableItem[]),
+ };
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={thenable}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ expect(
+ await screen.findByRole('checkbox', {name: 'Design'}),
+ ).toBeInTheDocument();
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Ener'},
+ });
+ expect(
+ await screen.findByRole('checkbox', {name: 'Energizer'}),
+ ).toBeInTheDocument();
+ expect(list()).not.toHaveAttribute('aria-busy');
+ expect(errors).not.toHaveBeenCalled();
+ } finally {
+ errors.mockRestore();
+ }
+ });
+
+ it('subscribes to matchMedia only for the adaptive presentation (runtime INV5)', () => {
+ const added: string[] = [];
+ const matchMedia = vi.fn().mockImplementation((query: string) => ({
+ matches: false,
+ media: query,
+ onchange: null,
+ addEventListener: () => {
+ added.push(query);
+ },
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }));
+ vi.stubGlobal('matchMedia', matchMedia);
+ // The default popover, with and without the experimental object: no
+ // query is evaluated and no listener is registered.
+ const {unmount} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ />,
+ );
+ render(<Harness presentation="popover" />);
+ render(<Harness presentation="bottom-sheet" />);
+ expect(
+ matchMedia.mock.calls.filter(([q]) => q === COMPACT_TOUCH_QUERY),
+ ).toHaveLength(0);
+ expect(added.filter(q => q === COMPACT_TOUCH_QUERY)).toHaveLength(0);
+ unmount();
+ // Only adaptive reads the policy, and subscribes once.
+ render(<Harness presentation="adaptive" />);
+ expect(added.filter(q => q === COMPACT_TOUCH_QUERY)).toHaveLength(1);
+ });
+
+ it('moves focus to the sheet panel on open, not the search field (FR18)', async () => {
+ render(<Harness />);
+ fireEvent.click(openTrigger());
+ const dialog = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Design'});
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ expect(screen.getByLabelText('Search Tags')).not.toHaveFocus();
+ });
+
+ it('moves focus to the search field after the create row is activated (FR22)', async () => {
+ render(<Harness hasCreate initial={[]} />);
+ fireEvent.click(openTrigger());
+ await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'Ops'},
+ });
+ const add = await screen.findByRole('button', {name: 'Add Ops'});
+ add.focus();
+ fireEvent.click(add);
+ expect(
+ screen.queryByRole('button', {name: 'Add Ops'}),
+ ).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ });
+
+ it("moves focus to the new presentation's control when adaptive changes while the sheet is closed (FR16)", async () => {
+ let compact = true;
+ const listeners = new Set<() => void>();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ get matches() {
+ return query === COMPACT_TOUCH_QUERY ? compact : false;
+ },
+ media: query,
+ onchange: null,
+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),
+ removeEventListener: (_: string, cb: () => void) =>
+ listeners.delete(cb),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ render(
+ <Harness presentation="adaptive" onFocus={onFocus} onBlur={onBlur} />,
+ );
+ const trigger = openTrigger();
+ trigger.focus();
+ expect(trigger).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // Trigger focused, phone turns to landscape: the input takes over, and
+ // the hand-off inside the field reports neither a blur nor a focus.
+ compact = false;
+ act(() => {
+ for (const cb of listeners) cb();
+ });
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).not.toHaveBeenCalled();
+ // And back: the input focused, the screen becomes compact again.
+ compact = true;
+ act(() => {
+ for (const cb of listeners) cb();
+ });
+ expect(openTrigger()).toHaveFocus();
+ // Unfocused, a change moves nothing.
+ openTrigger().blur();
+ compact = false;
+ act(() => {
+ for (const cb of listeners) cb();
+ });
+ expect(document.body).toHaveFocus();
+ });
+
+ it('carries hidden form inputs and the field chrome in the sheet presentation', () => {
+ const {container} = render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ htmlName="tags"
+ status={{type: 'error', message: 'Pick at least three'}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ const hidden = container.querySelectorAll('input[type="hidden"]');
+ expect(hidden).toHaveLength(2);
+ expect(hidden[0]).toHaveAttribute('name', 'tags');
+ expect(hidden[0]).toHaveValue('design');
+ const trigger = openTrigger();
+ expect(trigger).toHaveClass('astryx-tokenizer');
+ expect(trigger).toHaveAttribute('data-status', 'error');
+ expect(screen.getByText('Pick at least three')).toBeInTheDocument();
+ });
+
+ it('submits nothing while disabled, in the sheet presentation as in the inline field (FR10, FR17)', () => {
+ const field = (
+ presentation: 'popover' | 'bottom-sheet',
+ isDisabled: boolean,
+ ) => (
+ <form>
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ htmlName="tags"
+ isDisabled={isDisabled}
+ experimental={{presentation}}
+ />
+ </form>
+ );
+ for (const presentation of ['popover', 'bottom-sheet'] as const) {
+ const enabled = render(field(presentation, false));
+ expect(
+ new FormData(enabled.container.querySelector('form')!).getAll('tags'),
+ ).toEqual(['design', 'eng']);
+ enabled.unmount();
+ const disabled = render(field(presentation, true));
+ const form = disabled.container.querySelector('form')!;
+ expect([...new FormData(form).keys()]).toEqual([]);
+ expect(form.querySelector('input[type="hidden"]')).toBeNull();
+ disabled.unmount();
+ }
+ });
+});
+
+describe('Tokenizer sheet under the BottomSheet stack (component:BottomSheet FR8, FR9; AST-003 FR18)', () => {
+ const stackSummary = () =>
+ getBottomSheetStackForTests().map(({element, isOpen, view}) => {
+ const label = element?.getAttribute('aria-label') ?? '?';
+ const state = !isOpen ? 'exiting' : view.isTop ? 'top' : 'covered';
+ return `${label}:${state}:${view.depth}`;
+ });
+ const finishExit = (dialog: HTMLElement) => {
+ for (const panel of Array.from(
+ dialog.querySelectorAll<HTMLElement>('.astryx-bottom-sheet'),
+ )) {
+ if (panel.closest('dialog') === dialog) {
+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});
+ }
+ }
+ };
+ /** A field inside a host sheet, as PowerSearch's value step hosts one. */
+ function Hosted() {
+ const [isHostOpen, setIsHostOpen] = useState(false);
+ const [value, setValue] = useState<SearchableItem[]>([ITEMS[0]]);
+ return (
+ <>
+ <button type="button" onClick={() => setIsHostOpen(true)}>
+ Open step
+ </button>
+ <BottomSheet
+ isOpen={isHostOpen}
+ onOpenChange={setIsHostOpen}
+ label="Value">
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={value}
+ onChange={items => setValue(items)}
+ debounceMs={0}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </BottomSheet>
+ </>
+ );
+ }
+
+ it('opened from inside a host sheet, is one stacked standalone sheet on top: the host recedes, Escape closes only the field sheet, focus returns to the trigger inside the host', async () => {
+ render(<Hosted />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open step'}));
+ const host = screen.getByRole('dialog', {name: 'Value'});
+ expect(stackSummary()).toEqual(['Value:top:0']);
+ const trigger = openTrigger();
+ trigger.focus();
+ fireEvent.click(trigger);
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ // The field's sheet is the top of the stack; the host is covered and
+ // recedes, and its dialog, which contains the field sheet, is left to the
+ // browser's modal blocking rather than marked inert.
+ expect(stackSummary()).toEqual(['Value:covered:1', 'Tags:top:0']);
+ expect(host).toHaveAttribute('data-sheet-stack', 'covered');
+ expect(host).not.toHaveAttribute('inert');
+ expect(sheet).toHaveAttribute('aria-modal', 'true');
+ expect(sheet).not.toHaveAttribute('inert');
+ // A row toggle works on top of the host.
+ fireEvent.click(within(sheet).getByRole('checkbox', {name: 'Eng'}));
+ await waitFor(() =>
+ expect(within(sheet).getByRole('checkbox', {name: 'Eng'})).toBeChecked(),
+ );
+ // Escape reaches only the top sheet: the field sheet closes, the host
+ // stays open and is the top again; focus returns to the trigger inside
+ // the host (FR9: the opener, inside the revealed sheet).
+ fireEvent.keyDown(sheet, {key: 'Escape'});
+ finishExit(sheet);
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', {name: 'Tags'}),
+ ).not.toBeInTheDocument(),
+ );
+ expect(stackSummary()).toEqual(['Value:top:0']);
+ expect(host).not.toHaveAttribute('data-sheet-stack');
+ expect(host).toHaveAttribute('open');
+ await waitFor(() => expect(openTrigger()).toHaveFocus());
+ // The field's selection survived the dismissal.
+ expect(openTrigger()).toHaveAccessibleDescription(/2 selected Design Eng/);
+ });
+
+ it("the Clear all confirmation opens over the field's sheet and returns into it; a toast raised meanwhile lands in the field's dialog (AST-003 FR18)", async () => {
+ render(<Hosted />);
+ fireEvent.click(screen.getByRole('button', {name: 'Open step'}));
+ fireEvent.click(openTrigger());
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ // While the field's sheet is the top modal, it is the active outlet for
+ // app-global surfaces: a toast raised from inside lands in its dialog.
+ expect(getActiveModalOutlet()).toBe(sheet);
+ fireEvent.click(within(sheet).getByRole('button', {name: 'Clear all'}));
+ const confirmation = await screen.findByRole('alertdialog');
+ // A Dialog over the sheet does not join the sheet stack (only sheets
+ // count); the field sheet stays the top sheet while covered by it, and
+ // the confirmation is now the latest outlet.
+ expect(stackSummary()).toEqual(['Value:covered:1', 'Tags:top:0']);
+ expect(getActiveModalOutlet()).toBe(confirmation);
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ // Back in the field's sheet: focus on its search field, the sheet the
+ // outlet again, the host still covered beneath.
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ expect(getActiveModalOutlet()).toBe(sheet);
+ expect(stackSummary()).toEqual(['Value:covered:1', 'Tags:top:0']);
+ });
+});
diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx
new file mode 100644
index 0000000000..0e4b28620f
--- /dev/null
+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx
@@ -0,0 +1,957 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file TokenizerBottomSheet.tsx
+ * @input Uses BottomSheet, PanelSearchInput, Button, CheckboxIndicator,
+ * EmptyState, AlertDialog, Icon, Spinner, Text, useBusyAnnouncement, and
+ * the i18n translator
+ * @output Exports TokenizerBottomSheet — the touch surface of
+ * `Tokenizer experimental.presentation="bottom-sheet"`: one tall modal sheet
+ * with a search row on top, stable-order checkbox rows, progressive
+ * long-list rendering, an optional create row, and a confirmed Clear all
+ * @position Internal presentation surface of Tokenizer. Loaded on demand by
+ * Tokenizer.tsx so the inline combobox never carries it
+ * (`component:Tokenizer` PR6).
+ *
+ * Selection itself stays in Tokenizer: this surface receives `onAdd`,
+ * `onRemove`, and `onClearAll` so the add/remove announcements, the create
+ * sentinel, and the duplicate checks are the inline field's own. What lives
+ * here is the sheet session — the query, the fetched results, the row order
+ * snapshot taken when the sheet opens, and the rendered-row window.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/Tokenizer/Tokenizer.tsx (the trigger and the lazy host)
+ * - /packages/core/src/Tokenizer/Tokenizer.spec.md (FR16–FR24, AR6, PR6)
+ */
+
+import {
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {AlertDialog} from '../AlertDialog/AlertDialog';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {Button} from '../Button/Button';
+import {EmptyState} from '../EmptyState/EmptyState';
+import {PanelSearchInput} from '../Field/PanelSearchInput';
+import {Icon} from '../Icon';
+import {CheckboxIndicator} from '../Indicator/CheckboxIndicator';
+import {Spinner} from '../Spinner';
+import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {useAnnounce} from '../hooks/useAnnounce';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
+import {Text} from '../Text/Text';
+import {useTranslator} from '../i18n';
+import {warnOnce} from '../utils/devWarning';
+import type {SearchableItem, SearchSource} from '../Typeahead/types';
+import {colorVars, radiusVars, spacingVars} from '../theme/tokens.stylex';
+
+/**
+ * Sentinel prefix for the create row's synthetic item. Kept identical to the
+ * inline field's so Tokenizer's `handleAdd` recognizes it and turns it into a
+ * real item with a `create` change.
+ */
+const CREATABLE_ID_PREFIX = '__xds_create__';
+/** Rows rendered per batch while a long list scrolls (`component:Tokenizer` FR21). */
+export const LIST_RENDER_BATCH_SIZE = 50;
+const EMPTY_RESULTS: never[] = [];
+/** Distance from the list's end at which the next batch renders. */
+const LIST_LOAD_MORE_THRESHOLD_PX = 200;
+
+const styles = stylex.create({
+ body: {
+ display: 'flex',
+ flexDirection: 'column',
+ height: '100%',
+ minHeight: 0,
+ paddingInline: spacingVars['--spacing-3'],
+ paddingBlockStart: spacingVars['--spacing-8'],
+ paddingBlockEnd: spacingVars['--spacing-3'],
+ },
+ // The sheet has no dedicated close button; it keeps BottomSheet's gesture,
+ // scrim, and Escape dismissal paths, and the footer's Done.
+ searchRow: {
+ paddingBlockEnd: spacingVars['--spacing-2'],
+ },
+ // PanelSearchInput sizes its field to the 32px option rows of a dropdown
+ // panel. The sheet's rows are 44px thumb targets, so the field grows to
+ // match them and the query reads as the first row of the list.
+ searchField: {
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-2'],
+ },
+ list: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ overflowY: 'auto',
+ minHeight: 0,
+ },
+ rows: {
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ rowItem: {
+ display: 'contents',
+ },
+ row: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ width: '100%',
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-1'],
+ borderWidth: 0,
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-primary'],
+ fontFamily: 'inherit',
+ textAlign: 'start',
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ },
+ // An aria-disabled row gets no system disabled paint in forced colors;
+ // GrayText is the platform's disabled affordance there. The default repeats
+ // the base value, since StyleX merges per property.
+ rowDisabled: {
+ color: {
+ default: colorVars['--color-text-primary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ rowLabel: {
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ // Same for the indicator's border: GrayText in forced colors, and the
+ // default repeats the indicator's disabled border.
+ indicatorDisabled: {
+ borderColor: {
+ default: colorVars['--color-border'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ createRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ width: '100%',
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-1'],
+ },
+ createLabel: {
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ footer: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ paddingBlockStart: spacingVars['--spacing-3'],
+ marginTop: 'auto',
+ },
+ footerAction: {
+ flexGrow: 1,
+ flexBasis: 0,
+ },
+ emptyHost: {
+ display: 'contents',
+ },
+ empty: {
+ flexGrow: 1,
+ },
+ pending: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-2'],
+ },
+});
+
+export interface TokenizerBottomSheetProps<T extends SearchableItem> {
+ /** Whether the sheet is open. */
+ isOpen: boolean;
+ /** Called with `false` when the sheet dismisses or Done is pressed. */
+ onOpenChange: (isOpen: boolean) => void;
+ /** The trigger, which takes focus back after the sheet closes. */
+ finalFocusRef: RefObject<HTMLElement | null>;
+ /**
+ * The query this presentation starts with. The sheet is mounted only from
+ * a press until its exit completes, so the field keeps the query between
+ * mounts from what `onChangeQuery` reported: a close the field forces
+ * (becoming disabled while open) keeps it, as nothing the person did
+ * changed it, while a close the person makes clears and reports it
+ * (`component:Tokenizer` FR18).
+ */
+ initialQuery: string;
+ /** The field label; names the sheet, the search field, and the list. */
+ label: string;
+ searchSource: SearchSource<T>;
+ /** The committed selection. */
+ value: T[];
+ /** Whether `maxEntries` is reached. */
+ isAtMax: boolean;
+ hasCreate: boolean;
+ maxMenuItems: number;
+ minQueryLength: number;
+ debounceMs: number;
+ /** The no-results message; a string becomes the empty state's title. */
+ emptySearchText: ReactNode;
+ /**
+ * Tokenizer's add path — duplicate checks and the create sentinel — asked
+ * to stay silent: the sheet announces the change itself, from inside its
+ * dialog, where `useAnnounce` routes it (`spec:AST-086` FR14). Returns
+ * whether the item was added.
+ */
+ onAdd: (item: T, options: {silent: true}) => boolean;
+ /** Tokenizer's remove path, silent for the same reason. */
+ onRemove: (item: T, options: {silent: true}) => boolean;
+ /** Tokenizer's clear-all path. */
+ onClearAll: () => void;
+ onChangeQuery?: (query: string) => void;
+}
+
+/**
+ * The touch surface of Tokenizer's `bottom-sheet` presentation.
+ *
+ * Rows keep their position while the sheet is open: the items selected when it
+ * opened lead, in `value` order, then selected items the results do not carry,
+ * then the results. Toggling a row changes its checkbox and nothing else; the
+ * next open takes a fresh snapshot and regroups selected-first.
+ */
+/**
+ * The sheet: BottomSheet around the content. Split in two so the content —
+ * search, rows, footer, and every announcement about them — is rendered
+ * inside the sheet's dialog, where `useAnnounce` routes into it while it is
+ * open (`spec:AST-086` FR14): a component that renders a modal and announces
+ * about its content is inside that modal only when the announcing code is.
+ *
+ * The outer part also tells the content how a close came about: a close the
+ * person made (Done, swipe, scrim, Escape) clears the query so the next open
+ * lists the bootstrap set, while a close the field forced (becoming disabled
+ * while open) keeps it (`component:Tokenizer` FR18).
+ */
+export function TokenizerBottomSheet<T extends SearchableItem>({
+ isOpen,
+ onOpenChange,
+ finalFocusRef,
+ label,
+ ...content
+}: TokenizerBottomSheetProps<T>) {
+ // The content owns the query; a close the person makes clears it through
+ // this handle, from the closing event, so a close the field forces by
+ // becoming disabled (which never comes through here) keeps it.
+ const clearQueryRef = useRef<(() => void) | null>(null);
+ const requestClose = () => {
+ clearQueryRef.current?.();
+ onOpenChange(false);
+ };
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={next => {
+ if (next) {
+ onOpenChange(true);
+ } else {
+ requestClose();
+ }
+ }}
+ finalFocusRef={finalFocusRef}
+ label={label}
+ height="tall"
+ padding={0}>
+ <TokenizerSheetContent
+ {...content}
+ isOpen={isOpen}
+ label={label}
+ clearQueryRef={clearQueryRef}
+ onRequestClose={requestClose}
+ />
+ </BottomSheet>
+ );
+}
+
+TokenizerBottomSheet.displayName = 'TokenizerBottomSheet';
+
+type TokenizerSheetContentProps<T extends SearchableItem> = Omit<
+ TokenizerBottomSheetProps<T>,
+ 'onOpenChange' | 'finalFocusRef'
+> & {
+ /** Set by the content: clears and reports its query; called on a user close. */
+ clearQueryRef: RefObject<(() => void) | null>;
+ /** Close the sheet as the person's own act (Done). */
+ onRequestClose: () => void;
+};
+
+function TokenizerSheetContent<T extends SearchableItem>({
+ isOpen,
+ initialQuery,
+ clearQueryRef,
+ onRequestClose,
+ label,
+ searchSource,
+ value,
+ isAtMax,
+ hasCreate,
+ maxMenuItems,
+ minQueryLength,
+ debounceMs,
+ emptySearchText,
+ onAdd,
+ onRemove,
+ onClearAll,
+ onChangeQuery,
+}: TokenizerSheetContentProps<T>) {
+ const t = useTranslator();
+ const searchRef = useRef<HTMLInputElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ // Whether a checkbox row holds focus, kept by the list's own focus events,
+ // so the hand-off below fires only when it was a row that a settled search
+ // removed — not the search field or a footer action.
+ const isRowFocusedRef = useRef(false);
+ // The Clear all confirmation is in the DOM only from the Clear all press
+ // until it closes — mounted open, as the sheet itself is mounted from the
+ // trigger's press — so an open sheet with no confirmation pending carries
+ // no closed dialog (`architecture:component-style-authoring` INV7). Dialog
+ // has an entrance animation and no exit, so a close is its unmount; the
+ // sheet then places focus itself, in the Effect below, once the modal is
+ // gone and the sheet's content can take focus again: on the search field
+ // after a confirmed clear — the clear is spent, and the search field is
+ // where the next selection starts (FR24, `spec:AST-085` FR4) — and back on
+ // Clear all after a cancel. A confirmed clear is announced there too — a
+ // change the person hears about, as an add or a remove is
+ // (`component:Tokenizer` AR6) — after the confirmation's dialog has gone,
+ // so the sheet is the modal on top and the words are delivered inside it
+ // (`spec:AST-086` FR14), not into a covered sheet. Every announcement the
+ // sheet makes goes through `useAnnounce`, called inside the sheet's
+ // dialog, so FR14 routes the words into it while the sheet is open.
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
+ const clearAllRef = useRef<HTMLButtonElement>(null);
+ const afterConfirmationRef = useRef<'search' | 'clear-all' | null>(null);
+ const announce = useAnnounce();
+ const closeClearConfirmation = (confirmed: boolean) => {
+ afterConfirmationRef.current = confirmed ? 'search' : 'clear-all';
+ setIsClearConfirmationOpen(false);
+ };
+ useEffect(() => {
+ if (isClearConfirmationOpen || afterConfirmationRef.current == null) {
+ return;
+ }
+ const destination = afterConfirmationRef.current;
+ afterConfirmationRef.current = null;
+ if (destination === 'search') {
+ searchRef.current?.focus();
+ announce(t('@astryx.tokenizer.allRemoved'));
+ } else {
+ clearAllRef.current?.focus();
+ }
+ }, [announce, isClearConfirmationOpen, t]);
+ const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);
+
+ // ---- sheet session ----
+ // Starts from the field's copy, which `onChangeQuery` keeps current, so the
+ // query survives the sheet's unmount between presentations (FR18).
+ const [query, setQuery] = useState(initialQuery);
+ const [sourceResults, setSourceResults] = useState<T[]>([]);
+ const trimmedQueryForSearch = query.trim();
+ // A query shorter than `minQueryLength` is never searched: no source rows,
+ // no busy feedback, no empty state, no outcome announcement, as the inline
+ // field shows nothing for such a query (`component:Tokenizer` FR20).
+ const isBelowMinQuery =
+ trimmedQueryForSearch !== '' &&
+ trimmedQueryForSearch.length < minQueryLength;
+ const results = isBelowMinQuery ? EMPTY_RESULTS : sourceResults;
+ // Whether a query is one the source is asked about: empty (the bootstrap
+ // set) or at least `minQueryLength`. Below that nothing is searched, so
+ // nothing is pending and no outcome is owed. One rule for every way a query
+ // comes to be: the initial one, an open, a change.
+ const willSearchFor = (trimmed: string) =>
+ trimmed === '' || trimmed.length >= minQueryLength;
+ // Pending from open, and from each query change, until that search settles
+ // (`component:Tokenizer` FR20). Set where the change happens rather than in
+ // the Effect, so the debounce window never shows a stale empty state. The
+ // sheet mounts already open (the field mounts it from the press), so its
+ // first render is its open: the initial state is derived from the initial
+ // query the way an open derives it — a kept query below the threshold
+ // (after a close the field forced, FR18) starts settled, not pending for a
+ // search that never runs.
+ const [isPending, setIsPending] = useState(
+ () => !isOpen || willSearchFor(initialQuery.trim()),
+ );
+ const emptyStateRef = useRef<HTMLDivElement>(null);
+ // Each search that runs gets a number; its outcome is announced once, keyed
+ // on that number, so a stale effect from an earlier commit cannot claim a
+ // newer search's announcement and a rerender cannot repeat one. A first
+ // render whose query is not searched owes no announcement for search 0.
+ const [searchId, setSearchId] = useState(0);
+ const searchIdRef = useRef(0);
+ const announcedSearchIdRef = useRef(
+ isOpen && !willSearchFor(initialQuery.trim()) ? 0 : -1,
+ );
+ const startSearch = () => {
+ searchIdRef.current += 1;
+ setSearchId(searchIdRef.current);
+ };
+ const [renderedItemCount, setRenderedItemCount] = useState(
+ LIST_RENDER_BATCH_SIZE,
+ );
+ const seqRef = useRef(0);
+ const lastLoadScrollHeightRef = useRef<number | null>(null);
+ const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);
+
+ // Snapshot the selection and reset the rendered window in the render that
+ // opens the sheet, so the first open frame already shows selected-first
+ // order — an effect would paint one frame of the previous session's order.
+ const [wasOpen, setWasOpen] = useState(isOpen);
+ if (isOpen !== wasOpen) {
+ setWasOpen(isOpen);
+ if (isOpen) {
+ setSelectedItemsAtOpen(value);
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ // An open lists the bootstrap set, or searches a query kept across a
+ // close the field forced (FR18), and that load is pending; a kept
+ // query below the threshold leaves nothing pending, since no search
+ // runs for it.
+ const willSearch = willSearchFor(trimmedQueryForSearch);
+ setIsPending(willSearch);
+ if (willSearch) {
+ startSearch();
+ } else {
+ announcedSearchIdRef.current = searchIdRef.current;
+ }
+ lastLoadScrollHeightRef.current = null;
+ }
+ }
+
+ // Done, swipe, scrim, and Escape alike clear the query, so the next open
+ // lists the bootstrap set (FR18); a close the field forced (becoming
+ // disabled while open) keeps it, since nothing the person did changed it.
+ // Cleared and reported from the closing event through this handle, never
+ // from render (`architecture:react-component-runtime` INV2).
+ useImperativeHandle(
+ clearQueryRef,
+ () => () => {
+ if (query !== '') {
+ setQuery('');
+ onChangeQuery?.('');
+ }
+ },
+ [query, onChangeQuery],
+ );
+
+ // The source is read through a ref at request time, as the inline field
+ // reads it inside its search callbacks: a caller that rebuilds the source
+ // object in render (`searchSource={{search, bootstrap}}`) then causes no
+ // new request on an unrelated render — a row toggle, a selection change —
+ // and the sheet asks the source only on open, on a query change, and on
+ // clearing. The ref is updated in a layout effect, before any request this
+ // commit makes.
+ const searchSourceRef = useRef(searchSource);
+ useIsomorphicLayoutEffect(() => {
+ searchSourceRef.current = searchSource;
+ }, [searchSource]);
+ // Synchronizes the row list with the caller's `searchSource`, an external
+ // system this component does not own: it asks the source for the bootstrap
+ // set or the query's results and copies the answer into state. The
+ // bootstrap set is requested at once — on open and when the query clears —
+ // as the inline field requests its focus bootstrap; only a typed query
+ // waits `debounceMs`. A layout effect, so a source that answers
+ // synchronously settles before the browser paints the open commit: the
+ // Loading row never reaches the screen and no busy start is announced for
+ // it (`component:Tokenizer` FR20). Cleanup clears the debounce timer so a
+ // superseded query never fetches, and the sequence guard drops a response
+ // that lands after a newer request, so the list never shows stale results
+ // (`architecture:react-component-runtime` INV3).
+ useIsomorphicLayoutEffect(() => {
+ if (!isOpen) {
+ return;
+ }
+ const trimmed = query.trim();
+ const seq = ++seqRef.current;
+ if (trimmed !== '' && trimmed.length < minQueryLength) {
+ // Not searched; the derived `results` are already empty, and taking a
+ // sequence number retires a still-running search so its rows cannot
+ // land under this query.
+ return;
+ }
+ const settle = (items: T[]) => {
+ if (seqRef.current === seq) {
+ setSourceResults(items.slice(0, maxMenuItems));
+ setIsPending(false);
+ }
+ };
+ const run = () => {
+ let answer: T[] | PromiseLike<T[]>;
+ const source = searchSourceRef.current;
+ try {
+ answer = trimmed === '' ? source.bootstrap() : source.search(query);
+ } catch {
+ answer = [];
+ }
+ if (Array.isArray(answer)) {
+ // An instant source settles in the same tick, before any busy
+ // feedback or announcement could start.
+ settle(answer);
+ return;
+ }
+ // Anything else is awaited as a thenable — a native Promise, one from
+ // another realm, or a library's — as the inline field's `await` does.
+ void Promise.resolve(answer).then(settle, () => {
+ // A rejecting source settles to no results, as the inline field does:
+ // the previous query's rows are not this query's answer.
+ settle([]);
+ });
+ };
+ if (trimmed !== '' && debounceMs > 0) {
+ const timer = setTimeout(run, debounceMs);
+ return () => clearTimeout(timer);
+ }
+ run();
+ }, [isOpen, query, minQueryLength, maxMenuItems, debounceMs]);
+
+ const visibleItems = useMemo(() => {
+ const normalizedQuery = query.trim().toLowerCase();
+ const matchesQuery = (item: T) =>
+ normalizedQuery === '' ||
+ item.label.toLowerCase().includes(normalizedQuery);
+ const selectedAtOpenMatches = selectedItemsAtOpen.filter(matchesQuery);
+ const selectedAtOpenIds = new Set(
+ selectedAtOpenMatches.map(item => item.id),
+ );
+ const resultIds = new Set(results.map(item => item.id));
+ const selectedItemsMissingFromResults = value.filter(
+ item =>
+ !selectedAtOpenIds.has(item.id) &&
+ !resultIds.has(item.id) &&
+ matchesQuery(item),
+ );
+
+ // Selection changes update checkbox state without moving an existing row.
+ // The next open snapshots the latest value and applies selected-first order.
+ return [
+ ...selectedAtOpenMatches,
+ ...selectedItemsMissingFromResults,
+ ...results.filter(item => !selectedAtOpenIds.has(item.id)),
+ ];
+ }, [query, results, selectedItemsAtOpen, value]);
+
+ const renderedItems = visibleItems.slice(0, renderedItemCount);
+
+ // A settled search may remove the row that holds focus: it was listed from
+ // the previous search and is not in this one. Focus would fall to the page
+ // body behind the modal; the search field takes it instead, where the next
+ // query starts (FR20, `spec:AST-085` FR4).
+ useEffect(() => {
+ if (!isOpen || isPending || !isRowFocusedRef.current) {
+ return;
+ }
+ const active = document.activeElement;
+ if (active == null || active === document.body) {
+ isRowFocusedRef.current = false;
+ searchRef.current?.focus();
+ }
+ }, [isOpen, isPending, renderedItems]);
+
+ // `action` is declared on `SearchableItem` for the grid-adopting hosts; the
+ // sheet rows have not adopted it, so a row renders the item without the
+ // control and says so (`spec:AST-058` FR9), as the inline panel does.
+ useEffect(() => {
+ if (results.some(item => item.action != null)) {
+ warnOnce(
+ 'tokenizer-sheet:item-action',
+ 'Tokenizer',
+ 'A result carries `action`, which the bottom-sheet rows do not render ' +
+ 'yet; the item is shown without it.',
+ );
+ }
+ }, [results]);
+
+ // The pending Spinner below stays named, as the inline field's does
+ // (`family:input-fields` FR7), but is not a live region; the sheet announces
+ // each busy start once, through the region inside its own modal dialog
+ // (`spec:AST-086` FR8, FR14).
+ useBusyAnnouncement(
+ isOpen && isPending,
+ t('@astryx.typeahead.loading'),
+ listRef,
+ );
+
+ const trimmedQuery = query.trim();
+ const createItem = useMemo<T | null>(() => {
+ // Judged against this query's own results: while the search is pending
+ // `results` still hold the previous query's rows, and a create row then
+ // could offer a value the source already has.
+ if (!hasCreate || trimmedQuery === '' || isAtMax || isPending) {
+ return null;
+ }
+ const lowered = trimmedQuery.toLowerCase();
+ if (
+ selectedIds.has(trimmedQuery) ||
+ value.some(item => item.label.toLowerCase() === lowered) ||
+ results.some(item => item.label.toLowerCase() === lowered)
+ ) {
+ return null;
+ }
+ return {
+ id: `${CREATABLE_ID_PREFIX}${trimmedQuery}`,
+ label: t('@astryx.tokenizer.create', {value: trimmedQuery}),
+ } as unknown as T;
+ }, [
+ hasCreate,
+ trimmedQuery,
+ isAtMax,
+ isPending,
+ selectedIds,
+ value,
+ results,
+ t,
+ ]);
+
+ const resetListWindow = () => {
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ };
+
+ const handleQueryChange = (next: string) => {
+ resetListWindow();
+ const willSearch = willSearchFor(next.trim());
+ // A search still unsettled from the previous query is retired
+ // unannounced, so "0 results" is never said for a query that was never
+ // searched. Only a query that runs gets a search number.
+ setIsPending(willSearch);
+ if (willSearch) {
+ startSearch();
+ } else {
+ announcedSearchIdRef.current = searchIdRef.current;
+ }
+ setQuery(next);
+ onChangeQuery?.(next);
+ };
+
+ const searchLabel = t('@astryx.tokenizer.search', {label});
+ // An empty state only once the search has settled; while pending the busy
+ // row above stands in for it.
+ const isQueryEmpty = trimmedQuery === '';
+ // An empty state is a searched query's answer. An empty query that lists
+ // nothing — nothing selected and a source whose bootstrap set is empty,
+ // such as a search-only source — shows only the search field, no list, no
+ // message, and announces nothing, as the inline field opens no menu and
+ // reports nothing for a bootstrap that returned nothing (`component:Tokenizer`
+ // FR20): nothing has failed, typing is what finds items.
+ const isSettledEmpty =
+ !isPending &&
+ !isBelowMinQuery &&
+ !isQueryEmpty &&
+ visibleItems.length === 0 &&
+ createItem == null;
+ const isSettledBlank =
+ !isPending &&
+ !isBelowMinQuery &&
+ isQueryEmpty &&
+ visibleItems.length === 0 &&
+ createItem == null;
+ const noResultsTitle =
+ typeof emptySearchText === 'string'
+ ? emptySearchText
+ : t('@astryx.typeahead.emptySearchResults');
+
+ // How each search ended, once per settle (`component:Tokenizer` AR6),
+ // keyed on the search's number. The result count is an action announcement
+ // this owner makes. The empty state's words are rendered content: the
+ // default EmptyState announces its own title and description once when it
+ // appears (its own contract, `spec:AST-086` FR2, FR11), so the sheet speaks
+ // nothing for it; a caller's `emptySearchText` element is the sheet's own
+ // rendered content, so the shared own-content module reads and speaks it
+ // (`spec:AST-056` FR3, `architecture:react-component-runtime` INV10). Both
+ // go through `useAnnounce`, which, called from inside the sheet's dialog,
+ // routes into it while the sheet is open (`spec:AST-086` FR14).
+ const hasCustomEmptyElement =
+ typeof emptySearchText !== 'string' && emptySearchText != null;
+ useAnnounceRenderedText(
+ emptyStateRef,
+ isOpen && isSettledEmpty && hasCustomEmptyElement,
+ String(searchId),
+ );
+ useEffect(() => {
+ if (!isOpen || isPending || announcedSearchIdRef.current === searchId) {
+ return;
+ }
+ announcedSearchIdRef.current = searchId;
+ if (!isSettledEmpty && !isQueryEmpty) {
+ // The rows the sheet lists for this query — the source's results,
+ // capped by `maxMenuItems`, selected items the source did not return,
+ // such as a created value, and the create row when it is offered — as
+ // the inline field announces the entries it shows (its create entry
+ // included), not the source's count.
+ announce(
+ t('@astryx.typeahead.resultCount', {
+ count: visibleItems.length + (createItem == null ? 0 : 1),
+ }),
+ );
+ }
+ }, [
+ announce,
+ createItem,
+ isOpen,
+ isPending,
+ isQueryEmpty,
+ isSettledEmpty,
+ visibleItems.length,
+ searchId,
+ t,
+ ]);
+
+ return (
+ <div {...stylex.props(styles.body)}>
+ <div {...stylex.props(styles.searchRow)}>
+ <PanelSearchInput
+ ref={searchRef}
+ label={searchLabel}
+ clearLabel={t('@astryx.textInput.clearLabel', {label: searchLabel})}
+ placeholder={t('@astryx.tokenizer.searchPlaceholder')}
+ value={query}
+ onValueChange={handleQueryChange}
+ fieldXstyle={styles.searchField}
+ />
+ </div>
+ {/* The sheet's own content area is already a group named by the
+ label; naming this list the same would announce it twice. */}
+ <div
+ ref={listRef}
+ {...stylex.props(styles.list)}
+ aria-busy={isPending || undefined}
+ data-rendered-count={renderedItems.length}
+ data-total-count={visibleItems.length}
+ onFocusCapture={event => {
+ isRowFocusedRef.current =
+ event.target instanceof HTMLElement &&
+ event.target.getAttribute('role') === 'checkbox';
+ }}
+ onBlurCapture={event => {
+ // A row unmounted while focused fires no blur, so a blur that
+ // does arrive is a real move elsewhere.
+ if (event.relatedTarget != null) {
+ isRowFocusedRef.current = false;
+ }
+ }}
+ onScroll={event => {
+ const list = event.currentTarget;
+ const distanceFromBottom =
+ list.scrollHeight - list.scrollTop - list.clientHeight;
+ if (
+ distanceFromBottom <= LIST_LOAD_MORE_THRESHOLD_PX &&
+ lastLoadScrollHeightRef.current !== list.scrollHeight
+ ) {
+ lastLoadScrollHeightRef.current = list.scrollHeight;
+ setRenderedItemCount(current =>
+ Math.min(current + LIST_RENDER_BATCH_SIZE, visibleItems.length),
+ );
+ }
+ }}>
+ {createItem ? (
+ <div {...stylex.props(styles.createRow)}>
+ <Text type="body" xstyle={styles.createLabel}>
+ {createItem.label}
+ </Text>
+ <Button
+ label={t('@astryx.tokenizer.add')}
+ aria-label={t('@astryx.tokenizer.addValue', {
+ value: trimmedQuery,
+ })}
+ variant="secondary"
+ size="lg"
+ onClick={() => {
+ if (onAdd(createItem, {silent: true})) {
+ // The created value, as the inline field announces it; the
+ // item's label is the row's caption ("Create …").
+ announce(
+ t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),
+ );
+ }
+ // The same path a typed change takes, so the bootstrap
+ // reload shows its pending state and reports the change.
+ handleQueryChange('');
+ // The row this control sits on is gone with the query; the
+ // search field is where the next value starts (FR22).
+ searchRef.current?.focus();
+ }}
+ />
+ </div>
+ ) : null}
+ {isPending ? (
+ // Named busy feedback while the source works
+ // (`family:input-fields` FR7), above any rows still listed from
+ // the previous search; the empty states wait for it.
+ <div {...stylex.props(styles.pending)}>
+ <Spinner
+ size="md"
+ role="img"
+ aria-label={t('@astryx.typeahead.loading')}
+ />
+ </div>
+ ) : null}
+ {isSettledEmpty ? (
+ <div ref={emptyStateRef} {...stylex.props(styles.emptyHost)}>
+ {hasCustomEmptyElement ? (
+ <div {...stylex.props(styles.empty)}>{emptySearchText}</div>
+ ) : (
+ <EmptyState
+ icon={<Icon icon="search" size="lg" color="secondary" />}
+ title={noResultsTitle}
+ description={t('@astryx.tokenizer.noResultsDescription')}
+ isCompact
+ xstyle={styles.empty}
+ />
+ )}
+ </div>
+ ) : isSettledBlank ? null : (
+ // A list of items: each listitem carries its place in the whole
+ // set, not the rendered window, so a person moving through the
+ // rows hears "n of total" and learns more exist before the list
+ // has scrolled (FR21). The position attributes live on the
+ // listitem because `checkbox` does not admit them.
+ <div role="list" {...stylex.props(styles.rows)}>
+ {renderedItems.map((item, index) => {
+ const isSelected = selectedIds.has(item.id);
+ const rowDisabled = !isSelected && isAtMax;
+ const isLastRendered = index === renderedItems.length - 1;
+ return (
+ <div
+ key={item.id}
+ role="listitem"
+ aria-setsize={visibleItems.length}
+ aria-posinset={index + 1}
+ {...stylex.props(styles.rowItem)}>
+ <button
+ type="button"
+ role="checkbox"
+ aria-checked={isSelected}
+ aria-label={item.label}
+ aria-disabled={rowDisabled || undefined}
+ onFocus={
+ isLastRendered &&
+ renderedItems.length < visibleItems.length
+ ? () => {
+ // Focus reaching the last rendered row renders the
+ // next batch, so Tab and arrow keys reach every row
+ // without a scroll (FR21).
+ setRenderedItemCount(current =>
+ Math.min(
+ current + LIST_RENDER_BATCH_SIZE,
+ visibleItems.length,
+ ),
+ );
+ }
+ : undefined
+ }
+ onClick={() => {
+ if (rowDisabled) {
+ return;
+ }
+ if (isSelected) {
+ if (onRemove(item, {silent: true})) {
+ announce(
+ t('@astryx.tokenizer.tokenRemoved', {
+ label: item.label,
+ }),
+ );
+ }
+ } else if (onAdd(item, {silent: true})) {
+ announce(
+ t('@astryx.tokenizer.tokenAdded', {
+ label: item.label,
+ }),
+ );
+ }
+ }}
+ {...stylex.props(
+ styles.row,
+ rowDisabled && styles.rowDisabled,
+ )}>
+ <Text
+ type="body"
+ color={rowDisabled ? 'inherit' : undefined}
+ xstyle={styles.rowLabel}>
+ {item.label}
+ </Text>
+ <CheckboxIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
+ isDisabled={rowDisabled}
+ xstyle={
+ rowDisabled ? styles.indicatorDisabled : undefined
+ }
+ />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ {isQueryEmpty && (
+ <div {...stylex.props(styles.footer)}>
+ <Button
+ label={t('@astryx.tokenizer.clearAll')}
+ variant="secondary"
+ size="lg"
+ isDisabled={value.length === 0}
+ // With a tooltip, Button's disabled mode is `aria-disabled`: the
+ // action keeps its focus order and says why it does nothing
+ // (`spec:AST-085` FR1), instead of leaving the tab order as a
+ // natively disabled button does — a confirmed Clear all returns
+ // focus here before the search field takes it (FR24).
+ tooltip={
+ value.length === 0
+ ? t('@astryx.tokenizer.nothingToClear')
+ : undefined
+ }
+ ref={clearAllRef}
+ onClick={() => setIsClearConfirmationOpen(true)}
+ xstyle={styles.footerAction}
+ />
+ <Button
+ label={t('@astryx.tokenizer.done')}
+ variant="primary"
+ size="lg"
+ onClick={onRequestClose}
+ xstyle={styles.footerAction}
+ />
+ </div>
+ )}
+ {isClearConfirmationOpen && (
+ <AlertDialog
+ isOpen
+ onOpenChange={next => {
+ if (!next) {
+ closeClearConfirmation(false);
+ }
+ }}
+ title={t('@astryx.tokenizer.clearAllTitle')}
+ description={t('@astryx.tokenizer.clearAllDescription', {label})}
+ actionLabel={t('@astryx.tokenizer.clearSelection')}
+ onAction={() => {
+ onClearAll();
+ closeClearConfirmation(true);
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+TokenizerSheetContent.displayName = 'TokenizerSheetContent';
diff --git a/packages/core/src/hooks/useAdaptivePresentation.ts b/packages/core/src/hooks/useAdaptivePresentation.ts
index df5dcbd507..162155082f 100644
--- a/packages/core/src/hooks/useAdaptivePresentation.ts
+++ b/packages/core/src/hooks/useAdaptivePresentation.ts
@@ -4,17 +4,17 @@
/**
* @file useAdaptivePresentation.ts
- * @input Uses the shared SSR-safe media-query hook and the touch
- * presentation's compact-touch query
+ * @input Uses React's external-store subscription over window.matchMedia
+ * and the touch presentation's compact-touch query
* @output Resolves popover/bottom-sheet presentation policy
* @position Internal overlay policy shared across component families
*/
+import {useCallback, useSyncExternalStore} from 'react';
import {
COMPACT_TOUCH_QUERY,
useCompactDefinition,
} from '../utils/touchPresentation';
-import {useMediaQuery} from './useMediaQuery';
export type AdaptivePresentation = 'popover' | 'bottom-sheet' | 'adaptive';
export type ResolvedAdaptivePresentation = Exclude<
@@ -28,13 +28,43 @@ export type ResolvedAdaptivePresentation = Exclude<
// this constant is its value at the default width points.
export const COMPACT_TOUCH_PRESENTATION_QUERY = COMPACT_TOUCH_QUERY;
+const noSubscription = () => () => {};
+const notCompact = () => false;
+
+/**
+ * Resolve `adaptive` against the active theme's compact-touch query
+ * (`useCompactDefinition()`, so a theme that moves `md` is honored —
+ * spec:AST-012 FR9). Only an `adaptive` presentation subscribes to
+ * `matchMedia`; a fixed presentation never reads the query, so it holds no
+ * listener for it (`architecture:react-component-runtime` INV5). SSR-safe:
+ * the server snapshot is "not compact", as `useMediaQuery`'s default is.
+ */
export function useAdaptivePresentation(
presentation: AdaptivePresentation,
): ResolvedAdaptivePresentation {
- const isCompactTouch = useMediaQuery(
- useCompactDefinition().coarsePointerQuery,
+ const isAdaptive = presentation === 'adaptive';
+ const query = useCompactDefinition().coarsePointerQuery;
+ const subscribe = useCallback(
+ (onStoreChange: () => void) => {
+ if (!isAdaptive) {
+ return noSubscription();
+ }
+ const mql = window.matchMedia(query);
+ mql.addEventListener('change', onStoreChange);
+ return () => mql.removeEventListener('change', onStoreChange);
+ },
+ [isAdaptive, query],
+ );
+ const getSnapshot = useCallback(
+ () => (isAdaptive ? window.matchMedia(query).matches : false),
+ [isAdaptive, query],
+ );
+ const isCompactTouch = useSyncExternalStore(
+ subscribe,
+ getSnapshot,
+ notCompact,
);
- return presentation === 'adaptive'
+ return isAdaptive
? isCompactTouch
? 'bottom-sheet'
: 'popover'
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
index f4a8c6a109..0f7f246d45 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
@@ -62,6 +62,7 @@ const {Selector} = await import('../Selector');
const {MultiSelector} = await import('../MultiSelector');
const {CommandPalette} = await import('../CommandPalette');
const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');
+const {Tokenizer} = await import('../Tokenizer/Tokenizer');
const {createStaticSource} = await import('../Typeahead/createStaticSource');
const source = createStaticSource([{id: 'apple', label: 'Apple'}]);
@@ -160,6 +161,26 @@ const ADOPTERS: Record<string, () => Promise<void>> = {
fireEvent.change(screen.getByRole('combobox'), {target: {value: 'zzz'}});
await expectDelegated('No results found');
},
+ 'Tokenizer/TokenizerBottomSheet.tsx': async () => {
+ // The sheet's own content is a caller's `emptySearchText` element; the
+ // default EmptyState announces itself.
+ render(
+ <Tokenizer
+ label="Tags"
+ searchSource={source}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ emptySearchText={<em>Nothing called that</em>}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Tags'}));
+ fireEvent.change(await screen.findByLabelText('Search Tags'), {
+ target: {value: 'zzz'},
+ });
+ await expectDelegated('Nothing called that');
+ },
};
describe('own-content announcement adopters (react-component-runtime INV10)', () => {