An open source design system that's fully customizable and agent ready
TypeScript
chore(lab): remove MobileTokenizer and MobilePowerSearch, whose flows Core ships behind experimental.presentation (#9790)
Xinzi Zhou19081d81abab
diff --git a/.changeset/cli-discover-lab-mobile-sheets-removed.md b/.changeset/cli-discover-lab-mobile-sheets-removed.mdnew file mode 100644index 0000000000..7a1427ba2c--- /dev/null+++ b/.changeset/cli-discover-lab-mobile-sheets-removed.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[chore] `astryx discover` no longer lists the Lab components `MobileTokenizer` and `MobilePowerSearch`, which are removed from `@astryxdesign/lab`; their touch flows are Core's Tokenizer and PowerSearch `experimental.presentation` sheets.++@imdreamrunnerdiff --git a/.changeset/core-internal-touch-sheet-entry-removed.md b/.changeset/core-internal-touch-sheet-entry-removed.mdnew file mode 100644index 0000000000..6dcca16d29--- /dev/null+++ b/.changeset/core-internal-touch-sheet-entry-removed.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[chore] Internal: the undocumented `@astryxdesign/core/internal/touch-sheet` entry is removed. It re-exported the touch sheets' confirmation, search-drag dismissal and draft rules for the Lab prototypes of the Tokenizer and PowerSearch sheet presentations, which no longer exist; Core's sheets import the same modules by relative path. Internal entries are outside the public API and its compatibility promise.++@imdreamrunnerdiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex c2d1b6d9ad..e04b62b2e6 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -550,24 +550,6 @@"overlayRoot": "body"}},- {- "component": "MobilePowerSearch",- "storyId": "lab-mobilepowersearch--touch-flow",- "dims": ["D2"],- "selectors": {- "prev": ".astryx-token:has-text(\"Status\")",- "next": ".astryx-token:has-text(\"Priority\")"- }- },- {- "component": "MobileTokenizer",- "storyId": "lab-mobiletokenizer--touch-flow",- "dims": ["D2"],- "selectors": {- "prev": ".astryx-token:has-text(\"Design\")",- "next": ".astryx-token:has-text(\"Eng\")"- }- },{"component": "MoreMenu","storyId": "core-moremenu--default",diff --git a/apps/storybook/stories/MobilePowerSearch.stories.tsx b/apps/storybook/stories/MobilePowerSearch.stories.tsxdeleted file mode 100644index c09ee959de..0000000000--- a/apps/storybook/stories/MobilePowerSearch.stories.tsx+++ /dev/null@@ -1,364 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file MobilePowerSearch.stories.tsx- * @input Uses MobilePowerSearch (Lab) with a representative PowerSearch config- * covering enum, enum_list, string, entity_list, integer, float, date and- * string_list operators, plus a content-search variant- * @output Storybook try-it stories at phone width (390px): the field-wide- * trigger with tokens, the Filters sheet, Add filter, the operator step,- * choice rows, and the inline content-search suggestions- * @position Lab story; touch PowerSearch prototype- */-import {useState} from 'react';-import type {Meta, StoryObj} from '@storybook/react';-import type {- PowerSearchConfig,- PowerSearchFilter,-} from '@astryxdesign/core/PowerSearch';-import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';-import {MobilePowerSearch} from '@astryxdesign/lab';--// =============================================================================-// Sample data (mirrors the Core PowerSearch "full" configuration)-// =============================================================================--const statusValues = [- {value: 'open', label: 'Open'},- {value: 'in_progress', label: 'In Progress'},- {value: 'review', label: 'In Review'},- {value: 'closed', label: 'Closed'},- {value: 'blocked', label: 'Blocked'},-];--const priorityValues = [- {value: 'p0', label: 'P0 - Critical'},- {value: 'p1', label: 'P1 - High'},- {value: 'p2', label: 'P2 - Medium'},- {value: 'p3', label: 'P3 - Low'},-];--const tagValues = [- {value: 'bug', label: 'Bug'},- {value: 'feature', label: 'Feature'},- {value: 'docs', label: 'Documentation'},- {value: 'perf', label: 'Performance'},- {value: 'security', label: 'Security'},- {value: 'ux', label: 'UX'},- {value: 'infra', label: 'Infrastructure'},-];--const users: SearchableItem[] = [- {id: 'user-1', label: 'Alice Johnson'},- {id: 'user-2', label: 'Bob Smith'},- {id: 'user-3', label: 'Charlie Brown'},- {id: 'user-4', label: 'Diana Prince'},- {id: 'user-5', label: 'Eve Williams'},- {id: 'user-6', label: 'Frank Miller'},-];--const userSource: SearchSource = {- search: (query: string) =>- users.filter(u => u.label.toLowerCase().includes(query.toLowerCase())),- bootstrap: () => users,-};--const fullConfig: PowerSearchConfig = {- name: 'FullSearch',- fields: [- {- key: 'status',- label: 'Status',- defaultOperator: 'any_of',- operators: [- {- key: 'any_of',- label: 'is any of',- value: {type: 'enum_list', values: statusValues},- },- {- key: 'none_of',- label: 'is none of',- value: {type: 'enum_list', values: statusValues},- },- ],- },- {- key: 'title',- label: 'Title',- defaultOperator: 'contains',- operators: [- {key: 'contains', label: 'contains', value: {type: 'string'}},- {- key: 'not_contains',- label: 'does not contain',- value: {type: 'string'},- },- ],- },- {- key: 'priority',- label: 'Priority',- defaultOperator: 'is',- operators: [- {- key: 'is',- label: 'is',- value: {type: 'enum', values: priorityValues},- },- ],- },- {- key: 'assignee',- label: 'Assignee',- defaultOperator: 'any_of',- typeaheadAliases: ['owner', 'assigned'],- operators: [- {- key: 'any_of',- label: 'is any of',- value: {type: 'entity_list', searchSource: userSource},- },- {- key: 'none_of',- label: 'is none of',- value: {type: 'entity_list', searchSource: userSource},- },- ],- },- {- key: 'tags',- label: 'Tags',- group: 'Metadata',- defaultOperator: 'include',- operators: [- {- key: 'include',- label: 'include',- value: {type: 'enum_list', values: tagValues},- },- {- key: 'exclude',- label: 'exclude',- value: {type: 'enum_list', values: tagValues},- },- ],- },- {- key: 'line_count',- label: 'Line count',- group: 'Metadata',- defaultOperator: 'gt',- operators: [- {- key: 'gt',- label: 'is greater than',- value: {- type: 'integer',- minValue: 0,- maxValue: 10000,- units: 'lines',- },- },- {- key: 'lt',- label: 'is less than',- value: {- type: 'integer',- minValue: 0,- maxValue: 10000,- units: 'lines',- },- },- ],- },- {- key: 'cost',- label: 'Cost',- group: 'Metadata',- defaultOperator: 'gt',- operators: [- {- key: 'gt',- label: '>',- value: {type: 'float', minValue: 0, maxValue: 100000, units: 'USD'},- },- {- key: 'lt',- label: '<',- value: {type: 'float', minValue: 0, maxValue: 100000, units: 'USD'},- },- ],- },- {- key: 'created',- label: 'Created',- group: 'Dates',- defaultOperator: 'after',- operators: [- {- key: 'after',- label: 'is after',- value: {type: 'date_absolute', isDateOnly: true},- },- {- key: 'newer_than',- label: 'is newer than',- value: {- type: 'date_relative',- isPastAllowed: true,- isFutureAllowed: false,- },- },- {key: 'between', label: 'is between', value: {type: 'date_range'}},- ],- },- {- key: 'ids',- label: 'ID',- defaultOperator: 'in',- operators: [- {key: 'in', label: 'is any of', value: {type: 'string_list'}},- ],- },- {- key: 'unread',- label: 'Only show unread',- defaultOperator: 'yes',- operators: [{key: 'yes', label: '', value: {type: 'empty'}}],- },- ],-};--const contentSearchConfig: PowerSearchConfig = {- ...fullConfig,- name: 'ContentSearch',- contentSearchFieldKey: 'title',-};--// =============================================================================-// Stories-// =============================================================================--const meta: Meta<typeof MobilePowerSearch> = {- title: 'Lab/MobilePowerSearch',- component: MobilePowerSearch,- parameters: {- layout: 'padded',- viewport: {defaultViewport: 'mobile2'},- },-};-export default meta;-type Story = StoryObj<typeof MobilePowerSearch>;--function PhoneFrame({children}: {children: React.ReactNode}) {- return <div style={{width: 390, maxWidth: '100%'}}>{children}</div>;-}--function FilterDump({filters}: {filters: ReadonlyArray<PowerSearchFilter>}) {- if (filters.length === 0) {- return null;- }- return (- <pre- style={{- marginTop: 16,- padding: 12,- borderRadius: 8,- fontSize: 12,- overflow: 'auto',- maxWidth: 390,- }}>- {JSON.stringify(filters, null, 2)}- </pre>- );-}--export const TouchFlow: Story = {- render: args => {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([- {- field: 'status',- operator: 'any_of',- value: {type: 'enum_list', value: ['open', 'in_progress']},- },- {field: 'priority', operator: 'is', value: {type: 'enum', value: 'p1'}},- {- field: 'created',- operator: 'after',- value: {type: 'date_absolute', unixSeconds: 1710039600},- },- ]);- return (- <PhoneFrame>- <MobilePowerSearch- {...args}- config={fullConfig}- filters={filters}- onChange={next => setFilters(next)}- timezoneID="America/Los_Angeles"- />- <FilterDump filters={filters} />- </PhoneFrame>- );- },- name: 'Touch flow (field-wide trigger, Filters sheet, drill-down)',-};--export const WithContentSearch: Story = {- render: args => {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>(- [],- );- return (- <PhoneFrame>- <MobilePowerSearch- {...args}- config={contentSearchConfig}- filters={filters}- onChange={next => setFilters(next)}- placeholder="Search issues…"- />- <FilterDump filters={filters} />- </PhoneFrame>- );- },- name: 'Content search (Add filter with inline suggestions)',-};--export const ReadOnlyAndDisabled: Story = {- render: () => {- const filters: ReadonlyArray<PowerSearchFilter> = [- {field: 'priority', operator: 'is', value: {type: 'enum', value: 'p0'}},- {- field: 'tags',- operator: 'include',- value: {type: 'enum_list', value: ['bug', 'security']},- isReadOnly: true,- },- ];- return (- <PhoneFrame>- <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>- <MobilePowerSearch- label="Read-only filters"- isLabelHidden={false}- config={fullConfig}- filters={filters}- onChange={() => {}}- isReadOnly- />- <MobilePowerSearch- label="Disabled filters"- isLabelHidden={false}- config={fullConfig}- filters={filters}- onChange={() => {}}- isDisabled- disabledMessage="Pick a project first"- />- </div>- </PhoneFrame>- );- },- name: 'Read-only and disabled',-};diff --git a/apps/storybook/stories/MobileTokenizer.stories.tsx b/apps/storybook/stories/MobileTokenizer.stories.tsxdeleted file mode 100644index 8b2b0bd064..0000000000--- a/apps/storybook/stories/MobileTokenizer.stories.tsx+++ /dev/null@@ -1,102 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file MobileTokenizer.stories.tsx- * @input Uses MobileTokenizer (Lab) with a 1,000-entry searchable dataset- * @output Storybook try-it story at 390px: one searchable management sheet- * with stable checkbox rows and enough entries to evaluate progressive- * list rendering- * @position Lab story; single-sheet touch-flow prototype- */-import {useState} from 'react';-import type {Meta, StoryObj} from '@storybook/react';-import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';-import {MobileTokenizer} from '@astryxdesign/lab';--const tags: 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 source: SearchSource = {- search: (q: string) =>- tags.filter(t => t.label.toLowerCase().includes(q.toLowerCase())),- bootstrap: () => tags,-};--const meta: Meta<typeof MobileTokenizer> = {- title: 'Lab/MobileTokenizer',- component: MobileTokenizer,-};-export default meta;-type Story = StoryObj<typeof MobileTokenizer>;--export const TouchFlow: Story = {- render: () => {- const [value, setValue] = useState<SearchableItem[]>([tags[0], tags[1]]);- return (- <div style={{width: 350}}>- <MobileTokenizer- label="Tags"- searchSource={source}- value={value}- onChange={items => setValue(items)}- placeholder="Add tags"- hasCreate- maxMenuItems={1000}- debounceMs={0}- />- </div>- );- },- name: 'Touch flow (single searchable management sheet)',-};--export const Disabled: Story = {- render: () => (- <div style={{width: 350, display: 'grid', gap: 16}}>- <MobileTokenizer- label="Tags"- searchSource={source}- value={[tags[0], tags[1]]}- onChange={() => {}}- placeholder="Add tags"- isDisabled- />- <MobileTokenizer- label="Empty tags"- searchSource={source}- value={[]}- onChange={() => {}}- placeholder="Add tags"- isDisabled- />- </div>- ),-};--export const AtLimit: Story = {- render: () => {- const [value, setValue] = useState<SearchableItem[]>([tags[0], tags[1]]);- return (- <div style={{width: 350}}>- <MobileTokenizer- label="Tags"- searchSource={source}- value={value}- onChange={items => setValue(items)}- placeholder="Add tags"- maxEntries={2}- debounceMs={0}- />- </div>- );- },- name: 'At the maxEntries limit',-};diff --git a/docs/specs/AST-056-search-prop-shape/spec.md b/docs/specs/AST-056-search-prop-shape/spec.mdindex c078879022..1a98d05b26 100644--- a/docs/specs/AST-056-search-prop-shape/spec.md+++ b/docs/specs/AST-056-search-prop-shape/spec.md@@ -192,10 +192,9 @@ somebody made alone:query input _is_ the control. Both are locally right, which is exactly whyno component will fix this on its own.-Beyond core, `packages/lab` has already copied the drift and added a fifth-name: `MobileTokenizer` takes `searchSource` + `emptySearchResultsText`,-`TransferList` takes `hasSearch` + `searchPlaceholder` + `searchLabel`, and-`ChatEmojiPicker` takes `searchLabel`. Lab is not a stable public promise, so+Beyond core, `packages/lab` has copied the drift: `TransferList` takes+`hasSearch` + `searchPlaceholder` + `searchLabel`, and `ChatEmojiPicker` takes+`searchLabel`. Lab is not a stable public promise, sothis record does not govern it; it is evidence that the pattern spreads bycopying.diff --git a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.mdindex d8f14bd6b7..cac707ca21 100644--- a/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md+++ b/docs/specs/components/BottomSheet/BottomSheetSwitcher.spec.md@@ -96,7 +96,7 @@ Consumer migration instructions belong in consumer docs and release notes.| warning | `@deprecated` on the declarations; consumer docs, templates, stories, and release notes name the replacement. No runtime warning (`spec:AST-017` FR29) || migration | Ordered and testable, per flow: (1) replace `activeSheet` / `onActiveSheetChange` with one `step` value; (2) give each step `isOpen={step === 'id'}` and `onOpenChange={isOpen => !isOpen && setStep(current => (current === 'id' ? null : current))}` in place of `sheetId="id"`; (3) remove the wrapper, moving its `hasScrim` onto every step; (4) keep the step controls as they are (`setStep('next')`); (5) a flow stepped by a control outside its sheets (a page control beside a non-modal flow, or code acting while focus is on a page control) gets push and pop motion in place of the handoff — move such a control into the step, or accept the motion; code acting while focus is in the step or on the body keeps the handoff; (6) the switcher's other props: `onCancel` becomes a guarded `onOpenChange` on each step — one that ignores `false` while the flow must stay open — which keeps the step's dialog role; a standalone sheet reports Escape, the platform close, the scrim tap, and the swipe all as `onOpenChange(false)` with no reason, so the guard holds the step open against all of them while it applies, where the switcher's `onCancel` vetoed only the cancel request; a veto of Escape alone has no equivalent, and the only per-path lever is `purpose` (`form` keeps Escape and blocks the scrim tap and the swipe; `required` blocks all three and exposes the step as an `alertdialog`); there is no per-event veto; a consumer `aria-label` / `aria-labelledby` becomes each step's `label`, which names its dialog; `ref`, `id`, `data-testid`, `className`, `style`, `xstyle`, and the other dialog props have no dialog-level equivalent — a standalone sheet's `ref` and base props reach its panel `<div>` and its dialog is implementation — so a test or an anchor that needs the dialog queries the panel's `closest('dialog')`, and dialog-level styling is dropped || codemod | None; the rewrite moves state the caller owns and is short enough to read |-| downstream | The maintained published surfaces migrate in the deprecation patch (`spec:AST-017` FR29c): the CLI block templates and the stories. `@astryxdesign/lab` is marked `private` and is published to npm only under the `@canary` dist-tag, never as a stable `latest` release; `spec:AST-017` calls it "the private canary-only Lab package" (FR27), lists private packages among its non-goals, puts them outside the published compatibility promise (FR2), and says canary-only surfaces carry no stable compatibility promise, which this record reads as FR29c's "maintained Astryx packages" not reaching Lab, so Lab's migration is optional under it: Lab's `MobileTokenizer` and `MobilePowerSearch` are migrated, so no maintained surface uses the switcher. Whether `spec:AST-017` is read that way is its owner's to settle. The switcher's own stories remain as its labelled reference. |+| downstream | The maintained published surfaces migrate in the deprecation patch (`spec:AST-017` FR29c): the CLI block templates and the stories. `@astryxdesign/lab` is marked `private` and is published to npm only under the `@canary` dist-tag, never as a stable `latest` release; `spec:AST-017` calls it "the private canary-only Lab package" (FR27), lists private packages among its non-goals, puts them outside the published compatibility promise (FR2), and says canary-only surfaces carry no stable compatibility promise, which this record reads as FR29c's "maintained Astryx packages" not reaching Lab, so Lab's migration is optional under it; Lab has no switcher consumer, so no maintained surface uses the switcher. Whether `spec:AST-017` is read that way is its owner's to settle. The switcher's own stories remain as its labelled reference. || transition | no prior transition || state | `deprecated`: supported, documented with its replacement, unchanged at runtime — the deprecation patch `spec:AST-017` FR28 requires before a removal, projected through declarations and docs (FR29a, FR29b). || open decision | Which declared minor removes the surface, and whether a renamed compatibility export precedes the removal; either is a `[breaking]` change of a declared minor (`spec:AST-017` FR28, FR31) |diff --git a/docs/specs/components/Indicator/Indicator.spec.md b/docs/specs/components/Indicator/Indicator.spec.mdindex 19f7464af6..02d93adc31 100644--- a/docs/specs/components/Indicator/Indicator.spec.md+++ b/docs/specs/components/Indicator/Indicator.spec.md@@ -99,7 +99,7 @@ Consumer migration instructions belong in consumer docs and release notes.| ID | Invariant | Basis || --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- || FR1 | The default registry maps exactly `check` → CheckIndicator, `checkbox` → CheckboxIndicator, and `radio` → RadioIndicator. | Current tests |-| FR2 | A host resolves an indicator by name from the nearest theme: the theme's `indicators` entry for that name wins, otherwise the built-in. One override reaches every host that resolves that name. The Tokenizer bottom sheet and the Lab MobileTokenizer and MobilePowerSearch value editor render CheckboxIndicator and RadioIndicator directly, so a theme's `checkbox` or `radio` entry does not reach them. An augmented name resolves only when a theme supplies it. | `architecture:theme-authoring-contract`; current tests |+| FR2 | A host resolves an indicator by name from the nearest theme: the theme's `indicators` entry for that name wins, otherwise the built-in. One override reaches every host that resolves that name. The Tokenizer bottom sheet and the PowerSearch value step render CheckboxIndicator and RadioIndicator directly, so a theme's `checkbox` or `radio` entry does not reach them. An augmented name resolves only when a theme supplies it. | `architecture:theme-authoring-contract`; current tests || FR3 | Every built-in indicator root sets `aria-hidden="true"` after caller props, so a caller cannot expose it; the public props type rejects `role` and `tabIndex`. Indicators receive `state`, `size`, `isDisabled`, and `children` and nothing that would give them semantics. | `architecture:public-component-api` INV5; current tests || FR4 | Renderable `children` replace the built-in state mark inside the indicator; nullish, boolean, and empty-string children keep it, and `0` counts as content. | Current tests || FR5 | RadioIndicator renders one circular span (20 or 24 CSS px) whose border and fill follow the state: an emphasized border on the surface when unchecked, an accent fill when checked with an on-accent dot (8 or 10 CSS px) inside. Disabled halves the opacity and mutes the border (and the fill when unchecked). Under a hover-capable pointer, hovering the host's `indicatorScope` tints it. The dot stays visible under forced colors. Transitions are instant under reduced motion. | Current source and tests |@@ -169,9 +169,9 @@ their own records.## Current-state impact-- **Direct indicator imports (FR2).** The Tokenizer bottom sheet and the Lab- MobileTokenizer and MobilePowerSearch value editor render CheckboxIndicator- and RadioIndicator directly, so a theme's `checkbox` or `radio` override does+- **Direct indicator imports (FR2).** The Tokenizer bottom sheet and the+ PowerSearch value step render CheckboxIndicator and RadioIndicator+ directly, so a theme's `checkbox` or `radio` override doesnot reach them.## Decision logdiff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.mdindex c10317e586..aace41b754 100644--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md@@ -67,9 +67,7 @@ work moves into a stack of tall modal bottom sheets — Filters, Add filter, andvalue step, each opened above the one that led to it and each dismissed back toit — that reads on a compact touch screen without a software keyboard coveringthe editor. Omitting the option keeps the tokenizer and editor popover on every-device. The flow's shape is the one the Lab prototype `MobilePowerSearch`-ships; this record states it as Core's contract, with the differences DEC-3-lists.+device. DEC-3 states the flow's shape.Where the shipped PowerSearch does not yet meet a requirement, the row carries apresent-tense implementation gap note.@@ -221,15 +219,15 @@ FR10–FR21 govern.| FR7 | In the `popover` presentation, width and preferred-edge selection MUST still yield to the layer runtime's viewport collision handling so the editor remains horizontally visible within the runtime's existing safe area. | `architecture:layer-runtime` | Accepted contract; implementation pending || FR8 | In the `popover` presentation, the width and alignment change MUST NOT alter editor content, field/operator/value state, vertical placement, focus movement, selection, dismissal, or screen-reader semantics. | Compatibility and accessibility requirement | Accepted contract; implementation pending || FR9 | In the `popover` presentation, the opening-control descriptor owned by `component:Tokenizer/DEC-1` and consumed by PowerSearch MUST remain package-internal. PowerSearch MUST NOT add a public width, maximum-width, input-ref, or positioning prop for this behavior. | `component:Tokenizer/DEC-1`, `architecture:public-component-api`, and `component:PowerSearch/DEC-1` | Accepted contract; implementation pending |-| FR10 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the tokenizer field with its typeahead and editor popover, unchanged except as FR19 (no mount announcement) states. `bottom-sheet` is the trigger and sheet flow of FR11–FR21 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the same shared resolution the selection controls use (`component:Selector/FR4`). That resolution answers `popover` on the server and during the hydrating render, so an `adaptive` field server-renders as, and hydrates without a mismatch as, the popover presentation's tokenizer field; on a compact coarse-pointer screen the first client render after hydration swaps it to the trigger. Focus follows the resolution rule below: before any interaction nothing in the field has focus and nothing moves, except that with `hasAutoFocus` the server markup's `autofocus` has focused the combobox input, and the swap then moves focus to the trigger within the same visit — the caller is told of neither a blur nor a new focus. The two closed fields share the field's wrapper, border, and minimum height for the size, and show the same tokens, but their row counts may differ: the popover field's editable tokens each carry a 16 px remove control the trigger's display-only tokens do not (FR11), so the trigger's tokens can wrap into fewer rows (seven filters in a 326 px field take seven rows editable and six as display-only tokens), and the popover field also carries its inline combobox input after the tokens, which may take a row of its own — the swap then changes the field's height by those rows (none on the measured story at 390 px, one token row at 414 px). A resolution change while the flow is open takes effect after it closes and focus has returned to the trigger (the focus the close reports, FR11) — 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; when the new presentation is `popover`, focus then moves to the tokenizer's combobox input as the same visit — no `onBlur` and no second `onFocus` reaches the caller. A resolution change while the flow is closed takes effect at once; when focus is anywhere inside the closed field — the trigger, the combobox input, a token or its remove control, the clear control, or an interactive `endContent` — and the focused element does not survive the switch, focus moves to the other presentation's primary control (the combobox input, or the trigger) as a continuation of the same visit — no `onBlur` and no `onFocus` reaches the caller for the hand-off; when the focused element survives, or focus is outside the field, focus stays where it is. When the switch to the sheet presentation happens while the popover presentation's editor popover is open, the popover and its focused control unmount with the tokenizer field, and focus moves to the trigger. Focus never lands on the page body. | DEC-3; touch-flow evidence from the Lab prototype | Current contract; verified by focused sheet tests and real-engine touch evidence. |-| FR11 | In the sheet presentation the field's control is one trigger: a button with `aria-haspopup="dialog"` and `aria-expanded`, whose accessible name is the field label followed by the trigger's visible text — the placeholder while no filter exists, otherwise the text of the filter tokens — so the name contains what is visible and exposes the selected filters. The tokens are display-only — each is the token's static structure (`component:Token/FR2`): no remove control, no click of its own, no inner control inside the trigger button — and the tokens, the placeholder, and the empty space around them belong to the trigger: a tap on any of them opens the flow. Tokens wrap onto further lines; the trigger does not reserve a row of its own once a token exists. The trigger's tokens are the popover presentation's tokens, the same component and the same words for a value, and a `date_absolute` value reads as the sheet's date editor shows it (FR17): a date-only value as its day in `timezoneID`, else the UTC day, and a value whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone. The popover's token does not read dates this way yet (see the known gap on dates). A `components[type].Token` override renders on the trigger in place of PowerSearch's token, receiving the props the popover presentation hands it — `config`, `filter`, `field`, `operator`, `maxLength`, `isDisabled` — with `onClick` and `onRemove` undefined, as the popover hands them for a read-only filter: the trigger's tokens are display-only, and the override formats its own value. `startIcon` renders in the trigger's lane. The result count and `endContent` render in the field's end lane, outside the trigger button and after it: an interactive `endContent` keeps its own tab stop, its own taps, and its own accessible name, and a tap on it does not open the flow, so a caller's control is never nested inside the component's button and the end lane's text is not part of the trigger's name. `size` sizes the trigger field and its tokens as it sizes the tokenizer field; `statusVariant` places `status.message` as the popover presentation places it; `hasAutoFocus` focuses the trigger on mount. `onFocus` fires when focus enters the field from outside and `onBlur` when it leaves the field: opening the flow moves focus into a sheet, outside the field, so `onBlur` fires, and the close that returns focus to the trigger fires `onFocus` — as the popover presentation fires them around its editor. While disabled the trigger stays focusable with `aria-disabled="true"`, never carries the native `disabled` attribute, does not open, and shows `disabledMessage` as the field does (`spec:AST-085/FR1`, `FR2`). When the component becomes disabled with the flow open, every open sheet of the flow closes and focus moves to the trigger, the destination this record names (`spec:AST-085/FR4`). | DEC-3; Lab touch-flow evidence; `spec:AST-085`; WCAG 2.5.3 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: the trigger's token reads a `date_absolute` value as the popover presentation's token does, as its day in the device's zone with no time, not in `timezoneID`. |-| FR12 | Opening the flow from a field with at least one filter, or from a read-only field, shows the Filters sheet, a tall modal sheet named "Filters". Its header — a heading and, while the field is interactive and at least one filter exists, an Add filter button at the medium size whose hit area is at least 44 px tall — and its footer — Done and, while `hasClear` is set, the field is interactive, and at least one editable filter exists, Clear all — stay fixed while only the rows between them scroll, the scroll viewport reaching the sheet's edge so its scrollbar does too, with the rows' text on the header's inset. One row per filter shows "{field label} {operator label}" (one catalog message, so a locale can reorder it) and, in bold, the value as the trigger's token shows it — the same formatter, so the same words, with the token's width budget lifted: the row never truncates a single value and never collapses a list to its "{n} items" count — with the token's summaries resolved from the catalog (`@astryx.powersearch.valueEditor.dateRange`, `itemsCount`, `filtersCount`, ICU plurals): an `integer` or `float` value reads as the token's own text (`String(value)`: `2.3456`, `1e+21`, `1e-7`, and `0` for negative zero) wherever the locale writes numbers with the token's numerals — Latin digits and a `.` decimal mark — and elsewhere with the locale's digits and decimal mark, no grouping and no rounding; a `string_list`, `enum_list`, or `entity_list` value reads as all of its items joined by the locale's narrow conjunction list (`Intl.ListFormat`, `{type: 'conjunction', style: 'narrow'}` — "Open, Closed" in English, "高、中" in Simplified Chinese and Japanese, "A, B und C" in German); a date-only `date_absolute` value reads as its day in `timezoneID`, else the UTC day, with no time, and one whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone, a `date_range` as "date range", a `nested` value as "{n} filters", and a `date_relative` value as the value step's choice row reads it ("3 days ago", FR20) when a choice matches the stored value, otherwise as stored. A row's label and value are one catalog message, "{label} {value}", the same message the removal announcement of AR6 uses, with the value segment bold. A filter the field can edit is a row button that opens the value step on it, with a trailing remove action — an icon button at the medium size named "Remove {field label} filter", its hit area at least 44 px square, that commits `onChange(rest, 'remove', index)` without opening the step — except that a filter whose operator takes an `empty` value (a one-tap boolean filter) is a row whose tap removes it, with the same trailing remove action, since it has no value to edit; a read-only filter, or every filter while the field is read-only, is a plain row with no remove action, as the popover gives such a token no remove control. A `nested` filter's row is a row button like any other; its step edits the group with the popover presentation's built-in nested editor (FR14). An editable filter whose field or operator the config no longer has — which the trigger still shows as a token — lists as a row button reading the field's label when the config still has the field and the raw key for whatever is gone — "{field key} {operator key}" when both are, "{field label} {operator key}" when only the operator is — that opens the step's "This filter is no longer available" state (FR14), its trailing remove action still the removal path; it is a plain row while the filter, or the field, is read-only. With no filter the body is one empty state: a heading "No filters applied", a line of guidance, and, while the field is interactive, a centered primary Add filter action that is then the sheet's only Add filter (the header shows none), so the single thing to do is the only visible action. Done closes the flow. Clear all opens a confirmation above the sheet — a dialog titled "Clear all filters?" with "Clear filters" and "Keep filters" — and only confirming commits `onChange(kept, 'remove', <index of the first removed filter>)`, where `kept` is the read-only filters in their order: read-only filters are the consumer's, not the person's, so Clear all leaves them in place, as the popover presentation's Clear all does (FR23); the Filters sheet stays open for further editing and focus returns to it (FR16). After the flow closes focus returns to the trigger. | DEC-3; Lab touch-flow evidence; the read-only filter contract (`isReadOnly`, FR22); DEC-4 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a row reads a `date_absolute` value as the trigger's token does, as its day in the device's zone with no time, not in `timezoneID`. |-| FR13 | Add filter — from the Filters sheet's Add filter action, or directly when an interactive field with no filter opens — is a tall modal sheet named "Add filter" opened above the Filters sheet, which stays open beneath it (FR15a), so the sheet has no Back action: dismissing it — Escape, a scrim tap, a swipe — reveals Filters again, or closes the flow when Add filter was the entry point, in which case its fixed footer holds Done. Its header — the heading and, when one shows, the search field — stays fixed while the rows scroll. Without a content-search field it lists the visible fields grouped by `group`, each group a named list: the ungrouped fields first, under the heading "General", then each group under its name in order of first appearance, each a row button with the field's icon, a trailing chevron — or, for a field whose only operator takes an `empty` value, a trailing plus, since choosing it adds the filter at once (FR15) — and, once the field count reaches eight, a "Search filters" field above the list that matches labels and `typeaheadAliases` case-insensitively, caps a non-empty query's matches at `maxSearchResults`, and shows the empty state "No filters match your search" when nothing matches. With a `contentSearchFieldKey` whose default operator takes a `string` value it shows instead a "Search" searchbox using `placeholder`, with the same suggestions the popover presentation's typeahead offers listed inline as row buttons ("Search results"): fields, field-and-operator pairs, value matches, and a leading free-text item for the content field; Enter commits the first suggestion, ArrowDown and ArrowUp move between the search and the rows — arrow movement across independently focusable controls, recorded here as this record's exception to `spec:AST-020/FR15`, which adopts arrow keys for a single composite only: the searchbox-to-list continuity is what the popover presentation's combobox gives the same suggestions, and the rows stay in the Tab order as well — an IME-composing Enter does nothing, and a query with no suggestion shows the empty state "No results found" — the searchbox's `aria-controls` names the results list, or that message while nothing lists, so it always names an element; the field list's "No filters match your search" likewise shows only for a non-empty query that matches nothing, never for a config with no field. Each of the two is a compact empty state with a search icon, that title, and the description "Try a different search.", mounted only while the Add filter sheet is the open one. Neither search field takes focus when the sheet opens: the sheet opens with focus on its panel and the software keyboard stays down until the person taps the search; a direct vertical touch drag on the rows while a search field has focus blurs it, so the keyboard leaves and the rows can be read. A suggestion that carries a value commits `onChange([...filters, filter], 'add', filters.length)`, announces `Added {label}` inside the Filters sheet (AR6), and shows Filters as FR15a states; any other suggestion or field row opens the value step with that field and operator, above Add filter. Every visible field lists, a field whose every operator is `nested` included: the value step edits every operator's value (FR14). | DEC-3; Lab touch-flow evidence; current typeahead source | Current contract; verified by focused sheet tests and real-engine touch evidence. |-| FR14 | The value step is a tall modal sheet that edits every operator's value, opened above the sheet that led to it — Filters for an edit, Add filter for a creation — which stays open beneath it (FR15a); its title is the dialog's name (AR5), and for a filter whose field or operator the config no longer has it reads as the Filters row does (FR12): the field's label when the config still has the field, the raw key for whatever is gone. Its header and footer stay fixed while the body scrolls. When the field offers more than one operator the body starts with an "Operator" radio group whose options read "{field label} {operator label}" and list the field's operators, with the operator the step opened with checked — the filter's operator while editing, and while creating the operator the suggestion named (FR13) or else the field's default operator, else its first; otherwise there is no group and the title is "{field label} {operator label}" naming that operator. When no operator label applies the title is the field label. The body below the group is the editor for the checked operator's value type: the sheet-native controls of FR17, or for a `nested` value the popover presentation's built-in nested editor — the sub-filter tree with its Add action, each sub-filter's field, operator, and value controls, and removal — rendered as the popover renders it, with one difference: the step's Operator group takes the place of the editor's root group-operator picker, which is not shown, and the tree root reads the checked operator's label; a sub-filter's controls are the popover editor's own, in their default presentation (a Selector's menu, the Tokenizer's inline field), not the sheet's choice rows (FR17) or Tokenizer sheet (FR21), which govern the step's top-level value only, because the sheet passes no `experimental` option down to them; the tree is its own width container, so below 400 CSS px its rows wrap instead of overflowing the sheet, as they wrap in a narrow popover. A group is created and edited the same way in both presentations; switching the operator swaps the body. A value chosen in the body is staged, not committed: no `onChange` fires until the footer confirms it. Changing the operator keeps a staged value only when the new operator reads the same value type; an `empty` operator stages `{type: 'empty'}`. The body's sections sit on the sheet's surface when the editor is the body's only section; when the body has more than one section — the Operator group above the editor — each section is a muted container, so the grouping reads without a frame around a lone editor. The footer holds Cancel and the confirm action — `popoverSaveButtonLabel` when given, otherwise "Add filter" while creating and "Apply" while editing — disabled until the staged value is complete; the step has no Remove action: a filter is removed from its Filters row (FR12). When `components[type].Editor` is set for the checked operator's value type it replaces the body below the Operator group and the footer — the group stays outside it, so switching operators still swaps the body — receiving the props the popover presentation hands it, with the same meaning: the caller's `config`, the partial `filter`, `mode`, `saveButtonLabel`, `isReadOnly`, `onSave`, and `onCancel`, and nothing the popover does not pass; `onSave(filter)` commits it, `onSave(null)` removes the filter while editing and returns to Filters unchanged while creating. A controlled update that removes the field or operator being edited replaces the body with "This filter is no longer available", announced from its rendered element inside the sheet while the step is the open one (AR6), and keeps Cancel as the way out, the filter's trailing remove action on its Filters row being the removal path (FR12); when focus was on a control of the replaced body it moves to Cancel, so it never falls to the page body inside the open sheet (FR16). | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |-| FR15 | Confirming a created filter commits `onChange([...filters, filter], 'add', filters.length)`; choosing a field whose only operator takes an `empty` value commits that filter the same way from the Add filter row, with no value step. Tapping an editable Filters row opens the value step on that filter in edit mode; Apply commits `onChange(updated, 'edit', index)`; the row's trailing remove action, or a tap on an `empty`-valued filter's row, commits `onChange(rest, 'remove', index)`, where `index` is the filter's position at commit time: a controlled parent that reorders or clones its filters while the step is open is followed by object identity, then by a structurally equal filter in the original slot, then by a unique structural match; when the target is gone or ambiguous nothing is committed and the step closes back to Filters, focus landing as FR16 states for a row that no longer exists. Every commit shows the Filters sheet as FR15a states. While the field is read-only, or disabled, no commit happens. | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |+| FR10 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the tokenizer field with its typeahead and editor popover, unchanged except as FR19 (no mount announcement) states. `bottom-sheet` is the trigger and sheet flow of FR11–FR21 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the same shared resolution the selection controls use (`component:Selector/FR4`). That resolution answers `popover` on the server and during the hydrating render, so an `adaptive` field server-renders as, and hydrates without a mismatch as, the popover presentation's tokenizer field; on a compact coarse-pointer screen the first client render after hydration swaps it to the trigger. Focus follows the resolution rule below: before any interaction nothing in the field has focus and nothing moves, except that with `hasAutoFocus` the server markup's `autofocus` has focused the combobox input, and the swap then moves focus to the trigger within the same visit — the caller is told of neither a blur nor a new focus. The two closed fields share the field's wrapper, border, and minimum height for the size, and show the same tokens, but their row counts may differ: the popover field's editable tokens each carry a 16 px remove control the trigger's display-only tokens do not (FR11), so the trigger's tokens can wrap into fewer rows (seven filters in a 326 px field take seven rows editable and six as display-only tokens), and the popover field also carries its inline combobox input after the tokens, which may take a row of its own — the swap then changes the field's height by those rows (none on the measured story at 390 px, one token row at 414 px). A resolution change while the flow is open takes effect after it closes and focus has returned to the trigger (the focus the close reports, FR11) — 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; when the new presentation is `popover`, focus then moves to the tokenizer's combobox input as the same visit — no `onBlur` and no second `onFocus` reaches the caller. A resolution change while the flow is closed takes effect at once; when focus is anywhere inside the closed field — the trigger, the combobox input, a token or its remove control, the clear control, or an interactive `endContent` — and the focused element does not survive the switch, focus moves to the other presentation's primary control (the combobox input, or the trigger) as a continuation of the same visit — no `onBlur` and no `onFocus` reaches the caller for the hand-off; when the focused element survives, or focus is outside the field, focus stays where it is. When the switch to the sheet presentation happens while the popover presentation's editor popover is open, the popover and its focused control unmount with the tokenizer field, and focus moves to the trigger. Focus never lands on the page body. | DEC-3; touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |+| FR11 | In the sheet presentation the field's control is one trigger: a button with `aria-haspopup="dialog"` and `aria-expanded`, whose accessible name is the field label followed by the trigger's visible text — the placeholder while no filter exists, otherwise the text of the filter tokens — so the name contains what is visible and exposes the selected filters. The tokens are display-only — each is the token's static structure (`component:Token/FR2`): no remove control, no click of its own, no inner control inside the trigger button — and the tokens, the placeholder, and the empty space around them belong to the trigger: a tap on any of them opens the flow. Tokens wrap onto further lines; the trigger does not reserve a row of its own once a token exists. The trigger's tokens are the popover presentation's tokens, the same component and the same words for a value, and a `date_absolute` value reads as the sheet's date editor shows it (FR17): a date-only value as its day in `timezoneID`, else the UTC day, and a value whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone. The popover's token does not read dates this way yet (see the known gap on dates). A `components[type].Token` override renders on the trigger in place of PowerSearch's token, receiving the props the popover presentation hands it — `config`, `filter`, `field`, `operator`, `maxLength`, `isDisabled` — with `onClick` and `onRemove` undefined, as the popover hands them for a read-only filter: the trigger's tokens are display-only, and the override formats its own value. `startIcon` renders in the trigger's lane. The result count and `endContent` render in the field's end lane, outside the trigger button and after it: an interactive `endContent` keeps its own tab stop, its own taps, and its own accessible name, and a tap on it does not open the flow, so a caller's control is never nested inside the component's button and the end lane's text is not part of the trigger's name. `size` sizes the trigger field and its tokens as it sizes the tokenizer field; `statusVariant` places `status.message` as the popover presentation places it; `hasAutoFocus` focuses the trigger on mount. `onFocus` fires when focus enters the field from outside and `onBlur` when it leaves the field: opening the flow moves focus into a sheet, outside the field, so `onBlur` fires, and the close that returns focus to the trigger fires `onFocus` — as the popover presentation fires them around its editor. While disabled the trigger stays focusable with `aria-disabled="true"`, never carries the native `disabled` attribute, does not open, and shows `disabledMessage` as the field does (`spec:AST-085/FR1`, `FR2`). When the component becomes disabled with the flow open, every open sheet of the flow closes and focus moves to the trigger, the destination this record names (`spec:AST-085/FR4`). | DEC-3; touch-flow evidence; `spec:AST-085`; WCAG 2.5.3 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: the trigger's token reads a `date_absolute` value as the popover presentation's token does, as its day in the device's zone with no time, not in `timezoneID`. |+| FR12 | Opening the flow from a field with at least one filter, or from a read-only field, shows the Filters sheet, a tall modal sheet named "Filters". Its header — a heading and, while the field is interactive and at least one filter exists, an Add filter button at the medium size whose hit area is at least 44 px tall — and its footer — Done and, while `hasClear` is set, the field is interactive, and at least one editable filter exists, Clear all — stay fixed while only the rows between them scroll, the scroll viewport reaching the sheet's edge so its scrollbar does too, with the rows' text on the header's inset. One row per filter shows "{field label} {operator label}" (one catalog message, so a locale can reorder it) and, in bold, the value as the trigger's token shows it — the same formatter, so the same words, with the token's width budget lifted: the row never truncates a single value and never collapses a list to its "{n} items" count — with the token's summaries resolved from the catalog (`@astryx.powersearch.valueEditor.dateRange`, `itemsCount`, `filtersCount`, ICU plurals): an `integer` or `float` value reads as the token's own text (`String(value)`: `2.3456`, `1e+21`, `1e-7`, and `0` for negative zero) wherever the locale writes numbers with the token's numerals — Latin digits and a `.` decimal mark — and elsewhere with the locale's digits and decimal mark, no grouping and no rounding; a `string_list`, `enum_list`, or `entity_list` value reads as all of its items joined by the locale's narrow conjunction list (`Intl.ListFormat`, `{type: 'conjunction', style: 'narrow'}` — "Open, Closed" in English, "高、中" in Simplified Chinese and Japanese, "A, B und C" in German); a date-only `date_absolute` value reads as its day in `timezoneID`, else the UTC day, with no time, and one whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone, a `date_range` as "date range", a `nested` value as "{n} filters", and a `date_relative` value as the value step's choice row reads it ("3 days ago", FR20) when a choice matches the stored value, otherwise as stored. A row's label and value are one catalog message, "{label} {value}", the same message the removal announcement of AR6 uses, with the value segment bold. A filter the field can edit is a row button that opens the value step on it, with a trailing remove action — an icon button at the medium size named "Remove {field label} filter", its hit area at least 44 px square, that commits `onChange(rest, 'remove', index)` without opening the step — except that a filter whose operator takes an `empty` value (a one-tap boolean filter) is a row whose tap removes it, with the same trailing remove action, since it has no value to edit; a read-only filter, or every filter while the field is read-only, is a plain row with no remove action, as the popover gives such a token no remove control. A `nested` filter's row is a row button like any other; its step edits the group with the popover presentation's built-in nested editor (FR14). An editable filter whose field or operator the config no longer has — which the trigger still shows as a token — lists as a row button reading the field's label when the config still has the field and the raw key for whatever is gone — "{field key} {operator key}" when both are, "{field label} {operator key}" when only the operator is — that opens the step's "This filter is no longer available" state (FR14), its trailing remove action still the removal path; it is a plain row while the filter, or the field, is read-only. With no filter the body is one empty state: a heading "No filters applied", a line of guidance, and, while the field is interactive, a centered primary Add filter action that is then the sheet's only Add filter (the header shows none), so the single thing to do is the only visible action. Done closes the flow. Clear all opens a confirmation above the sheet — a dialog titled "Clear all filters?" with "Clear filters" and "Keep filters" — and only confirming commits `onChange(kept, 'remove', <index of the first removed filter>)`, where `kept` is the read-only filters in their order: read-only filters are the consumer's, not the person's, so Clear all leaves them in place, as the popover presentation's Clear all does (FR23); the Filters sheet stays open for further editing and focus returns to it (FR16). After the flow closes focus returns to the trigger. | DEC-3; touch-flow evidence; the read-only filter contract (`isReadOnly`, FR22); DEC-4 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a row reads a `date_absolute` value as the trigger's token does, as its day in the device's zone with no time, not in `timezoneID`. |+| FR13 | Add filter — from the Filters sheet's Add filter action, or directly when an interactive field with no filter opens — is a tall modal sheet named "Add filter" opened above the Filters sheet, which stays open beneath it (FR15a), so the sheet has no Back action: dismissing it — Escape, a scrim tap, a swipe — reveals Filters again, or closes the flow when Add filter was the entry point, in which case its fixed footer holds Done. Its header — the heading and, when one shows, the search field — stays fixed while the rows scroll. Without a content-search field it lists the visible fields grouped by `group`, each group a named list: the ungrouped fields first, under the heading "General", then each group under its name in order of first appearance, each a row button with the field's icon, a trailing chevron — or, for a field whose only operator takes an `empty` value, a trailing plus, since choosing it adds the filter at once (FR15) — and, once the field count reaches eight, a "Search filters" field above the list that matches labels and `typeaheadAliases` case-insensitively, caps a non-empty query's matches at `maxSearchResults`, and shows the empty state "No filters match your search" when nothing matches. With a `contentSearchFieldKey` whose default operator takes a `string` value it shows instead a "Search" searchbox using `placeholder`, with the same suggestions the popover presentation's typeahead offers listed inline as row buttons ("Search results"): fields, field-and-operator pairs, value matches, and a leading free-text item for the content field; Enter commits the first suggestion, ArrowDown and ArrowUp move between the search and the rows — arrow movement across independently focusable controls, recorded here as this record's exception to `spec:AST-020/FR15`, which adopts arrow keys for a single composite only: the searchbox-to-list continuity is what the popover presentation's combobox gives the same suggestions, and the rows stay in the Tab order as well — an IME-composing Enter does nothing, and a query with no suggestion shows the empty state "No results found" — the searchbox's `aria-controls` names the results list, or that message while nothing lists, so it always names an element; the field list's "No filters match your search" likewise shows only for a non-empty query that matches nothing, never for a config with no field. Each of the two is a compact empty state with a search icon, that title, and the description "Try a different search.", mounted only while the Add filter sheet is the open one. Neither search field takes focus when the sheet opens: the sheet opens with focus on its panel and the software keyboard stays down until the person taps the search; a direct vertical touch drag on the rows while a search field has focus blurs it, so the keyboard leaves and the rows can be read. A suggestion that carries a value commits `onChange([...filters, filter], 'add', filters.length)`, announces `Added {label}` inside the Filters sheet (AR6), and shows Filters as FR15a states; any other suggestion or field row opens the value step with that field and operator, above Add filter. Every visible field lists, a field whose every operator is `nested` included: the value step edits every operator's value (FR14). | DEC-3; touch-flow evidence; current typeahead source | Current contract; verified by focused sheet tests and real-engine touch evidence. |+| FR14 | The value step is a tall modal sheet that edits every operator's value, opened above the sheet that led to it — Filters for an edit, Add filter for a creation — which stays open beneath it (FR15a); its title is the dialog's name (AR5), and for a filter whose field or operator the config no longer has it reads as the Filters row does (FR12): the field's label when the config still has the field, the raw key for whatever is gone. Its header and footer stay fixed while the body scrolls. When the field offers more than one operator the body starts with an "Operator" radio group whose options read "{field label} {operator label}" and list the field's operators, with the operator the step opened with checked — the filter's operator while editing, and while creating the operator the suggestion named (FR13) or else the field's default operator, else its first; otherwise there is no group and the title is "{field label} {operator label}" naming that operator. When no operator label applies the title is the field label. The body below the group is the editor for the checked operator's value type: the sheet-native controls of FR17, or for a `nested` value the popover presentation's built-in nested editor — the sub-filter tree with its Add action, each sub-filter's field, operator, and value controls, and removal — rendered as the popover renders it, with one difference: the step's Operator group takes the place of the editor's root group-operator picker, which is not shown, and the tree root reads the checked operator's label; a sub-filter's controls are the popover editor's own, in their default presentation (a Selector's menu, the Tokenizer's inline field), not the sheet's choice rows (FR17) or Tokenizer sheet (FR21), which govern the step's top-level value only, because the sheet passes no `experimental` option down to them; the tree is its own width container, so below 400 CSS px its rows wrap instead of overflowing the sheet, as they wrap in a narrow popover. A group is created and edited the same way in both presentations; switching the operator swaps the body. A value chosen in the body is staged, not committed: no `onChange` fires until the footer confirms it. Changing the operator keeps a staged value only when the new operator reads the same value type; an `empty` operator stages `{type: 'empty'}`. The body's sections sit on the sheet's surface when the editor is the body's only section; when the body has more than one section — the Operator group above the editor — each section is a muted container, so the grouping reads without a frame around a lone editor. The footer holds Cancel and the confirm action — `popoverSaveButtonLabel` when given, otherwise "Add filter" while creating and "Apply" while editing — disabled until the staged value is complete; the step has no Remove action: a filter is removed from its Filters row (FR12). When `components[type].Editor` is set for the checked operator's value type it replaces the body below the Operator group and the footer — the group stays outside it, so switching operators still swaps the body — receiving the props the popover presentation hands it, with the same meaning: the caller's `config`, the partial `filter`, `mode`, `saveButtonLabel`, `isReadOnly`, `onSave`, and `onCancel`, and nothing the popover does not pass; `onSave(filter)` commits it, `onSave(null)` removes the filter while editing and returns to Filters unchanged while creating. A controlled update that removes the field or operator being edited replaces the body with "This filter is no longer available", announced from its rendered element inside the sheet while the step is the open one (AR6), and keeps Cancel as the way out, the filter's trailing remove action on its Filters row being the removal path (FR12); when focus was on a control of the replaced body it moves to Cancel, so it never falls to the page body inside the open sheet (FR16). | DEC-3; touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |+| FR15 | Confirming a created filter commits `onChange([...filters, filter], 'add', filters.length)`; choosing a field whose only operator takes an `empty` value commits that filter the same way from the Add filter row, with no value step. Tapping an editable Filters row opens the value step on that filter in edit mode; Apply commits `onChange(updated, 'edit', index)`; the row's trailing remove action, or a tap on an `empty`-valued filter's row, commits `onChange(rest, 'remove', index)`, where `index` is the filter's position at commit time: a controlled parent that reorders or clones its filters while the step is open is followed by object identity, then by a structurally equal filter in the original slot, then by a unique structural match; when the target is gone or ambiguous nothing is committed and the step closes back to Filters, focus landing as FR16 states for a row that no longer exists. Every commit shows the Filters sheet as FR15a states. While the field is read-only, or disabled, no commit happens. | DEC-3; touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. || FR15a | The steps stack: each step opens above the sheet that led to it, which stays open — receded and blocked as a covered sheet of the stack (`component:BottomSheet` FR5, FR6) — so the stack is Filters alone; Filters under Add filter; Filters under the value step for an edit; Filters under Add filter under the value step for a creation; or, when Add filter was the entry point, Add filter alone and then Add filter under the value step. No sheet of the flow carries a Back action: a dismissal — Escape, a scrim tap, a swipe, a platform close request — reaches only the top sheet (`component:BottomSheet` FR7), closes it, and reveals the sheet beneath, which takes focus back as FR16 states; dismissing the bottom sheet of the stack closes the flow. Cancel on the value step is that dismissal. A commit closes the step that made it: an edit's commit reveals Filters beneath the value step; a creation's commit, from the value step or from an Add filter row or suggestion that commits directly, closes Add filter, and the value step above it, together and shows Filters, so the person sees the filter just added: Filters is revealed when it is open beneath them; after a direct entry it opens in the same update that closes them — BottomSheet's same-update replace (`component:BottomSheet` FR10) when Add filter alone closes, and the stack's ordinary closes and open (`component:BottomSheet` FR5–FR9) when the value step closes with it. A creating `Editor` override's `onSave(null)` (FR14) shows Filters the same way. The flow therefore has one direction forward (open a step above) and one back (close the top step): no dismissal replaces a step, and Filters opens as other sheets close only when a creation ends after a direct entry. | DEC-3; `component:BottomSheet` FR5–FR9 | Current contract; verified by focused sheet tests and real-engine touch evidence. |-| FR16 | Focus follows the step: after a commit from the value step while creating, the value step and Add filter close and focus lands on the Filters header's Add filter, ready for the next filter; after a content-search suggestion or an `empty`-valued field row commits a filter directly, that filter's row; after Apply or Cancel from editing, the edited filter's row — followed across a controlled reorder or clone, and, when a controlled update removed it or left two filters it could be, the nearest remaining row that is a button around its former position (the following one on a tie), else Add filter; after a row's trailing remove action, or a caller's `Editor` override's `onSave(null)` while editing, which closes the value step, the trailing remove action of the nearest remaining row that has one (the following one on a tie) — a plain row, a read-only filter's, has none and is passed over — so a run of removals needs no re-aiming, else Add filter when no such row remains; after Cancel from creation, Add filter is revealed with focus on the field row that opened the step, or on the content search when a suggestion opened it — and when a controlled update has removed that field, or the content-search field itself, the Add filter sheet's first control: its search field when one shows, else its first field row; after Add filter is dismissed, the Filters header's Add filter, or the empty state's; after a caller's `Editor` override calls `onSave(null)` while creating, the same (the flow returns to Filters unchanged, FR14); after a confirmed Clear all, the Filters sheet's first remaining control — a kept read-only filter's row has none, so Add filter — with the sheet still open; after Keep filters, Escape, or a scrim tap dismisses the confirmation, Clear all (`component:Dialog` AR2); and, as one rule for the Filters and Add filter sheets, when a controlled update unmounts the control that holds focus — a filter's row or its remove action, a dropped field's row, Clear all gone with the last editable filter — the nearest remaining row that is a button, counted among the button rows by the removed one's index (the following one, else the last) — a plain row (a read-only filter, or every filter while the field is read-only) is passed over — else the sheet's first control (the Add filter sheet's search field, Add filter in the Filters header or empty state), else the sheet's panel, so focus never lands on the page body inside the open sheet; when a controlled update replaces the value step's body with the unavailable state while focus was on one of its controls, Cancel (FR14); after the flow closes, the trigger. A sheet that opens takes focus on its panel, not on a control, except where this row names one; the Add filter sheet's search fields never take it on open (FR13). | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |-| FR17 | The value step edits every value type with the same editor the popover presentation uses (`nested` through its built-in nested editor, FR14), with four sheet-native differences: `enum`, `enum_list`, and `date_relative` render as full-width choice rows with a trailing indicator instead of a dropdown that would stack a second layer on the sheet — `radio` rows in a `radiogroup` named by the field label for `enum` and `date_relative` (a tap selects the row; the group is one tab stop — the checked row, else the first — and the arrow keys move focus and check the row they land on, wrapping, Home and End move to and check the first and last row, and Space or Enter checks the focused row — `spec:AST-020/FR15`), `checkbox` rows in a `group` named by the field label for `enum_list` (a tap toggles the row; each row is its own tab stop, toggled with Space or Enter), each carrying its state as `aria-checked`, as the Tokenizer's sheet rows do; `integer` and `float` stage every parseable keystroke, so the confirm action enables while the person is still typing, and unstage when the field is cleared or stops parsing, so it disables again over an empty field; a `string_list` or `entity_list` value edits through the Tokenizer's own sheet presentation (`component:Tokenizer/FR16–FR24`), its trigger showing the staged tokens in the step and its sheet titled with the field label; and a `date_absolute` value with `isDateOnly` unset or `true`, and a `date_range` value, edit through an inline Calendar on the sheet's surface — no popover opens from a sheet — reading a stored instant as its day in `timezoneID`, else the UTC day, and writing a picked day as that day's midnight in the same zone, the day the trigger's token and the Filters row show (FR11, FR12); a `date_absolute` value with `isDateOnly: false` edits through a date-and-time input, sized for touch, that reads and writes the wall-clock time in `timezoneID`, else the viewer's zone. The popover presentation's date editors do not follow these zones yet (see the known gap on dates). `maxOperatorMenuItems` caps the string and entity suggestions as in the popover presentation. | DEC-3; Lab touch-flow evidence; current value editors | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a date-only `date_absolute` value and a `date_range` value edit through the popover presentation's date fields in their sheet presentation, which read and write the UTC day whatever `timezoneID` is, not through an inline Calendar; a value whose operator sets `isDateOnly: false` edits a date only and stores its midnight. |+| FR16 | Focus follows the step: after a commit from the value step while creating, the value step and Add filter close and focus lands on the Filters header's Add filter, ready for the next filter; after a content-search suggestion or an `empty`-valued field row commits a filter directly, that filter's row; after Apply or Cancel from editing, the edited filter's row — followed across a controlled reorder or clone, and, when a controlled update removed it or left two filters it could be, the nearest remaining row that is a button around its former position (the following one on a tie), else Add filter; after a row's trailing remove action, or a caller's `Editor` override's `onSave(null)` while editing, which closes the value step, the trailing remove action of the nearest remaining row that has one (the following one on a tie) — a plain row, a read-only filter's, has none and is passed over — so a run of removals needs no re-aiming, else Add filter when no such row remains; after Cancel from creation, Add filter is revealed with focus on the field row that opened the step, or on the content search when a suggestion opened it — and when a controlled update has removed that field, or the content-search field itself, the Add filter sheet's first control: its search field when one shows, else its first field row; after Add filter is dismissed, the Filters header's Add filter, or the empty state's; after a caller's `Editor` override calls `onSave(null)` while creating, the same (the flow returns to Filters unchanged, FR14); after a confirmed Clear all, the Filters sheet's first remaining control — a kept read-only filter's row has none, so Add filter — with the sheet still open; after Keep filters, Escape, or a scrim tap dismisses the confirmation, Clear all (`component:Dialog` AR2); and, as one rule for the Filters and Add filter sheets, when a controlled update unmounts the control that holds focus — a filter's row or its remove action, a dropped field's row, Clear all gone with the last editable filter — the nearest remaining row that is a button, counted among the button rows by the removed one's index (the following one, else the last) — a plain row (a read-only filter, or every filter while the field is read-only) is passed over — else the sheet's first control (the Add filter sheet's search field, Add filter in the Filters header or empty state), else the sheet's panel, so focus never lands on the page body inside the open sheet; when a controlled update replaces the value step's body with the unavailable state while focus was on one of its controls, Cancel (FR14); after the flow closes, the trigger. A sheet that opens takes focus on its panel, not on a control, except where this row names one; the Add filter sheet's search fields never take it on open (FR13). | DEC-3; touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |+| FR17 | The value step edits every value type with the same editor the popover presentation uses (`nested` through its built-in nested editor, FR14), with four sheet-native differences: `enum`, `enum_list`, and `date_relative` render as full-width choice rows with a trailing indicator instead of a dropdown that would stack a second layer on the sheet — `radio` rows in a `radiogroup` named by the field label for `enum` and `date_relative` (a tap selects the row; the group is one tab stop — the checked row, else the first — and the arrow keys move focus and check the row they land on, wrapping, Home and End move to and check the first and last row, and Space or Enter checks the focused row — `spec:AST-020/FR15`), `checkbox` rows in a `group` named by the field label for `enum_list` (a tap toggles the row; each row is its own tab stop, toggled with Space or Enter), each carrying its state as `aria-checked`, as the Tokenizer's sheet rows do; `integer` and `float` stage every parseable keystroke, so the confirm action enables while the person is still typing, and unstage when the field is cleared or stops parsing, so it disables again over an empty field; a `string_list` or `entity_list` value edits through the Tokenizer's own sheet presentation (`component:Tokenizer/FR16–FR24`), its trigger showing the staged tokens in the step and its sheet titled with the field label; and a `date_absolute` value with `isDateOnly` unset or `true`, and a `date_range` value, edit through an inline Calendar on the sheet's surface — no popover opens from a sheet — reading a stored instant as its day in `timezoneID`, else the UTC day, and writing a picked day as that day's midnight in the same zone, the day the trigger's token and the Filters row show (FR11, FR12); a `date_absolute` value with `isDateOnly: false` edits through a date-and-time input, sized for touch, that reads and writes the wall-clock time in `timezoneID`, else the viewer's zone. The popover presentation's date editors do not follow these zones yet (see the known gap on dates). `maxOperatorMenuItems` caps the string and entity suggestions as in the popover presentation. | DEC-3; touch-flow evidence; current value editors | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a date-only `date_absolute` value and a `date_range` value edit through the popover presentation's date fields in their sheet presentation, which read and write the UTC day whatever `timezoneID` is, not through an inline Calendar; a value whose operator sets `isDateOnly: false` edits a date only and stores its midnight. || FR18 | Every list in the sheets derives synchronously from the config — the field list, its search, the content-search suggestions, and the choice rows — so no sheet shows an empty state before results arrive: "No filters match your search" and "No results found" render only for a non-empty query whose synchronous result set is empty, and only while their sheet is the open one; a sheet that is open beneath another, or closed with its body retained, renders and announces no empty-result or unavailable message (AR6). The value typeaheads and tokenizers inside the value step own their own pending states. | DEC-3; `architecture:react-component-runtime/INV1` | Current contract; verified by focused sheet tests and real-engine touch evidence. || FR19 | The result count renders at the end of the field in both presentations and is announced only when it changes after mount; the first render announces nothing, including under StrictMode's effect replay. The announcement takes the route `spec:AST-086/FR14` names for where the field is at that moment: inside the open sheet's dialog while a sheet of the flow is open (AR6), otherwise inside the nearest open native modal that holds the field (a Dialog, a modal Drawer), and the shared polite channel only when no modal does — never a channel the record names itself. | Current popover behavior; `architecture:react-component-runtime/INV3` | Current contract; verified by focused sheet tests and real-engine touch evidence. || FR20 | Every string the sheets introduce comes from the `@astryx.powersearch.*` catalog, reusing the existing editor keys where their meaning fits (Cancel, Apply, Operator, Value, Values, Entities, the placeholders, the result count). Content the popover presentation already renders keeps its source — field, operator, and value text from the config and its formatters — except that every label the sheets render for a generated choice comes from the catalog as one ICU message with a plural: the relative-date choice rows (`@astryx.powersearch.sheet.relative{Days,Weeks,Months}{Ago,FromNow}`, the same choices and, in English, the same words as the popover's editor lists) and the value summaries of FR12. | DEC-3; catalog contract | Current contract; verified by focused sheet tests and real-engine touch evidence. |@@ -574,8 +572,7 @@ editor popover on every device. `adaptive` resolves through the shared compactcoarse-pointer policy, so a PowerSearch, a Tokenizer, and a Selector on the samepage switch together.-The sheet surface follows the Lab touch flow of `MobilePowerSearch`, which the-owner named the target for Core (2026-11-02): the whole field is one trigger+The sheet surface: the whole field is one triggerwith display-only tokens; a Filters sheet lists the filters as rows withtrailing remove actions, under a fixed header with Add filter and over a fixedfooter with Done and Clear all, and is one centered Add filter when empty; Add@@ -591,23 +588,17 @@ Calendar in `timezoneID`, else UTC, and a value with a time of day on adate-and-time control in `timezoneID`, else the viewer's zone; every other valuetype uses the editor the popover presentation uses. Clear all asks forconfirmation, removes the filters the person can edit, keeps read-only ones, and-leaves Filters open. Core's contract differs from the prototype in places that-include these eight: a date-only value with no `timezoneID` is its UTC day,-where the prototype reads the viewer's zone; a field whose every operator is-`nested` lists, edited through the built-in nested editor, where the prototype-leaves it out; every string comes from the catalog (FR20), where the prototype-writes English; the empty results of Add filter's searches carry Core's titles-(FR13), where the prototype titles the field search's "No filters found"; Clear-all says "All filters removed" when no read-only filter remains (AR6), where the-prototype always says "Editable filters removed"; a one-tap `empty` filter added-from its field row is announced `Added {label}` (AR6), where the prototype-announces only a suggestion's; a caller's `Editor` override receives only what-the popover presentation passes it (FR14), where the prototype also passes-`timezoneID`; and the flow mounts nothing until a press (PR5), where the-prototype keeps its sheets mounted from the first render. Rejected: switching+leaves Filters open. Eight details the flow fixes: a date-only value with no+`timezoneID` is its UTC day; a field whose every operator is `nested` lists,+edited through the built-in nested editor; every string comes from the catalog+(FR20); the empty results of Add filter's searches carry Core's titles (FR13);+Clear all says "All filters removed" when no read-only filter remains (AR6); a+one-tap `empty` filter added from its field row is announced `Added {label}`+(AR6); a caller's `Editor` override receives only what the popover presentation+passes it (FR14); and the flow mounts nothing until a press (PR5). Rejected: switchingsurfaces automatically on `pointer: coarse` without an opt-in (changes stablebehavior). Rejected: steps that replace one another in place with Back actions-to return (the first Core draft and the earlier Lab flow): a dismissal then+to return (an earlier draft of the flow): a dismissal thenclosed the whole flow from any step, and the person re-entered Filters by itsentry point rather than finding it where they left it. Rejected: Remove in thevalue step's footer (a second removal path, reached only by opening the step;@@ -630,11 +621,7 @@ and its staged state and scroll position recreated, and a dismissal could notreveal it. The counts are `document.body.querySelectorAll('*').length` at390×844. The bound AV5 measures the flow against is the popover presentation'sopen editor on the Experimental Adaptive story under a fine pointer: 334, and-166 at rest. The prototype's Touch flow story under a coarse pointer reads 338-at rest, 339 with Filters open, 340 with Add filter above Filters, 366 with a-choice-row value step above both, 429 with a list-value step above both, and 413-with an edit step above Filters; it keeps all three sheets mounted from the-first render, so its rest count already carries them. Core's sheet flow, on the same story under a coarse pointer, each state read once it has settled (every open dialog is that state's own and two readings one second apart agree), reads 123 at rest, 313 with Filters open, 314 with Add filter above Filters, 332 with a choice-row value step above both, 349 with a list-value step above both and 420 with the Tokenizer's list-value sheet above that step, 373 with an edit step above Filters, and 333 with the Clear all confirmation above Filters. From the first press until the exit completes, it keeps the closed Add filter sheet and value step mounted, which is most of the step from 123 to 313; the confirmation mounts only while it is open.+166 at rest. The sheet flow, on that story under a coarse pointer, each state read once it has settled (every open dialog is that state's own and two readings one second apart agree), reads 123 at rest, 313 with Filters open, 314 with Add filter above Filters, 332 with a choice-row value step above both, 349 with a list-value step above both and 420 with the Tokenizer's list-value sheet above that step, 373 with an edit step above Filters, and 333 with the Clear all confirmation above Filters. From the first press until the exit completes, it keeps the closed Add filter sheet and value step mounted, which is most of the step from 123 to 313; the confirmation mounts only while it is open.Owner exception to INV7's surface budget, which asks that a pointer-specificpresentation be a change of attributes and styles on the same elements: underdiff --git a/docs/specs/components/Tokenizer/Tokenizer.spec.md b/docs/specs/components/Tokenizer/Tokenizer.spec.mdindex fdf2e7a1fa..05598c90f8 100644--- a/docs/specs/components/Tokenizer/Tokenizer.spec.md+++ b/docs/specs/components/Tokenizer/Tokenizer.spec.md@@ -17,7 +17,7 @@ verified_by:packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx,packages/core/src/internal/SheetConfirmation.test.tsx,packages/core/src/internal/useDismissSearchOnTouchDrag.test.tsx,- packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx,+ packages/core/src/internal/sheetDraft.test.ts,packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx,packages/core/src/PowerSearch/PowerSearch.test.tsx,packages/core/src/Typeahead/Typeahead.test.tsx,@@ -201,35 +201,35 @@ FR16–FR24, FR26, and FR27 describe the `experimental.presentation` optionand its sheet presentation, which has no inline combobox, suggestion menu, orend 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, FR26, and FR27 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 is the inline field's control box: the shared input box — its 1px border, focus ring, surface and radius — the inline field's token inset and row gap, and the `size` block size, so before the sheet opens the field looks the same as the inline field; the touch-sized targets belong to the sheet's rows and actions, not to the closed field. 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 field at the top, a scrolling list of rows, and a footer with Clear all and Save pinned below the list. There is no second sheet. The search field is the shared panel search field drawn as a bordered input box (the input border and surface, element radius, the `lg` input height — 36px — above the sheet's 44px rows) rather than the borderless field a dropdown panel draws; it does not scroll with the list. The footer is rendered in every state of the sheet — while searching, while pending, with an empty query — so Clear all and Save are reachable without clearing the query. 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`). Save commits the draft and closes the sheet (FR26); swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"` and close directly while the draft is unchanged, and ask first while it is changed (FR27). Each close the person makes — Save, a clean dismissal, a confirmed discard — 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. While the search field holds focus on a touch screen, a direct vertical finger drag on the results of at least 8px moves focus from it to the sheet's panel, without clearing the query — a focus rule of the sheet's, so the rows the person reaches for come into view and focus never rests on the page body behind the open modal (`spec:AST-085/FR4`); what the on-screen keyboard does when the field loses focus is `spec:AST-099`'s. A tap, a shorter move, a multi-touch gesture, and a scroll event the list fires on its own (filtering can clamp its scroll position while the person is typing) leave focus where it is. | DEC-3; Lab touch-flow evidence; `component:BottomSheet` | Verified current behavior; the sheet tests and the Lab prototype's share the rows' cases. |-| FR19 | Each row is a `checkbox` named by the item label whose `aria-checked` mirrors membership in the sheet's draft (FR26): the selection the person is editing, which starts as `value` when the sheet opens. Activating an unchecked row adds the item to the draft; a checked row removes it; both apply to the draft at once and are announced with the inline field's words through the sheet's own live region (AR6); `value` and `onChange` are untouched until Save. Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then draft-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; the sheet tests and the Lab prototype's share the rows' cases. |-| 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 draft-selected id, no draft-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 adds to the draft an item with the text as both id and label — reported by Save as a `create` when that create is the last edit that still holds (FR26) — announces it, 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 while the draft is at `maxEntries`. | DEC-3; Lab touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior; the sheet tests and the Lab prototype's share the rows' cases. |-| FR23 | `maxEntries` is enforced on the draft: while the draft holds `maxEntries` items, 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`). While the draft holds more than `maxEntries` — a `value` over the limit when the sheet opened, or `maxEntries` lowered while the sheet is open — Save is `aria-disabled`, still in the focus order, with a tooltip naming the limit ("Select up to {count} items"), and does nothing until the draft is within it. | DEC-3; Lab touch-flow evidence; `spec:AST-085` | Verified current behavior; the sheet tests and the Lab prototype's share the rows' cases. |-| FR24 | Clear all is disabled while the draft 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 the sheet's confirmation (FR27) naming the field, with Cancel as the safe action and Clear selection as the destructive one; confirming empties the draft — recorded as a removal of the draft's last item, which Save names in its `remove` when the clear is the last edit that holds (FR26); `value` is untouched until Save, so a discard restores it — 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. Clear all stays visible and reachable while searching, since the footer is pinned (FR18). | DEC-3; Lab touch-flow evidence | Verified current behavior; the sheet tests and the Lab prototype's share the rows' cases. |-| FR25 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 | Verified current behavior |-| FR26 | One open sheet edits one draft. The draft starts as `value` when the sheet opens and takes every row toggle, create, and Clear all (FR19, FR22, FR24); `value` and `onChange` are untouched while the sheet is open. Save closes the sheet; with an unchanged draft it reports nothing, and with a changed one it reports the whole draft once through `onChange(items, change)`, where `change` names the last edit that still holds: the last toggle, create, or clear when its item is in the draft and was not selected at open (`add`, or `create` for an item created in this sheet) or was selected at open and is not in the draft (`remove`); otherwise, when the last edit was a removal and some item selected at open is gone, a `remove` naming one such item; otherwise an `add` (`create` when the last edit created that item) naming an item in the draft that was not selected at open; otherwise a `remove` naming an item gone since open. A field that is disabled when Save fires reports nothing. A toggle is announced when it happens (AR6), not again on Save. | DEC-4; the Lab prototype's draft and Save | Verified current behavior; the sheet tests and the Lab prototype's share the rows' cases. |-| FR27 | Swipe, scrim, and Escape dismissal of the sheet close it directly while the draft equals the selection at open. While the draft differs, they open a discard confirmation inside the sheet — "Discard changes?", "Your changes to {label} haven't been saved." — with Discard changes as the destructive action and Keep editing as the safe one, which is focused first; Discard changes closes the sheet without reporting the draft, and Keep editing closes the confirmation and moves focus to the search field so editing resumes where the sheet's own reading order starts (`spec:AST-085/FR4`). The sheet's confirmations (this one and Clear all's, FR24) are one modal dialog shape: a title, a description, and two full-width large actions stacked in reading order — the destructive action, then the safe action, which takes focus first; the two actions are one action group (`family:action-groups`) while keeping their separated, full-width, stacked look; scrim and Escape take the safe action. A close the field forces (becoming disabled, FR17) asks nothing and reports nothing: the draft is dropped. | DEC-4; the Lab prototype's discard confirmation | Verified current behavior, with one implementation gap: the confirmation's two actions are separated Buttons, not yet one action group (`family:action-groups`); the Lab prototype's confirmation has the same gap. |+| 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, FR26, and FR27 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 | 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 is the inline field's control box: the shared input box — its 1px border, focus ring, surface and radius — the inline field's token inset and row gap, and the `size` block size, so before the sheet opens the field looks the same as the inline field; the touch-sized targets belong to the sheet's rows and actions, not to the closed field. 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; touch-flow evidence; `spec:AST-085` | Verified current behavior. |+| FR18 | The sheet is a single surface: a search field at the top, a scrolling list of rows, and a footer with Clear all and Save pinned below the list. There is no second sheet. The search field is the shared panel search field drawn as a bordered input box (the input border and surface, element radius, the `lg` input height — 36px — above the sheet's 44px rows) rather than the borderless field a dropdown panel draws; it does not scroll with the list. The footer is rendered in every state of the sheet — while searching, while pending, with an empty query — so Clear all and Save are reachable without clearing the query. 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`). Save commits the draft and closes the sheet (FR26); swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"` and close directly while the draft is unchanged, and ask first while it is changed (FR27). Each close the person makes — Save, a clean dismissal, a confirmed discard — 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. While the search field holds focus on a touch screen, a direct vertical finger drag on the results of at least 8px moves focus from it to the sheet's panel, without clearing the query — a focus rule of the sheet's, so the rows the person reaches for come into view and focus never rests on the page body behind the open modal (`spec:AST-085/FR4`); what the on-screen keyboard does when the field loses focus is `spec:AST-099`'s. A tap, a shorter move, a multi-touch gesture, and a scroll event the list fires on its own (filtering can clamp its scroll position while the person is typing) leave focus where it is. | DEC-3; 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 the sheet's draft (FR26): the selection the person is editing, which starts as `value` when the sheet opens. Activating an unchecked row adds the item to the draft; a checked row removes it; both apply to the draft at once and are announced with the inline field's words through the sheet's own live region (AR6); `value` and `onChange` are untouched until Save. Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then draft-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; 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; 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; touch-flow evidence | Verified current behavior. |+| FR22 | With `hasCreate`, a non-empty trimmed query that matches no draft-selected id, no draft-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 adds to the draft an item with the text as both id and label — reported by Save as a `create` when that create is the last edit that still holds (FR26) — announces it, 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 while the draft is at `maxEntries`. | DEC-3; touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior. |+| FR23 | `maxEntries` is enforced on the draft: while the draft holds `maxEntries` items, 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`). While the draft holds more than `maxEntries` — a `value` over the limit when the sheet opened, or `maxEntries` lowered while the sheet is open — Save is `aria-disabled`, still in the focus order, with a tooltip naming the limit ("Select up to {count} items"), and does nothing until the draft is within it. | DEC-3; touch-flow evidence; `spec:AST-085` | Verified current behavior. |+| FR24 | Clear all is disabled while the draft 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 the sheet's confirmation (FR27) naming the field, with Cancel as the safe action and Clear selection as the destructive one; confirming empties the draft — recorded as a removal of the draft's last item, which Save names in its `remove` when the clear is the last edit that holds (FR26); `value` is untouched until Save, so a discard restores it — 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. Clear all stays visible and reachable while searching, since the footer is pinned (FR18). | DEC-3; touch-flow evidence | Verified current behavior. |+| FR25 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 | Verified current behavior |+| FR26 | One open sheet edits one draft. The draft starts as `value` when the sheet opens and takes every row toggle, create, and Clear all (FR19, FR22, FR24); `value` and `onChange` are untouched while the sheet is open. Save closes the sheet; with an unchanged draft it reports nothing, and with a changed one it reports the whole draft once through `onChange(items, change)`, where `change` names the last edit that still holds: the last toggle, create, or clear when its item is in the draft and was not selected at open (`add`, or `create` for an item created in this sheet) or was selected at open and is not in the draft (`remove`); otherwise, when the last edit was a removal and some item selected at open is gone, a `remove` naming one such item; otherwise an `add` (`create` when the last edit created that item) naming an item in the draft that was not selected at open; otherwise a `remove` naming an item gone since open. A field that is disabled when Save fires reports nothing. A toggle is announced when it happens (AR6), not again on Save. | DEC-4 | Verified current behavior. |+| FR27 | Swipe, scrim, and Escape dismissal of the sheet close it directly while the draft equals the selection at open. While the draft differs, they open a discard confirmation inside the sheet — "Discard changes?", "Your changes to {label} haven't been saved." — with Discard changes as the destructive action and Keep editing as the safe one, which is focused first; Discard changes closes the sheet without reporting the draft, and Keep editing closes the confirmation and moves focus to the search field so editing resumes where the sheet's own reading order starts (`spec:AST-085/FR4`). The sheet's confirmations (this one and Clear all's, FR24) are one modal dialog shape: a title, a description, and two full-width large actions stacked in reading order — the destructive action, then the safe action, which takes focus first; the two actions are one action group (`family:action-groups`) while keeping their separated, full-width, stacked look; scrim and Escape take the safe action. A close the field forces (becoming disabled, FR17) asks nothing and reports nothing: the draft is dropped. | DEC-4 | Verified current behavior, with one implementation gap: the confirmation's two actions are separated Buttons, not yet one action group (`family:action-groups`). |### Allowed variation@@ -477,18 +477,18 @@ 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` |-| AR7 | Focused Tokenizer tests, inline and sheet, and the PowerSearch test | inline Clear all; a localized catalog; a Clear all confirmed in the sheet counted across every live region; PowerSearch's own words | The inline Clear all is silent, speaks words other than its catalog message, a sheet Clear all is announced twice, or PowerSearch speaks Tokenizer's words. | `audit:Tokenizer/accessibility` |-| FR16–FR24, FR26, FR27, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, the Lab prototype's MobileTokenizer tests for the draft, Save, pinned footer, discard confirmation, and results-drag rows, 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, `value` unchanged through toggles, create, and Clear all until Save, Save with an unchanged draft reporting nothing and with a changed one reporting the whole draft and the last holding edit, a clean dismissal closing directly, a dirty dismissal asking — Keep editing back to the search field, Discard changes closing without a report —, the footer present while searching, Save disabled over the limit, a results drag moving focus off the search with the query kept | A field without `experimental` changes, a toggle moves a row, a toggle, the create row, or a confirmed Clear all changes `value` before Save, Save reports more than one change or reports when the draft is unchanged, a swipe, scrim, or Escape closes a changed draft without the discard confirmation or asks on an unchanged one, Save or Clear all leaves while the query is non-empty, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |-| FR25 | `Tokenizer.test.tsx` press-inside case; `component:BaseTypeahead` FR12's verification | Press in the input, press elsewhere | A press in the input that closes the list, or a press elsewhere that leaves it open, fails. | — |-| 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` |+| AR7 | Focused Tokenizer tests, inline and sheet, and the PowerSearch test | inline Clear all; a localized catalog; a Clear all confirmed in the sheet counted across every live region; PowerSearch's own words | The inline Clear all is silent, speaks words other than its catalog message, a sheet Clear all is announced twice, or PowerSearch speaks Tokenizer's words. | `audit:Tokenizer/accessibility` |+| FR16–FR24, FR26, FR27, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, the sheet's draft, Save, pinned footer, discard confirmation and results-drag tests with the draft rule's unit tests, 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, `value` unchanged through toggles, create, and Clear all until Save, Save with an unchanged draft reporting nothing and with a changed one reporting the whole draft and the last holding edit, a clean dismissal closing directly, a dirty dismissal asking — Keep editing back to the search field, Discard changes closing without a report —, the footer present while searching, Save disabled over the limit, a results drag moving focus off the search with the query kept | A field without `experimental` changes, a toggle moves a row, a toggle, the create row, or a confirmed Clear all changes `value` before Save, Save reports more than one change or reports when the draft is unchanged, a swipe, scrim, or Escape closes a changed draft without the discard confirmation or asks on an unchanged one, Save or Clear all leaves while the query is non-empty, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |+| FR25 | `Tokenizer.test.tsx` press-inside case; `component:BaseTypeahead` FR12's verification | Press in the input, press elsewhere | A press in the input that closes the list, or a press elsewhere that leaves it open, fails. | — |+| 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 logdiff --git a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.jsonindex 5d4d0a970e..c39391188f 100644--- a/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json+++ b/internal/eslint-plugin-astryx/no-comment-provenance.baseline.json@@ -2497,85 +2497,6 @@],"packages/lab/src/DiffViewer/DiffViewer.tsx": ["FR13", "FR3", "FR3"],"packages/lab/src/LogStream/LogStream.tsx": ["FR3"],- "packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx": [- "AST-086",- "AST-086",- "AST-086",- "AST-086",- "FR14",- "FR14",- "FR14",- "FR14",- "spec quote",- "spec quote",- "spec quote"- ],- "packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts": [- "FR11",- "FR12",- "component:PowerSearch"- ],- "packages/lab/src/MobileTokenizer/MobileTokenizer.tsx": [- "AR6",- "AR6",- "AR6",- "AR6",- "AR6",- "DEC-3",- "FR14",- "FR14",- "FR16",- "FR16",- "FR17",- "FR17",- "FR17",- "FR17",- "FR18",- "FR18",- "FR18",- "FR18",- "FR20",- "FR20",- "FR20",- "FR20",- "FR20",- "FR20",- "FR24",- "FR24",- "FR3",- "FR3",- "FR5",- "FR5",- "FR5",- "FR5",- "FR7",- "INV3",- "INV7",- "INV7",- "INV7",- "INV7",- "architecture:component-style-authoring",- "architecture:component-style-authoring",- "architecture:react-component-runtime",- "component:Tokenizer",- "component:Tokenizer",- "component:Tokenizer",- "component:Tokenizer",- "family:input-fields",- "spec quote",- "spec quote",- "spec quote",- "spec quote",- "spec quote",- "spec:AST-085",- "spec:AST-085",- "spec:AST-085",- "spec:AST-085",- "spec:AST-085",- "spec:AST-085",- "spec:AST-086",- "spec:AST-086"- ],"packages/lab/src/Sankey/SankeyLabel.tsx": ["#0", "#1"],"packages/lab/src/Schedule/MonthlyView.tsx": ["AR7",diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 5299341137..f9d2ebbbb3 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -617,16 +617,6 @@"path": "components/lab/log-stream","aliases": []},- {- "name": "component-lab-mobile-power-search",- "path": "components/lab/mobile-power-search",- "aliases": []- },- {- "name": "component-lab-mobile-tokenizer",- "path": "components/lab/mobile-tokenizer",- "aliases": []- },{"name": "component-lab-radial-chart","path": "components/lab/radial-chart",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex 0c0c37c09e..3a1276fa7d 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -140,14 +140,6 @@"kind": "component","name": "LogStream"},- {- "kind": "component",- "name": "MobilePowerSearch"- },- {- "kind": "component",- "name": "MobileTokenizer"- },{"kind": "component","name": "RadialChart"diff --git a/packages/core/package.json b/packages/core/package.jsonindex d3da118020..41da5b6138 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -834,11 +834,6 @@"types": "./dist/internal/touch.d.ts","default": "./dist/internal/touch.js"},- "./internal/touch-sheet": {- "source": "./src/internal/touch-sheet.ts",- "types": "./dist/internal/touch-sheet.d.ts",- "default": "./dist/internal/touch-sheet.js"- },"./internal/selectable-card": {"source": "./src/internal/selectable-card.ts","types": "./dist/internal/selectable-card.d.ts",diff --git a/packages/core/src/internal/sheetDraft.ts b/packages/core/src/internal/sheetDraft.tsindex 7e24b489ff..ad310792b2 100644--- a/packages/core/src/internal/sheetDraft.ts+++ b/packages/core/src/internal/sheetDraft.ts@@ -4,8 +4,8 @@* @input A sheet's selection at open, its draft, and the last edit made* @output SheetDraftChange, hasSameSelection, nameSheetDraftChange — the* rules a touch sheet's Save and dismissal share- * @position Core-internal, shared by the Tokenizer sheet and the Lab sheets- * through `internal/touch-sheet`; not a public export+ * @position Core-internal. The Tokenizer sheet uses it, and PowerSearch's+ * list-value step renders that sheet. Not a public export.** A touch sheet edits a draft and reports it once, on Save, with one change:* the last edit that still holds, else the nearest net add or remove. Adiff --git a/packages/core/src/internal/touch-sheet.ts b/packages/core/src/internal/touch-sheet.tsdeleted file mode 100644index 970353ccd9..0000000000--- a/packages/core/src/internal/touch-sheet.ts+++ /dev/null@@ -1,21 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file touch-sheet.ts- * @input The touch sheets' shared confirmation, search-drag dismissal and- * draft rules- * @output `@astryxdesign/core/internal/touch-sheet`: SheetConfirmation,- * useDismissSearchOnTouchDrag, hasSameSelection and nameSheetDraftChange,- * re-exported by name for Lab's sheets- * @position An internal entry reserved for Astryx's own packages:- * undocumented, outside the public API and its compatibility promise,- * versioned in lockstep with Core, and allowed only in Core and Lab by the- * `@astryx/no-core-internal-import` lint rule. Core components import the- * same modules by relative path. Named re-exports only.- *- * SYNC: When modified, update scripts/sync-exports.js.- */-export {SheetConfirmation} from './SheetConfirmation';-export type {SheetConfirmationProps} from './SheetConfirmation';-export {useDismissSearchOnTouchDrag} from './useDismissSearchOnTouchDrag';-export {hasSameSelection, nameSheetDraftChange} from './sheetDraft';-export type {SheetDraftChange} from './sheetDraft';diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjsdeleted file mode 100644index 4e83290e8e..0000000000--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs+++ /dev/null@@ -1,160 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */-export const docs = {- name: 'MobilePowerSearch',- displayName: 'Mobile Power Search',- group: 'MobilePowerSearch',- category: 'Form Controls',- keywords: [- 'power search',- 'filters',- 'mobile',- 'touch',- 'bottom sheet',- 'filter builder',- ],- props: [- {- name: 'config',- type: 'PowerSearchConfig',- description:- 'Core PowerSearch configuration: fields, operators, and an optional contentSearchFieldKey.',- required: true,- },- {- name: 'filters',- type: 'ReadonlyArray<PowerSearchFilter>',- description: 'Currently active filters (Core PowerSearchFilter).',- required: true,- },- {- name: 'onChange',- type: '(filters, changeType, index) => void',- description:- "Mirrors Core PowerSearch: the next filters plus 'add' | 'edit' | 'remove' and the affected index.",- required: true,- },- {- name: 'label',- type: 'string',- description: 'Accessible label for the field and its trigger.',- default: "'Manage filters'",- },- {- name: 'placeholder',- type: 'string',- description:- 'Trigger text when no filter is selected; also the content-search placeholder.',- },- {- name: 'size',- type: "'sm' | 'md' | 'lg'",- description: 'Field size; tokens follow it.',- default: "'md'",- },- {- name: 'isDisabled',- type: 'boolean',- description:- 'Disables the field; the sheet cannot open. Pair with disabledMessage to explain why.',- default: 'false',- },- {- name: 'isReadOnly',- type: 'boolean',- description:- 'Filters stay visible in the Filters sheet but cannot be added, edited, or removed.',- default: 'false',- },- {- name: 'hasClear',- type: 'boolean',- description:- 'Shows Clear all in the Filters sheet footer. Clear all removes every filter, read-only ones included, as the Core PowerSearch clear control does, and reports one `remove` change at the last index.',- default: 'true',- },- {- name: 'timezoneID',- type: 'string',- description:- 'IANA timezone for date values. Used by tokens, Filters rows, and the date editors alike, so a boundary date reads the same everywhere.',- },- {- name: 'maxSearchResults',- type: 'number',- description:- 'Max suggestions for a non-empty field or content-search query.',- default: '10',- },- {- name: 'popoverSaveButtonLabel',- type: 'string',- description: "Label for the edit sheet's confirm action.",- default: "'Apply' when editing, 'Add filter' when creating",- },- {- name: 'components',- type: 'PowerSearchComponents',- description:- 'Core per-type Token and Editor overrides. Tokens render display-only (no onClick/onRemove); an Editor replaces the value sheet body.',- },- {- name: 'resultCount',- type: 'number | string',- description:- 'Shown at the end of the field and announced when it changes.',- },- ],- usage: {- description:- 'Lab prototype for trying the touch PowerSearch flow. Choose it explicitly on touch layouts (for example `const Search = isTouch ? MobilePowerSearch : PowerSearch`); it never switches on pointer type by itself. The whole field is one Manage filters trigger showing display-only tokens. Tapping it opens a tall Filters sheet listing each filter with its value in bold and a direct trailing remove action, an Add filter icon button at the top right, and sticky Clear all and Done actions. One-tap boolean filters use the same trailing remove action as every other removable filter. When there are no filters, the centered Add filter action stands alone; the duplicate header add and footer Done controls are hidden. Clear all asks for confirmation, removes editable filters without closing the sheet, and preserves read-only filters. Opening the rest of a row edits that filter with Cancel and Apply. Add filter opens directly when no filter exists and leaves search unfocused until the user chooses it; when the config names a content-search field it carries that search with inline suggestions. Creating a filter drills field → operator (radios, only when a field has more than one) → value. A value editor that is the sheet’s only section sits directly on the sheet surface; multiple sections use separate muted containers. The previous step remains open beneath the current standalone BottomSheet, so Escape, a scrim press, or a downward swipe dismisses the current sheet and reveals that retained step; the Add filter header stays action-free. the stack keeps one scrim and blocks covered sheets. Single-value choices use persistent radio indicators and multi-value choices use persistent checkbox indicators. Searchable string and entity lists and date calendars remain inline in the value sheet; date-only and date-range selections honor timezoneID, while date-time operators keep their date-and-time input. Announcements made while a sheet is open are delivered inside that dialog. Filters remain keyed by identity across controlled reorder, stale filters stay visible and removable, and controlled removals re-home focus. The scroll viewport reaches the sheet edge while padded inner content aligns with the fixed header. Dragging the results dismisses the search keyboard without clearing the query; filtering keeps search focused. Fields whose only operators are nested are left out with a development warning.',- bestPractices: [- {- guidance: true,- description:- 'Try this in Lab/canary on touch layouts to validate the flow; the API mirrors Core PowerSearch so graduating is an import swap.',- },- {- guidance: true,- description:- 'Pass timezoneID whenever filters carry dates, so tokens, rows, and editors agree on the calendar day.',- },- {- guidance: false,- description:- 'Do not switch between MobilePowerSearch and PowerSearch while a sheet is open: the two keep separate draft state.',- },- {- guidance: false,- description:- 'Do not ship stable product on this Lab API; it has no theming, i18n, or spec contract yet.',- },- ],- anatomy: [- {- name: 'Trigger field',- required: true,- description:- 'Bordered field with display-only tokens; the entire field opens the sheet.',- },- {- name: 'Filters sheet',- required: true,- description:- 'Tall sheet with a heading, an Add filter icon button, editable rows with direct trailing remove actions, and sticky Clear all plus Done.',- },- {- name: 'Add filter sheet',- required: true,- description:- 'A full-width Done footer when entered directly; otherwise the action-free header is followed by a field list grouped under General or each configured field group (searchable past eight fields), or the content search with inline suggestions.',- },- {- name: 'Value sheet',- required: true,- description:- 'Field or field-and-operator title, operator radios when needed, the value editor, and Cancel plus Add filter or Apply. String and entity lists search and select inline in the current sheet; date-only and date-range values use an inline Calendar.',- },- ],- },-};diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsxdeleted file mode 100644index e13e4d7f69..0000000000--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx+++ /dev/null@@ -1,2860 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file MobilePowerSearch.test.tsx- * @input Uses vitest, @testing-library/react, MobilePowerSearch (Lab) and its- * helpers- * @output Unit tests for the Lab touch PowerSearch flow: trigger, Filters- * sheet, Add filter, operator step, each value type, content search, focus- * restoration, timezone boundary dates, disabled/read-only, onChange- * metadata, nested exclusion- * @position Lab testing; validates MobilePowerSearch.tsx,- * MobilePowerSearchValueEditor.tsx and mobilePowerSearchUtils.ts- *- * SYNC: When MobilePowerSearch.tsx changes, update tests to match new behavior- */--import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {- act,- render,- screen,- fireEvent,- waitFor,- within,-} from '@testing-library/react';-import React, {createRef, StrictMode, useState} from 'react';-import type {- PowerSearchConfig,- PowerSearchEditorProps,- PowerSearchFilter,- PowerSearchHandle,- PowerSearchTokenProps,-} from '@astryxdesign/core/PowerSearch';-import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';-import {MobilePowerSearch} from './MobilePowerSearch';-import {- createContentSearchSource,- createMobilePowerSearchConfig,- isoDateTimeToUnixSeconds,- isoDateToUnixSeconds,- nearestEditableIndex,- resolveFilterIdentityIndex,- filterSignature,- unixSecondsToISODate,- unixSecondsToISODateTime,-} from './mobilePowerSearchUtils';--// jsdom implements neither <dialog> open/close nor pointer capture; the sheet-// needs both. Same stubs BottomSheet's own tests install.-beforeEach(async () => {- 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();- }- // jsdom has no showModal(), so an open dialog never matches `:modal`; stand- // in for the sheets the browser presents modally, so `useAnnounce` routes- // into the open sheet's dialog as it does in a browser.- const matches = Element.prototype.matches;- vi.spyOn(Element.prototype, 'matches').mockImplementation(function (- this: Element,- selector: string,- ) {- return selector === ':modal'- ? this instanceof HTMLDialogElement && this.open- : matches.call(this, selector);- });- vi.stubGlobal(- 'matchMedia',- vi.fn().mockReturnValue({- matches: false,- media: '',- onchange: null,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- addListener: vi.fn(),- removeListener: vi.fn(),- dispatchEvent: vi.fn(),- }),- );- // useAnnounce reads the frame id inside its callback, so the callback must- // not run before requestAnimationFrame returns.- vi.stubGlobal(- 'requestAnimationFrame',- vi.fn((callback: FrameRequestCallback) =>- window.setTimeout(() => callback(performance.now()), 0),- ),- );- vi.stubGlobal(- 'cancelAnimationFrame',- vi.fn((id: number) => window.clearTimeout(id)),- );- window.scrollTo = vi.fn();- // The shared page-body live regions outlive a test and clear on a 2s- // timer, and a previous test's announcement may still be a frame away —- // or, for words a closing modal dialog hands on to the page body, two; let- // them land, then start this test with the regions empty.- await new Promise(resolve => setTimeout(resolve, 20));- for (const region of document.querySelectorAll(- 'body > [data-astryx-live-region]',- )) {- region.textContent = '';- }-});--afterEach(() => {- vi.unstubAllGlobals();- vi.restoreAllMocks();-});--// =============================================================================-// Fixtures-// =============================================================================--const STATUS_VALUES = [- {value: 'open', label: 'Open'},- {value: 'closed', label: 'Closed'},-];--const config: PowerSearchConfig = {- name: 'Issues',- fields: [- {- key: 'status',- label: 'Status',- description: 'Workflow state',- operators: [- {key: 'is', label: 'is', value: {type: 'enum', values: STATUS_VALUES}},- {- key: 'isNot',- label: 'is not',- value: {type: 'enum', values: STATUS_VALUES},- },- {key: 'isEmpty', label: 'is empty', value: {type: 'empty'}},- ],- },- {- key: 'author',- label: 'Author',- operators: [{key: 'is', label: 'is', value: {type: 'string'}}],- },- {- key: 'labels',- label: 'Labels',- group: 'Metadata',- operators: [- {- key: 'isAnyOf',- label: 'is any of',- value: {- type: 'enum_list',- values: [- {value: 'bug', label: 'Bug'},- {value: 'urgent', label: 'Urgent'},- ],- },- },- ],- },- {- key: 'unassigned',- label: 'Unassigned',- operators: [{key: 'isTrue', label: 'is true', value: {type: 'empty'}}],- },- ],-};--const contentSearchConfig: PowerSearchConfig = {- ...config,- name: 'ContentSearch',- contentSearchFieldKey: 'author',-};--const openFilter: PowerSearchFilter = {- field: 'status',- operator: 'is',- value: {type: 'enum', value: 'open'},-};--const authorFilter: PowerSearchFilter = {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'Ada'},-};--const unassignedFilter: PowerSearchFilter = {- field: 'unassigned',- operator: 'isTrue',- value: {type: 'empty'},-};--const people: SearchableItem[] = [- {id: 'p1', label: 'Ada Lovelace'},- {id: 'p2', label: 'Grace Hopper'},-];-const peopleSource: SearchSource = {- search: q =>- people.filter(p => p.label.toLowerCase().includes(q.toLowerCase())),- bootstrap: () => people,-};--/** One field per non-nested value type Core PowerSearch supports. */-const valueTypesConfig: PowerSearchConfig = {- name: 'ValueTypes',- fields: [- {- key: 'title',- label: 'Title',- operators: [- {key: 'contains', label: 'contains', value: {type: 'string'}},- ],- },- {- key: 'owner',- label: 'Owner',- operators: [- {- key: 'is',- label: 'is',- value: {type: 'string', searchSource: peopleSource},- },- ],- },- {- key: 'ids',- label: 'ID',- operators: [- {key: 'in', label: 'is any of', value: {type: 'string_list'}},- ],- },- {- key: 'lines',- label: 'Lines',- operators: [- {- key: 'gt',- label: 'is greater than',- value: {type: 'integer', minValue: 0, units: 'lines'},- },- ],- },- {- key: 'cost',- label: 'Cost',- operators: [{key: 'gt', label: '>', value: {type: 'float'}}],- },- {- key: 'alarm',- label: 'Alarm',- operators: [{key: 'at', label: 'at', value: {type: 'time'}}],- },- {- key: 'created',- label: 'Created',- operators: [- {- key: 'after',- label: 'is after',- value: {type: 'date_absolute', isDateOnly: true},- },- ],- },- {- key: 'updated',- label: 'Updated',- operators: [- {- key: 'after',- label: 'is after',- value: {type: 'date_absolute', isDateOnly: false},- },- ],- },- {- key: 'age',- label: 'Age',- operators: [- {- key: 'newer',- label: 'is newer than',- value: {type: 'date_relative', isFutureAllowed: false},- },- ],- },- {- key: 'window',- label: 'Window',- operators: [- {key: 'between', label: 'is between', value: {type: 'date_range'}},- ],- },- {- key: 'assignee',- label: 'Assignee',- operators: [- {- key: 'anyOf',- label: 'is any of',- value: {type: 'entity_list', searchSource: peopleSource},- },- ],- },- {- key: 'color',- label: 'Color',- operators: [- {- key: 'is',- label: 'is',- value: {- type: 'custom',- Editor: ({value, onChange, placeholder}) => (- <input- aria-label="Color editor"- placeholder={placeholder}- value={value ?? ''}- onChange={e => onChange(e.target.value)}- />- ),- getString: v => v.toUpperCase(),- },- },- ],- },- ],-};--function setup(- props: Partial<React.ComponentProps<typeof MobilePowerSearch>> = {},-) {- const onChange = vi.fn();- const result = render(- <MobilePowerSearch- config={config}- filters={[]}- onChange={onChange}- {...props}- />,- );- return {onChange, ...result};-}--/**- * The polite live region `useAnnounce` keeps inside an open sheet's dialog,- * created on the first message delivered there; read inside `waitFor`.- */-function sheetRegion(): HTMLElement {- const region = sheet().querySelector<HTMLElement>(- ':scope > [data-astryx-modal-live-region="polite"]',- );- if (!region) {- throw new Error('no live region inside the open sheet yet');- }- return region;-}--const pageRegionText = () =>- document.querySelector('body > [data-astryx-live-region="polite"]')- ?.textContent ?? '';--function trigger(): HTMLElement {- return document.querySelector<HTMLElement>('[aria-haspopup="dialog"]')!;-}--/** The field wrapper holding the tokens and the trigger. */-function field(): HTMLElement {- return trigger().parentElement!;-}--function openSheet(): void {- fireEvent.click(trigger());-}--/**- * Whether the flow is open. The dialog element outlives a close by an exit- * transition that jsdom never fires, so the flow's state is read from the- * trigger's aria-expanded.- */-function isSheetOpen(): boolean {- return trigger().getAttribute('aria-expanded') === 'true';-}--/**- * Every step is its own sheet with its own dialog. During a replace handoff- * the outgoing dialog stays open but inert until its fade completes, so- * return only the active one.- */-function sheet(): HTMLElement {- const dialog = document.querySelector<HTMLElement>(- 'dialog[open]:not([inert])',- );- if (!dialog) {- throw new Error('no active sheet');- }- return dialog;-}--/**- * Completes every pending sheet motion. jsdom resolves no transition timing,- * so the panels wait for a native transitionend; this fires it.- */-function settleSheets(): void {- for (const panel of document.querySelectorAll<HTMLElement>(- '.astryx-bottom-sheet',- )) {- fireEvent.transitionEnd(panel, {propertyName: 'transform'});- fireEvent.transitionEnd(panel, {propertyName: 'opacity'});- }-}--function tapRow(name: RegExp | string): void {- const matches = within(sheet()).getAllByRole('button', {name});- // The replace handoff keeps the outgoing sheet presented while the incoming- // one enters; the last match is always on the sheet that just arrived.- fireEvent.click(matches[matches.length - 1]);- settleSheets();-}--function openAddFlow(): void {- openSheet();- if (within(sheet()).queryByRole('heading', {name: 'Filters'})) {- tapRow('Add filter');- }-}--function openEditFlow(name: RegExp | string): void {- openSheet();- tapRow(name);-}--function apply(): void {- fireEvent.click(within(sheet()).getByRole('button', {name: 'Apply'}));-}--function addFilter(): void {- const matches = within(sheet()).getAllByRole('button', {name: 'Add filter'});- fireEvent.click(matches[matches.length - 1]);-}--// =============================================================================-// Trigger field-// =============================================================================--/**- * The sheet bodies pad their content and publish that padding as container- * padding; each list in them runs edge to edge with `edge="bleed"`, so row- * text keeps the body's inset (spacing-4) while dividers and backgrounds- * reach the sheet's sides. No private Item variable is set.- */-function expectBleedRowsOnBodyInset(list: HTMLElement): void {- expect(list.className).toContain('reachesContainerPadding');- const rows = list.querySelectorAll('li');- expect(rows.length).toBeGreaterThan(0);- for (const row of rows) {- expect(row.className).toMatch(/edgeBleed/);- expect(row.getAttribute('style') ?? '').not.toContain('--_item-inset');- }- // The published padding is the body's inline padding (spacing-4).- const body = list.closest(- '[class*="body"], [class*="scrollContent"]',- ) as HTMLElement | null;- expect(body).not.toBeNull();- const computed = getComputedStyle(body!);- expect(computed.getPropertyValue('--container-padding-inline-start')).toBe(- 'var(--spacing-4)',- );- expect(computed.getPropertyValue('--container-padding-inline-end')).toBe(- 'var(--spacing-4)',- );-}--describe('MobilePowerSearch trigger', () => {- it('names its single sheet trigger by the field label followed by its visible text', () => {- setup({label: 'Filter issues'});- const button = screen.getByRole('button', {name: 'Filter issues Filters…'});- expect(button).toHaveAttribute('aria-haspopup', 'dialog');- expect(button).toHaveTextContent('Filters…');- expect(screen.getAllByRole('button')).toHaveLength(1);- });-- it("keeps the trigger's visible text inside its accessible name with a custom label and placeholder, and with tokens", () => {- // WCAG 2.5.3: a speech-input user says what they see. The name is the- // label plus the visible content: the placeholder when empty...- const {rerender} = setup({- label: 'Search issues',- placeholder: 'Search content…',- });- expect(trigger()).toHaveAccessibleName('Search issues Search content…');- expect(trigger().textContent).toBe('Search content…');- // ...or the tokens once filters are selected.- rerender(- <MobilePowerSearch- config={config}- filters={[openFilter, authorFilter]}- onChange={vi.fn()}- label="Search issues"- placeholder="Search content…"- />,- );- const name = trigger().getAttribute('aria-labelledby')!;- expect(name.split(' ')).toHaveLength(2);- expect(trigger()).toHaveAccessibleName(- /^Search issues .*Status: is.*Open.*Author: is/,- );- for (const visible of ['Status: is', 'Open', 'Author: is']) {- expect(within(field()).getByText(visible)).toBeTruthy();- }- });-- it('renders display-only tokens with bold values and no remove controls', () => {- setup({filters: [openFilter, authorFilter]});- expect(within(field()).getByText('Status: is')).toBeTruthy();- expect(within(field()).getByText('Open')).toHaveStyle({- fontWeight: 'var(--font-weight-bold)',- });- expect(within(field()).getByText('Author: is')).toBeTruthy();- expect(within(field()).queryByRole('button', {name: /^Remove/})).toBeNull();- expect(screen.queryByRole('button', {name: 'Clear all'})).toBeNull();- });-- it('opens the Filters sheet when a token is tapped and returns focus to the trigger', () => {- setup({filters: [openFilter]});- fireEvent.click(within(field()).getByText('Open'));- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));- settleSheets();- expect(trigger()).toHaveFocus();- });-- it('wraps tokens without reserving a row for the trigger', () => {- setup({filters: [openFilter, authorFilter]});- const button = screen.getByRole('button', {name: /^Manage filters/});- expect(getComputedStyle(button.parentElement!).flexWrap).toBe('wrap');- expect(getComputedStyle(button).position).toBe('absolute');- });-- it('does not open when disabled, and the trigger stays focusable through aria-disabled rather than native disabled', () => {- setup({isDisabled: true});- openSheet();- expect(isSheetOpen()).toBe(false);- expect(trigger()).not.toBeDisabled();- expect(trigger()).toHaveAttribute('aria-disabled', 'true');- trigger().focus();- expect(trigger()).toHaveFocus();- });-- it('keeps the trigger focusable when a disabled reason is given', () => {- setup({isDisabled: true, disabledMessage: 'Pick a project first'});- expect(trigger().hasAttribute('disabled')).toBe(false);- expect(trigger().getAttribute('aria-disabled')).toBe('true');- openSheet();- expect(isSheetOpen()).toBe(false);- });-- it('auto-focuses the trigger when requested', () => {- setup({hasAutoFocus: true});- expect(trigger()).toHaveFocus();- });-- it('fires focus callbacks when focus crosses the field boundary', () => {- const onFocus = vi.fn();- const onBlur = vi.fn();- setup({filters: [openFilter], onFocus, onBlur});- fireEvent.focus(trigger(), {relatedTarget: null});- expect(onFocus).toHaveBeenCalledTimes(1);- expect(onBlur).not.toHaveBeenCalled();- fireEvent.blur(trigger(), {relatedTarget: document.body});- expect(onBlur).toHaveBeenCalledTimes(1);- });-- it('focuses the trigger through the Core imperative handle', () => {- const handle = createRef<PowerSearchHandle>();- setup({handleRef: handle});- handle.current?.focusTypeahead();- expect(trigger()).toHaveFocus();- handle.current?.blurTypeahead();- expect(trigger()).not.toHaveFocus();- });-- it('renders the result count and announces a change to it', () => {- const {rerender} = setup({resultCount: 12});- expect(screen.getByText('12 results')).toBeTruthy();- rerender(- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- resultCount={1}- />,- );- expect(screen.getByText('1 result')).toBeTruthy();- });-- it('announces a result count change through the page channel while closed, and nothing for the count present on mount, under StrictMode', async () => {- const pageRegion = () =>- document.querySelector('[data-astryx-live-region="polite"]');- const {rerender} = render(- <StrictMode>- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- resultCount={12}- />- </StrictMode>,- );- // StrictMode mounts, unmounts and remounts effects; a mounted-flag guard- // announces the initial count on the replay. The region stays empty.- await act(async () => {- await new Promise(resolve => setTimeout(resolve, 20));- });- expect(pageRegion()?.textContent ?? '').toBe('');- // A real change announces once, with the words shown.- rerender(- <StrictMode>- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- resultCount={1}- />- </StrictMode>,- );- await waitFor(() => expect(pageRegion()?.textContent).toBe('1 result'));- // The same value again is not a new occasion.- rerender(- <StrictMode>- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- resultCount={1}- />- </StrictMode>,- );- await act(async () => {- await new Promise(resolve => setTimeout(resolve, 20));- });- expect(pageRegion()?.textContent).toBe('1 result');- });-- it('routes a result count change to the live region useAnnounce keeps inside the open sheet, not the page body', async () => {- const {rerender} = setup({resultCount: 12});- openSheet();- rerender(- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- resultCount={3}- />,- );- await waitFor(() => expect(sheetRegion().textContent).toBe('3 results'));- expect(sheetRegion()).toHaveAttribute('aria-live', 'polite');- // The page-body channel, which a native modal hides, is left alone.- expect(pageRegionText()).toBe('');- });-- it('forwards display-only props to token overrides', () => {- const seenProps = vi.fn();- function CustomToken(props: PowerSearchTokenProps) {- seenProps(props);- return <span>Custom token</span>;- }- setup({filters: [openFilter], components: {enum: {Token: CustomToken}}});- expect(screen.getByText('Custom token')).toBeTruthy();- expect(seenProps).toHaveBeenCalledWith(- expect.objectContaining({- filter: openFilter,- onClick: undefined,- onRemove: undefined,- }),- );- });-});--// =============================================================================-// Filters sheet-// =============================================================================--describe('MobilePowerSearch Filters sheet', () => {- it('shows selected filters as editable rows with direct remove actions and bold values', () => {- setup({filters: [openFilter]});- openSheet();- const list = within(sheet()).getByRole('list');- const row = within(list).getByRole('button', {name: 'Status is Open'});- expect(within(row).getByText('Open')).toHaveStyle({- fontWeight: 'var(--font-weight-bold)',- });- expect(- within(list).getByRole('button', {name: 'Remove Status filter'}),- ).toBeTruthy();- });-- it('uses a direct remove button for an applied one-tap filter instead of a checked indicator', () => {- const {onChange} = setup({filters: [unassignedFilter]});- openSheet();- const remove = within(sheet()).getByRole('button', {- name: 'Remove Unassigned filter',- });- expect(remove.querySelector('svg')).toBeTruthy();- expect(within(sheet()).queryByText('Unassigned, selected')).toBeNull();- fireEvent.click(remove);- expect(onChange).toHaveBeenCalledWith([], 'remove', 0);- });-- it('shows only the centered Add filter action when no filters are applied', () => {- function EmptyStateHarness() {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([- openFilter,- ]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<EmptyStateHarness />);- openSheet();- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove Status filter'}),- );- const addActions = within(sheet()).getAllByRole('button', {- name: 'Add filter',- });- expect(addActions).toHaveLength(1);- expect(within(sheet()).queryByRole('button', {name: 'Done'})).toBeNull();- expect(- within(sheet()).queryByRole('button', {name: 'Clear all'}),- ).toBeNull();- });-- it('places the Add filter icon in the header and full-width Clear all plus Done in the fixed footer', () => {- setup({filters: [openFilter]});- openSheet();- const heading = within(sheet()).getByRole('heading', {name: 'Filters'});- const list = within(sheet()).getByRole('list');- const add = within(sheet()).getByRole('button', {name: 'Add filter'});- const clearAll = within(sheet()).getByRole('button', {name: 'Clear all'});- const done = within(sheet()).getByRole('button', {name: 'Done'});- expect(- heading.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();- expect(- add.compareDocumentPosition(list) & Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();- expect(- list.compareDocumentPosition(clearAll) & Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();- expect(add).toHaveAttribute('data-variant', 'secondary');- expect(done).toHaveAttribute('data-variant', 'primary');- expect(clearAll).toHaveAttribute('data-variant', 'secondary');- expect(getComputedStyle(clearAll).flexGrow).toBe('1');- expect(getComputedStyle(done).flexGrow).toBe('1');- expect(getComputedStyle(clearAll.parentElement!).position).toBe('relative');- });-- it('runs filter rows edge to edge on the body inset (List edge="bleed")', () => {- setup({filters: [openFilter, authorFilter]});- openSheet();- expectBleedRowsOnBodyInset(within(sheet()).getByRole('list'));- });-- it('closes on Done and restores focus to the trigger', () => {- setup({filters: [openFilter]});- openSheet();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));- expect(isSheetOpen()).toBe(false);- settleSheets();- expect(trigger()).toHaveFocus();- });-- it('clears removable filters, keeps Filters open, and announces the outcome there', async () => {- function Harness() {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([- openFilter,- ]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<Harness />);- openSheet();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));- const confirmation = screen.getByRole('alertdialog', {- name: 'Clear all filters?',- });- fireEvent.click(- within(confirmation).getByRole('button', {name: 'Clear filters'}),- );- expect(isSheetOpen()).toBe(true);- expect(within(sheet()).getByText('No filters applied')).toBeTruthy();- expect(within(field()).queryByText('Open')).toBeNull();- await waitFor(() =>- expect(sheetRegion().textContent).toContain('Editable filters removed'),- );- expect(pageRegionText()).toBe('');- });-- it('returns to Filters unchanged when the clear confirmation scrim is pressed', () => {- const {onChange} = setup({filters: [openFilter]});- openSheet();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));- const confirmation = screen.getByRole('alertdialog', {- name: 'Clear all filters?',- });- // A scrim press starts and ends on the dialog itself.- fireEvent.pointerDown(confirmation);- fireEvent.pointerUp(confirmation);- fireEvent.click(confirmation);- expect(- screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),- ).toBeNull();- expect(onChange).not.toHaveBeenCalled();- expect(isSheetOpen()).toBe(true);- expect(within(sheet()).getByText('Status is')).toBeTruthy();- });-- it('clears every removable filter but keeps read-only ones', () => {- const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};- const {onChange} = setup({filters: [authorFilter, pinned]});- openSheet();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));- expect(onChange).not.toHaveBeenCalled();- fireEvent.click(- within(- screen.getByRole('alertdialog', {name: 'Clear all filters?'}),- ).getByRole('button', {name: 'Clear filters'}),- );- expect(onChange).toHaveBeenCalledWith([pinned], 'remove', 0);- expect(isSheetOpen()).toBe(true);- });-- it('respects hasClear', () => {- setup({filters: [openFilter], hasClear: false});- openSheet();- expect(- within(sheet()).queryByRole('button', {name: 'Clear all'}),- ).toBeNull();- expect(within(sheet()).getByRole('button', {name: 'Done'})).toBeTruthy();- });-- it('opens a read-only Filters sheet without mutation actions', () => {- const {onChange} = setup({filters: [openFilter], isReadOnly: true});- openSheet();- expect(isSheetOpen()).toBe(true);- expect(within(sheet()).getByText('Status is')).toBeTruthy();- expect(- within(sheet()).queryByRole('button', {name: 'Status is Open'}),- ).toBe(null);- expect(- within(sheet()).queryByRole('button', {name: 'Clear all'}),- ).toBeNull();- expect(- within(sheet()).queryByRole('button', {name: 'Add filter'}),- ).toBeNull();- expect(onChange).not.toHaveBeenCalled();- });-- it('keeps read-only filters as plain rows next to editable ones', () => {- const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};- setup({filters: [pinned, authorFilter]});- openSheet();- expect(- within(sheet()).queryByRole('button', {name: 'Status is Open'}),- ).toBe(null);- expect(- within(sheet()).getByRole('button', {name: 'Author is Ada'}),- ).toBeTruthy();- });-- it('hides Clear all when every filter is read-only', () => {- setup({filters: [{...openFilter, isReadOnly: true}]});- openSheet();- expect(- within(sheet()).queryByRole('button', {name: 'Clear all'}),- ).toBeNull();- });-});--// =============================================================================-// Add filter-// =============================================================================--describe('MobilePowerSearch Add filter', () => {- it('keeps the sticky header above the rows that scroll under it, without covering the grab handle', () => {- setup();- openAddFlow();- const title = within(sheet()).getByRole('heading', {name: 'Add filter'});- // The title sits in the sticky header; the header's parent is the sheet- // content wrapper.- let header: HTMLElement | null = title;- while (header && getComputedStyle(header).position !== 'sticky') {- header = header.parentElement;- }- expect(header).not.toBeNull();- const content = header!.parentElement!;- // jsdom resolves the injected StyleX rules: the header has a layer above- // the List rows (position: relative, z-index auto) that follow it...- expect(getComputedStyle(header!).zIndex).toBe('1');- // ...scoped to the sheet content, so the panel's grab handle (z-index 1,- // outside this wrapper) still paints above the header.- const rules: string[] = [];- for (const styleSheet of Array.from(document.styleSheets)) {- for (const rule of Array.from(styleSheet.cssRules)) {- rules.push(rule.cssText);- }- }- const isolated = Array.from(content.classList).some(className =>- rules.some(- text =>- text.includes(`.${className}`) && /isolation:\s*isolate/.test(text),- ),- );- expect(isolated).toBe(true);- });-- it('opens directly to Add filter when no filters are selected', () => {- setup();- openSheet();- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- expect(- within(sheet()).queryByRole('heading', {name: 'Filters'}),- ).toBeNull();- });-- it('closes to the trigger when footer Done is pressed from direct entry', () => {- setup();- openSheet();- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- expect(within(sheet()).queryByRole('button', {name: 'Close'})).toBeNull();- expect(within(sheet()).queryByRole('button', {name: 'Cancel'})).toBeNull();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));- expect(isSheetOpen()).toBe(false);- settleSheets();- expect(trigger()).toHaveFocus();- });-- it('returns to Filters and focuses Add filter when Add filter is dismissed from management', () => {- setup({filters: [openFilter]});- openAddFlow();- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- fireEvent.keyDown(sheet(), {key: 'Escape'});- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- expect(- within(sheet()).getByRole('button', {name: 'Add filter'}),- ).toHaveFocus();- });-- it('lists the fields, grouped, with chevrons', () => {- setup();- openAddFlow();- const status = within(sheet()).getByRole('button', {name: 'Status'});- expect(status.textContent).toBe('Status');- expect(- within(sheet()).getByRole('heading', {name: 'General', level: 4}),- ).toBeTruthy();- expect(within(sheet()).getByRole('list', {name: 'General'})).toBeTruthy();- expect(within(sheet()).getByRole('button', {name: 'Author'})).toBeTruthy();- expect(- within(sheet()).getByRole('heading', {name: 'Metadata', level: 4}),- ).toBeTruthy();- expect(within(sheet()).getByRole('list', {name: 'Metadata'})).toBeTruthy();- expect(status.closest('li')?.querySelectorAll('svg')).toHaveLength(1);- });-- it('offers no field search for a short list', () => {- setup();- openAddFlow();- expect(within(sheet()).queryByRole('textbox')).toBeNull();- });-- it('searches the field list once there are enough fields', () => {- const many: PowerSearchConfig = {- name: 'Many',- fields: Array.from({length: 10}, (_, i) => ({- key: `f${i}`,- label: `Field ${i}`,- operators: [{key: 'is', label: 'is', value: {type: 'string'} as const}],- })),- };- setup({config: many, maxSearchResults: 2});- openAddFlow();- const search = within(sheet()).getByRole('textbox', {- name: 'Search filters',- });- expect(search).not.toHaveFocus();- search.focus();- const scrollBody = Array.from(- sheet().querySelectorAll<HTMLElement>('div'),- ).find(element => getComputedStyle(element).overflowY === 'auto')!;- fireEvent.scroll(scrollBody);- expect(search).toHaveFocus();- fireEvent.touchStart(scrollBody, {touches: [{clientY: 100}]});- fireEvent.touchMove(scrollBody, {touches: [{clientY: 107}]});- expect(search).toHaveFocus();- fireEvent.touchMove(scrollBody, {touches: [{clientY: 109}]});- expect(search).not.toHaveFocus();- search.focus();- fireEvent.change(search, {target: {value: 'Field'}});- fireEvent.scroll(scrollBody);- expect(search).toHaveFocus();- expect(- within(sheet()).getAllByRole('button', {name: /^Field/}),- ).toHaveLength(2);- fireEvent.change(search, {target: {value: 'Field 7'}});- expect(within(sheet()).getByRole('button', {name: 'Field 7'})).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Field 3'})).toBeNull();- fireEvent.change(search, {target: {value: 'nope'}});- expect(within(sheet()).getByText('No filters found')).toBeTruthy();- });-- it('leaves out nested-only fields and warns the developer', () => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});- const withNested: PowerSearchConfig = {- name: 'Nested',- fields: [- ...config.fields,- {- key: 'group',- label: 'Group',- operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],- },- {- key: 'mixed',- label: 'Mixed',- operators: [- {key: 'all', label: 'all of', value: {type: 'nested'}},- {key: 'is', label: 'is', value: {type: 'string'}},- ],- },- ],- };- setup({config: withNested});- openAddFlow();- expect(within(sheet()).queryByRole('button', {name: 'Group'})).toBeNull();- expect(within(sheet()).getByRole('button', {name: 'Mixed'})).toBeTruthy();- expect(warn).toHaveBeenCalledWith(- expect.stringContaining('MobilePowerSearch: 1 field(s) were left out'),- );- // The mixed field offers only its non-nested operator.- tapRow('Mixed');- expect(- within(sheet()).getByRole('heading', {name: 'Mixed is'}),- ).toBeTruthy();- expect(within(sheet()).queryByRole('radiogroup')).toBeNull();- warn.mockRestore();- });-- it('disables an open field picker when the component becomes read-only', () => {- const {rerender} = setup();- openAddFlow();- rerender(- <MobilePowerSearch- config={config}- filters={[]}- onChange={vi.fn()}- isReadOnly- />,- );- const status = within(sheet()).getByRole('button', {name: 'Status'});- expect(status).toBeDisabled();- fireEvent.click(status);- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- });-});--// =============================================================================-// Value sheet: create, operator step, edit, remove-// =============================================================================--describe('MobilePowerSearch value sheet', () => {- it('keeps field rows edge to edge and contains choice rows in their own section', () => {- setup();- openAddFlow();- for (const list of within(sheet()).getAllByRole('list')) {- expectBleedRowsOnBodyInset(list);- }- tapRow('Status');- expect(within(sheet()).getByRole('list').className).not.toContain(- 'reachesContainerPadding',- );- });-- it('stages an enum selection and commits it with exact add metadata', () => {- const {onChange} = setup();- openAddFlow();- tapRow('Status');- tapRow('Closed');- expect(- within(sheet()).getByRole('button', {name: 'Closed, selected'}),- ).toBeTruthy();- expect(onChange).not.toHaveBeenCalled();- addFilter();- expect(onChange).toHaveBeenCalledTimes(1);- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'status',- operator: 'is',- value: {type: 'enum', value: 'closed'},- },- ],- 'add',- 0,- );- });-- it('tapping the full row toggles a choice, not only its label', () => {- setup();- openAddFlow();- tapRow('Labels');- const bugRow = within(sheet())- .getByRole('button', {name: 'Bug'})- .closest('li')!;- // The invisible button fills the row: a tap on the row's padding lands.- fireEvent.click(bugRow.querySelector('button')!);- expect(- within(sheet()).getByRole('button', {name: 'Bug, selected'}),- ).toBeTruthy();- expect(within(bugRow).queryByRole('button', {name: 'Bug'})).toBeNull();- });-- it('returns to Filters with focus on Add filter once a filter is committed', () => {- setup();- openAddFlow();- tapRow('Status');- tapRow('Closed');- addFilter();- expect(isSheetOpen()).toBe(true);- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- expect(- within(sheet())- .getAllByRole('button', {name: 'Add filter'})- .some(button => button === document.activeElement),- ).toBe(true);- });-- it('adds a single empty-value field immediately without opening an empty editor', () => {- const {onChange} = setup();- openAddFlow();- const fieldPickerPlus = within(sheet())- .getByText('Unassigned')- .closest('li');- expect(fieldPickerPlus?.querySelectorAll('svg')).toHaveLength(1);- tapRow('Unassigned');- expect(onChange).toHaveBeenCalledWith(- [{field: 'unassigned', operator: 'isTrue', value: {type: 'empty'}}],- 'add',- 0,- );- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- });-- it('shows the operator step as radios only when a field has several', () => {- const {onChange} = setup();- openAddFlow();- tapRow('Status');- expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();- expect(- within(sheet()).getByRole('radiogroup', {name: 'Operator'}),- ).toBeTruthy();- const selectedOperator = within(sheet()).getByRole('radio', {- name: 'Status is',- });- expect(selectedOperator).toBeChecked();- expect(- getComputedStyle(selectedOperator.closest('.astryx-item')!).flexDirection,- ).toBe('row-reverse');- fireEvent.click(- within(sheet()).getByRole('radio', {name: 'Status is not'}),- );- tapRow('Open');- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'status',- operator: 'isNot',- value: {type: 'enum', value: 'open'},- },- ],- 'add',- 0,- );- });-- it('puts a single-operator field and its operator on one title line', () => {- setup();- openAddFlow();- tapRow('Author');- expect(- within(sheet()).getByRole('heading', {name: 'Author is'}),- ).toBeTruthy();- expect(within(sheet()).queryByRole('radiogroup')).toBeNull();- });-- it('keeps a staged value across operators of the same type and drops it otherwise', () => {- const {onChange} = setup();- openAddFlow();- tapRow('Status');- tapRow('Open');- fireEvent.click(- within(sheet()).getByRole('radio', {name: 'Status is not'}),- );- expect(- within(sheet()).getByRole('button', {name: 'Open, selected'}),- ).toBeTruthy();- fireEvent.click(- within(sheet()).getByRole('radio', {name: 'Status is empty'}),- );- expect(- within(sheet()).queryByRole('button', {name: /selected/}),- ).toBeNull();- addFilter();- expect(onChange).toHaveBeenCalledWith(- [{field: 'status', operator: 'isEmpty', value: {type: 'empty'}}],- 'add',- 0,- );- });-- it('keeps Add filter disabled until a value is chosen', () => {- setup();- openAddFlow();- tapRow('Author');- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Remove'})).toBeNull();- expect(- within(sheet()).getByRole('button', {name: 'Add filter'}),- ).toBeDisabled();- fireEvent.change(within(sheet()).getByRole('textbox', {name: 'Value'}), {- target: {value: 'Ada'},- });- expect(- within(sheet()).getByRole('button', {name: 'Add filter'}),- ).toBeEnabled();- });-- it('restores focus to the chosen field when creation is canceled', () => {- setup();- openAddFlow();- tapRow('Author');- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- expect(within(sheet()).getByRole('button', {name: 'Author'})).toHaveFocus();- });-- it('stages a multi-select and commits it from the footer', () => {- const {onChange} = setup();- openAddFlow();- tapRow('Labels');- fireEvent.click(within(sheet()).getByRole('button', {name: 'Bug'}));- fireEvent.click(within(sheet()).getByRole('button', {name: 'Urgent'}));- const bug = within(sheet()).getByRole('button', {name: 'Bug, selected'});- const urgent = within(sheet()).getByRole('button', {- name: 'Urgent, selected',- });- expect(bug.closest('li')?.querySelectorAll('svg')).toHaveLength(1);- expect(urgent.closest('li')?.querySelectorAll('svg')).toHaveLength(1);- expect(onChange).not.toHaveBeenCalled();- // Tapping a checked row unchecks it.- fireEvent.click(urgent);- expect(within(sheet()).getByRole('button', {name: 'Urgent'})).toBeTruthy();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Urgent'}));- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'labels',- operator: 'isAnyOf',- value: {type: 'enum_list', value: ['bug', 'urgent']},- },- ],- 'add',- 0,- );- });-- it('opens the edit sheet with only Cancel and Apply from a selected row', () => {- setup({filters: [openFilter]});- openEditFlow('Status is Open');- expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toBeTruthy();- expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: /^Remove/})).toBeNull();- expect(- within(sheet()).getByRole('button', {name: 'Open, selected'}),- ).toBeTruthy();- });-- it('edits a filter only after Apply, with exact edit metadata', () => {- const {onChange} = setup({filters: [authorFilter, openFilter]});- openEditFlow('Status is Open');- tapRow('Closed');- expect(onChange).not.toHaveBeenCalled();- apply();- expect(onChange).toHaveBeenCalledTimes(1);- expect(onChange).toHaveBeenCalledWith(- [- authorFilter,- {- field: 'status',- operator: 'is',- value: {type: 'enum', value: 'closed'},- },- ],- 'edit',- 1,- );- });-- it('uses popoverSaveButtonLabel for the confirm action', () => {- setup({filters: [openFilter], popoverSaveButtonLabel: 'Save'});- openEditFlow('Status is Open');- expect(within(sheet()).getByRole('button', {name: 'Save'})).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();- });-- it('returns from editing to Filters without changes and restores row focus', () => {- const {onChange} = setup({filters: [openFilter]});- openEditFlow('Status is Open');- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(isSheetOpen()).toBe(true);- expect(- within(sheet()).getByRole('button', {name: 'Status is Open'}),- ).toHaveFocus();- expect(onChange).not.toHaveBeenCalled();- });-- it('removes a filter directly from the Filters sheet with exact remove metadata', () => {- const {onChange} = setup({filters: [authorFilter, openFilter]});- openSheet();- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove Status filter'}),- );- expect(onChange).toHaveBeenCalledWith([authorFilter], 'remove', 1);- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- });-- it('moves focus to the nearest editable row after a removal', () => {- const readOnlyLabel: PowerSearchFilter = {- field: 'labels',- operator: 'isAnyOf',- value: {type: 'enum_list', value: ['bug']},- isReadOnly: true,- };- const after: PowerSearchFilter = {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'Grace'},- };- function Harness() {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([- authorFilter,- openFilter,- readOnlyLabel,- after,- ]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<Harness />);- openSheet();- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove Status filter'}),- );- expect(- within(sheet())- .getAllByRole('button', {name: 'Remove Author filter'})- .some(button => button === document.activeElement),- ).toBe(true);- });-- it('focuses Add filter after the last editable filter is removed', () => {- function Harness() {- const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([- openFilter,- ]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<Harness />);- openSheet();- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove Status filter'}),- );- expect(within(sheet()).getByText('No filters applied')).toBeTruthy();- expect(- within(sheet()).getAllByRole('button', {name: 'Add filter'})[0],- ).toHaveFocus();- });-- it('follows the original filter when controlled props reorder it', () => {- const onChange = vi.fn();- const {rerender} = render(- <MobilePowerSearch- config={config}- filters={[openFilter, authorFilter]}- onChange={onChange}- />,- );- openEditFlow('Status is Open');- rerender(- <MobilePowerSearch- config={config}- filters={[{...authorFilter}, {...openFilter}]}- onChange={onChange}- />,- );- tapRow('Closed');- apply();- expect(onChange).toHaveBeenCalledWith(- [- authorFilter,- {- field: 'status',- operator: 'is',- value: {type: 'enum', value: 'closed'},- },- ],- 'edit',- 1,- );- });-- it('does not edit a different filter when the controlled target disappears', () => {- const onChange = vi.fn();- const {rerender} = render(- <MobilePowerSearch- config={config}- filters={[openFilter]}- onChange={onChange}- />,- );- openEditFlow('Status is Open');- rerender(- <MobilePowerSearch- config={config}- filters={[authorFilter]}- onChange={onChange}- />,- );- tapRow('Closed');- apply();- expect(onChange).not.toHaveBeenCalled();- expect(isSheetOpen()).toBe(true);- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- });-- it('keeps a way out when a config update removes the edited field', () => {- const onChange = vi.fn();- const {rerender} = render(- <MobilePowerSearch- config={config}- filters={[openFilter]}- onChange={onChange}- />,- );- openEditFlow('Status is Open');- rerender(- <MobilePowerSearch- config={{- ...config,- fields: config.fields.filter(f => f.key !== 'status'),- }}- filters={[openFilter]}- onChange={onChange}- />,- );- expect(- within(sheet()).getByText('This filter is no longer available'),- ).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- expect(onChange).not.toHaveBeenCalled();- });-- it('closes the flow when the field becomes disabled while a step is open, and does not reopen it when re-enabled', () => {- const {rerender} = setup({filters: [openFilter]});- openEditFlow('Status is Open');- expect(isSheetOpen()).toBe(true);- rerender(- <MobilePowerSearch- config={config}- filters={[openFilter]}- onChange={vi.fn()}- isDisabled- />,- );- expect(isSheetOpen()).toBe(false);- // The trigger is never natively disabled, so the closing flow can hand- // focus back to it instead of the page body.- settleSheets();- expect(trigger()).toHaveFocus();- expect(trigger()).toHaveAttribute('aria-disabled', 'true');- expect(trigger()).not.toBeDisabled();- rerender(- <MobilePowerSearch- config={config}- filters={[openFilter]}- onChange={vi.fn()}- />,- );- expect(isSheetOpen()).toBe(false);- });-- it('commits the complete filter returned by a custom editor', () => {- const savedFilter: PowerSearchFilter = {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'Grace'},- isReadOnly: true,- };- function CustomEditor({onSave, timezoneID}: PowerSearchEditorProps) {- return (- <button type="button" onClick={() => onSave(savedFilter)}>- Custom save {timezoneID}- </button>- );- }- const {onChange} = setup({- components: {enum: {Editor: CustomEditor}},- timezoneID: 'Asia/Tokyo',- });- openAddFlow();- tapRow('Status');- fireEvent.click(- screen.getByRole('button', {name: 'Custom save Asia/Tokyo'}),- );- expect(onChange).toHaveBeenCalledWith([savedFilter], 'add', 0);- });-- it('returns to Filters unchanged when a creating custom editor saves null', () => {- function CustomEditor({onSave}: PowerSearchEditorProps) {- return (- <button type="button" onClick={() => onSave(null)}>- Cancel custom- </button>- );- }- const {onChange} = setup({components: {enum: {Editor: CustomEditor}}});- openAddFlow();- tapRow('Status');- fireEvent.click(screen.getByRole('button', {name: 'Cancel custom'}));- expect(onChange).not.toHaveBeenCalled();- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- });-});--// =============================================================================-// Content search-// =============================================================================--describe('MobilePowerSearch step sheets (retained stack)', () => {- // Dismissing the top step closes only that sheet, so the prior step returns- // through the stack's reveal motion instead of reopening above the current- // one. These assertions read only what a person or assistive technology can- // observe.- function stepDialogs(): HTMLElement[] {- return Array.from(document.querySelectorAll<HTMLElement>('dialog[open]'));- }-- it('Filters opens as one modal dialog, named by the step', () => {- setup({filters: [openFilter]});- openSheet();- // One dialog per presented step, each with its own accessible name.- expect(stepDialogs().map(d => d.getAttribute('aria-label'))).toEqual([- 'Filters',- ]);- expect(sheet()).toHaveAttribute('aria-modal', 'true');- });-- it('pushes Add filter above Filters without a Back button and dismisses it to reveal Filters', () => {- setup({filters: [openFilter]});- openSheet();- const filters = sheet();- tapRow('Add filter');- expect(stepDialogs().map(d => d.getAttribute('aria-label'))).toEqual([- 'Filters',- 'Add filter',- ]);- expect(filters).toHaveAttribute('inert');- expect(filters).toHaveAttribute('aria-hidden', 'true');- expect(sheet()).toHaveAttribute('aria-label', 'Add filter');- expect(sheet()).not.toHaveAttribute('inert');- expect(sheet()).not.toHaveAttribute('aria-hidden');-- settleSheets();- expect(stepDialogs().map(d => d.getAttribute('aria-label'))).toEqual([- 'Filters',- 'Add filter',- ]);-- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- fireEvent.keyDown(sheet(), {key: 'Escape'});- settleSheets();- expect(stepDialogs().map(d => d.getAttribute('aria-label'))).toEqual([- 'Filters',- ]);- expect(sheet()).not.toHaveAttribute('inert');- expect(sheet()).not.toHaveAttribute('aria-hidden');- });-- it('a step on its own is one open modal dialog, interactive and exposed', () => {- setup({filters: [openFilter]});- openSheet();- settleSheets();- expect(stepDialogs()).toHaveLength(1);- expect(sheet()).toHaveAttribute('aria-modal', 'true');- expect(sheet()).not.toHaveAttribute('inert');- expect(sheet()).not.toHaveAttribute('aria-hidden');- });-- it('focus returns to the trigger after a flow that crossed every step (the return target survives each handoff)', () => {- setup({filters: [openFilter]});- trigger().focus();- openSheet();- tapRow('Add filter');- settleSheets();- tapRow(/^Status/);- settleSheets();- expect(sheet()).toHaveAttribute(- 'aria-label',- expect.stringContaining('Status'),- );- // Cancel from the value step, dismiss Add filter, Done from Filters.- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- settleSheets();- expect(sheet()).toHaveAttribute('aria-label', 'Add filter');- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- fireEvent.keyDown(sheet(), {key: 'Escape'});- settleSheets();- expect(sheet()).toHaveAttribute('aria-label', 'Filters');- fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));- expect(isSheetOpen()).toBe(false);- settleSheets();- expect(trigger()).toHaveFocus();- });-- it('Escape on the Filters step closes the flow and returns focus to the trigger', () => {- setup({filters: [openFilter]});- trigger().focus();- openSheet();- settleSheets();- fireEvent.keyDown(sheet(), {key: 'Escape'});- expect(isSheetOpen()).toBe(false);- settleSheets();- expect(trigger()).toHaveFocus();- });-- it('Escape on a nested value step reveals its retained parent', () => {- setup({filters: [openFilter]});- openSheet();- tapRow('Add filter');- tapRow(/^Status/);- settleSheets();- fireEvent.keyDown(sheet(), {key: 'Escape'});- settleSheets();- expect(isSheetOpen()).toBe(true);- expect(sheet()).toHaveAttribute('aria-label', 'Add filter');- });-- it('a scrim press on the Filters step closes the flow; a nested value scrim reveals its parent', () => {- setup({filters: [openFilter]});- openSheet();- settleSheets();- // A click on the dialog element itself is the scrim.- fireEvent.click(sheet());- expect(isSheetOpen()).toBe(false);- settleSheets();-- openSheet();- tapRow('Add filter');- tapRow(/^Status/);- settleSheets();- expect(sheet()).toHaveAttribute(- 'aria-label',- expect.stringContaining('Status'),- );- fireEvent.click(sheet());- settleSheets();- expect(isSheetOpen()).toBe(true);- expect(sheet()).toHaveAttribute('aria-label', 'Add filter');- });-- it('a downward swipe on Add filter reveals Filters instead of closing the flow', () => {- setup({filters: [openFilter]});- openSheet();- tapRow('Add filter');- settleSheets();- const handle = sheet().querySelector<HTMLElement>(- '.astryx-bottom-sheet > div[aria-hidden="true"]',- )!;- fireEvent.pointerDown(handle, {- pointerId: 1,- clientY: 0,- button: 0,- isPrimary: true,- pointerType: 'touch',- });- fireEvent.pointerMove(handle, {- pointerId: 1,- clientY: 40,- pointerType: 'touch',- });- fireEvent.pointerMove(handle, {- pointerId: 1,- clientY: 120,- pointerType: 'touch',- });- fireEvent.pointerUp(handle, {- pointerId: 1,- clientY: 120,- pointerType: 'touch',- });- settleSheets();- expect(isSheetOpen()).toBe(true);- expect(sheet()).toHaveAttribute('aria-label', 'Filters');- });-- it('a scrim press on the covered Filters sheet is ignored while Add filter is on top', () => {- setup({filters: [openFilter]});- openSheet();- const filters = sheet();- tapRow('Add filter');- // The covered Filters dialog stays presented but inert. A click on its own- // dialog must not dismiss the active Add filter sheet or end the flow.- fireEvent.click(filters);- expect(isSheetOpen()).toBe(true);- expect(sheet()).toHaveAttribute('aria-label', 'Add filter');- });-});--describe('MobilePowerSearch content search', () => {- it('opens empty content-search configurations directly to Add filter without focusing the search', () => {- setup({config: contentSearchConfig, placeholder: 'Search content…'});- openSheet();- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- expect(input).toHaveAttribute('placeholder', 'Search content…');- expect(input).not.toHaveFocus();- });-- it('lists suggestions inline below the search, reachable with ArrowDown', () => {- setup({config: contentSearchConfig});- openSheet();- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- const results = within(sheet()).getByRole('list', {name: 'Search results'});- const options = within(results).getAllByRole('button');- expect(options.map(option => option.textContent)).toEqual([- 'Status',- 'Author',- 'Unassigned',- 'Labels',- ]);- expect(document.querySelectorAll('[role="option"]')).toHaveLength(0);- fireEvent.keyDown(input, {key: 'ArrowDown'});- expect(options[0]).toHaveFocus();- fireEvent.keyDown(options[0], {key: 'ArrowDown'});- expect(options[1]).toHaveFocus();- fireEvent.keyDown(options[1], {key: 'ArrowUp'});- expect(options[0]).toHaveFocus();- fireEvent.keyDown(options[0], {key: 'ArrowUp'});- expect(input).toHaveFocus();- });-- it('opens a structured editor from a field suggestion and returns to the search on Cancel', () => {- setup({config: contentSearchConfig});- openSheet();- const results = within(sheet()).getByRole('list', {name: 'Search results'});- fireEvent.click(within(results).getByRole('button', {name: 'Status'}));- expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(- within(sheet()).getByRole('searchbox', {name: 'Search'}),- ).toHaveFocus();- });-- it('adds a free-text suggestion as a content filter and keeps the flow open', async () => {- const {onChange} = setup({- config: contentSearchConfig,- filters: [openFilter],- });- openSheet();- expect(within(sheet()).queryByRole('searchbox')).toBeNull();- tapRow('Add filter');- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- fireEvent.change(input, {target: {value: 'release notes'}});- fireEvent.click(- within(sheet()).getByRole('button', {name: '"release notes"'}),- );- expect(onChange).toHaveBeenCalledWith(- [- openFilter,- {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'release notes'},- },- ],- 'add',- 1,- );- await waitFor(() => expect(isSheetOpen()).toBe(true));- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- // The search sheet held focus as it closed, so words sent with the close- // wait for its exit to end (component:BottomSheet FR9, spec:AST-086- // FR14); settle that exit.- act(() => settleSheets());- // The add is announced inside the sheet the flow is now on, not on the- // page body, which assistive technology does not expose under a native- // modal dialog.- await waitFor(() =>- expect(sheetRegion().textContent).toBe('Added "release notes"'),- );- expect(pageRegionText()).toBe('');- });-- it('announces both the add and a result count that follows the filters in the same commit, joined in the sheet region', async () => {- // A consumer that derives `resultCount` from `filters` re-renders in the- // add's commit, so the count's announcement arrives while the add's is- // still a frame away. Neither may drop the other (FR6, once per- // occasion; FR9's join for messages that arrive before exposure).- function CountFollowsFilters() {- const [filters, setFilters] = useState<PowerSearchFilter[]>([openFilter]);- return (- <MobilePowerSearch- config={contentSearchConfig}- filters={filters}- onChange={next => setFilters([...next])}- resultCount={filters.length * 10}- />- );- }- render(<CountFollowsFilters />);- openSheet();- tapRow('Add filter');- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- fireEvent.change(input, {target: {value: 'release notes'}});- fireEvent.click(- within(sheet()).getByRole('button', {name: '"release notes"'}),- );- await waitFor(() => expect(isSheetOpen()).toBe(true));- // The search sheet held focus as it closed, so words sent with the close- // wait for its exit to end (component:BottomSheet FR9, spec:AST-086- // FR14); settle that exit.- act(() => settleSheets());- await waitFor(() =>- expect(sheetRegion().textContent).toBe(- 'Added "release notes" 20 results',- ),- );- expect(pageRegionText()).toBe('');- });-- it('adds a value suggestion from Enter and announces it', () => {- const {onChange} = setup({config: contentSearchConfig});- openSheet();- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- fireEvent.change(input, {target: {value: 'status clo'}});- expect(- within(sheet()).getByRole('button', {name: 'Status is Closed'}),- ).toBeTruthy();- fireEvent.keyDown(input, {key: 'Enter'});- // The first suggestion is the free-text content item.- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'status clo'},- },- ],- 'add',- 0,- );- });-- it('does not submit a composing suggestion (IME guard)', () => {- const {onChange} = setup({config: contentSearchConfig});- openSheet();- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- fireEvent.change(input, {target: {value: '검색'}});- expect(within(sheet()).getByRole('button', {name: '"검색"'})).toBeTruthy();- fireEvent.keyDown(input, {key: 'Enter', isComposing: true});- expect(onChange).not.toHaveBeenCalled();- expect(input).toHaveValue('검색');- });-- it('shows an empty state for a query with no suggestions', () => {- const noContent: PowerSearchConfig = {- ...contentSearchConfig,- fields: contentSearchConfig.fields.map(f =>- f.key === 'author' ? {...f, isValueMatchAllowed: false} : f,- ),- };- setup({config: {...noContent, contentSearchFieldKey: undefined}});- // Without a content field, Add filter shows the field list instead.- openSheet();- expect(within(sheet()).queryByRole('searchbox')).toBeNull();- expect(within(sheet()).getByRole('button', {name: 'Status'})).toBeTruthy();- });-});--// =============================================================================-// Value types-// =============================================================================--describe('MobilePowerSearch value types', () => {- function setupValues(- props: Partial<React.ComponentProps<typeof MobilePowerSearch>> = {},- ) {- return setup({config: valueTypesConfig, ...props});- }-- it('string: text input stages on change', () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Title');- fireEvent.change(within(sheet()).getByRole('textbox', {name: 'Value'}), {- target: {value: 'hello'},- });- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'title',- operator: 'contains',- value: {type: 'string', value: 'hello'},- },- ],- 'add',- 0,- );- });-- it('string with searchSource: typeahead stages the picked label', async () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Owner');- const input = within(sheet()).getByRole('combobox', {name: 'Value'});- fireEvent.change(input, {target: {value: 'Gra'}});- // The suggestion layer is a popover jsdom cannot show; query it hidden.- const option = await screen.findByRole('option', {- name: /Grace Hopper/,- hidden: true,- });- fireEvent.click(option);- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'owner',- operator: 'is',- value: {type: 'string', value: 'Grace Hopper'},- },- ],- 'add',- 0,- );- });-- it('string_list: creates and selects an ID inline, then commits it from the value footer', async () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('ID');- const input = within(sheet()).getByRole('textbox', {name: 'Search ID'});- fireEvent.change(input, {target: {value: 'ABC-1'}});- const result = await within(sheet()).findByRole(- 'button',- {name: 'Add ABC-1'},- {timeout: 15000},- );- const resultList = result.closest('[role="list"]') as HTMLElement;- expect(- getComputedStyle(resultList.parentElement!.parentElement!)- .backgroundColor,- ).not.toBe('var(--color-background-muted)');- fireEvent.click(result);- expect(- within(sheet()).getByRole('button', {name: 'Add ABC-1, selected'}),- ).toBeTruthy();- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'ids',- operator: 'in',- value: {type: 'string_list', value: ['ABC-1']},- },- ],- 'add',- 0,- );- });-- it('integer: number input stages as typed and commits on blur', () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Lines');- const input = within(sheet()).getByRole('spinbutton', {name: 'Value'});- const add = within(sheet()).getByRole('button', {name: 'Add filter'});- expect(add).toBeDisabled();- fireEvent.input(input, {target: {value: '12'}});- expect(- within(sheet()).getByRole('button', {name: 'Add filter'}),- ).toBeEnabled();- fireEvent.blur(input);- addFilter();- expect(onChange).toHaveBeenCalledWith(- [{field: 'lines', operator: 'gt', value: {type: 'integer', value: 12}}],- 'add',- 0,- );- });-- it('integer: a decimal does not stage', () => {- setupValues();- openAddFlow();- tapRow('Lines');- fireEvent.input(within(sheet()).getByRole('spinbutton', {name: 'Value'}), {- target: {value: '1.5'},- });- expect(- within(sheet()).getByRole('button', {name: 'Add filter'}),- ).toBeDisabled();- });-- it('float: number input stages a decimal', () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Cost');- const input = within(sheet()).getByRole('spinbutton', {name: 'Value'});- fireEvent.input(input, {target: {value: '2.5'}});- fireEvent.blur(input);- addFilter();- expect(onChange).toHaveBeenCalledWith(- [{field: 'cost', operator: 'gt', value: {type: 'float', value: 2.5}}],- 'add',- 0,- );- });-- it('time: the time input is rendered and a staged value shows', () => {- const timeFilter: PowerSearchFilter = {- field: 'alarm',- operator: 'at',- value: {type: 'time', value: '09:30'},- };- setupValues({filters: [timeFilter]});- openEditFlow('Alarm at 09:30');- expect(- within(sheet()).getByRole('heading', {name: 'Alarm at'}),- ).toBeTruthy();- expect(within(sheet()).getByLabelText('Time')).toBeTruthy();- expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeEnabled();- });-- it('date_absolute (date only): renders the stored day in an inline calendar', () => {- const dateFilter: PowerSearchFilter = {- field: 'created',- operator: 'after',- // 2024-03-10T12:00:00Z- value: {type: 'date_absolute', unixSeconds: 1710072000},- };- setupValues({filters: [dateFilter], timezoneID: 'UTC'});- openEditFlow(/^Created is after/);- expect(within(sheet()).getByRole('grid')).toBeTruthy();- expect(- sheet()- .querySelector('button[data-date="2024-03-10"]')- ?.closest('[role="gridcell"]'),- ).toHaveAttribute('aria-selected', 'true');- });-- it('date_absolute with isDateOnly: false keeps the large date-and-time editor', () => {- setupValues();- openAddFlow();- tapRow('Updated');- expect(within(sheet()).getByLabelText('Date and time')).toBeTruthy();- expect(within(sheet()).queryByRole('grid')).toBeNull();- });-- it('date_relative: rows stage a single relative value', () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Age');- expect(- within(sheet()).queryByRole('button', {name: /from now/}),- ).toBeNull();- tapRow('7 days ago');- expect(- within(sheet()).getByRole('button', {name: '7 days ago, selected'}),- ).toBeTruthy();- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'age',- operator: 'newer',- value: {type: 'date_relative', value: '7d_ago'},- },- ],- 'add',- 0,- );- });-- it('date_range: renders the stored range in an inline calendar', () => {- const rangeFilter: PowerSearchFilter = {- field: 'window',- operator: 'between',- value: {- type: 'date_range',- value: {- start: {type: 'ABSOLUTE', unixSeconds: 1709251200}, // 2024-03-01Z- end: {type: 'ABSOLUTE', unixSeconds: 1709942400}, // 2024-03-09Z- },- },- };- setupValues({filters: [rangeFilter], timezoneID: 'UTC'});- openEditFlow(/^Window is between/);- expect(within(sheet()).getByRole('grid')).toBeTruthy();- expect(- sheet()- .querySelector('button[data-date="2024-03-01"]')- ?.closest('[role="gridcell"]'),- ).toHaveAttribute('aria-selected', 'true');- expect(- sheet()- .querySelector('button[data-date="2024-03-09"]')- ?.closest('[role="gridcell"]'),- ).toHaveAttribute('aria-selected', 'true');- });-- it('entity_list: searches and selects an entity inline, then commits it from the value footer', async () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Assignee');- const input = within(sheet()).getByRole('textbox', {- name: 'Search Assignee',- });- fireEvent.change(input, {target: {value: 'Ada'}});- fireEvent.click(- await within(sheet()).findByRole(- 'button',- {name: 'Ada Lovelace'},- {timeout: 15000},- ),- );- expect(- within(sheet()).getByRole('button', {name: 'Ada Lovelace, selected'}),- ).toBeTruthy();- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'assignee',- operator: 'anyOf',- value: {- type: 'entity_list',- value: [{id: 'p1', label: 'Ada Lovelace'}],- },- },- ],- 'add',- 0,- );- });-- it('custom: the configured editor stages a JSON string', () => {- const {onChange} = setupValues();- openAddFlow();- tapRow('Color');- fireEvent.change(within(sheet()).getByLabelText('Color editor'), {- target: {value: 'teal'},- });- addFilter();- expect(onChange).toHaveBeenCalledWith(- [- {- field: 'color',- operator: 'is',- value: {type: 'custom', value: 'teal'},- },- ],- 'add',- 0,- );- });-- it('custom: tokens and rows use getString', () => {- const colorFilter: PowerSearchFilter = {- field: 'color',- operator: 'is',- value: {type: 'custom', value: 'teal'},- };- setupValues({filters: [colorFilter]});- expect(within(field()).getByText('TEAL')).toBeTruthy();- openSheet();- expect(- within(sheet()).getByRole('button', {name: 'Color is TEAL'}),- ).toBeTruthy();- });-});--// =============================================================================-// Timezone-// =============================================================================--describe('MobilePowerSearch timezone', () => {- // 2024-03-10T03:00:00Z: March 10 in Tokyo (UTC+9), still March 9 in- // Honolulu (UTC-10). A boundary instant exposes any surface that formats- // without the configured zone.- const BOUNDARY_SECONDS = 1710039600;- const dateFilter: PowerSearchFilter = {- field: 'created',- operator: 'after',- value: {type: 'date_absolute', unixSeconds: BOUNDARY_SECONDS},- };-- it.each([- ['Asia/Tokyo', 'Mar 10, 2024', 'March 10, 2024'],- ['Pacific/Honolulu', 'Mar 9, 2024', 'March 9, 2024'],- ])(- 'formats the token, the row and the editor in %s',- (timezoneID, compact) => {- setup({config: valueTypesConfig, filters: [dateFilter], timezoneID});- const tokenValue = within(field()).getByText(new RegExp(compact));- expect(tokenValue).toHaveStyle({fontWeight: 'var(--font-weight-bold)'});- openSheet();- const row = within(sheet()).getByRole('button', {- name: new RegExp(`^Created is after ${compact}`),- });- expect(within(row).getByText(new RegExp(compact))).toHaveStyle({- fontWeight: 'var(--font-weight-bold)',- });- fireEvent.click(row);- expect(- sheet()- .querySelector(- `button[data-date="${timezoneID === 'Asia/Tokyo' ? '2024-03-10' : '2024-03-09'}"]`,- )- ?.closest('[role="gridcell"]'),- ).toHaveAttribute('aria-selected', 'true');- },- );-- it('converts a picked day to midnight in the configured zone', () => {- expect(isoDateToUnixSeconds('2024-03-09', 'Pacific/Honolulu')).toBe(- Date.UTC(2024, 2, 9, 10, 0) / 1000,- );- expect(isoDateToUnixSeconds('2024-03-10', 'Asia/Tokyo')).toBe(- Date.UTC(2024, 2, 9, 15, 0) / 1000,- );- expect(unixSecondsToISODate(BOUNDARY_SECONDS, 'Asia/Tokyo')).toBe(- '2024-03-10',- );- expect(unixSecondsToISODate(BOUNDARY_SECONDS, 'Pacific/Honolulu')).toBe(- '2024-03-09',- );- expect(unixSecondsToISODateTime(BOUNDARY_SECONDS, 'Asia/Tokyo')).toBe(- '2024-03-10T12:00',- );- expect(- isoDateTimeToUnixSeconds(- unixSecondsToISODateTime(BOUNDARY_SECONDS, 'Pacific/Honolulu'),- 'Pacific/Honolulu',- ),- ).toBe(BOUNDARY_SECONDS);- });-});--// =============================================================================-// Core parity-// =============================================================================--describe('MobilePowerSearch Core parity', () => {- const third: PowerSearchFilter = {- field: 'status',- operator: 'isNot',- value: {type: 'enum', value: 'closed'},- };- const legacyFilter: PowerSearchFilter = {- field: 'legacy',- operator: 'was',- value: {type: 'string', value: 'x'},- };- function Harness({- filters,- cfg = config,- hasClear,- }: {- filters: ReadonlyArray<PowerSearchFilter>;- cfg?: PowerSearchConfig;- hasClear?: boolean;- }) {- return (- <MobilePowerSearch- config={cfg}- filters={filters}- onChange={() => {}}- hasClear={hasClear}- />- );- }-- describe('a controlled update that removes the focused control re-homes focus over the button rows', () => {- it('moves focus from a removed Filters row to the row that followed it, counting only button rows', () => {- const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};- const fourth: PowerSearchFilter = {- field: 'author',- operator: 'is',- value: {type: 'string', value: 'Grace'},- };- const {rerender} = render(- <Harness filters={[pinned, authorFilter, third, fourth]} />,- );- openSheet();- within(sheet()).getByRole('button', {name: 'Author is Ada'}).focus();- rerender(<Harness filters={[pinned, third, fourth]} />);- // The row that followed it — not one row too far for the plain row.- expect(- within(sheet()).getByRole('button', {name: 'Status is not Closed'}),- ).toHaveFocus();- // The last button row removed: the new last one takes focus.- within(sheet()).getByRole('button', {name: 'Author is Grace'}).focus();- rerender(<Harness filters={[pinned, third]} />);- expect(- within(sheet()).getByRole('button', {name: 'Status is not Closed'}),- ).toHaveFocus();- });-- it('moves focus from Clear all, gone with the last filter, to Add filter', () => {- const {rerender} = render(<Harness filters={[openFilter]} hasClear />);- openSheet();- within(sheet()).getByRole('button', {name: 'Clear all'}).focus();- rerender(<Harness filters={[]} hasClear />);- expect(- within(sheet()).queryByRole('button', {name: 'Clear all'}),- ).toBeNull();- const addFilterButtons = within(sheet()).getAllByRole('button', {- name: 'Add filter',- });- expect(addFilterButtons).toHaveLength(1);- expect(addFilterButtons[0]).toHaveFocus();- });-- it("moves focus from a dropped field's row in Add filter to a remaining row", () => {- const {rerender} = render(<Harness filters={[]} />);- openAddFlow();- within(sheet()).getByRole('button', {name: 'Author'}).focus();- rerender(- <Harness- filters={[]}- cfg={{- ...config,- fields: config.fields.filter(f => f.key !== 'author'),- }}- />,- );- expect(- within(sheet()).queryByRole('button', {name: 'Author'}),- ).toBeNull();- const focused = document.activeElement as HTMLElement;- expect(focused.closest('li')).not.toBeNull();- expect(sheet().contains(focused)).toBe(true);- });- });-- describe('rows keyed by filter identity', () => {- it('keeps focus on the same filter when the parent reorders the filters, with the same objects and with clones', () => {- const {rerender} = render(- <Harness filters={[openFilter, authorFilter, third]} />,- );- openSheet();- const authorRow = within(sheet()).getByRole('button', {- name: 'Author is Ada',- });- authorRow.focus();- rerender(<Harness filters={[third, openFilter, authorFilter]} />);- expect(within(sheet()).getByRole('button', {name: 'Author is Ada'})).toBe(- authorRow,- );- expect(authorRow).toHaveFocus();- rerender(- <Harness filters={[{...authorFilter}, {...third}, {...openFilter}]} />,- );- expect(within(sheet()).getByRole('button', {name: 'Author is Ada'})).toBe(- authorRow,- );- expect(authorRow).toHaveFocus();- });-- it('keeps focus on the same filter when the parent removes a filter above it', () => {- const {rerender} = render(- <Harness filters={[openFilter, authorFilter, third]} />,- );- openSheet();- const authorRow = within(sheet()).getByRole('button', {- name: 'Author is Ada',- });- authorRow.focus();- rerender(<Harness filters={[authorFilter, third]} />);- expect(authorRow).toHaveFocus();- expect(- within(sheet()).getByRole('button', {name: 'Status is not Closed'}),- ).not.toHaveFocus();- });- });-- describe('a filter the config no longer knows', () => {- it('lists it by its raw keys, exposes the unavailable state, and removes it directly from Filters', () => {- function Removable() {- const [filters, setFilters] = useState<- ReadonlyArray<PowerSearchFilter>- >([openFilter, legacyFilter]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<Removable />);- expect(within(field()).getByText('legacy: was')).toBeTruthy();- openSheet();- const row = within(sheet()).getByRole('button', {name: 'legacy was'});- fireEvent.click(row);- expect(- within(sheet()).getByRole('heading', {name: 'legacy was'}),- ).toBeTruthy();- expect(sheet()).toHaveAttribute('aria-label', 'legacy was');- expect(- within(sheet()).getByText('This filter is no longer available'),- ).toBeTruthy();- expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove legacy filter'}),- );- expect(- within(sheet()).queryByRole('button', {name: 'legacy was'}),- ).toBeNull();- expect(- within(sheet()).getByRole('button', {name: 'Remove Status filter'}),- ).toHaveFocus();- });-- it('reads the field label next to the raw operator key when only the operator is gone', () => {- const staleOperator: PowerSearchFilter = {- field: 'author',- operator: 'was',- value: {type: 'string', value: 'Ada'},- };- setup({filters: [staleOperator]});- openSheet();- expect(- within(sheet()).getByRole('button', {name: 'Author was'}),- ).toBeTruthy();- });- });-- describe('the unavailable state', () => {- it('moves focus to Cancel when a controlled config update removes the edited operator, and announces it in the sheet', async () => {- const {rerender} = setup({filters: [openFilter]});- openEditFlow('Status is Open');- within(sheet()).getByRole('radio', {name: 'Status is not'}).focus();- rerender(- <MobilePowerSearch- config={{- ...config,- fields: config.fields.map(f =>- f.key === 'status'- ? {...f, operators: f.operators.filter(o => o.key !== 'is')}- : f,- ),- }}- filters={[openFilter]}- onChange={vi.fn()}- />,- );- expect(- within(sheet()).getByText('This filter is no longer available'),- ).toBeTruthy();- expect(- within(sheet()).getByRole('button', {name: 'Cancel'}),- ).toHaveFocus();- await waitFor(() =>- expect(sheetRegion().textContent).toBe(- 'This filter is no longer available',- ),- );- });- });-- describe('Apply and Cancel after a controlled update', () => {- it('Apply with the edited filter gone writes nothing and focuses the nearest remaining row, else Add filter', () => {- const onChange = vi.fn();- const {rerender} = render(- <MobilePowerSearch- config={config}- filters={[openFilter, authorFilter, third]}- onChange={onChange}- />,- );- openEditFlow('Author is Ada');- rerender(- <MobilePowerSearch- config={config}- filters={[openFilter, third]}- onChange={onChange}- />,- );- fireEvent.click(within(sheet()).getByRole('button', {name: 'Apply'}));- expect(onChange).not.toHaveBeenCalled();- expect(- within(sheet()).getByRole('button', {name: 'Status is not Closed'}),- ).toHaveFocus();- });-- it('Cancel from creation after the opening field was removed focuses the first control of Add filter', () => {- const {rerender} = render(<Harness filters={[]} />);- openAddFlow();- tapRow('Author');- rerender(- <Harness- filters={[]}- cfg={{- ...config,- fields: config.fields.filter(f => f.key !== 'author'),- }}- />,- );- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- const focused = document.activeElement as HTMLElement;- expect(focused.closest('li')).not.toBeNull();- expect(sheet().contains(focused)).toBe(true);- });- });-- describe('announcements inside the open sheet', () => {- it('announces "Removed {label}" in Filters after direct row removal', async () => {- function Removable() {- const [filters, setFilters] = useState<- ReadonlyArray<PowerSearchFilter>- >([openFilter, authorFilter]);- return (- <MobilePowerSearch- config={config}- filters={filters}- onChange={next => setFilters(next)}- />- );- }- render(<Removable />);- openSheet();- fireEvent.click(- within(sheet()).getByRole('button', {name: 'Remove Author filter'}),- );- await waitFor(() =>- expect(sheetRegion().textContent).toBe('Removed Author is Ada'),- );- expect(pageRegionText()).toBe('');- });-- it('speaks "No filters found" from its rendered element once per query, and not for an empty query', async () => {- const many: PowerSearchConfig = {- name: 'Many',- fields: Array.from({length: 9}, (_, i) => ({- key: `f${i}`,- label: `Field ${i}`,- operators: [- {key: 'is', label: 'is', value: {type: 'string' as const}},- ],- })),- };- setup({config: many});- openSheet();- const search = within(sheet()).getByRole('textbox', {- name: 'Search filters',- });- fireEvent.change(search, {target: {value: 'nope'}});- expect(within(sheet()).getByText('No filters found')).toBeTruthy();- await waitFor(() =>- expect(sheetRegion().textContent).toBe(- 'No filters found Try a different search.',- ),- );- fireEvent.change(search, {target: {value: ''}});- // The message is gone from the body; only the live region still holds- // the words it spoke.- expect(- within(sheet()).queryByText('No filters found', {- ignore:- '[data-astryx-modal-live-region] *, [data-astryx-modal-live-region]',- }),- ).toBeNull();- expect(- within(sheet()).getAllByRole('button', {name: /^Field/}),- ).toHaveLength(9);- });-- it('does not announce "No results found" when Add filter is left after a query that listed suggestions', async () => {- setup({config: contentSearchConfig, filters: [openFilter]});- openSheet();- tapRow('Add filter');- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- fireEvent.change(input, {target: {value: 'status'}});- expect(- within(sheet()).getAllByRole('button', {name: /Status/}).length,- ).toBeGreaterThan(0);- // Back to Filters: the Add filter sheet's body stays mounted, its- // results list emptied by the step change — no empty-result message is- // spoken, not on the page and not in the Filters dialog.- expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();- fireEvent.keyDown(sheet(), {key: 'Escape'});- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- await new Promise(resolve => setTimeout(resolve, 40));- expect(pageRegionText()).toBe('');- expect(- sheet().querySelector(- ':scope > [data-astryx-modal-live-region="polite"]',- )?.textContent ?? '',- ).not.toContain('No results found');- // Escape out of the flow after another query: nothing on the page.- tapRow('Add filter');- fireEvent.change(- within(sheet()).getByRole('searchbox', {name: 'Search'}),- {target: {value: 'status'}},- );- fireEvent.keyDown(sheet(), {key: 'Escape'});- settleSheets();- await new Promise(resolve => setTimeout(resolve, 40));- expect(pageRegionText()).toBe('');- });-- it('announces the unavailable state only while its step is open, and again when the same stale filter reopens', async () => {- const stale: PowerSearchConfig = {- ...config,- fields: config.fields.map(f =>- f.key === 'status'- ? {...f, operators: f.operators.filter(o => o.key !== 'is')}- : f,- ),- };- const {rerender} = setup({filters: [openFilter, authorFilter]});- openEditFlow('Status is Open');- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- expect(- within(sheet()).getByRole('heading', {name: 'Filters'}),- ).toBeTruthy();- // The value step is closed but its body stays mounted with the draft; a- // config update that drops the edited operator must not be spoken — not- // now, and not held for the next dialog that opens.- rerender(- <MobilePowerSearch- config={stale}- filters={[openFilter, authorFilter]}- onChange={vi.fn()}- />,- );- await new Promise(resolve => setTimeout(resolve, 40));- expect(pageRegionText()).toBe('');- // Opening another filter's step: words held for the closed step would- // surface in the value step's dialog here.- tapRow('Author is Ada');- await new Promise(resolve => setTimeout(resolve, 40));- for (const region of document.querySelectorAll('[aria-live]')) {- expect(region.textContent ?? '').not.toContain(- 'This filter is no longer available',- );- }- fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));- // Reopening the stale filter — its row now reads the field's label and- // the raw operator key — speaks it, in its own dialog, as a new- // occasion even though the filter is the same.- tapRow('Status is');- await waitFor(() =>- expect(sheetRegion().textContent).toBe(- 'This filter is no longer available',- ),- );- });-- it('shows no "no match" message for a config with no field', () => {- setup({config: {name: 'Empty', fields: []}});- openSheet();- expect(- within(sheet()).getByRole('heading', {name: 'Add filter'}),- ).toBeTruthy();- expect(within(sheet()).queryByText('No filters found')).toBeNull();- });-- it("keeps the content searchbox's aria-controls pointing at an element while nothing lists", () => {- setup({config: contentSearchConfig});- openSheet();- const input = within(sheet()).getByRole('searchbox', {name: 'Search'});- const controlled = () =>- document.getElementById(input.getAttribute('aria-controls') as string);- expect(controlled()).not.toBeNull();- fireEvent.change(input, {target: {value: 'zzzz-nothing-matches'}});- expect(controlled()).not.toBeNull();- expect(sheet().contains(controlled())).toBe(true);- });- });-- describe('the trigger', () => {- it('does not open the flow for a tap on the end lane, where endContent keeps its own taps', () => {- const onAction = vi.fn();- setup({- filters: [openFilter],- endContent: (- <button type="button" onClick={onAction}>- Save view- </button>- ),- });- fireEvent.click(screen.getByRole('button', {name: 'Save view'}));- expect(onAction).toHaveBeenCalledTimes(1);- expect(isSheetOpen()).toBe(false);- // A tap on a token still opens it.- fireEvent.click(within(field()).getByText('Open'));- expect(isSheetOpen()).toBe(true);- });-- it('fires onBlur when the flow opens and onFocus when it closes, once each', () => {- const onFocus = vi.fn();- const onBlur = vi.fn();- setup({filters: [openFilter], onFocus, onBlur});- openSheet();- expect(onFocus).toHaveBeenCalledTimes(1);- expect(onBlur).toHaveBeenCalledTimes(1);- fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));- settleSheets();- expect(trigger()).toHaveFocus();- expect(onFocus).toHaveBeenCalledTimes(2);- expect(onBlur).toHaveBeenCalledTimes(1);- });- });-});--// =============================================================================-// Helpers-// =============================================================================--describe('mobilePowerSearchUtils', () => {- it('resolves filter identity by reference, then slot, then unique signature', () => {- const a: PowerSearchFilter = {...openFilter};- const b: PowerSearchFilter = {...authorFilter};- const sig = filterSignature(a);- expect(resolveFilterIdentityIndex([b, a], a, sig, 0)).toBe(1);- expect(resolveFilterIdentityIndex([{...a}, b], a, sig, 0)).toBe(0);- expect(resolveFilterIdentityIndex([b, {...a}], a, sig, 0)).toBe(1);- expect(resolveFilterIdentityIndex([{...a}, {...a}], a, sig, 1)).toBe(1);- expect(resolveFilterIdentityIndex([{...a}, {...a}], a, sig, 5)).toBeNull();- expect(resolveFilterIdentityIndex([b], a, sig, 0)).toBeNull();- });-- it('picks the nearest editable neighbor after a removal, preferring the next', () => {- const ro: PowerSearchFilter = {...openFilter, isReadOnly: true};- expect(nearestEditableIndex([authorFilter, authorFilter], 1)).toBe(1);- expect(nearestEditableIndex([authorFilter, ro], 1)).toBe(0);- expect(nearestEditableIndex([ro, ro], 0)).toBeUndefined();- expect(nearestEditableIndex([authorFilter, ro, authorFilter], 1)).toBe(2);- });-- it('builds content-search suggestions like Core PowerSearch', () => {- const source = createContentSearchSource(- createMobilePowerSearchConfig(contentSearchConfig),- key => key,- 10,- );- expect(source.bootstrap().map(item => item.id)).toEqual([- 'status',- 'author',- 'unassigned',- 'labels',- ]);- const results = source.search('status is clo');- expect(results[0]).toMatchObject({- label: '"status is clo"',- auxiliaryData: {fieldKey: 'author', operatorKey: 'is'},- });- expect(results[1]).toMatchObject({- label: 'Status is Closed',- auxiliaryData: {- fieldKey: 'status',- operatorKey: 'is',- filterValue: {type: 'enum', value: 'closed'},- },- });- // An exact field match drops the free-text item.- expect(- source.search('Author').some(item => item.id.startsWith('__content')),- ).toBe(false);- });-});diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsxdeleted file mode 100644index 4d39081b4e..0000000000--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx+++ /dev/null@@ -1,2386 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file MobilePowerSearch.tsx- * @input Core PowerSearch config, filters and onChange (the same props as- * @astryxdesign/core PowerSearch); public Core primitives and private Lab- * mobile-sheet confirmation and search-drag dismissal owners- * @output Exports MobilePowerSearch — Lab prototype of the touch PowerSearch- * flow: the whole field is one "Manage filters" trigger with display-only- * tokens, a Filters sheet with editable rows and direct remove actions, Add- * filter and sticky Clear all / Done, and a field → operator → value- * drill-down whose edit sheet holds Cancel / Apply; forward navigation stacks each step- * above the one that opened it, and dismissing the current sheet reveals the- * retained previous step- * @position Lab (canary) stack layer 1: validates the touch design before any- * Core promotion. The caller chooses it explicitly- * (`isTouch ? MobilePowerSearch : PowerSearch`); there is no pointer- * switching inside the component.- *- * API mirrors Core PowerSearchProps (config, filters, onChange with the same- * change metadata, label, placeholder, size, isDisabled, isReadOnly,- * timezoneID, status, startIcon, endContent, resultCount, handleRef,- * components, ...) so graduation is an import swap. Differences from Core are- * the Lab deltas:- * - no `menuWidth` or `tokenOverflowBehavior`: there is no typeahead popover- * and tokens wrap inside the trigger;- * - strings are literals (no new i18n keys; existing Core keys are reused- * for the result count, the add and the removal announcements);- * - announcements made while a sheet is open are delivered inside that- * sheet's dialog by `useAnnounce`, called from a `SheetAnnouncer` rendered- * in each step (spec AST-086 FR14): the shared page-body channel is not- * exposed while a native modal dialog is open. Visual EmptyStates mount only- * while their step is open; empty-result and unavailable messages are spoken- * from their rendered element, once per occasion; Clear all announces after- * its confirmation closes inside the still-open Filters sheet;- * - no theming contract: no `power-search` theme target or selectors;- * - `components[type].Token` overrides receive Core's PowerSearchTokenProps;- * the built-in token renders Core `Token` directly, with the value text- * the Filters rows share and date values formatted in `timezoneID`;- * - fields whose every operator is `nested` are left out with a development- * warning; `nested` has no sheet editor yet (Core's built-in nested editor- * is not exported);- * - date-only and date-range values use inline Calendars in `timezoneID`,- * `isDateOnly: false` uses a large date-and-time input, and `date_relative`- * remains a row list;- * - Clear all asks for confirmation, removes editable filters while preserving- * read-only ones, and keeps the Filters sheet open for continued editing;- * - every removable Filters row, including one-tap boolean filters, uses the- * same trailing remove button instead of a selected-state indicator; when- * no filters exist, the centered Add filter is the only visible action;- * - Add filter leaves its search input unfocused until the user chooses it, so- * opening the sheet does not summon the software keyboard;- * - a value editor that is the sheet's only section sits directly on the sheet- * surface; muted section containers distinguish only multi-section editors;- * - a filter whose field or operator the config no longer knows lists by its- * raw keys and remains directly removable from the Filters row; rows and- * tokens are keyed by filter identity, so controlled reorder and removal- * keep focus stable or move it to the nearest remaining action;- * - the scroll viewport reaches the sheet edge so its scrollbar does too;- * padded inner content keeps list text aligned with the fixed header;- * - the sheets pad their own content (`padding={0}` on BottomSheet); each- * sheet body publishes that padding as container padding so its- * `edge="bleed"` lists run edge to edge with row text on the body's inset.- *- * The sheets are pinned tall on purpose: the field list resizes as it is- * searched and the editor changes with the operator, and only a fully- * expanded tall sheet gives mobile-keyboard accommodation.- *- * SYNC: When modified, update:- * - /packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs- * - /packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx- * - /apps/storybook/stories/MobilePowerSearch.stories.tsx- */--import React, {- useCallback,- useEffect,- useId,- useImperativeHandle,- useLayoutEffect,- useMemo,- useRef,- useState,- type ReactNode,- type SVGProps,-} from 'react';-import * as stylex from '@stylexjs/stylex';-import type {BaseProps} from '@astryxdesign/core';-import {BottomSheet} from '@astryxdesign/core/BottomSheet';-import {Button} from '@astryxdesign/core/Button';-import {EmptyState} from '@astryxdesign/core/EmptyState';-import {- Field,- inputStatusBorderStyles,- inputStatusFocusWithinStyles,- inputStatusHoverShadowStyles,- inputWrapperStyles,- type FieldStatusVariant,- type InputStatus,-} from '@astryxdesign/core/Field';-import {Heading} from '@astryxdesign/core/Heading';-import {Icon, renderIconSlot, type IconType} from '@astryxdesign/core/Icon';-import {IconButton} from '@astryxdesign/core/IconButton';-import {containerPaddingInlineVarStyles} from '@astryxdesign/core/Layout/padding.stylex';-import {List, ListItem} from '@astryxdesign/core/List';-import {resolveOperatorLabel} from '@astryxdesign/core/PowerSearch';-import type {- FilterValue,- PowerSearchChangeType,- PowerSearchComponents,- PowerSearchConfig,- PowerSearchField,- PowerSearchFilter,- PowerSearchHandle,- PowerSearchOperator,- PowerSearchSize,-} from '@astryxdesign/core/PowerSearch';-import {formatFilterValue} from '@astryxdesign/core/PowerSearch/utils';-import type {InternalConfig} from '@astryxdesign/core/PowerSearch/utils';-import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';-import {useSize} from '@astryxdesign/core/SizeContext';-import {Text} from '@astryxdesign/core/Text';-import {TextInput} from '@astryxdesign/core/TextInput';-import {Token} from '@astryxdesign/core/Token';-import {useTooltip} from '@astryxdesign/core/Tooltip';-import {- useAnnounce,- useDevWarning,- useMergedRefs,- type AnnounceFn,-} from '@astryxdesign/core/hooks';-import {useLocale, useTranslator} from '@astryxdesign/core/i18n';-import {- colorVars,- fontWeightVars,- radiusVars,- sizeVars,- spacingVars,- typeScaleVars,- typographyVars,-} from '@astryxdesign/core/theme/tokens.stylex';-import {isImeKeyEvent, isRenderable, rtlStyles} from '@astryxdesign/core/utils';--import {- SheetConfirmation,- useDismissSearchOnTouchDrag,-} from '@astryxdesign/core/internal/touch-sheet';-import {MobilePowerSearchValueEditor} from './MobilePowerSearchValueEditor';-import {- createContentSearchSource,- createFilterIdentities,- fieldMatchesQuery,- filterSignature,- isSupportedOperator,- nearestEditableIndex,- resolveFilterIdentityIndex,- useMobilePowerSearchConfig,- type MobilePowerSearchItem,-} from './mobilePowerSearchUtils';--// =============================================================================-// Props-// =============================================================================--export interface MobilePowerSearchProps extends Omit<- BaseProps<HTMLElement>,- 'onChange'-> {- /** PowerSearch configuration defining available fields and operators. */- config: PowerSearchConfig;- /** Currently active filters. */- filters: ReadonlyArray<PowerSearchFilter>;- /** Called when filters change, with the same metadata as Core PowerSearch. */- onChange: (- filters: ReadonlyArray<PowerSearchFilter>,- changeType: PowerSearchChangeType,- index: number,- ) => void;- /** Accessible label for the field and its trigger. @default 'Manage filters' */- label?: string;- /** Visually hide the label. @default true */- isLabelHidden?: boolean;- /** Trigger text when no filter is selected, and the content-search placeholder. */- placeholder?: string;- /** Auto-focus the trigger on mount. @default false */- hasAutoFocus?: boolean;- /** Show Clear all in the Filters sheet. @default true */- hasClear?: boolean;- /** Filters stay visible but cannot be added, edited, or removed. @default false */- isReadOnly?: boolean;- /** Disable the field; the sheet cannot open. @default false */- isDisabled?: boolean;- /**- * Explains why the field is disabled. With `isDisabled`, the trigger stays- * focusable (via `aria-disabled`) and shows this text in a tooltip.- */- disabledMessage?: string;- /** Icon at the start of the field. */- startIcon?: ReactNode | IconType;- /** Fires when focus enters the field from outside. */- onFocus?: (e: React.FocusEvent) => void;- /** Fires when focus leaves the field entirely. */- onBlur?: (e: React.FocusEvent) => void;- /** Validation status. */- status?: InputStatus;- /** How the status message is placed. @default 'attached' */- statusVariant?: FieldStatusVariant | 'tooltip';- /** Max display length for token values. @default 40 */- maxTokenLength?: number;- /** Max suggestions in string and entity value typeaheads. @default 10 */- maxOperatorMenuItems?: number;- /** Max ranked results for a non-empty field or content query. @default 10 */- maxSearchResults?: number;- /** Label for the edit sheet's save action. @default 'Apply' when editing, 'Add filter' when creating */- popoverSaveButtonLabel?: string;- /**- * Accepted for API parity with Core PowerSearch. Dates follow Core's- * semantics: tokens and rows show a `date_absolute` as the Core token does- * (its day in the browser's zone) and the date editors read and write the- * UTC day, so this prop does not change a date value today.- */- timezoneID?: string;- /** Content at the end of the field row. */- endContent?: ReactNode;- /** Result count: a number formats as "N results"; a string shows as-is. */- resultCount?: number | string;- /** Ref forwarded to the root element. */- ref?: React.Ref<HTMLDivElement>;- /** Imperative handle; `focusTypeahead` focuses the sheet trigger. */- handleRef?: React.Ref<PowerSearchHandle>;- /** Size of the field. @default 'md' */- size?: PowerSearchSize;- /** Per-type overrides for token and editor rendering. */- components?: PowerSearchComponents;-}--// =============================================================================-// Styles-// =============================================================================--function PlusIcon(props: SVGProps<SVGSVGElement>) {- return (- <svg- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth={1.5}- strokeLinecap="round"- strokeLinejoin="round"- {...props}>- <path d="M5 12h14" />- <path d="M12 5v14" />- </svg>- );-}--const sizeStyles = stylex.create({- sm: {minHeight: sizeVars['--size-element-sm']},- md: {minHeight: sizeVars['--size-element-md']},- lg: {minHeight: sizeVars['--size-element-lg']},-});--const styles = stylex.create({- wrapper: {- position: 'relative',- flexWrap: 'nowrap',- gap: spacingVars['--spacing-1'],- height: 'auto',- cursor: {- default: 'pointer',- ':is([aria-disabled="true"])': 'default',- },- },- wrapperWithTokens: {- paddingBlock: `calc(${spacingVars['--spacing-1']} - 1px)`,- paddingInline: `calc(${spacingVars['--spacing-1']} - 1px)`,- },- contentSection: {- position: 'relative',- minWidth: 0,- flexGrow: 1,- display: 'flex',- alignItems: 'center',- flexWrap: 'wrap',- columnGap: spacingVars['--spacing-1'],- rowGap: `calc(${spacingVars['--spacing-1']} - 1px)`,- },- startIconWithTokens: {- marginInlineStart: `calc(${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px)`,- },- // The only tab stop in the field. It stays visually borderless while the- // wrapper delegates taps on tokens and empty space to it.- trigger: {- appearance: 'none',- flex: '1 1 40px',- minWidth: '40px',- alignSelf: 'stretch',- display: 'flex',- alignItems: 'center',- paddingBlock: 0,- paddingInline: spacingVars['--spacing-1'],- margin: 0,- borderWidth: 0,- borderStyle: 'none',- backgroundColor: 'transparent',- color: colorVars['--color-text-secondary'],- fontFamily: typographyVars['--font-family-body'],- fontSize: typeScaleVars['--text-body-size'],- lineHeight: typeScaleVars['--text-body-leading'],- textAlign: 'start',- whiteSpace: 'nowrap',- cursor: {- default: 'pointer',- ':is(:disabled,[aria-disabled="true"])': 'default',- },- outline: 'none',- },- // Once a token is present the empty trigger covers the token lane instead- // of reserving 40px or wrapping onto an otherwise blank row.- triggerWithTokens: {- position: 'absolute',- inset: 0,- minWidth: 0,- padding: 0,- },- tokenValue: {- fontWeight: fontWeightVars['--font-weight-bold'],- },- endSection: {- display: 'flex',- alignItems: 'center',- gap: spacingVars['--spacing-2'],- flexShrink: 0,- paddingInlineEnd: spacingVars['--spacing-1'],- },- resultCount: {- fontSize: typeScaleVars['--text-supporting-size'],- lineHeight: typeScaleVars['--text-supporting-leading'],- color: colorVars['--color-text-secondary'],- whiteSpace: 'nowrap',- },- // 44px touch targets for every sheet action, without resizing inputs.- touchAction: {- minHeight: 44,- },- touchIconAction: {- minWidth: 44,- minHeight: 44,- },- // --- sheet shell ---------------------------------------------------------- // Scopes the sticky header's and footer's layer to this sheet's content:- // the List rows are `position: relative` and come after the header, so- // without a layer of its own the header is painted under the rows that- // scroll beneath it. Isolating the content keeps that z-index inside it, so- // the sheet's grab handle (z-index 1 on the panel, outside this wrapper)- // still paints above.- sheet: {- display: 'flex',- flexDirection: 'column',- minHeight: '100%',- isolation: 'isolate',- },- sheetWithFixedFooter: {- height: '100%',- overflow: 'hidden',- },- header: {- position: 'sticky',- insetBlockStart: 0,- // Above the rows that scroll under it, within the isolated sheet content.- zIndex: 1,- display: 'flex',- flexDirection: 'column',- gap: spacingVars['--spacing-3'],- // Clears the sheet's floating grab handle.- paddingBlockStart: spacingVars['--spacing-6'],- paddingBlockEnd: spacingVars['--spacing-3'],- paddingInline: spacingVars['--spacing-4'],- backgroundColor: colorVars['--color-background-surface'],- },- headerRow: {- display: 'flex',- alignItems: 'center',- gap: spacingVars['--spacing-2'],- },- headerText: {- minWidth: 0,- flexGrow: 1,- display: 'flex',- flexDirection: 'column',- },- // The body pads the sheet's content and publishes that inline padding as- // the container padding its lists read: with `edge="bleed"` their rows run- // edge to edge (full-bleed dividers) while row text keeps this inset, so- // row text, group headings and the sheet title share one edge. The sheet- // itself has `padding={0}`, so it publishes none.- body: {- flexGrow: 1,- display: 'flex',- flexDirection: 'column',- gap: spacingVars['--spacing-4'],- paddingInline: spacingVars['--spacing-4'],- paddingBlockEnd: spacingVars['--spacing-4'],- },- scrollViewport: {- flexGrow: 1,- minHeight: 0,- overflowY: 'auto',- overscrollBehaviorY: 'contain',- },- scrollContent: {- minHeight: '100%',- display: 'flex',- flexDirection: 'column',- gap: spacingVars['--spacing-4'],- paddingInline: spacingVars['--spacing-4'],- paddingBlockEnd: spacingVars['--spacing-4'],- },- footer: {- position: 'sticky',- insetBlockEnd: 0,- zIndex: 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'space-between',- gap: spacingVars['--spacing-2'],- paddingBlock: spacingVars['--spacing-3'],- paddingInline: spacingVars['--spacing-4'],- backgroundColor: colorVars['--color-background-surface'],- },- footerSoleAction: {- flexGrow: 1,- },- footerEqualAction: {- flexGrow: 1,- flexBasis: 0,- minWidth: 0,- minHeight: 44,- },- fixedFooter: {- position: 'relative',- insetBlockEnd: 'auto',- flexShrink: 0,- },- empty: {- paddingBlock: spacingVars['--spacing-6'],- textAlign: 'center',- },- emptyState: {- flexGrow: 1,- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- },- controlSection: {- padding: spacingVars['--spacing-3'],- borderRadius: radiusVars['--radius-container'],- backgroundColor: colorVars['--color-background-muted'],- },- trailingControlRow: {- flexDirection: 'row-reverse',- },- rowValue: {- fontWeight: fontWeightVars['--font-weight-bold'],- },-});--// =============================================================================-// Draft state-// =============================================================================--type SheetStep = 'manage' | 'fields' | 'value';--type PendingSheetFocus =- | {readonly type: 'manager-add'}- | {readonly type: 'content-search'}- | {- readonly type: 'manager-filter';- readonly sourceFilter: PowerSearchFilter;- readonly sourceSignature: string;- readonly preferredIndex: number;- }- | {readonly type: 'field'; readonly fieldKey: string};--interface FilterDraft {- readonly mode: 'create' | 'edit';- /** Where Cancel returns for a new filter. */- readonly returnStep?: 'fields' | 'manage';- /** Control within the return sheet that launched this draft. */- readonly returnFocus?: 'field' | 'content-search';- /** Index in `filters` when edit mode opened. */- readonly filterIndex?: number;- /** Original controlled filter identity, used to follow immutable reorders. */- readonly sourceFilter?: PowerSearchFilter;- /** Structural snapshot, used when controlled parents clone their values. */- readonly sourceSignature?: string;- readonly field: string;- readonly operator?: string;- readonly value?: FilterValue;-}--function resolveDraftFilterIndex(- filters: ReadonlyArray<PowerSearchFilter>,- draft: FilterDraft,-): number | null {- if (- draft.mode !== 'edit' ||- draft.filterIndex == null ||- draft.sourceFilter == null ||- draft.sourceSignature == null- ) {- return null;- }- return resolveFilterIdentityIndex(- filters,- draft.sourceFilter,- draft.sourceSignature,- draft.filterIndex,- );-}--// Below this many fields a search box is noise: the whole list is on screen.-const SEARCHABLE_FIELD_COUNT = 8;-const DEFAULT_MAX_SEARCH_RESULTS = 10;-const MAX_BROWSE_MENU_ITEMS = 1000;--// =============================================================================-// In-sheet announcements-// =============================================================================--/**- * Rendered inside a step's BottomSheet so that `useAnnounce` resolves the- * sheet's dialog as the enclosing modal (spec AST-086 FR14): a message- * written through it is delivered inside that dialog, the only channel- * assistive technology exposes while the native modal is open. Publishes- * that dialog's `announce` to the flow above while mounted. Renders nothing.- */-function SheetAnnouncer({- onAnnounceChange,-}: {- onAnnounceChange: (announce: AnnounceFn | null) => void;-}) {- const announce = useAnnounce();- useEffect(() => {- onAnnounceChange(announce);- return () => {- onAnnounceChange(null);- };- }, [announce, onAnnounceChange]);- return null;-}--/**- * A sheet's empty-result or unavailable message, rendered inside the step's- * dialog and spoken from its rendered text once per occasion — a query that- * matches nothing, a filter that became unavailable — through `useAnnounce`,- * which, called from inside the sheet, delivers into the sheet's dialog. The- * message is plain text, not an EmptyState, so nothing announces it twice.- * (Core's own-content hook is not reachable from Lab; this is its shape.)- */-function SheetEmptyMessage({- id,- message,- occasion,- isShown,-}: {- id?: string;- message: string;- occasion: string;- /**- * Whether the message's step is the open one. A closed sheet keeps its body- * mounted, so the message can exist — and its occasion change — while no- * one is in the sheet: nothing is spoken then, and the occasion is- * forgotten so the same one is spoken again when the step reopens on it.- */- isShown: boolean;-}) {- const ref = useRef<HTMLDivElement>(null);- const announce = useAnnounce();- const spokenOccasionRef = useRef<string | null>(null);- useEffect(() => {- if (!isShown) {- spokenOccasionRef.current = null;- return;- }- if (spokenOccasionRef.current === occasion) {- return;- }- spokenOccasionRef.current = occasion;- const text = ref.current?.textContent?.trim();- if (text) {- announce(text);- }- }, [announce, isShown, occasion]);- return (- <div ref={ref} id={id} {...stylex.props(styles.empty)}>- <Text type="supporting" color="secondary">- {message}- </Text>- </div>- );-}--// =============================================================================-// Token-// =============================================================================--/** Formats the value text shared by trigger tokens and Filters rows. */-function formatValueText(- config: InternalConfig,- operator: PowerSearchOperator,- filter: PowerSearchFilter,- maxLength: number,- t: ReturnType<typeof useTranslator>,- locale: string,- timezoneID: string | undefined,-): string {- return formatFilterValue(- config,- operator.value,- filter.value,- maxLength,- t,- locale,- timezoneID,- );-}--/**- * Display-only token for the trigger. Core's PowerSearchToken has no- * `timezoneID` prop, so the value is formatted here with the same formatter- * the Filters rows use. A filter whose field or operator the config no- * longer has still shows, by its raw keys, as the Core token does.- */-function MobilePowerSearchToken({- config,- filter,- field,- operator,- maxLength,- size,- isDisabled,- timezoneID,-}: {- config: InternalConfig;- filter: PowerSearchFilter;- field: PowerSearchField | undefined;- operator: PowerSearchOperator | undefined;- maxLength: number;- size: PowerSearchSize;- isDisabled: boolean;- timezoneID?: string;-}) {- const t = useTranslator();- const locale = useLocale();- const fieldLabel = field?.label ?? filter.field;- const operatorLabel =- operator == null ? filter.operator : resolveOperatorLabel(operator, t);- const tokenLabel = operatorLabel- ? `${fieldLabel}: ${operatorLabel}`- : fieldLabel;- const adjustedMaxLength = Math.max(- maxLength - fieldLabel.length - operatorLabel.length,- 10,- );- const value =- operator == null- ? ''- : formatValueText(- config,- operator,- filter,- adjustedMaxLength,- t,- locale,- timezoneID,- );- return (- <Token- label={tokenLabel}- size={size}- isDisabled={isDisabled}- endContent={- value ? (- <span {...stylex.props(styles.tokenValue)}>{value}</span>- ) : undefined- }- />- );-}--// =============================================================================-// Component-// =============================================================================--/**- * Lab prototype of the touch PowerSearch flow. The outer field keeps active- * filters as display-only tokens and acts as one sheet trigger. The Filters- * sheet lists selected filters as editable rows with direct remove actions,- * Add filter in its header, and Clear all plus Done in its sticky footer;- * opening a row edits that filter in a sheet with Cancel and Apply. Add filter- * when no filter exists and, when the config names a content-search field,- * carries that search with inline suggestions.- */-export function MobilePowerSearch({- config: configProp,- filters,- onChange,- label: labelFromProps,- isLabelHidden = true,- placeholder: placeholderFromProps,- hasAutoFocus = false,- hasClear = true,- isReadOnly = false,- isDisabled = false,- disabledMessage,- startIcon,- onFocus,- onBlur,- status,- statusVariant = 'attached',- maxTokenLength = 40,- maxOperatorMenuItems,- maxSearchResults = DEFAULT_MAX_SEARCH_RESULTS,- popoverSaveButtonLabel,- timezoneID,- endContent,- resultCount,- ref,- handleRef,- size: sizeProp,- 'data-testid': testId,- xstyle,- className,- style,- components: componentOverrides,-}: MobilePowerSearchProps) {- const size = useSize(sizeProp, 'md');- const config = useMobilePowerSearchConfig(configProp);- const t = useTranslator();- const locale = useLocale();- const announceOnPage = useAnnounce();- // `useAnnounce` delivers inside the open Astryx modal that encloses its- // caller (spec AST-086 FR14), and this component renders above the sheets,- // so with a sheet open it cannot call the hook itself: each step's body- // renders a `SheetAnnouncer` inside its BottomSheet, which publishes the- // dialog's own `announce` here while that step is the active one. With no- // sheet open the field's own `useAnnounce` routes a message by where the- // field is — a Dialog or modal Drawer that holds it, else the shared- // page-body channel.- const sheetAnnounceRef = useRef<AnnounceFn | null>(null);- const handleAnnounceChange = useCallback((next: AnnounceFn | null) => {- sheetAnnounceRef.current = next;- }, []);- const stepRef = useRef<SheetStep | null>(null);- const announce = useCallback(- (message: string) => {- const inSheet = stepRef.current == null ? null : sheetAnnounceRef.current;- (inSheet ?? announceOnPage)(message);- },- [announceOnPage],- );- // An announcement queued by a step change — a suggestion or a removal that- // changed the filters — is spoken in the commit that shows the next step,- // so it lands in that step's dialog rather than the one about to close.- const pendingAnnouncementRef = useRef<string | null>(null);- // Clear all closes only its confirmation dialog; announce the result after- // that alertdialog has gone so the message lands in the still-open Filters- // sheet, coalesced with a result-count update from the same commit.- const pendingClearAnnouncementRef = useRef(false);-- const triggerLabel = labelFromProps ?? 'Manage filters';- const fieldPlaceholder = placeholderFromProps ?? 'Filters…';- const contentSearchPlaceholder = placeholderFromProps ?? 'Search…';-- const contentSearchFieldKey = config.config.contentSearchFieldKey;- const contentSearchOperator =- contentSearchFieldKey == null- ? undefined- : config.getDefaultOperator(contentSearchFieldKey);- const hasContentSearch = contentSearchOperator?.value.type === 'string';- const contentSearchSource = useMemo(- () => createContentSearchSource(config, t, maxSearchResults),- [config, maxSearchResults, t],- );-- const triggerId = useId();- const triggerLabelId = useId();- const triggerContentId = useId();- const statusMessageId = useId();- const contentResultsId = useId();- const triggerRef = useRef<HTMLButtonElement>(null);- const wrapperRef = useRef<HTMLDivElement>(null);- // The field's end lane — the result count and `endContent` — sits outside- // the trigger button: a caller's action button there keeps its own tab- // stop and taps, so a tap on it must not open the flow.- const endLaneRef = useRef<HTMLDivElement>(null);- const managerAddButtonRef = useRef<HTMLButtonElement>(null);- const contentSearchRef = useRef<HTMLDivElement>(null);- const fieldSearchRef = useRef<HTMLDivElement>(null);- const contentSuggestionListRef = useRef<HTMLUListElement>(null);- const managerRowsRef = useRef(new Map<number, HTMLLIElement>());- const fieldRowsRef = useRef(new Map<string, HTMLLIElement>());- const manageSheetRef = useRef<HTMLDivElement>(null);- const fieldsSheetRef = useRef<HTMLDivElement>(null);- const fieldPickerOriginRef = useRef<'manage' | 'trigger'>('manage');- const latestFiltersRef = useRef(filters);- const pendingSheetFocusRef = useRef<PendingSheetFocus | null>(null);- const pendingMutationFocusRef = useRef(false);- // Where focus was inside the Filters or Add filter sheet — the sheet and- // the index among its button rows — read on every focus change there, so a- // controlled update that unmounts the focused control can put focus on the- // nearest remaining row, else the sheet's first control or panel.- const lastSheetFocusRef = useRef<{- sheet: 'manage' | 'fields';- rowIndex: number | null;- } | null>(null);- const buttonRowsOf = (panel: HTMLElement): HTMLElement[] =>- Array.from(panel.querySelectorAll<HTMLLIElement>('li'))- .map(row => row.querySelector<HTMLElement>('button'))- .filter((button): button is HTMLElement => button != null);- const noteSheetFocus = useCallback(- (sheet: 'manage' | 'fields') => (event: React.FocusEvent) => {- const row = (event.target as HTMLElement).closest('li');- const button = row?.querySelector<HTMLElement>('button') ?? null;- const rowIndex =- button == null- ? -1- : buttonRowsOf(event.currentTarget as HTMLElement).indexOf(button);- lastSheetFocusRef.current = {- sheet,- rowIndex: rowIndex === -1 ? null : rowIndex,- };- },- [],- );- // Direct row removal returns focus to the next row's trailing remove action,- // avoiding the clipped full-row focus ring that appears as a black line.- const pendingRemovalFocusRef = useRef(false);-- const [step, setStep] = useState<SheetStep | null>(null);- const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);- stepRef.current = step;- // A field that becomes disabled cannot keep its flow open, and must not- // reopen it when re-enabled. Adjusted in the render that sees the change,- // not an effect, so no frame shows both.- const [wasDisabled, setWasDisabled] = useState(isDisabled);- if (isDisabled !== wasDisabled) {- setWasDisabled(isDisabled);- if (isDisabled) {- if (step != null) {- setStep(null);- }- if (isClearConfirmationOpen) {- setIsClearConfirmationOpen(false);- }- }- }- // The draft outlives a step change on purpose: the replace handoff keeps- // the outgoing sheet presented while the incoming one enters, and clearing- // the draft with the step would blank that sheet mid-transition.- const [draft, setDraft] = useState<FilterDraft | null>(null);- const [fieldQuery, setFieldQuery] = useState('');- const [contentQuery, setContentQuery] = useState('');-- const isInteractive = !isDisabled && !isReadOnly;- // Whether a Filters row is a button: the field is interactive and the filter- // is not read-only. Known filters open the value editor; stale filters open- // an unavailable state, while their trailing × remains the removal path.- const isRowButton = useCallback(- (filter: PowerSearchFilter): boolean => !filter.isReadOnly && isInteractive,- [isInteractive],- );- const contentResults = useMemo(() => {- if (step !== 'fields' || !hasContentSearch || !isInteractive) {- return [];- }- const results =- contentQuery.trim() === ''- ? contentSearchSource.bootstrap()- : contentSearchSource.search(contentQuery);- return results.slice(0, MAX_BROWSE_MENU_ITEMS);- }, [- contentQuery,- contentSearchSource,- hasContentSearch,- isInteractive,- step,- ]);-- // ------------------------------------------------------------------ focus ---- // A drag moves focus to the sheet's panel, never to the page body behind- // the open modal.- const fieldPickerDragProps = useDismissSearchOnTouchDrag(- () => [- contentSearchRef.current?.querySelector('input'),- fieldSearchRef.current?.querySelector('input'),- ],- () =>- (- fieldSearchRef.current ?? contentSearchRef.current- )?.closest<HTMLElement>('[tabindex="-1"]'),- );-- const focusPendingSheetTarget = useCallback(() => {- const target = pendingSheetFocusRef.current;- if (target == null) {- return;- }- pendingSheetFocusRef.current = null;- if (target.type === 'manager-add') {- managerAddButtonRef.current?.focus({preventScroll: true});- return;- }- // Add filter's fallback: a controlled update may have removed the field- // whose row opened the step, or the content-search field itself; the- // sheet's first focusable control then takes focus — the search field- // when one shows, else the first field row, else the first button.- const firstFieldsControl = () => {- const panel = fieldsSheetRef.current;- return (- panel?.querySelector<HTMLElement>('input') ??- panel?.querySelector<HTMLElement>('li button') ??- panel?.querySelector<HTMLElement>('button') ??- null- );- };- if (target.type === 'content-search') {- (- contentSearchRef.current?.querySelector<HTMLInputElement>('input') ??- firstFieldsControl()- )?.focus({preventScroll: true});- return;- }- if (target.type === 'field') {- (- fieldRowsRef.current- .get(target.fieldKey)- ?.querySelector<HTMLButtonElement>('button') ?? firstFieldsControl()- )?.focus({preventScroll: true});- return;- }- // Follow the row across controlled reorder or clone. If it disappeared,- // use the nearest remaining editable row, else Add filter. A removal puts- // focus on the next row's × action rather than the invisible row button.- const index =- resolveFilterIdentityIndex(- latestFiltersRef.current,- target.sourceFilter,- target.sourceSignature,- target.preferredIndex,- ) ??- nearestEditableIndex(- latestFiltersRef.current,- target.preferredIndex,- isRowButton,- );- const row = index == null ? null : managerRowsRef.current.get(index);- const rowButton = pendingRemovalFocusRef.current- ? (row?.querySelector<HTMLButtonElement>('[aria-label^="Remove "]') ??- row?.querySelector<HTMLButtonElement>('button'))- : row?.querySelector<HTMLButtonElement>('button');- pendingRemovalFocusRef.current = false;- (rowButton ?? managerAddButtonRef.current)?.focus({preventScroll: true});- }, [isRowButton]);-- // A controlled update that unmounts the focused control of the Filters or- // Add filter sheet leaves focus on the page body inside the open modal.- // Read before paint on every commit of an open step: when focus is no- // longer inside the sheet's dialog, the nearest remaining row by the last- // focused index takes it, else the sheet's first control, else its panel.- // The pending-target effects below run after and win when a step change- // named a control.- useLayoutEffect(() => {- const last = lastSheetFocusRef.current;- if (step !== 'manage' && step !== 'fields') {- return;- }- if (last == null || last.sheet !== step) {- return;- }- const panel =- step === 'manage' ? manageSheetRef.current : fieldsSheetRef.current;- const dialog = panel?.closest('dialog');- const active = document.activeElement;- if (- panel == null ||- dialog == null ||- (active != null && active !== document.body && dialog.contains(active))- ) {- return;- }- const rowButtons = buttonRowsOf(panel);- let target: HTMLElement | null = null;- if (last.rowIndex != null && rowButtons.length > 0) {- // The following button row, else the last.- target = rowButtons[Math.min(last.rowIndex, rowButtons.length - 1)];- }- target ??=- panel.querySelector<HTMLElement>('input') ??- rowButtons[0] ??- panel.querySelector<HTMLElement>('button') ??- null;- if (target != null) {- target.focus({preventScroll: true});- } else {- const focusable = dialog.querySelector<HTMLElement>('[tabindex="-1"]');- (focusable ?? dialog).focus({preventScroll: true});- }- });-- // Both effects run after the entering sheet's own panel focus (child- // effects commit first), so the intended control wins. The filters effect- // is declared first so a mutation that lands in the same commit as the step- // change resolves its row against the new filters.- useEffect(() => {- latestFiltersRef.current = filters;- if (step === 'manage' && pendingMutationFocusRef.current) {- pendingMutationFocusRef.current = false;- focusPendingSheetTarget();- }- }, [filters, focusPendingSheetTarget, step]);-- useEffect(() => {- if (step != null) {- focusPendingSheetTarget();- }- }, [focusPendingSheetTarget, step]);-- // An announcement queued by a step change is spoken in the commit that- // shows the next step, so it lands in that step's dialog.- useEffect(() => {- const message = pendingAnnouncementRef.current;- if (step != null && message != null) {- pendingAnnouncementRef.current = null;- announce(message);- }- }, [announce, step]);-- // ----------------------------------------------------------------- fields ---- const fields = useMemo(- () =>- config- .getVisibleFields()- .filter(field => field.operators.some(isSupportedOperator)),- [config],- );-- const droppedFieldCount = config.getVisibleFields().length - fields.length;- useDevWarning(- 'MobilePowerSearch',- `${droppedFieldCount} field(s) were left out of the filter list because every operator they define has a 'nested' value type, which the sheet editor cannot edit yet. Give those fields a non-nested operator to make them available.`,- droppedFieldCount > 0,- );-- const normalizedFieldQuery = fieldQuery.trim().toLowerCase();- const matchingFields = useMemo(() => {- const matches = fields.filter(field =>- fieldMatchesQuery(field, normalizedFieldQuery),- );- return normalizedFieldQuery === ''- ? matches- : matches.slice(0, maxSearchResults);- }, [fields, maxSearchResults, normalizedFieldQuery]);-- const groupedFields = useMemo(() => {- const groups = new Map<string, PowerSearchField[]>();- for (const field of matchingFields) {- const key = field.group ?? '';- const existing = groups.get(key);- if (existing) {- existing.push(field);- } else {- groups.set(key, [field]);- }- }- return [...groups.entries()];- }, [matchingFields]);-- const isFieldSearchShown = fields.length >= SEARCHABLE_FIELD_COUNT;-- // ------------------------------------------------------------------ draft ---- const draftField = draft ? config.getField(draft.field) : undefined;- const draftOperator =- draft?.operator != null- ? config.getOperator(draft.field, draft.operator)- : undefined;- const draftOperators = useMemo(- () =>- draft- ? config.getVisibleOperators(draft.field).filter(isSupportedOperator)- : [],- [config, draft],- );-- const closeSheet = useCallback(() => {- setStep(null);- }, []);-- const openManager = useCallback(() => {- if (isDisabled) {- return;- }- // A sheet returns focus to the element that was active when its dialog- // opened, and a replace handoff carries that target from step to step;- // make sure it is the trigger even for a tap on a token.- triggerRef.current?.focus({preventScroll: true});- if (filters.length === 0 && isInteractive) {- fieldPickerOriginRef.current = 'trigger';- setFieldQuery('');- setContentQuery('');- pendingSheetFocusRef.current = null;- setStep('fields');- return;- }- fieldPickerOriginRef.current = 'manage';- setStep('manage');- }, [filters.length, hasContentSearch, isDisabled, isInteractive]);-- const handleWrapperClick = useCallback(- (event: React.MouseEvent<HTMLDivElement>) => {- // Tokens are display-only; a tap on them or the empty space around them- // opens the sheet. The trigger button handles its own click, and the- // end lane handles its own.- if (- event.target instanceof Node &&- (triggerRef.current?.contains(event.target) ||- endLaneRef.current?.contains(event.target))- ) {- return;- }- openManager();- },- [openManager],- );-- const openFieldList = useCallback(() => {- if (!isInteractive) {- return;- }- fieldPickerOriginRef.current = 'manage';- setFieldQuery('');- setContentQuery('');- pendingSheetFocusRef.current = null;- setStep('fields');- }, [isInteractive]);-- const queueManagerAddFocus = useCallback(() => {- pendingSheetFocusRef.current = {type: 'manager-add'};- }, []);-- const commitSavedFilter = useCallback(- (next: FilterDraft, filter: PowerSearchFilter) => {- if (!isInteractive) {- queueManagerAddFocus();- setStep('manage');- return;- }- if (next.mode === 'edit') {- const filterIndex = resolveDraftFilterIndex(filters, next);- const currentFilter =- filterIndex == null ? undefined : filters[filterIndex];- if (- filterIndex == null ||- currentFilter == null ||- currentFilter.isReadOnly- ) {- // A controlled update removed the edited filter, or left two it- // could be, or made it read-only: nothing is written, and focus- // returns to the nearest row that is a button around where it was,- // else Add filter.- pendingSheetFocusRef.current =- next.sourceFilter != null &&- next.sourceSignature != null &&- next.filterIndex != null- ? {- type: 'manager-filter',- sourceFilter: next.sourceFilter,- sourceSignature: next.sourceSignature,- preferredIndex: next.filterIndex,- }- : {type: 'manager-add'};- setStep('manage');- return;- }- pendingSheetFocusRef.current = {- type: 'manager-filter',- sourceFilter: filter,- sourceSignature: filterSignature(filter),- preferredIndex: filterIndex,- };- const updated = [...filters];- updated[filterIndex] = filter;- onChange(updated, 'edit', filterIndex);- } else {- queueManagerAddFocus();- onChange([...filters, filter], 'add', filters.length);- }- setStep('manage');- },- [filters, isInteractive, onChange, queueManagerAddFocus],- );-- // Opening a new filter can come from a field row or a content-search- // suggestion. The origin is kept so Cancel returns to the control the user- // came from.- const openCreateEditor = useCallback(- (- field: PowerSearchField,- operator: PowerSearchOperator,- returnFocus: 'field' | 'content-search' = 'field',- ) => {- setDraft({- mode: 'create',- returnStep: 'fields',- returnFocus,- field: field.key,- operator: operator.key,- value: operator.value.type === 'empty' ? {type: 'empty'} : undefined,- });- pendingSheetFocusRef.current = null;- setStep('value');- },- [],- );-- const handleFieldSelect = useCallback(- (field: PowerSearchField) => {- if (!isInteractive) {- return;- }- const operators = field.operators.filter(isSupportedOperator);- const preferred = config.getDefaultOperator(field.key);- const operator =- preferred && isSupportedOperator(preferred) ? preferred : operators[0];- if (operator == null) {- return;- }- if (operator.value.type === 'empty' && operators.length === 1) {- const nextFilter: PowerSearchFilter = {- field: field.key,- operator: operator.key,- value: {type: 'empty'},- };- pendingSheetFocusRef.current = {- type: 'manager-filter',- sourceFilter: nextFilter,- sourceSignature: filterSignature(nextFilter),- preferredIndex: filters.length,- };- pendingMutationFocusRef.current = true;- onChange([...filters, nextFilter], 'add', filters.length);- setStep('manage');- return;- }- openCreateEditor(field, operator);- },- [config, filters, isInteractive, onChange, openCreateEditor],- );-- const handleContentSuggestionSelect = useCallback(- (item: MobilePowerSearchItem | null) => {- if (!isInteractive || item?.auxiliaryData == null) {- return;- }- const {fieldKey, filterValue, operatorKey} = item.auxiliaryData;- const field = config.getField(fieldKey);- const operator =- operatorKey == null- ? config.getDefaultOperator(fieldKey)- : config.getOperator(fieldKey, operatorKey);- if (field == null || operator == null || !isSupportedOperator(operator)) {- return;- }- setContentQuery('');- if (filterValue != null) {- const nextFilter: PowerSearchFilter = {- field: field.key,- operator: operator.key,- value: filterValue,- };- pendingSheetFocusRef.current = {- type: 'manager-filter',- sourceFilter: nextFilter,- sourceSignature: filterSignature(nextFilter),- preferredIndex: filters.length,- };- pendingMutationFocusRef.current = true;- onChange([...filters, nextFilter], 'add', filters.length);- // Spoken once the Filters sheet is the open dialog, so it lands there- // rather than in the Add filter dialog about to be replaced.- pendingAnnouncementRef.current = t('@astryx.tokenizer.tokenAdded', {- label: item.label,- });- setStep('manage');- return;- }- openCreateEditor(field, operator, 'content-search');- },- [config, filters, isInteractive, onChange, openCreateEditor, t],- );-- const handleFilterEdit = useCallback(- (index: number) => {- const filter = filters[index];- if (!isInteractive || filter == null || filter.isReadOnly) {- return;- }- setDraft({- mode: 'edit',- filterIndex: index,- sourceFilter: filter,- sourceSignature: filterSignature(filter),- field: filter.field,- operator: filter.operator,- value: filter.value,- });- pendingSheetFocusRef.current = null;- setStep('value');- },- [filters, isInteractive],- );-- // A filter as its Filters row reads it: the field's label when the field- // remains, the raw key for what the config no longer has, and the value as- // the token shows it.- const describeFilterParts = useCallback(- (filter: PowerSearchFilter): {label: string; value: string | null} => {- const field = config.getField(filter.field);- const operator = config.getOperator(filter.field, filter.operator);- const fieldLabel = field?.label ?? filter.field;- const operatorLabel =- operator == null ? filter.operator : resolveOperatorLabel(operator, t);- const label = [fieldLabel, operatorLabel].filter(Boolean).join(' ');- if (operator == null) {- return {label, value: null};- }- const value = formatValueText(- config,- operator,- filter,- Number.MAX_SAFE_INTEGER,- t,- locale,- timezoneID,- );- return {label, value: value || null};- },- [config, locale, t, timezoneID],- );- const describeFilter = useCallback(- (filter: PowerSearchFilter): string => {- const parts = describeFilterParts(filter);- return parts.value ? `${parts.label} ${parts.value}` : parts.label;- },- [describeFilterParts],- );-- const handleRemoveFilter = useCallback(- (index: number) => {- const filter = filters[index];- if (!isInteractive || filter == null || filter.isReadOnly) {- return;- }- const nextFilters = filters.filter((_, i) => i !== index);- const nextIndex = nearestEditableIndex(nextFilters, index, isRowButton);- if (nextIndex == null) {- pendingSheetFocusRef.current = {type: 'manager-add'};- } else {- const nextFilter = nextFilters[nextIndex];- pendingSheetFocusRef.current = {- type: 'manager-filter',- sourceFilter: nextFilter,- sourceSignature: filterSignature(nextFilter),- preferredIndex: nextIndex,- };- }- pendingRemovalFocusRef.current = true;- pendingMutationFocusRef.current = true;- onChange(nextFilters, 'remove', index);- const message = t('@astryx.tokenizer.tokenRemoved', {- label: describeFilter(filter),- });- // A direct Filters-row removal stays in the same sheet, so announce- // immediately there. A custom editor that removes while returning to- // Filters defers until the step handoff has completed.- if (stepRef.current === 'manage') {- announce(message);- } else {- pendingAnnouncementRef.current = message;- }- },- [- announce,- describeFilter,- filters,- isInteractive,- isRowButton,- onChange,- t,- ],- );-- // Clear all is a management action: confirm it, remove only filters the user- // can edit, preserve read-only filters, and keep the sheet open.- const handleClearAll = useCallback(() => {- const kept = filters.filter(filter => filter.isReadOnly);- const firstRemovedIndex = filters.findIndex(filter => !filter.isReadOnly);- if (firstRemovedIndex < 0) {- return;- }- pendingClearAnnouncementRef.current = true;- onChange(kept, 'remove', firstRemovedIndex);- }, [filters, onChange]);-- const handleOperatorSelect = useCallback((operator: PowerSearchOperator) => {- setDraft(current => {- if (current == null) {- return current;- }- // A value survives an operator change only when the new operator- // reads the same value type.- const keepsValue =- current.value != null && current.value.type === operator.value.type;- return {- ...current,- operator: operator.key,- value:- operator.value.type === 'empty'- ? {type: 'empty'}- : keepsValue- ? current.value- : undefined,- };- });- }, []);-- const handleDraftValueChange = useCallback((value: FilterValue) => {- setDraft(current => (current == null ? current : {...current, value}));- }, []);-- const handleSave = useCallback(() => {- if (draft?.value == null || draft.operator == null) {- return;- }- commitSavedFilter(draft, {- field: draft.field,- operator: draft.operator,- value: draft.value,- });- }, [commitSavedFilter, draft]);-- const returnFromValue = useCallback(() => {- if (draft == null) {- queueManagerAddFocus();- setStep('manage');- return;- }- if (- draft.mode === 'edit' &&- draft.sourceFilter != null &&- draft.sourceSignature != null &&- draft.filterIndex != null- ) {- pendingSheetFocusRef.current = {- type: 'manager-filter',- sourceFilter: draft.sourceFilter,- sourceSignature: draft.sourceSignature,- preferredIndex:- resolveDraftFilterIndex(filters, draft) ?? draft.filterIndex,- };- setStep('manage');- return;- }- if (draft.returnFocus === 'content-search') {- pendingSheetFocusRef.current = {type: 'content-search'};- setStep('fields');- return;- }- pendingSheetFocusRef.current = {type: 'field', fieldKey: draft.field};- setStep('fields');- }, [draft, filters, queueManagerAddFocus]);-- const handleRemove = useCallback(() => {- if (draft?.mode !== 'edit') {- return;- }- const filterIndex = resolveDraftFilterIndex(filters, draft);- if (filterIndex == null || filters[filterIndex]?.isReadOnly) {- queueManagerAddFocus();- setStep('manage');- return;- }- handleRemoveFilter(filterIndex);- setStep('manage');- }, [draft, filters, handleRemoveFilter, queueManagerAddFocus]);-- // Each step sheet is controlled by `step`; a sheet only ever asks to close- // (a dismissal its `purpose` allows: Escape, the scrim, a swipe), and only- // the current step's request ends the flow. Every step change goes through- // the handlers above.- const handleStepOpenChange = useCallback(- (sheetStep: SheetStep, isOpen: boolean) => {- if (!isOpen && stepRef.current === sheetStep) {- setStep(null);- }- },- [],- );- const handleManageOpenChange = useCallback(- (isOpen: boolean) => handleStepOpenChange('manage', isOpen),- [handleStepOpenChange],- );- const handleFieldsOpenChange = useCallback(- (isOpen: boolean) => {- if (isOpen || stepRef.current !== 'fields') {- return;- }- if (fieldPickerOriginRef.current === 'manage') {- queueManagerAddFocus();- setStep('manage');- } else {- setStep(null);- }- },- [queueManagerAddFocus],- );- const handleValueOpenChange = useCallback(- (isOpen: boolean) => {- if (!isOpen && stepRef.current === 'value') {- returnFromValue();- }- },- [returnFromValue],- );-- const handleFocusWithin = useCallback(- (event: React.FocusEvent<HTMLDivElement>) => {- if (- !(event.relatedTarget instanceof Node) ||- !event.currentTarget.contains(event.relatedTarget)- ) {- onFocus?.(event);- }- },- [onFocus],- );- const handleBlurWithin = useCallback(- (event: React.FocusEvent<HTMLDivElement>) => {- if (- !(event.relatedTarget instanceof Node) ||- !event.currentTarget.contains(event.relatedTarget)- ) {- onBlur?.(event);- }- },- [onBlur],- );-- // ------------------------------------------------------------- imperative ---- useImperativeHandle(handleRef, () => ({- focusTypeahead() {- triggerRef.current?.focus();- },- blurTypeahead() {- triggerRef.current?.blur();- },- }));-- // ----------------------------------------------------------- result count ---- const resultCountText = useMemo((): string | null => {- if (resultCount == null) {- return null;- }- if (typeof resultCount === 'number') {- return t('@astryx.powersearch.resultCount', {count: resultCount});- }- return resultCount;- }, [resultCount, t]);-- // This Effect synchronizes a polite live region with the result count- // through `announce`, which routes by where the field is: into the open- // sheet's dialog while a step is open (its `SheetAnnouncer`), else by the- // field's own `useAnnounce` — a Dialog or modal Drawer that holds the- // field, or the shared page-body channel (spec AST-086 FR14). A count- // present on mount is not announced unprompted, and the guard compares- // against the last announced text rather than a mounted flag, so- // StrictMode's effect replay announces nothing either. The announcement- // acquires no resource, so there is no cleanup.- const announcedResultCountRef = useRef(resultCountText);- useEffect(() => {- if (isClearConfirmationOpen || !pendingClearAnnouncementRef.current) {- return;- }- pendingClearAnnouncementRef.current = false;- announcedResultCountRef.current = resultCountText;- announce(- resultCountText == null- ? 'Editable filters removed'- : `Editable filters removed. ${resultCountText}`,- );- }, [announce, isClearConfirmationOpen, resultCountText]);-- useEffect(() => {- if (resultCountText === announcedResultCountRef.current) {- return;- }- announcedResultCountRef.current = resultCountText;- if (resultCountText == null) {- return;- }- announce(resultCountText);- }, [resultCountText, announce]);-- // --------------------------------------------------------------- tooltip ---- const showsDisabledMessage = isDisabled && !!disabledMessage;- const disabledMessageTooltip = useTooltip({- placement: 'above',- focusTrigger: 'always',- isEnabled: showsDisabledMessage,- });- const mergedWrapperRef = useMergedRefs(- wrapperRef,- disabledMessageTooltip.ref,- );-- const triggerDescribedBy =- [- status?.message ? statusMessageId : null,- showsDisabledMessage ? disabledMessageTooltip.describedBy : null,- ]- .filter(Boolean)- .join(' ') || undefined;-- // ---------------------------------------------------------------- render ---- // Rows and tokens are keyed by filter identity, not position: a parent's- // reorder or a removal above the focused row then moves elements instead- // of remounting them, and focus stays on the same filter. Only a filter- // that is itself removed loses its element, and the re-home effect above- // takes over. Every filter lists — one whose field or operator the config- // no longer has by its raw keys, as its token shows on the trigger, and its- // trailing × remains available even when the editor becomes unavailable.- const [filterIdentities] = useState(createFilterIdentities);- const filterIds = filterIdentities.next(filters);- const filterRows = filters.map((filter, index) => {- const {label, value} = describeFilterParts(filter);- const displayLabel = value ? (- <>- {label} <span {...stylex.props(styles.rowValue)}>{value}</span>- </>- ) : (- label- );- return {- displayLabel,- filter,- index,- isEditable: isRowButton(filter),- key: `filter-${filterIds[index]}`,- };- });-- const tokens = filters.map((filter, index) => {- const field = config.getField(filter.field);- const operator = config.getOperator(filter.field, filter.operator);- const key = `filter-${filterIds[index]}`;- const TokenOverride =- field != null && operator != null- ? componentOverrides?.[operator.value.type]?.Token- : undefined;- if (TokenOverride && field != null && operator != null) {- return (- <TokenOverride- key={key}- config={configProp}- filter={filter}- field={field}- operator={operator}- maxLength={maxTokenLength}- onClick={undefined}- onRemove={undefined}- isDisabled={isDisabled}- />- );- }- return (- <MobilePowerSearchToken- key={key}- config={config}- filter={filter}- field={field}- operator={operator}- maxLength={maxTokenLength}- size={size}- isDisabled={isDisabled}- timezoneID={timezoneID}- />- );- });-- const hasRemovableFilter = filters.some(filter => !filter.isReadOnly);- const isClearAllShown = hasClear && isInteractive && hasRemovableFilter;-- const EditorOverride =- draftOperator != null- ? componentOverrides?.[draftOperator.value.type]?.Editor- : undefined;-- const draftOperatorLabel =- draftOperator == null ? '' : resolveOperatorLabel(draftOperator, t);- // The title — the dialog's name — reads the field and operator as the- // Filters row does: by their labels, or, for a filter whose field or- // operator the config no longer has, by the raw keys the row shows.- const editorTitle =- draft == null- ? 'Add filter'- : draftField == null || (draftOperator == null && draft.operator != null)- ? [- draftField?.label ?? draft.field,- draftOperatorLabel !== '' ? draftOperatorLabel : draft.operator,- ]- .filter(Boolean)- .join(' ')- : draftOperators.length <= 1 && draftOperatorLabel !== ''- ? `${draftField.label} ${draftOperatorLabel}`- : draftField.label;- const saveButtonLabel =- popoverSaveButtonLabel ?? (draft?.mode === 'edit' ? 'Apply' : 'Add filter');-- // Every sheet body: padded, and publishing that padding to its lists.- const bodyProps = stylex.props(- styles.body,- containerPaddingInlineVarStyles[4],- );- const scrollViewportProps = stylex.props(styles.scrollViewport);- const scrollContentProps = stylex.props(- styles.scrollContent,- containerPaddingInlineVarStyles[4],- );-- const isEditorDisabled = isDisabled || isReadOnly;- const isFieldPickerDirectEntry = fieldPickerOriginRef.current === 'trigger';- const isManageSheetOpen =- step === 'manage' ||- (step === 'fields' && !isFieldPickerDirectEntry) ||- (step === 'value' && (draft?.mode === 'edit' || !isFieldPickerDirectEntry));- const isFieldsSheetOpen =- step === 'fields' || (step === 'value' && draft?.mode === 'create');- const isSaveDisabled =- isEditorDisabled || draft?.operator == null || draft.value == null;- const isDraftRenderable =- draft != null && draftField != null && draftOperator != null;- // A controlled config update that removes the field or operator being- // edited replaces the step's body with the unavailable state while focus- // may be on one of the body's controls. Focus moves to Cancel, the remaining- // way back to the Filters row where direct removal lives.- const cancelButtonRef = useRef<HTMLButtonElement>(null);- const wasDraftRenderableRef = useRef(isDraftRenderable);- useLayoutEffect(() => {- const becameUnavailable =- wasDraftRenderableRef.current && !isDraftRenderable && draft != null;- wasDraftRenderableRef.current = isDraftRenderable;- if (!becameUnavailable || step !== 'value') {- return;- }- const active = document.activeElement;- const dialog = cancelButtonRef.current?.closest('dialog');- if (dialog != null && active != null && dialog.contains(active)) {- return;- }- cancelButtonRef.current?.focus();- }, [draft, isDraftRenderable, step]);-- return (- <>- <Field- ref={ref}- label={triggerLabel}- labelID={triggerLabelId}- isLabelHidden={isLabelHidden}- inputID={triggerId}- isDisabled={isDisabled}- status={- status- ? {- type: status.type,- message: status.message,- messageID: status.message ? statusMessageId : undefined,- }- : undefined- }- statusVariant={statusVariant}- xstyle={xstyle}- className={className}- style={style}>- <div- ref={mergedWrapperRef}- onClick={handleWrapperClick}- onFocus={handleFocusWithin}- onBlur={handleBlurWithin}- data-testid={testId}- aria-disabled={isDisabled ? true : undefined}- {...stylex.props(- inputWrapperStyles.base,- styles.wrapper,- filters.length > 0 && styles.wrapperWithTokens,- sizeStyles[size],- isDisabled && inputWrapperStyles.disabled,- status && inputStatusBorderStyles[status.type],- status && !isDisabled && inputStatusHoverShadowStyles[status.type],- status && inputStatusFocusWithinStyles[status.type],- )}>- {/* The trigger's name is the label plus everything visible here:- the placeholder, or the tokens, so speech input can say what it- sees and assistive technology hears the selected filters- (WCAG 2.5.3). */}- <div id={triggerContentId} {...stylex.props(styles.contentSection)}>- {startIcon && (- <span- {...stylex.props(- filters.length > 0 && styles.startIconWithTokens,- )}>- {renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}- </span>- )}- {tokens}- <button- type="button"- id={triggerId}- ref={triggerRef}- autoFocus={hasAutoFocus}- onClick={openManager}- // Never natively `disabled`: the trigger stays focusable, so it- // can take focus back when a flow closes because the field- // became disabled, and so a disabled reason can be read from- // it; `openManager` refuses to open while disabled.- aria-disabled={isDisabled ? true : undefined}- aria-haspopup="dialog"- aria-expanded={step != null}- aria-labelledby={`${triggerLabelId} ${triggerContentId}`}- aria-describedby={triggerDescribedBy}- {...stylex.props(- styles.trigger,- filters.length > 0 && styles.triggerWithTokens,- )}>- {filters.length === 0 ? fieldPlaceholder : null}- </button>- </div>- {(endContent || isRenderable(resultCountText)) && (- <div ref={endLaneRef} {...stylex.props(styles.endSection)}>- {isRenderable(resultCountText) && (- <span {...stylex.props(styles.resultCount)}>- {resultCountText}- </span>- )}- {endContent}- </div>- )}- </div>- {showsDisabledMessage &&- disabledMessageTooltip.renderTooltip(disabledMessage)}- </Field>-- <BottomSheet- isOpen={isManageSheetOpen}- onOpenChange={handleManageOpenChange}- finalFocusRef={triggerRef}- label="Filters"- height="tall"- padding={0}>- <div- ref={manageSheetRef}- onFocus={noteSheetFocus('manage')}- {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>- {step === 'manage' && (- <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />- )}- <div {...stylex.props(styles.header)}>- <div {...stylex.props(styles.headerRow)}>- <div {...stylex.props(styles.headerText)}>- <Heading level={3}>Filters</Heading>- </div>- {isInteractive && filterRows.length > 0 && (- <Button- ref={managerAddButtonRef}- label="Add filter"- icon={<Icon icon={PlusIcon} size="sm" />}- isIconOnly- variant="secondary"- size="md"- onClick={openFieldList}- />- )}- </div>- </div>- <div {...stylex.props(styles.scrollViewport)}>- <div {...scrollContentProps}>- {filterRows.length === 0 ? (- isManageSheetOpen ? (- <EmptyState- title="No filters applied"- description="Add a filter to narrow your results and find what you need faster."- headingLevel={4}- icon={<Icon icon="funnel" size="lg" color="secondary" />}- xstyle={styles.emptyState}- actions={- isInteractive ? (- <Button- ref={managerAddButtonRef}- label="Add filter"- icon={<Icon icon={PlusIcon} size="sm" />}- variant="primary"- size="lg"- onClick={openFieldList}- />- ) : undefined- }- />- ) : null- ) : (- <List hasDividers density="spacious" edge="bleed">- {filterRows.map(row => {- const canEdit = row.isEditable;- const operator = config.getOperator(- row.filter.field,- row.filter.operator,- );- const fieldLabel =- config.getField(row.filter.field)?.label ??- row.filter.field;- const isImmediateToggle = operator?.value.type === 'empty';- return (- <ListItem- key={row.key}- ref={node => {- if (node == null) {- managerRowsRef.current.delete(row.index);- } else {- managerRowsRef.current.set(row.index, node);- }- }}- label={row.displayLabel}- onClick={- canEdit- ? isImmediateToggle- ? () => handleRemoveFilter(row.index)- : () => handleFilterEdit(row.index)- : undefined- }- endContent={- canEdit ? (- <IconButton- label={`Remove ${fieldLabel} filter`}- tooltip={`Remove ${fieldLabel} filter`}- icon={<Icon icon="close" size="sm" />}- variant="ghost"- size="md"- onClick={event => {- event.stopPropagation();- handleRemoveFilter(row.index);- }}- />- ) : undefined- }- />- );- })}- </List>- )}- </div>- </div>- {filterRows.length > 0 && (- <div {...stylex.props(styles.footer, styles.fixedFooter)}>- {isClearAllShown && (- <Button- label="Clear all"- variant="secondary"- size="lg"- xstyle={styles.footerEqualAction}- onClick={() => setIsClearConfirmationOpen(true)}- />- )}- <Button- label="Done"- variant="primary"- size="lg"- xstyle={- isClearAllShown- ? styles.footerEqualAction- : styles.footerSoleAction- }- onClick={closeSheet}- width={isClearAllShown ? undefined : '100%'}- />- </div>- )}- </div>- </BottomSheet>-- <BottomSheet- isOpen={isFieldsSheetOpen}- onOpenChange={handleFieldsOpenChange}- finalFocusRef={triggerRef}- label="Add filter"- height="tall"- padding={0}>- <div- ref={fieldsSheetRef}- onFocus={noteSheetFocus('fields')}- {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>- {step === 'fields' && (- <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />- )}- <div {...stylex.props(styles.header)}>- <div {...stylex.props(styles.headerRow)}>- <div {...stylex.props(styles.headerText)}>- <Heading level={3}>Add filter</Heading>- </div>- </div>- {hasContentSearch ? (- <div ref={contentSearchRef}>- <TextInput- label="Search"- isLabelHidden- role="searchbox"- aria-controls={contentResultsId}- value={contentQuery}- onChange={setContentQuery}- onKeyDown={event => {- if (isImeKeyEvent(event.nativeEvent)) {- return;- }- if (event.key === 'Enter' && contentResults[0] != null) {- event.preventDefault();- handleContentSuggestionSelect(contentResults[0]);- return;- }- if (event.key === 'ArrowDown') {- event.preventDefault();- contentSuggestionListRef.current- ?.querySelector<HTMLButtonElement>('button')- ?.focus();- }- }}- placeholder={contentSearchPlaceholder}- hasClear- startIcon={<Icon icon="search" size="sm" color="secondary" />}- isDisabled={!isInteractive}- size="lg"- width="100%"- />- </div>- ) : isFieldSearchShown ? (- <div ref={fieldSearchRef}>- <TextInput- label="Search filters"- isLabelHidden- placeholder="Search filters…"- value={fieldQuery}- onChange={setFieldQuery}- startIcon={<Icon icon="search" size="sm" color="secondary" />}- isDisabled={!isInteractive}- size="lg"- width="100%"- />- </div>- ) : null}- </div>- <div {...scrollViewportProps} {...fieldPickerDragProps}>- <div {...scrollContentProps}>- {hasContentSearch ? (- contentResults.length > 0 ? (- <List- ref={contentSuggestionListRef}- id={contentResultsId}- aria-label="Search results"- hasDividers- density="spacious"- edge="bleed">- {contentResults.map((item, index) => (- <ListItem- key={item.id}- label={item.label}- isDisabled={!isInteractive}- onClick={() => handleContentSuggestionSelect(item)}- onKeyDown={event => {- if (- isImeKeyEvent(event.nativeEvent) ||- (event.key !== 'ArrowDown' &&- event.key !== 'ArrowUp')- ) {- return;- }- event.preventDefault();- const buttons = [- ...(contentSuggestionListRef.current?.querySelectorAll<HTMLButtonElement>(- 'button',- ) ?? []),- ];- const nextIndex =- event.key === 'ArrowDown'- ? Math.min(index + 1, buttons.length - 1)- : index - 1;- if (nextIndex < 0) {- contentSearchRef.current- ?.querySelector<HTMLInputElement>('input')- ?.focus();- } else {- buttons[nextIndex]?.focus();- }- }}- />- ))}- </List>- ) : contentQuery.trim() !== '' ? (- <div id={contentResultsId}>- {step === 'fields' && (- <EmptyState- icon={- <Icon icon="search" size="lg" color="secondary" />- }- title="No results found"- description="Try a different search."- headingLevel={4}- isCompact- xstyle={styles.emptyState}- />- )}- </div>- ) : (- <div id={contentResultsId} />- )- ) : groupedFields.length === 0 ? (- normalizedFieldQuery !== '' && step === 'fields' ? (- <EmptyState- icon={<Icon icon="search" size="lg" color="secondary" />}- title="No filters found"- description="Try a different search."- headingLevel={4}- isCompact- xstyle={styles.emptyState}- />- ) : null- ) : (- groupedFields.map(([group, groupFields]) => (- <List- key={group}- hasDividers- density="spacious"- header={- <Heading level={4}>- {group === '' ? 'General' : group}- </Heading>- }- edge="bleed">- {groupFields.map(field => (- <ListItem- key={field.key}- ref={node => {- if (node == null) {- fieldRowsRef.current.delete(field.key);- } else {- fieldRowsRef.current.set(field.key, node);- }- }}- label={field.label}- isDisabled={!isInteractive}- startContent={field.icon}- endContent={- field.operators.length === 1 &&- field.operators[0]?.value.type === 'empty' ? (- <Icon icon={PlusIcon} size="sm" color="secondary" />- ) : (- <Icon- icon="chevronRight"- size="sm"- color="secondary"- xstyle={rtlStyles.mirror}- />- )- }- onClick={() => handleFieldSelect(field)}- />- ))}- </List>- ))- )}- </div>- </div>- {isFieldPickerDirectEntry && (- <div {...stylex.props(styles.footer, styles.fixedFooter)}>- <Button- label="Done"- variant="primary"- width="100%"- xstyle={styles.touchAction}- onClick={closeSheet}- />- </div>- )}- </div>- </BottomSheet>-- <BottomSheet- isOpen={step === 'value'}- onOpenChange={handleValueOpenChange}- finalFocusRef={triggerRef}- label={editorTitle}- height="tall"- padding={0}- purpose="info">- <div {...stylex.props(styles.sheet)}>- {step === 'value' && (- <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />- )}- <div {...stylex.props(styles.header)}>- <div {...stylex.props(styles.headerRow)}>- <div {...stylex.props(styles.headerText)}>- <Heading level={3} maxLines={1}>- {editorTitle}- </Heading>- </div>- </div>- </div>- {isDraftRenderable && EditorOverride != null ? (- <div {...bodyProps}>- <EditorOverride- key={`${draft.mode}-${draft.filterIndex ?? 'new'}-${draft.field}`}- config={configProp}- filter={{- field: draft.field,- operator: draft.operator,- value: draft.value,- }}- mode={draft.mode}- onSave={saved => {- if (saved == null) {- if (draft.mode === 'edit') {- handleRemove();- } else {- queueManagerAddFocus();- setStep('manage');- }- return;- }- commitSavedFilter(draft, saved);- }}- onCancel={returnFromValue}- saveButtonLabel={saveButtonLabel}- isReadOnly={isEditorDisabled}- timezoneID={timezoneID}- />- </div>- ) : (- <>- <div {...bodyProps}>- {isDraftRenderable ? (- <>- {draftOperators.length > 1 && (- <div {...stylex.props(styles.controlSection)}>- <RadioList- label="Operator"- isLabelHidden- value={draft.operator ?? ''}- onChange={operatorKey => {- const operator = draftOperators.find(- candidate => candidate.key === operatorKey,- );- if (operator != null) {- handleOperatorSelect(operator);- }- }}- isDisabled={isEditorDisabled}>- {draftOperators.map(operator => (- <RadioListItem- key={operator.key}- label={`${draftField.label} ${resolveOperatorLabel(operator, t)}`}- value={operator.key}- xstyle={styles.trailingControlRow}- />- ))}- </RadioList>- </div>- )}- {draftOperators.length > 1 ? (- <div {...stylex.props(styles.controlSection)}>- <MobilePowerSearchValueEditor- key={`${draft.field}-${draft.operator}`}- operatorValue={draftOperator.value}- filterValue={draft.value}- onChange={handleDraftValueChange}- label={draftField.label}- isDisabled={isEditorDisabled}- maxMenuItems={maxOperatorMenuItems}- timezoneID={timezoneID}- />- </div>- ) : (- <MobilePowerSearchValueEditor- key={`${draft.field}-${draft.operator}`}- operatorValue={draftOperator.value}- filterValue={draft.value}- onChange={handleDraftValueChange}- label={draftField.label}- isDisabled={isEditorDisabled}- maxMenuItems={maxOperatorMenuItems}- timezoneID={timezoneID}- />- )}- </>- ) : (- // A controlled config update removed the field or operator- // being edited: say so and keep a way out.- draft != null && (- <SheetEmptyMessage- message="This filter is no longer available"- occasion={`${draft.field}-${draft.operator ?? ''}`}- isShown={step === 'value'}- />- )- )}- </div>- <div {...stylex.props(styles.footer)}>- {isReadOnly ? (- <Button- ref={cancelButtonRef}- label="Cancel"- variant="secondary"- width="100%"- xstyle={styles.footerSoleAction}- onClick={returnFromValue}- />- ) : (- <>- <Button- ref={cancelButtonRef}- label="Cancel"- variant="secondary"- size="lg"- xstyle={styles.footerEqualAction}- onClick={returnFromValue}- />- {isDraftRenderable && (- <Button- label={saveButtonLabel}- variant="primary"- size="lg"- isDisabled={isSaveDisabled}- xstyle={styles.footerEqualAction}- onClick={handleSave}- />- )}- </>- )}- </div>- </>- )}- </div>- </BottomSheet>-- <SheetConfirmation- isOpen={isClearConfirmationOpen}- onOpenChange={setIsClearConfirmationOpen}- title="Clear all filters?"- description="This removes all editable filters from this search."- actionLabel="Clear filters"- cancelLabel="Keep filters"- onAction={() => {- handleClearAll();- setIsClearConfirmationOpen(false);- }}- />- </>- );-}--MobilePowerSearch.displayName = 'MobilePowerSearch';diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsxdeleted file mode 100644index 813d1b0a6f..0000000000--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsx+++ /dev/null@@ -1,776 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file MobilePowerSearchValueEditor.tsx- * @input OperatorValue, staged FilterValue, onChange, label, timezoneID;- * public @astryxdesign/core inputs (Calendar, DateTimeInput, EmptyState,- * Icon, List, NumberInput, TextInput, TimeInput, Typeahead, VisuallyHidden)- * @output Sheet-native value editor for MobilePowerSearch: enum, enum_list and- * date_relative as full-row List choices with persistent radio or checkbox- * indicators; string_list and entity_list as inline searchable checkbox- * rows; every other non-nested value type as the matching public input- * @position Lab sub-component consumed by MobilePowerSearch.tsx- *- * Core's PowerSearchValueEditor is private, so this file rebuilds each editor- * from public inputs. Closed vocabularies render as rows, open lists keep their- * search and selectable results inline, and date-only values use an inline- * Calendar. Every editor stages its value; the sheet footer confirms it.- */--import React, {- useCallback,- useEffect,- useMemo,- useRef,- useState,- type FormEvent,-} from 'react';-import * as stylex from '@stylexjs/stylex';-import {Calendar, type DateRange} from '@astryxdesign/core/Calendar';-import {DateTimeInput} from '@astryxdesign/core/DateTimeInput';-import {EmptyState} from '@astryxdesign/core/EmptyState';-import {Icon} from '@astryxdesign/core/Icon';-import {CheckboxIndicator, RadioIndicator} from '@astryxdesign/core/Indicator';-import {List, ListItem} from '@astryxdesign/core/List';-import {NumberInput} from '@astryxdesign/core/NumberInput';-import type {- DateTimeRangePart,- FilterValue,- OperatorValue,- PowerSearchEntity,-} from '@astryxdesign/core/PowerSearch';-import {TextInput} from '@astryxdesign/core/TextInput';-import {TimeInput} from '@astryxdesign/core/TimeInput';-import {Typeahead} from '@astryxdesign/core/Typeahead';-import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';-import type {ISODateString, ISOTimeString} from '@astryxdesign/core/utils';-import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';-import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';-import {- isoDateTimeToUnixSeconds,- isoDateToUnixSeconds,- unixSecondsToISODate,- unixSecondsToISODateTime,-} from './mobilePowerSearchUtils';--const styles = stylex.create({- input: {- paddingBlockStart: spacingVars['--spacing-1'],- },- inlineCalendar: {- display: 'flex',- justifyContent: 'center',- },- inlineSearch: {- display: 'flex',- flexDirection: 'column',- gap: spacingVars['--spacing-3'],- },-});--export interface MobilePowerSearchValueEditorProps {- operatorValue: OperatorValue;- filterValue: FilterValue | undefined;- /** Stage a value without leaving the sheet. */- onChange: (value: FilterValue) => void;- /**- * The field's name. Titles the sheet a list value's tokenizer opens, so it- * reads as the field being edited.- */- label?: string;- isDisabled?: boolean;- /** Max suggestions in string and entity value typeaheads. */- maxMenuItems?: number;- /** IANA timezone used by date-only, date-time, and date-range editors. */- timezoneID?: string;-}--const EMPTY_SOURCE: SearchSource<SearchableItem> = {- search: () => [],- bootstrap: () => [],-};--// =============================================================================-// Choice rows (enum, enum_list, date_relative)-// =============================================================================--interface ChoiceItem {- readonly value: string;- readonly label: string;- readonly icon?: React.ReactNode;-}--function ChoiceRows({- items,- selected,- selectionMode,- isDisabled,- onToggle,-}: {- items: ReadonlyArray<ChoiceItem>;- selected: ReadonlySet<string>;- selectionMode: 'single' | 'multiple';- isDisabled?: boolean;- onToggle: (value: string, isSelected: boolean) => void;-}) {- return (- <List density="spacious" edge="flush">- {items.map(item => {- const isSelected = selected.has(item.value);- return (- <ListItem- key={item.value}- label={- isSelected ? (- <>- <span aria-hidden="true">{item.label}</span>- <VisuallyHidden>{`${item.label}, selected`}</VisuallyHidden>- </>- ) : (- item.label- )- }- startContent={item.icon}- isDisabled={isDisabled}- endContent={- selectionMode === 'multiple' ? (- <CheckboxIndicator- state={isSelected ? 'checked' : 'unchecked'}- isDisabled={isDisabled}- />- ) : (- <RadioIndicator- state={isSelected ? 'checked' : 'unchecked'}- isDisabled={isDisabled}- />- )- }- onClick={() => onToggle(item.value, isSelected)}- />- );- })}- </List>- );-}--function InlineListSearch({- label,- searchSource,- selectedItems,- allowsCreate = false,- renderItem,- isDisabled,- maxMenuItems = 10,- onChange,-}: {- label: string;- searchSource: SearchSource<SearchableItem>;- selectedItems: ReadonlyArray<SearchableItem>;- allowsCreate?: boolean;- renderItem?: (item: SearchableItem) => React.ReactNode;- isDisabled: boolean;- maxMenuItems?: number;- onChange: (items: SearchableItem[]) => void;-}) {- const [query, setQuery] = useState('');- const [results, setResults] = useState<SearchableItem[]>([]);- const requestIdRef = useRef(0);- const selectedIds = useMemo(- () => new Set(selectedItems.map(item => item.id)),- [selectedItems],- );-- useEffect(() => {- const requestId = ++requestIdRef.current;- const trimmed = query.trim();- const timeout = setTimeout(- () => {- let pending: Promise<SearchableItem[]> | SearchableItem[];- try {- pending =- trimmed === ''- ? searchSource.bootstrap()- : searchSource.search(trimmed);- } catch {- if (requestId === requestIdRef.current) {- setResults([]);- }- return;- }- void Promise.resolve(pending).then(- items => {- if (requestId === requestIdRef.current) {- setResults(items.slice(0, maxMenuItems));- }- },- () => {- if (requestId === requestIdRef.current) {- setResults([]);- }- },- );- },- trimmed === '' ? 0 : 150,- );- return () => {- clearTimeout(timeout);- searchSource.cancel?.();- };- }, [maxMenuItems, query, searchSource]);-- const visibleItems = useMemo(() => {- const byId = new Map<string, SearchableItem>();- if (query.trim() === '') {- for (const item of selectedItems) {- byId.set(item.id, item);- }- }- for (const item of results) {- byId.set(item.id, item);- }- const trimmed = query.trim();- if (- allowsCreate &&- trimmed !== '' &&- ![...byId.values()].some(- item => item.label.toLocaleLowerCase() === trimmed.toLocaleLowerCase(),- )- ) {- byId.set(`__inline_create__${trimmed}`, {- id: `__inline_create__${trimmed}`,- label: trimmed,- auxiliaryData: {isCreate: true},- });- }- return [...byId.values()];- }, [allowsCreate, query, results, selectedItems]);-- return (- <div {...stylex.props(styles.inlineSearch)}>- <TextInput- label={`Search ${label}`}- isLabelHidden- value={query}- onChange={setQuery}- placeholder="Search…"- startIcon={<Icon icon="search" size="sm" color="secondary" />}- hasClear- size="lg"- isDisabled={isDisabled}- width="100%"- />- {visibleItems.length === 0 ? (- <EmptyState- icon={<Icon icon="search" size="lg" color="secondary" />}- title={- allowsCreate && query.trim() === ''- ? `Add ${label === 'ID' ? 'an ID' : 'a value'}`- : 'No results found'- }- description={- allowsCreate && query.trim() === ''- ? `Enter ${label === 'ID' ? 'an ID' : 'a value'} above, then select it to include it.`- : 'Try a different search.'- }- headingLevel={4}- isCompact- />- ) : (- <List density="spacious" edge="flush">- {visibleItems.map(item => {- const isCreate =- (item.auxiliaryData as {isCreate?: boolean} | undefined)- ?.isCreate === true;- const valueId = isCreate ? item.label : item.id;- const isSelected = selectedIds.has(valueId);- const visibleLabel = isCreate ? `Add ${item.label}` : item.label;- return (- <ListItem- key={item.id}- label={- renderItem != null && !isCreate ? (- renderItem(item)- ) : isSelected ? (- <>- <span aria-hidden="true">{visibleLabel}</span>- <VisuallyHidden>{`${visibleLabel}, selected`}</VisuallyHidden>- </>- ) : (- visibleLabel- )- }- aria-label={- renderItem != null- ? `${visibleLabel}${isSelected ? ', selected' : ''}`- : undefined- }- isDisabled={isDisabled}- endContent={- <CheckboxIndicator- state={isSelected ? 'checked' : 'unchecked'}- isDisabled={isDisabled}- />- }- onClick={() => {- if (isSelected) {- onChange(- selectedItems.filter(selected => selected.id !== valueId),- );- } else {- onChange([- ...selectedItems,- isCreate ? {id: item.label, label: item.label} : item,- ]);- }- }}- />- );- })}- </List>- )}- </div>- );-}--function relativeDateChoices(- operatorValue: OperatorValue & {type: 'date_relative'},-): ChoiceItem[] {- const result: ChoiceItem[] = [];- const units = [- {unit: 'day', plural: 'days', amounts: [1, 3, 7, 14, 30]},- {unit: 'week', plural: 'weeks', amounts: [1, 2, 4]},- {unit: 'month', plural: 'months', amounts: [1, 3, 6, 12]},- ];- for (const {unit, plural, amounts} of units) {- for (const amount of amounts) {- const noun = amount === 1 ? unit : plural;- if (operatorValue.isPastAllowed !== false) {- result.push({- value: `${amount}${unit[0]}_ago`,- label: `${amount} ${noun} ago`,- });- }- if (operatorValue.isFutureAllowed !== false) {- result.push({- value: `${amount}${unit[0]}_from_now`,- label: `${amount} ${noun} from now`,- });- }- }- }- return result;-}--// =============================================================================-// Dates-// =============================================================================--const SECONDS_BY_UNIT = {- second: 1,- minute: 60,- hour: 3600,- day: 86400,- week: 604800,- month: 2592000,- year: 31536000,-} as const;--function resolveRangePart(part: DateTimeRangePart, nowSeconds: number): number {- switch (part.type) {- case 'NOW':- return Math.floor(nowSeconds);- case 'ABSOLUTE':- return part.unixSeconds;- case 'RELATIVE':- return Math.floor(- nowSeconds - part.backValue * SECONDS_BY_UNIT[part.unit],- );- }-}--// =============================================================================-// Editor-// =============================================================================--/**- * Renders the value control for one filter inside the sheet editor.- */-export function MobilePowerSearchValueEditor({- operatorValue,- filterValue,- onChange,- label,- isDisabled = false,- maxMenuItems,- timezoneID,-}: MobilePowerSearchValueEditorProps) {- const selectedValues = useMemo<ReadonlySet<string>>(() => {- if (filterValue?.type === 'enum' || filterValue?.type === 'date_relative') {- return new Set([filterValue.value]);- }- if (filterValue?.type === 'enum_list') {- return new Set(filterValue.value);- }- return new Set();- }, [filterValue]);-- const handleNumberInput = useCallback(- (event: FormEvent<HTMLElement>) => {- // NumberInput commits on blur or Enter. Staging the raw text as it is- // typed lets the footer action enable while the user is still in the- // field; the committed value replaces it when the input blurs.- if (operatorValue.type !== 'integer' && operatorValue.type !== 'float') {- return;- }- const raw = (event.currentTarget as HTMLInputElement).value.trim();- if (raw === '') {- return;- }- const parsed = Number(raw.replace(/,/g, ''));- if (!Number.isFinite(parsed)) {- return;- }- if (operatorValue.type === 'integer') {- if (Number.isInteger(parsed)) {- onChange({type: 'integer', value: parsed});- }- return;- }- onChange({type: 'float', value: parsed});- },- [onChange, operatorValue.type],- );-- switch (operatorValue.type) {- case 'empty':- case 'nested':- return null;-- case 'string': {- const current = filterValue?.type === 'string' ? filterValue.value : '';- if (operatorValue.searchSource) {- return (- <div {...stylex.props(styles.input)}>- <Typeahead- label="Value"- isLabelHidden- size="lg"- searchSource={operatorValue.searchSource}- value={current ? {id: current, label: current} : null}- onChange={item =>- onChange({type: 'string', value: item?.label ?? ''})- }- placeholder="Search..."- debounceMs={150}- maxMenuItems={maxMenuItems}- isDisabled={isDisabled}- width="100%"- />- </div>- );- }- return (- <div {...stylex.props(styles.input)}>- <TextInput- label="Value"- isLabelHidden- size="lg"- value={current}- placeholder="Enter a value"- onChange={value => onChange({type: 'string', value})}- isDisabled={isDisabled}- width="100%"- />- </div>- );- }-- case 'string_list': {- const selectedItems: SearchableItem[] =- filterValue?.type === 'string_list'- ? filterValue.value.map(value => ({id: value, label: value}))- : [];- return (- <InlineListSearch- label={label ?? 'values'}- searchSource={operatorValue.searchSource ?? EMPTY_SOURCE}- selectedItems={selectedItems}- allowsCreate={- operatorValue.isArbitraryStringAllowed ||- !operatorValue.searchSource- }- isDisabled={isDisabled}- maxMenuItems={maxMenuItems}- onChange={items =>- onChange({- type: 'string_list',- value: items.map(item => item.label),- })- }- />- );- }-- case 'integer':- case 'float': {- const current =- filterValue?.type === operatorValue.type ? filterValue.value : null;- return (- <div {...stylex.props(styles.input)}>- <NumberInput- label="Value"- isLabelHidden- size="lg"- value={current}- onChange={value =>- onChange(- operatorValue.type === 'integer'- ? {type: 'integer', value}- : {type: 'float', value},- )- }- onInput={handleNumberInput}- min={operatorValue.minValue}- max={operatorValue.maxValue}- units={operatorValue.units}- isIntegerOnly={operatorValue.type === 'integer'}- placeholder="Enter a number"- isDisabled={isDisabled}- width="100%"- />- </div>- );- }-- case 'time': {- const current =- filterValue?.type === 'time'- ? (filterValue.value as ISOTimeString)- : undefined;- return (- <div {...stylex.props(styles.input)}>- <TimeInput- label="Time"- isLabelHidden- size="lg"- value={current}- onChange={value => {- if (value != null) {- onChange({type: 'time', value});- }- }}- min={operatorValue.minValue as ISOTimeString | undefined}- max={operatorValue.maxValue as ISOTimeString | undefined}- isDisabled={isDisabled}- width="100%"- />- </div>- );- }-- case 'date_absolute': {- const unixSeconds =- filterValue?.type === 'date_absolute'- ? filterValue.unixSeconds- : undefined;- if (operatorValue.isDateOnly === false) {- return (- <div {...stylex.props(styles.input)}>- <DateTimeInput- label="Date and time"- isLabelHidden- size="lg"- value={- unixSeconds == null- ? undefined- : unixSecondsToISODateTime(unixSeconds, timezoneID)- }- onChange={value => {- if (value != null) {- onChange({- type: 'date_absolute',- unixSeconds: isoDateTimeToUnixSeconds(value, timezoneID),- });- }- }}- isDisabled={isDisabled}- width="100%"- />- </div>- );- }- return (- <div {...stylex.props(styles.inlineCalendar)}>- <Calendar- mode="single"- value={- unixSeconds == null- ? null- : unixSecondsToISODate(unixSeconds, timezoneID)- }- onChange={value => {- if (!isDisabled) {- onChange({- type: 'date_absolute',- unixSeconds: isoDateToUnixSeconds(value, timezoneID),- });- }- }}- dateConstraints={isDisabled ? [() => false] : undefined}- />- </div>- );- }-- case 'date_relative':- return (- <ChoiceRows- items={relativeDateChoices(operatorValue)}- selected={selectedValues}- selectionMode="single"- isDisabled={isDisabled}- onToggle={value => onChange({type: 'date_relative', value})}- />- );-- case 'date_range': {- let current: DateRange | null = null;- if (filterValue?.type === 'date_range') {- const nowSeconds = Date.now() / 1000;- current = {- start: unixSecondsToISODate(- resolveRangePart(filterValue.value.start, nowSeconds),- timezoneID,- ),- end: unixSecondsToISODate(- resolveRangePart(filterValue.value.end, nowSeconds),- timezoneID,- ),- };- }- return (- <div {...stylex.props(styles.inlineCalendar)}>- <Calendar- mode="range"- value={current}- onChange={range => {- if (!isDisabled) {- onChange({- type: 'date_range',- value: {- start: {- type: 'ABSOLUTE',- unixSeconds: isoDateToUnixSeconds(- range.start as ISODateString,- timezoneID,- ),- },- end: {- type: 'ABSOLUTE',- unixSeconds: isoDateToUnixSeconds(- range.end as ISODateString,- timezoneID,- ),- },- },- });- }- }}- dateConstraints={isDisabled ? [() => false] : undefined}- />- </div>- );- }-- case 'enum':- return (- <ChoiceRows- items={operatorValue.values}- selected={selectedValues}- selectionMode="single"- isDisabled={isDisabled}- onToggle={value => onChange({type: 'enum', value})}- />- );-- case 'enum_list':- return (- <ChoiceRows- items={operatorValue.values}- selected={selectedValues}- selectionMode="multiple"- isDisabled={isDisabled}- onToggle={(value, isSelected) => {- const existing =- filterValue?.type === 'enum_list' ? filterValue.value : [];- onChange({- type: 'enum_list',- value: isSelected- ? existing.filter(v => v !== value)- : [...existing, value],- });- }}- />- );-- case 'entity_list': {- const selectedItems: SearchableItem[] =- filterValue?.type === 'entity_list'- ? filterValue.value.map((entity: PowerSearchEntity) => ({- id: entity.id,- label: entity.label,- auxiliaryData: entity.photo ? {photo: entity.photo} : undefined,- }))- : [];- return (- <InlineListSearch- label={label ?? 'entities'}- searchSource={operatorValue.searchSource ?? EMPTY_SOURCE}- selectedItems={selectedItems}- renderItem={operatorValue.renderItem}- isDisabled={isDisabled}- maxMenuItems={maxMenuItems}- onChange={items =>- onChange({- type: 'entity_list',- value: items.map(item => {- const auxiliaryData = item.auxiliaryData as- {photo?: string} | undefined;- return {- id: item.id,- label: item.label,- ...(auxiliaryData?.photo ? {photo: auxiliaryData.photo} : {}),- };- }),- })- }- />- );- }-- case 'custom': {- const EditorComponent = operatorValue.Editor;- return (- <div {...stylex.props(styles.input)}>- <EditorComponent- isDisabled={isDisabled}- onChange={value => {- if (value != null) {- onChange({type: 'custom', value});- }- }}- placeholder="Enter a value"- value={filterValue?.type === 'custom' ? filterValue.value : null}- />- </div>- );- }-- default:- return null;- }-}--MobilePowerSearchValueEditor.displayName = 'MobilePowerSearchValueEditor';diff --git a/packages/lab/src/MobilePowerSearch/index.ts b/packages/lab/src/MobilePowerSearch/index.tsdeleted file mode 100644index 3e95ffc1c9..0000000000--- a/packages/lab/src/MobilePowerSearch/index.ts+++ /dev/null@@ -1,13 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file index.ts- * @input MobilePowerSearch component- * @output Public MobilePowerSearch entry point for @astryxdesign/lab- * @position Component barrel; re-exported by /packages/lab/src/index.ts- */--export {MobilePowerSearch} from './MobilePowerSearch';-export type {MobilePowerSearchProps} from './MobilePowerSearch';diff --git a/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts b/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.tsdeleted file mode 100644index 474a8476e2..0000000000--- a/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts+++ /dev/null@@ -1,591 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file mobilePowerSearchUtils.ts- * @input Public @astryxdesign/core PowerSearch config/filter types, i18n- * translator, Typeahead SearchableItem, plain-date utilities- * @output Pure helpers for MobilePowerSearch: a local InternalConfig adapter- * (Core's useInternalConfig is private), the content-search suggestion- * source, filter identity tracking across controlled re-renders, nested- * operator exclusion, field matching, and timezone-aware date conversion- * @position Lab helper module; consumed by MobilePowerSearch.tsx and- * MobilePowerSearchValueEditor.tsx- */--import {useMemo} from 'react';-import type {- FilterValue,- PowerSearchConfig,- PowerSearchField,- PowerSearchFilter,- PowerSearchOperator,-} from '@astryxdesign/core/PowerSearch';-import {resolveOperatorLabel} from '@astryxdesign/core/PowerSearch';-import type {InternalConfig} from '@astryxdesign/core/PowerSearch/utils';-import type {TranslatorFn} from '@astryxdesign/core/i18n';-import type {SearchableItem} from '@astryxdesign/core/Typeahead';-import type {ISODateTimeString} from '@astryxdesign/core/DateTimeInput';-import type {ISODateString} from '@astryxdesign/core/utils';-import {- groupItems,- plainDateFromDate,- plainDateFromInstant,- plainDateFromISO,- plainDateToDate,- plainDateToInstant,- plainDateToISO,-} from '@astryxdesign/core/utils';--// =============================================================================-// Config adapter-// =============================================================================--/**- * Builds the `InternalConfig` shape that `formatFilterValue` and the rest of- * the public PowerSearch utilities take. Core's `useInternalConfig` is private- * to the package, so Lab carries this equivalent.- */-export function createMobilePowerSearchConfig(- config: PowerSearchConfig,-): InternalConfig {- const fieldMap = new Map<string, PowerSearchField>();- const operatorMap = new Map<string, Map<string, PowerSearchOperator>>();- for (const field of config.fields) {- fieldMap.set(field.key, field);- const opMap = new Map<string, PowerSearchOperator>();- for (const op of field.operators) {- opMap.set(op.key, op);- }- operatorMap.set(field.key, opMap);- }- return {- config,- getField(key) {- return fieldMap.get(key);- },- getOperator(fieldKey, operatorKey) {- return operatorMap.get(fieldKey)?.get(operatorKey);- },- getDefaultOperator(fieldKey) {- const field = fieldMap.get(fieldKey);- if (!field) {- return undefined;- }- if (field.defaultOperator) {- return operatorMap.get(fieldKey)?.get(field.defaultOperator);- }- return field.operators[0];- },- getVisibleFields() {- return config.fields;- },- getVisibleOperators(fieldKey) {- return fieldMap.get(fieldKey)?.operators ?? [];- },- };-}--export function useMobilePowerSearchConfig(- config: PowerSearchConfig,-): InternalConfig {- return useMemo(() => createMobilePowerSearchConfig(config), [config]);-}--// =============================================================================-// Operators and fields-// =============================================================================--/**- * Operators the sheet editor can render. Nested filter groups have no touch- * editor yet: offering the field and then showing a blank sheet is worse than- * leaving it out, so fields whose every operator is nested are dropped (with a- * development warning).- */-export function isSupportedOperator(operator: PowerSearchOperator): boolean {- return operator.value.type !== 'nested';-}--export function fieldMatchesQuery(- field: PowerSearchField,- normalizedQuery: string,-): boolean {- if (normalizedQuery === '') {- return true;- }- if (field.label.toLowerCase().includes(normalizedQuery)) {- return true;- }- return (- field.typeaheadAliases?.some(alias =>- alias.toLowerCase().includes(normalizedQuery),- ) ?? false- );-}--// =============================================================================-// Filter identity across controlled updates-// =============================================================================--function stableSerialize(value: unknown): string {- if (Array.isArray(value)) {- return `[${value.map(stableSerialize).join(',')}]`;- }- if (value != null && typeof value === 'object') {- return `{${Object.entries(value)- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))- .map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry)}`)- .join(',')}}`;- }- return JSON.stringify(value) ?? 'undefined';-}--/**- * Stable identities for the Filters rows and the trigger's tokens across- * controlled updates, so a row keeps its element — and its focus — when the- * parent reorders the filters or removes one above it. A filter object seen- * before keeps its id; a new object takes the id of a filter from the- * previous update with the same signature that no present object claims (a- * parent that clones its values on every change); anything else mints a new- * id. Two equal filters are told apart by order. Call `next` once per render- * with the current list.- */-export function createFilterIdentities(): {- next: (filters: ReadonlyArray<PowerSearchFilter>) => number[];-} {- const byObject = new WeakMap<PowerSearchFilter, number>();- let previousBySignature = new Map<string, number[]>();- let nextId = 0;- return {- next(filters) {- const used = new Set<number>();- const ids: (number | null)[] = filters.map(filter => {- const known = byObject.get(filter);- if (known == null || used.has(known)) {- return null;- }- used.add(known);- return known;- });- const bySignature = new Map<string, number[]>();- filters.forEach((filter, index) => {- const signature = filterSignature(filter);- let id = ids[index];- if (id == null) {- id =- previousBySignature- .get(signature)- ?.find(candidate => !used.has(candidate)) ?? nextId++;- used.add(id);- byObject.set(filter, id);- ids[index] = id;- }- bySignature.set(signature, [...(bySignature.get(signature) ?? []), id]);- });- previousBySignature = bySignature;- return ids as number[];- },- };-}--/**- * A `date_absolute` value as the Core PowerSearch token shows it- * (`component:PowerSearch` FR11, FR12): year, abbreviated month and day in- * the locale's Gregorian calendar, with no time of day, read in the- * browser's zone — the same text, so a Lab token or row and a Core token- * agree byte for byte. (The editors read the UTC day the value stores, as- * Core's do; Core's record carries the zone difference as a known gap.)- */-export function formatDateDay(unixSeconds: number, locale: string): string {- return new Intl.DateTimeFormat(locale, {- year: 'numeric',- month: 'short',- day: 'numeric',- calendar: 'gregory',- }).format(unixSeconds * 1000);-}--/** Structural snapshot of a filter, for parents that clone their values. */-export function filterSignature(filter: PowerSearchFilter): string {- return stableSerialize({- field: filter.field,- operator: filter.operator,- value: filter.value,- isReadOnly: filter.isReadOnly ?? false,- });-}--/**- * Finds the filter a draft was opened on after the controlled parent may have- * reordered, cloned, or removed it: object identity first, then the original- * slot when it still holds a structurally equal filter, then a unique- * structural match anywhere. Returns null when the target is gone or- * ambiguous, so an edit never lands on a different filter.- */-export function resolveFilterIdentityIndex(- filters: ReadonlyArray<PowerSearchFilter>,- sourceFilter: PowerSearchFilter,- sourceSignature: string,- preferredIndex: number,-): number | null {- const identityIndex = filters.indexOf(sourceFilter);- if (identityIndex >= 0) {- return identityIndex;- }- if (- filters[preferredIndex] != null &&- filterSignature(filters[preferredIndex]) === sourceSignature- ) {- return preferredIndex;- }- const matchingIndices = filters.flatMap((filter, index) =>- filterSignature(filter) === sourceSignature ? [index] : [],- );- return matchingIndices.length === 1 ? matchingIndices[0] : null;-}--/**- * After removing the filter at `removedIndex`, the editable row focus should- * land on: the nearest remaining editable filter, preferring the one after.- */-export function nearestEditableIndex(- nextFilters: ReadonlyArray<PowerSearchFilter>,- removedIndex: number,- isRowButton: (filter: PowerSearchFilter) => boolean = filter =>- !filter.isReadOnly,-): number | undefined {- const editableIndices = nextFilters.flatMap((candidate, candidateIndex) =>- isRowButton(candidate) ? [candidateIndex] : [],- );- return editableIndices.reduce<number | undefined>((nearest, candidate) => {- if (nearest == null) {- return candidate;- }- const candidateDistance = Math.abs(candidate - removedIndex);- const nearestDistance = Math.abs(nearest - removedIndex);- if (candidateDistance < nearestDistance) {- return candidate;- }- if (- candidateDistance === nearestDistance &&- candidate >= removedIndex &&- nearest < removedIndex- ) {- return candidate;- }- return nearest;- }, undefined);-}--// =============================================================================-// Content-search suggestions-// =============================================================================--export interface MobilePowerSearchAuxData {- readonly fieldKey: string;- readonly operatorKey?: string;- readonly filterValue?: FilterValue;- readonly group?: string;-}--export type MobilePowerSearchItem = SearchableItem<MobilePowerSearchAuxData>;--/** Synchronous suggestion source; the sheet renders results inline. */-export interface ContentSearchSource {- search(query: string): MobilePowerSearchItem[];- bootstrap(): MobilePowerSearchItem[];-}--interface ValueMatch {- displayValue: string;- filterValue: FilterValue;- quoted: boolean;-}--function resolveValueMatches(- op: PowerSearchOperator,- rawValue: string,-): ValueMatch[] {- const opType = op.value.type;- if (opType === 'string') {- return [- {- displayValue: rawValue,- filterValue: {type: 'string', value: rawValue},- quoted: true,- },- ];- }- if (opType === 'string_list') {- return [- {- displayValue: rawValue,- filterValue: {type: 'string_list', value: [rawValue]},- quoted: true,- },- ];- }- if (opType === 'enum') {- const lower = rawValue.toLowerCase();- return op.value.values- .filter(item => item.label.toLowerCase().includes(lower))- .map(item => ({- displayValue: item.label,- filterValue: {type: 'enum' as const, value: item.value},- quoted: false,- }));- }- if (opType === 'enum_list') {- const lower = rawValue.toLowerCase();- return op.value.values- .filter(item => item.label.toLowerCase().includes(lower))- .map(item => ({- displayValue: item.label,- filterValue: {type: 'enum_list' as const, value: [item.value]},- quoted: false,- }));- }- return [];-}--/**- * The suggestion source behind Add filter's content search: field names,- * field + operator combinations, field + operator + value matches for string- * and enum operators, and a leading free-text `"query"` item for the- * configured content-search field. Mirrors Core PowerSearch's typeahead- * suggestions, which are private to Core; nested-only fields are excluded.- */-export function createContentSearchSource(- config: InternalConfig,- t: TranslatorFn,- maxTypedResults: number,-): ContentSearchSource {- const fields = config- .getVisibleFields()- .filter(field => field.operators.some(isSupportedOperator));- const opLabel = (op: PowerSearchOperator): string =>- resolveOperatorLabel(op, t);- const allItems: MobilePowerSearchItem[] = groupItems(- fields.map(field => ({- id: field.key,- label: field.label,- auxiliaryData: {- fieldKey: field.key,- operatorKey: config.getDefaultOperator(field.key)?.key,- group: field.group,- },- })),- {ungroupedFirst: true},- ).flatMap(group => group.items);-- return {- search(query: string): MobilePowerSearchItem[] {- const lower = query.toLowerCase().trim();- if (lower === '') {- return allItems;- }- const results: MobilePowerSearchItem[] = [];- const seen = new Set<string>();-- for (const field of fields) {- if (- field.typeaheadMinQueryLength != null &&- lower.length < field.typeaheadMinQueryLength- ) {- continue;- }- if (fieldMatchesQuery(field, lower) && !seen.has(field.key)) {- seen.add(field.key);- results.push({- id: field.key,- label: field.label,- auxiliaryData: {- fieldKey: field.key,- operatorKey: config.getDefaultOperator(field.key)?.key,- },- });- }- for (const op of field.operators.filter(isSupportedOperator)) {- const combinedLabel = `${field.label} ${opLabel(op)}`;- if (combinedLabel.toLowerCase().includes(lower)) {- const id = `${field.key}:${op.key}`;- if (!seen.has(id)) {- seen.add(id);- results.push({- id,- label: combinedLabel,- auxiliaryData: {fieldKey: field.key, operatorKey: op.key},- });- }- }- }- }-- for (const field of fields) {- if (field.isValueMatchAllowed === false) {- continue;- }- const operators = field.operators.filter(isSupportedOperator);- const fieldLabel = field.label.toLowerCase();- const pushMatches = (op: PowerSearchOperator, rawValue: string) => {- const matches = resolveValueMatches(op, rawValue);- for (const match of matches) {- const id = `${field.key}:${op.key}:value:${match.displayValue}`;- if (!seen.has(id)) {- seen.add(id);- results.push({- id,- label: `${field.label} ${opLabel(op)} ${- match.quoted ? `"${match.displayValue}"` : match.displayValue- }`,- auxiliaryData: {- fieldKey: field.key,- operatorKey: op.key,- filterValue: match.filterValue,- },- });- }- }- return matches.length > 0;- };-- let hasExactOperatorMatch = false;- for (const op of operators) {- const prefix = `${fieldLabel} ${opLabel(op).toLowerCase()} `;- if (lower.startsWith(prefix) && lower.length > prefix.length) {- if (pushMatches(op, query.slice(prefix.length))) {- hasExactOperatorMatch = true;- }- }- }-- const fieldPrefix = `${fieldLabel} `;- if (- !hasExactOperatorMatch &&- lower.startsWith(fieldPrefix) &&- lower.length > fieldPrefix.length- ) {- const remainder = lower.slice(fieldPrefix.length);- const isOperatorPrefix = operators.some(op =>- opLabel(op).toLowerCase().startsWith(remainder),- );- if (!isOperatorPrefix) {- const rawValue = query.slice(fieldPrefix.length);- for (const op of operators) {- pushMatches(op, rawValue);- }- }- }- }-- const contentFieldKey = config.config.contentSearchFieldKey;- const hasExactMatch = fields.some(- field =>- field.label.toLowerCase() === lower ||- field.operators.some(- op => `${field.label} ${opLabel(op)}`.toLowerCase() === lower,- ),- );- if (contentFieldKey != null && !hasExactMatch) {- const contentOp = config.getDefaultOperator(contentFieldKey);- if (- config.getField(contentFieldKey) != null &&- contentOp?.value.type === 'string'- ) {- results.unshift({- id: `__content_search__:${query}`,- label: `"${query}"`,- auxiliaryData: {- fieldKey: contentFieldKey,- operatorKey: contentOp.key,- filterValue: {type: 'string', value: query},- },- });- }- }-- return results.slice(0, maxTypedResults);- },- bootstrap(): MobilePowerSearchItem[] {- return allItems;- },- };-}--// =============================================================================-// Dates-// =============================================================================--/**- * The calendar date an instant falls on in `timezoneID`, or in the viewer's- * zone when none is configured. The same zone drives `formatFilterValue`, so- * the editor and the token agree on a boundary date.- */-export function unixSecondsToISODate(- unixSeconds: number,- timezoneID: string | undefined,-): ISODateString {- const instant = unixSeconds * 1000;- const plain =- timezoneID != null- ? plainDateFromInstant(instant, timezoneID)- : plainDateFromDate(new Date(instant));- return plainDateToISO(plain);-}--/** Wall-clock `YYYY-MM-DDTHH:mm` of an instant in `timezoneID` or the viewer's zone. */-export function unixSecondsToISODateTime(- unixSeconds: number,- timezoneID: string | undefined,-): ISODateTimeString {- const date = new Date(unixSeconds * 1000);- const parts = new Intl.DateTimeFormat('en-US', {- ...(timezoneID != null ? {timeZone: timezoneID} : {}),- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit',- hourCycle: 'h23',- calendar: 'gregory',- }).formatToParts(date);- const lookup = Object.fromEntries(- parts.filter(part => part.type !== 'literal').map(p => [p.type, p.value]),- );- return `${lookup.year}-${lookup.month}-${lookup.day}T${lookup.hour}:${lookup.minute}` as ISODateTimeString;-}--/** The instant a wall-clock `YYYY-MM-DDTHH:mm` names in `timezoneID` or the viewer's zone. */-export function isoDateTimeToUnixSeconds(- value: ISODateTimeString,- timezoneID: string | undefined,-): number {- const [datePart, timePart = '00:00'] = value.split('T');- const [hour, minute] = timePart.split(':').map(Number);- const plain = plainDateFromISO(datePart as ISODateString);- const instant =- timezoneID != null- ? plainDateToInstant(plain, timezoneID, hour, minute)- : new Date(- plain.year,- plain.month - 1,- plain.day,- hour,- minute,- ).getTime();- return Math.floor(instant / 1000);-}--/** Midnight at the start of `date` in `timezoneID` (or the viewer's zone). */-export function isoDateToUnixSeconds(- date: ISODateString,- timezoneID: string | undefined,-): number {- const plain = plainDateFromISO(date);- const instant =- timezoneID != null- ? plainDateToInstant(plain, timezoneID)- : plainDateToDate(plain).getTime();- return Math.floor(instant / 1000);-}diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjsdeleted file mode 100644index 27a086b612..0000000000--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs+++ /dev/null@@ -1,37 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */-export const docs = {- name: 'MobileTokenizer',- displayName: 'Mobile Tokenizer',- group: 'MobileTokenizer',- category: 'Form Controls',- keywords: ['tokenizer', 'mobile', 'touch', 'bottom sheet', 'tags', 'chips'],- props: [- {name: 'label', type: 'string', description: 'Field label and sheet heading.', required: true},- {name: 'isLabelHidden', type: 'boolean', description: 'Hide the visible label; the trigger and the sheet keep it as their accessible name.', default: 'false'},- {name: 'searchSource', type: 'SearchSource<T>', description: 'Core Typeahead search source (search + bootstrap).', required: true},- {name: 'value', type: 'T[]', description: 'Selected items (Core SearchableItem).', required: true},- {name: 'onChange', type: '(items: T[], change: MobileTokenizerChange<T>) => void', description: 'Called by Save when the selection draft differs from the opening value. Receives the complete committed selection plus the latest add/create/remove metadata.', required: true},- {name: 'renderItem', type: '(item: T) => ReactNode', description: 'Custom content for a result row, shown beside its checkbox. Default: the item label.'},- {name: 'placeholder', type: 'string', description: 'Trigger text when nothing is selected.'},- {name: 'description', type: 'string', description: 'Help text under the field, read with the trigger.'},- {name: 'status', type: "{type: 'error' | 'warning' | 'success'; message: string}", description: 'Status shown under the field and read with the trigger.'},- {name: 'disabledMessage', type: 'string', description: 'Why the field is disabled: the disabled trigger exposes it as its description and tooltip.'},- {name: 'htmlName', type: 'string', description: 'Form field name: one hidden input per selected item while the field is enabled.'},- {name: 'hasCreate', type: 'boolean', description: 'Offer Create "<query>" for unmatched free text.', default: 'false'},- {name: 'maxEntries', type: 'number', description: 'Cap selections; add rows disable at the cap.'},- {name: 'maxMenuItems', type: 'number', description: 'Maximum source results retained, for a search and for the empty-query bootstrap list alike; long lists render progressively in 50-item batches.', default: '10'},- ],- usage: {- description:- 'Lab prototype for trying the touch Tokenizer flow: tap the field to open one searchable sheet where selected and available items share a full-row checkbox list. Selection changes remain in a draft until Save commits them; swipe, scrim, or Escape dismissal asks before discarding a dirty draft, while a clean dismissal closes directly. Selected items are grouped first when the sheet opens, while checkbox changes keep every existing row in place until the sheet closes; the latest selection is regrouped the next time it opens. Selected custom values stay in the list, and long result sets render progressively in 50-item batches. Custom text uses a trailing Add action. The bordered large search stays above the list, and scrolling or dragging results dismisses the software keyboard without clearing the query. Clear all and Save remain visible while searching. Clear all updates the draft only and requires confirmation; a confirmed clear returns focus to the search field and is announced inside the sheet. Every announcement — additions, removals, result counts — is delivered inside the open sheet. The trigger describes its committed selection to assistive technology (count, then the tokens) after the field description, status, and disabled reason. Strings come from the shared Astryx catalog.',- bestPractices: [- {guidance: true, description: 'Try this in Lab/canary to validate the flow; graduate via Core Tokenizer presentation="adaptive" when it ships.'},- {guidance: false, description: 'Do not ship stable product on this Lab API; it has no theming or spec contract yet.'},- ],- anatomy: [- {name: 'Trigger field', required: true, description: 'Button showing tokens as a summary, in the inline Tokenizer field\'s own box: same border, radius, surface, block size and token inset as the desktop field.'},- {name: 'Management sheet', required: true, description: 'One searchable list with trailing checkboxes for existing items, a trailing Add action for custom text, and persistent equal-width Clear all and Save footer actions. Save commits the draft; dirty dismissal asks before discarding. Nothing of the sheet is in the page while it is closed.'},- ],- },-};diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsxdeleted file mode 100644index 3df60093e4..0000000000--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx+++ /dev/null@@ -1,1346 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file MobileTokenizer.test.tsx- * @input Uses vitest, @testing-library/react, MobileTokenizer- * @output Lab tests for the single-sheet touch flow- * @position Lab tests; validates MobileTokenizer.tsx- */-import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';-import {- act,- render,- screen,- fireEvent,- waitFor,- within,-} from '@testing-library/react';-import userEvent from '@testing-library/user-event';-import {useState} from 'react';-import * as stylex from '@stylexjs/stylex';-import {- colorVars,- sizeVars,- spacingVars,-} from '@astryxdesign/core/theme/tokens.stylex';-import {inputWrapperStyles} from '@astryxdesign/core/Field';-import {MobileTokenizer, type MobileTokenizerChange} from './MobileTokenizer';-import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';--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,-};--function Harness({- spy,-}: {- spy?: (- items: SearchableItem[],- change: MobileTokenizerChange<SearchableItem>,- ) => void;-}) {- const [value, setValue] = useState<SearchableItem[]>([ITEMS[0], ITEMS[1]]);- return (- <MobileTokenizer- label="Tags"- searchSource={source}- value={value}- debounceMs={0}- placeholder="Add tags"- onChange={(items, change) => {- setValue(items);- spy?.(items, change);- }}- />- );-}--function CreateHarness({- spy,-}: {- spy: (- items: SearchableItem[],- change: MobileTokenizerChange<SearchableItem>,- ) => void;-}) {- const [value, setValue] = useState<SearchableItem[]>([]);- return (- <MobileTokenizer- label="Tags"- searchSource={source}- value={value}- hasCreate- debounceMs={0}- onChange={(items, change) => {- setValue(items);- spy(items, change);- }}- />- );-}--beforeEach(() => {- 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();- }- vi.stubGlobal(- 'matchMedia',- vi.fn().mockReturnValue({- matches: false,- media: '',- onchange: null,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- addListener: vi.fn(),- removeListener: vi.fn(),- dispatchEvent: vi.fn(),- }),- );- window.scrollTo = vi.fn();- vi.stubGlobal(- 'requestAnimationFrame',- // Next microtask, not synchronously: a real frame never runs before- // requestAnimationFrame returns, and callers may rely on its id.- vi.fn((cb: FrameRequestCallback) => {- queueMicrotask(() => cb(0));- return 1;- }),- );-});-afterEach(() => vi.unstubAllGlobals());--describe('MobileTokenizer (Lab, single-sheet flow)', () => {- it('keeps the bordered large search and footer actions visible while searching, and dismisses the keyboard without clearing the query when results move', async () => {- render(<Harness />);- fireEvent.click(screen.getByRole('button', {name: /Tags/}));- const search = await screen.findByLabelText('Search Tags');- const list = await screen.findByTestId('mobile-tokenizer-list');- await screen.findByRole('checkbox', {name: 'Energizer'});-- expect(search.closest('.astryx-text-input')).toBeInTheDocument();- act(() => search.focus());- fireEvent.change(search, {target: {value: 'En'}});- await screen.findByRole('checkbox', {name: 'Eng'});- expect(screen.getByRole('button', {name: 'Clear all'})).toBeVisible();- expect(screen.getByRole('button', {name: 'Save'})).toBeVisible();-- fireEvent.scroll(list);- expect(search).toHaveFocus();- expect(search).toHaveValue('En');-- // Filtering a scrolled list can produce its own scroll event as the- // browser clamps scrollTop; typing must continue to own focus.- fireEvent.change(search, {target: {value: 'Eng'}});- fireEvent.scroll(list);- expect(search).toHaveFocus();- fireEvent.change(search, {target: {value: 'Engi'}});- expect(search).toHaveValue('Engi');- expect(search).toHaveFocus();-- fireEvent.touchStart(list, {- touches: [{identifier: 1, target: list, clientY: 120}],- });- fireEvent.touchMove(list, {- touches: [{identifier: 1, target: list, clientY: 115}],- });- expect(search).toHaveFocus();- fireEvent.touchMove(list, {- touches: [{identifier: 1, target: list, clientY: 100}],- });- expect(search).not.toHaveFocus();- expect(search).toHaveValue('Engi');- });-- it('guards dirty Escape, scrim, and swipe dismissal; keeps the draft after confirmation scrim or Keep editing; and discards only on request', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);- const sheet = await screen.findByRole('dialog', {name: 'Tags'});- const energizer = await screen.findByRole('checkbox', {name: 'Energizer'});- fireEvent.click(energizer);- expect(energizer).toBeChecked();- expect(spy).not.toHaveBeenCalled();-- fireEvent.keyDown(sheet, {key: 'Escape'});- let discard = await screen.findByRole('alertdialog', {- name: 'Discard changes?',- });- // A scrim press starts and ends on the dialog itself.- fireEvent.pointerDown(discard);- fireEvent.pointerUp(discard);- fireEvent.click(discard);- await waitFor(() =>- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),- );- expect(energizer).toBeChecked();- expect(screen.getByLabelText('Search Tags')).toHaveFocus();- expect(trigger).toHaveAttribute('aria-expanded', 'true');-- fireEvent.click(sheet);- discard = await screen.findByRole('alertdialog', {- name: 'Discard changes?',- });- fireEvent.click(- within(discard).getByRole('button', {name: 'Keep editing'}),- );- await waitFor(() =>- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),- );- expect(energizer).toBeChecked();- expect(screen.getByLabelText('Search Tags')).toHaveFocus();-- const handle = sheet.querySelector<HTMLElement>(- '.astryx-bottom-sheet > div[aria-hidden="true"]',- )!;- fireEvent.pointerDown(handle, {- pointerId: 1,- clientY: 0,- button: 0,- isPrimary: true,- pointerType: 'touch',- });- fireEvent.pointerMove(handle, {- pointerId: 1,- clientY: 40,- pointerType: 'touch',- });- fireEvent.pointerMove(handle, {- pointerId: 1,- clientY: 120,- pointerType: 'touch',- });- fireEvent.pointerUp(handle, {- pointerId: 1,- clientY: 120,- pointerType: 'touch',- });- discard = await screen.findByRole('alertdialog', {- name: 'Discard changes?',- });- const actions = within(discard).getAllByRole('button');- expect(actions.map(action => action.textContent)).toEqual([- 'Discard changes',- 'Keep editing',- ]);- expect(actions[0]).toHaveAttribute('data-variant', 'destructive');- expect(actions[1]).toHaveAttribute('data-variant', 'secondary');- fireEvent.click(actions[0]);- expect(trigger).toHaveAttribute('aria-expanded', 'false');- expect(spy).not.toHaveBeenCalled();- });-- it('forced disabled closure also closes a dirty-discard confirmation', async () => {- const spy = vi.fn();- const props = {- label: 'Tags',- searchSource: source,- value: [ITEMS[0]],- debounceMs: 0,- onChange: spy,- };- const {rerender} = render(<MobileTokenizer {...props} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);- const sheet = await screen.findByRole('dialog', {name: 'Tags'});- fireEvent.click(await screen.findByRole('checkbox', {name: 'Energizer'}));- fireEvent.keyDown(sheet, {key: 'Escape'});- expect(- await screen.findByRole('alertdialog', {name: 'Discard changes?'}),- ).toBeInTheDocument();-- rerender(<MobileTokenizer {...props} isDisabled />);- expect(trigger).toHaveAttribute('aria-expanded', 'false');- await waitFor(() =>- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),- );- expect(spy).not.toHaveBeenCalled();- });-- it('blocks Save if maxEntries drops below the current draft until the draft returns within the limit', async () => {- const spy = vi.fn();- const props = {- label: 'Tags',- searchSource: source,- value: [] as SearchableItem[],- debounceMs: 0,- onChange: spy,- };- const {rerender} = render(<MobileTokenizer {...props} maxEntries={2} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);- const design = await screen.findByRole('checkbox', {name: 'Design'});- const eng = await screen.findByRole('checkbox', {name: 'Eng'});- fireEvent.click(design);- fireEvent.click(eng);-- rerender(<MobileTokenizer {...props} maxEntries={1} />);- const save = screen.getByRole('button', {name: 'Save'});- expect(save).toHaveAttribute('aria-disabled', 'true');- expect(save).toHaveAccessibleDescription('Select up to 1 item');- fireEvent.click(save);- expect(trigger).toHaveAttribute('aria-expanded', 'true');- expect(spy).not.toHaveBeenCalled();-- fireEvent.click(eng);- expect(save).not.toHaveAttribute('aria-disabled');- fireEvent.click(save);- expect(spy).toHaveBeenCalledWith(- [ITEMS[0]],- expect.objectContaining({item: ITEMS[0], type: 'add'}),- );- });-- it('closes directly when edits return the draft to its opening selection', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);- const sheet = await screen.findByRole('dialog', {name: 'Tags'});- const energizer = await screen.findByRole('checkbox', {name: 'Energizer'});- fireEvent.click(energizer);- fireEvent.click(energizer);-- fireEvent.keyDown(sheet, {key: 'Escape'});- expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();- expect(trigger).toHaveAttribute('aria-expanded', 'false');- expect(spy).not.toHaveBeenCalled();- });-- it('keeps rows stable while open and applies selected-first order on reopen', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);-- const list = await screen.findByTestId('mobile-tokenizer-list');- 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',- ]);- const search = screen.getByLabelText('Search Tags');- expect(- search.closest('.astryx-text-input')?.querySelector('.astryx-icon'),- ).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).not.toHaveBeenCalled();- 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).not.toHaveBeenCalled();- expect(checkboxLabels()).toEqual([- 'Design',- 'Eng',- 'Engineer',- 'Energizer',- ]);-- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- expect(spy).toHaveBeenCalledWith(- [ITEMS[0], ITEMS[3]],- expect.objectContaining({item: ITEMS[1], type: 'remove'}),- );- expect(trigger).toHaveAttribute('aria-expanded', 'false');-- await act(async () => {- fireEvent.click(trigger);- });- expect(checkboxLabels()).toEqual([- 'Design',- 'Energizer',- 'Eng',- 'Engineer',- ]);- });-- it('reports the net changed item when draft actions cancel each other', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- const trigger = screen.getByRole('button', {name: /Tags/});- fireEvent.click(trigger);- await screen.findByRole('checkbox', {name: 'Energizer'});-- fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));- fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));- fireEvent.click(screen.getByRole('button', {name: 'Save'}));-- expect(spy).toHaveBeenCalledTimes(1);- expect(spy).toHaveBeenCalledWith([ITEMS[1]], {- item: ITEMS[0],- type: 'remove',- });- });-- it('does not commit a selection toggled back to its opening value', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- fireEvent.click(screen.getByRole('button', {name: /Tags/}));- await screen.findByRole('checkbox', {name: 'Design'});-- fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- fireEvent.click(screen.getByRole('button', {name: 'Save'}));-- expect(spy).not.toHaveBeenCalled();- });-- it('creates a custom entry with a trailing Add action', async () => {- const spy = vi.fn();- render(<CreateHarness spy={spy} />);- const trigger = screen.getByRole('button', {name: /Tags/});- 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.getByRole('button', {name: 'Clear all'})).toBeInTheDocument();- expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();- expect(create).toHaveAttribute('data-size', 'lg');- expect(screen.getByTestId('mobile-tokenizer-create-row')).toHaveTextContent(- 'Create "Custom"',- );- await act(async () => {- fireEvent.click(create);- });- expect(spy).not.toHaveBeenCalled();- expect(trigger).not.toHaveTextContent('Custom');- expect(search).toHaveValue('');- const custom = await screen.findByRole('checkbox', {name: 'Custom'});- expect(custom).toBeChecked();-- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- expect(spy).toHaveBeenCalledWith(- [{id: 'Custom', label: 'Custom'}],- expect.objectContaining({type: 'create'}),- );- await waitFor(() => expect(trigger).toHaveTextContent('Custom'));- });-- it('renders long lists in 50-item batches and resets the window for search', 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(- <MobileTokenizer- label="Items"- searchSource={longSource}- value={[]}- onChange={() => {}}- maxMenuItems={120}- debounceMs={0}- />,- );- fireEvent.click(screen.getByRole('button', {name: 'Items'}));- const list = await screen.findByTestId('mobile-tokenizer-list');- await waitFor(() => {- expect(list).toHaveAttribute('data-rendered-count', '50');- expect(list).toHaveAttribute('data-total-count', '120');- });- expect(screen.getAllByRole('checkbox')).toHaveLength(50);- expect(- screen.queryByRole('checkbox', {name: 'Item 051'}),- ).not.toBeInTheDocument();-- Object.defineProperties(list, {- clientHeight: {configurable: true, value: 600},- scrollHeight: {configurable: true, value: 2400},- scrollTop: {configurable: true, value: 1700, writable: true},- });- fireEvent.scroll(list);- expect(list).toHaveAttribute('data-rendered-count', '100');- expect(screen.getAllByRole('checkbox')).toHaveLength(100);- expect(- screen.getByRole('checkbox', {name: 'Item 100'}),- ).toBeInTheDocument();-- Object.defineProperties(list, {- scrollHeight: {configurable: true, value: 4400},- scrollTop: {- configurable: true,- value: 3600,- writable: true,- },- });- fireEvent.scroll(list);- expect(list).toHaveAttribute('data-rendered-count', '120');- expect(screen.getAllByRole('checkbox')).toHaveLength(120);-- fireEvent.change(screen.getByLabelText('Search Items'), {- target: {value: 'Item'},- });- await waitFor(() =>- expect(list).toHaveAttribute('data-rendered-count', '50'),- );- expect(screen.getAllByRole('checkbox')).toHaveLength(50);-- fireEvent.scroll(list);- expect(list).toHaveAttribute('data-rendered-count', '100');- expect(screen.getAllByRole('checkbox')).toHaveLength(100);- });-- it('searches within the same sheet and centers the no-results state', async () => {- render(<Harness />);- fireEvent.click(screen.getByRole('button', {name: /Tags/}));- const search = await screen.findByLabelText('Search Tags');- fireEvent.change(search, {target: {value: 'zzz'}});-- const title = await screen.findByRole('heading', {- name: 'No results found',- });- const emptyState = title.closest('.astryx-empty-state');- expect(emptyState).toHaveTextContent('Try a different search.');- expect(emptyState?.querySelector('.astryx-icon')).toHaveAttribute(- 'data-size',- 'lg',- );- });-- it('keeps large equal-width Clear all and Save footer actions while guarding the bulk clear', async () => {- const spy = vi.fn();- render(<Harness spy={spy} />);- fireEvent.click(screen.getByRole('button', {name: /Tags/}));- const list = await screen.findByTestId('mobile-tokenizer-list');-- const clearAll = screen.getByRole('button', {name: 'Clear all'});- const save = screen.getByRole('button', {name: 'Save'});- expect(clearAll).toHaveAttribute('data-size', 'lg');- expect(clearAll).toHaveAttribute('data-variant', 'secondary');- expect(save).toHaveAttribute('data-size', 'lg');- expect(list.compareDocumentPosition(clearAll)).toBe(- Node.DOCUMENT_POSITION_FOLLOWING,- );- expect(list.compareDocumentPosition(save)).toBe(- Node.DOCUMENT_POSITION_FOLLOWING,- );- fireEvent.click(clearAll);- const confirmation = screen.getByRole('alertdialog');- expect(confirmation).toHaveClass('astryx-alert-dialog');- expect(confirmation).toHaveTextContent('Clear all selected items?');- const confirmationActions = within(confirmation).getAllByRole('button');- expect(confirmationActions.map(action => action.textContent)).toEqual([- 'Clear selection',- 'Cancel',- ]);- expect(confirmationActions[0]).toHaveAttribute(- 'data-variant',- 'destructive',- );- expect(confirmationActions[1]).toHaveAttribute('data-variant', 'secondary');- expect(spy).not.toHaveBeenCalled();- fireEvent.click(- within(confirmation).getByRole('button', {name: 'Clear selection'}),- );- expect(spy).not.toHaveBeenCalled();- await waitFor(() =>- expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute(- 'aria-disabled',- 'true',- ),- );- fireEvent.click(save);- expect(spy).toHaveBeenLastCalledWith(- [],- expect.objectContaining({type: 'remove'}),- );- });-- it('hides the visible label on request while the trigger and the sheet keep it as their name, and renders rows through renderItem', async () => {- render(- <MobileTokenizer- label="Tags"- isLabelHidden- searchSource={source}- value={[]}- debounceMs={0}- onChange={() => {}}- renderItem={item => <em data-testid="custom-row">{item.label}!</em>}- />,- );- const trigger = screen.getByRole('button', {name: 'Tags'});- // The Field's label is clipped out of the layout (sr-only), as Core- // Tokenizer's is, while the trigger keeps it as its name.- const label = screen.getByText('Tags', {selector: 'label'});- expect(getComputedStyle(label).position).toBe('absolute');- expect(getComputedStyle(label).clip).toMatch(- /^rect\(0(px)?, 0(px)?, 0(px)?, 0(px)?\)$/,- );- expect(trigger).toHaveAccessibleName('Tags');- fireEvent.click(trigger);- expect(await screen.findByRole('dialog')).toHaveAccessibleName('Tags');- const row = await screen.findByRole('checkbox', {name: 'Design'});- expect(within(row).getByTestId('custom-row')).toHaveTextContent('Design!');- });-- it('keeps a disabled trigger focusable without opening the sheet (AST-085 FR1, FR2)', () => {- render(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[ITEMS[0]]}- onChange={() => {}}- isDisabled- />,- );- const trigger = screen.getByRole('button', {name: /Tags/});- 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.queryByTestId('mobile-tokenizer-list'),- ).not.toBeInTheDocument();- });-- it('keeps an unselectable row at the limit focusable but inert (AST-085 FR1, FR2)', async () => {- const spy = vi.fn();- render(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[ITEMS[0]]}- maxEntries={1}- debounceMs={0}- onChange={spy}- />,- );- fireEvent.click(screen.getByRole('button', {name: /Tags/}));- 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({- indicator: {- borderColor: {- default: colorVars['--color-border'],- '@media (forced-colors: active)': 'GrayText',- },- },- }).indicator,- )- .className!.split(' ')- .filter(name => !name.includes('__'));- const indicator = row.querySelector('.astryx-checkbox-indicator')!;- for (const name of indicatorClasses) {- expect(indicator).toHaveClass(name);- }-- fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- expect(row).not.toHaveAttribute('aria-disabled');- fireEvent.click(row);- expect(row).toBeChecked();- expect(spy).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- expect(spy).toHaveBeenCalledWith(- [ITEMS[3]],- expect.objectContaining({item: ITEMS[3], type: 'add'}),- );- });-- it('paints the placeholder of a disabled empty trigger GrayText in forced colors (AST-085 FR6)', () => {- const placeholderClasses = stylex- .props(- stylex.create({- placeholder: {- color: {- default: colorVars['--color-text-secondary'],- '@media (forced-colors: active)': 'GrayText',- },- },- }).placeholder,- )- .className!.split(' ')- .filter(name => !name.includes('__'));- render(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[]}- onChange={() => {}}- placeholder="Add tags"- isDisabled- />,- );- const placeholder = screen.getByText('Add tags');- for (const name of placeholderClasses) {- expect(placeholder).toHaveClass(name);- }- });-- it('paints a disabled trigger and its tokens GrayText in forced colors (AST-085 FR6)', () => {- // The same declarations as the component's styles compile to the same- // atomic classes; without them the tokens keep their CanvasText label.- 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',- },- },- });- render(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- isDisabled- />,- );- const trigger = screen.getByRole('button', {name: /Tags/});- 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);- }- }- });-});--/**- * Behaviors at parity with Core's sheet presentation (`component:Tokenizer`- * DEC-3, FR16–FR24, AR6), ported into the Lab prototype.- */-describe('MobileTokenizer Core-sheet parity', () => {- // The live region the hook writes inside an open modal (AST-086 FR14);- // created by the first announcement, so absent means nothing was said.- const liveText = (root: HTMLElement) =>- root.querySelector('[data-astryx-modal-live-region]')?.textContent ?? '';- // jsdom has no showModal(), so an open dialog never matches `:modal`;- // stand in for the sheet the browser presents modally.- let matchesSpy: ReturnType<typeof vi.spyOn> | null = null;- const presentModally = () => {- const matches = Element.prototype.matches;- matchesSpy = vi- .spyOn(Element.prototype, 'matches')- .mockImplementation(function (this: Element, selector: string) {- return selector === ':modal'- ? this instanceof HTMLDialogElement && this.open- : matches.call(this, selector);- });- };- beforeEach(async () => {- // The page's live regions outlive a test's tree, and a previous test's- // announcement may still be a frame away; let it land, then start with- // nothing said on the page.- await new Promise(resolve => setTimeout(resolve, 0));- for (const region of document.querySelectorAll(- 'body > [data-astryx-live-region]',- )) {- region.textContent = '';- }- });- afterEach(() => {- matchesSpy?.mockRestore();- matchesSpy = null;- });- const openSheet = async (name = /Tags/) => {- fireEvent.click(screen.getByRole('button', {name}));- const sheet = await screen.findByRole('dialog');- return sheet;- };-- it('mounts the sheet only from the press until its exit completes, and keeps nothing of it at rest (INV7)', async () => {- presentModally();- render(<Harness />);- expect(screen.queryByRole('dialog')).toBeNull();- expect(screen.queryByLabelText('Search Tags')).toBeNull();- const sheet = await openSheet();- expect(sheet).toHaveAttribute('open');- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- // Closed but retained for its exit; the trigger's focus (BottomSheet's- // hand-back after the exit) releases it.- const trigger = screen.getByRole('button', {name: /Tags/});- expect(trigger).toHaveAttribute('aria-expanded', 'false');- act(() => trigger.focus());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- });-- it('caps the empty-query bootstrap set at maxMenuItems, and an empty bootstrap shows only the search field (FR20)', async () => {- presentModally();- const many: SearchableItem[] = Array.from({length: 30}, (_, i) => ({- id: `i${i}`,- label: `Item ${i + 1}`,- }));- const bigSource: SearchSource<SearchableItem> = {- search: () => many,- bootstrap: () => many,- };- const {unmount} = render(- <MobileTokenizer- label="Items"- searchSource={bigSource}- value={[]}- onChange={() => {}}- debounceMs={0}- maxMenuItems={7}- />,- );- await openSheet(/Items/);- await waitFor(() =>- expect(screen.getAllByRole('checkbox')).toHaveLength(7),- );- unmount();-- const emptySource: SearchSource<SearchableItem> = {- search: () => [],- bootstrap: () => [],- };- render(- <MobileTokenizer- label="Blank"- searchSource={emptySource}- value={[]}- onChange={() => {}}- debounceMs={0}- />,- );- const sheet = await openSheet(/Blank/);- await waitFor(() =>- expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull(),- );- expect(screen.getByLabelText('Search Blank')).toBeInTheDocument();- expect(screen.queryByTestId('mobile-tokenizer-list')).toBeNull();- expect(screen.queryByRole('checkbox')).toBeNull();- expect(screen.queryByText('No items available')).toBeNull();- expect(screen.queryByText('No results found')).toBeNull();- expect(liveText(sheet)).toBe('');- });-- it("describes the trigger in the inline input's order — caller ids, description, status, disabled reason, count, then the tokens by id — with no label repeated (AR6, AST-085 FR5)", async () => {- render(- <>- <p id="hint">Pick a few</p>- <MobileTokenizer- label="Tags"- aria-describedby="hint"- description="Up to three"- status={{type: 'error', message: 'Pick at least one'}}- isDisabled- disabledMessage="Locked by the owner"- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- />- </>,- );- const trigger = screen.getByRole('button', {name: 'Tags'});- const ids = trigger.getAttribute('aria-describedby')!.split(' ');- const texts = ids.map(id => document.getElementById(id)!.textContent);- expect(texts).toEqual([- 'Pick a few',- 'Up to three',- 'Pick at least one',- 'Locked by the owner',- '2 selected',- 'Design',- 'Eng',- ]);- expect(trigger).toHaveAccessibleDescription(- 'Pick a few Up to three Pick at least one Locked by the owner 2 selected Design Eng',- );- expect(trigger).toHaveAttribute('aria-disabled', 'true');- // The reason is a tooltip, not a native title: it is the element the- // description names, and it opens on focus, so keyboard and touch users- // get it too.- expect(trigger).not.toHaveAttribute('title');- const tooltip = screen.getByRole('tooltip', {hidden: true});- expect(tooltip).toHaveTextContent('Locked by the owner');- expect(ids).toContain(tooltip.id);- // jsdom has no Popover API; the shared setup stubs showPopover, so the- // open is observed as the call on the tooltip's element.- const shown = vi.spyOn(HTMLElement.prototype, 'showPopover');- try {- // Keyboard focus: the tooltip opens for `:focus-visible` focus only.- await userEvent.setup().tab();- expect(trigger).toHaveFocus();- await waitFor(() => {- expect(shown.mock.instances).toContain(tooltip);- });- } finally {- shown.mockRestore();- }- });-- it("draws the closed trigger as the inline Tokenizer field's box: the shared input wrapper (1px emphasized border, element radius, surface), the md block size, the 3px token-row inset and gap — no 44px touch height (FR16)", () => {- const atoms = (className: string | undefined) =>- (className ?? '')- .split(' ')- .filter(name => name !== '' && !name.includes('__'));- const inset = `calc(${spacingVars['--spacing-1']} - 1px)`;- const own = stylex.create({- box: {- minHeight: sizeVars['--size-element-md'],- paddingBlock: inset,- paddingInline: inset,- gap: spacingVars['--spacing-1'],- rowGap: inset,- flexWrap: 'wrap',- },- touch: {minHeight: 44},- });- render(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- />,- );- const trigger = screen.getByRole('button', {name: 'Tags'});- // The very classes Core's inline field and sheet trigger compose: the- // shared box with the field's own wrap, inset and size on top (later- // wins per property, as in the component).- for (const name of atoms(- stylex.props(inputWrapperStyles.base, own.box).className,- )) {- expect(trigger).toHaveClass(name);- }- for (const name of atoms(stylex.props(own.touch).className)) {- expect(trigger).not.toHaveClass(name);- }- });-- it('paints the trigger on the input surface, so a status band behind it does not show through the tokens', () => {- const atoms = (style: stylex.StyleXStyles) =>- stylex- .props(style)- .className!.split(' ')- .filter(name => !name.includes('__'));- const surface = stylex.create({- trigger: {backgroundColor: colorVars['--color-background-surface']},- });- render(- <MobileTokenizer- label="Tags"- status={{type: 'error', message: 'Pick at least one'}}- searchSource={source}- value={[ITEMS[0]]}- onChange={() => {}}- />,- );- const trigger = screen.getByRole('button', {name: 'Tags'});- for (const name of atoms(surface.trigger)) {- expect(trigger).toHaveClass(name);- }- expect(screen.getByText('Pick at least one')).toBeInTheDocument();- });-- it("composes the trigger's own handlers and attributes with the caller's: onClick after the open, onFocus for focus from outside only, aria-label winning, aria-describedby merged, className and style on the trigger", async () => {- presentModally();- const onClick = vi.fn();- const onFocus = vi.fn();- const onBlur = vi.fn();- render(- <>- <p id="hint">Pick a few</p>- <button type="button">Elsewhere</button>- <MobileTokenizer- label="Tags"- aria-label="Project tags"- aria-describedby="hint"- className="caller-class"- style={{marginBlockStart: 3}}- onClick={onClick}- onFocus={onFocus}- onBlur={onBlur}- searchSource={source}- value={[ITEMS[0]]}- onChange={() => {}}- debounceMs={0}- />- </>,- );- // The caller's name wins; the description still starts with its ids.- const trigger = screen.getByRole('button', {name: 'Project tags'});- expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');- expect(trigger.getAttribute('aria-describedby')!.split(' ')[0]).toBe(- 'hint',- );- expect(trigger).toHaveAccessibleDescription(- /^Pick a few 1 selected Design/,- );- expect(trigger).toHaveClass('caller-class');- expect(trigger.style.marginBlockStart).toBe('3px');- // Focus from outside reports; the field's own label and tokens too.- act(() => trigger.focus());- expect(onFocus).toHaveBeenCalledTimes(1);- // The click opens the sheet and then reaches the caller.- fireEvent.click(trigger);- expect(onClick).toHaveBeenCalledTimes(1);- expect(trigger).toHaveAttribute('aria-expanded', 'true');- const sheet = await screen.findByRole('dialog');- await screen.findByRole('checkbox', {name: 'Design'});- // Focus moving into the sheet is still the field's: no blur reported.- act(() => screen.getByLabelText('Search Tags').focus());- expect(onBlur).not.toHaveBeenCalled();- // Closing hands focus back to the trigger: that is not focus entering- // from outside, so the caller's onFocus stays quiet for it.- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- act(() => trigger.focus());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- expect(sheet).not.toBeInTheDocument();- expect(onFocus).toHaveBeenCalledTimes(1);- // Leaving the field reports the blur once.- act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());- expect(onBlur).toHaveBeenCalledTimes(1);- });-- it("reports the sheet's focus hand-back as the entry when the trigger never had focus (a tap that opens without focusing, as Safari does), so the caller never gets a blur without its focus", async () => {- presentModally();- const events: string[] = [];- render(- <>- <button type="button">Elsewhere</button>- <MobileTokenizer- label="Tags"- onFocus={() => events.push('focus')}- onBlur={() => events.push('blur')}- searchSource={source}- value={[ITEMS[0]]}- onChange={() => {}}- debounceMs={0}- />- </>,- );- const trigger = screen.getByRole('button', {name: 'Tags'});- // A click with no focus first: the sheet opens, nothing reported yet.- fireEvent.click(trigger);- await screen.findByRole('dialog');- await screen.findByRole('checkbox', {name: 'Design'});- expect(trigger).not.toHaveFocus();- expect(events).toEqual([]);- // Save: BottomSheet hands focus to the trigger. The trigger never had- // focus, so this is the entry.- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- act(() => trigger.focus());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- expect(events).toEqual(['focus']);- // Leaving the field reports the blur, after its focus.- act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());- expect(events).toEqual(['focus', 'blur']);- // A second round from a focused trigger: entry on focus, quiet on the- // hand-back, blur on leaving — one pair again.- act(() => trigger.focus());- fireEvent.click(trigger);- await screen.findByRole('dialog');- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- act(() => trigger.focus());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());- expect(events).toEqual(['focus', 'blur', 'focus', 'blur']);- });-- it('forwards the base props — id, data-*, aria-*, handlers — to the trigger button, not the field root', () => {- const onPointerDown = vi.fn();- render(- <MobileTokenizer- label="Tags"- id="tags-field"- data-testid="tags-trigger"- aria-label="Project tags"- onPointerDown={onPointerDown}- searchSource={source}- value={[ITEMS[0]]}- onChange={() => {}}- />,- );- const trigger = screen.getByTestId('tags-trigger');- expect(trigger.tagName).toBe('BUTTON');- expect(trigger).toHaveAttribute('id', 'tags-field');- expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');- // The field's label still points at the control.- expect(screen.getByText('Tags').closest('label')).toHaveAttribute(- 'for',- 'tags-field',- );- fireEvent.pointerDown(trigger);- expect(onPointerDown).toHaveBeenCalledTimes(1);- expect(trigger.closest('.astryx-field')).not.toHaveAttribute('id');- expect(trigger.closest('.astryx-field')).not.toHaveAttribute('data-testid');- });-- it('renders one hidden form carrier per selected item only while enabled with an htmlName (FR10, FR17)', () => {- const {container, rerender} = render(- <MobileTokenizer- label="Tags"- htmlName="tags"- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- />,- );- const carriers = () =>- Array.from(- container.querySelectorAll<HTMLInputElement>(- 'input[type="hidden"][name="tags"]',- ),- ).map(input => input.value);- expect(carriers()).toEqual(['design', 'eng']);- rerender(- <MobileTokenizer- label="Tags"- htmlName="tags"- isDisabled- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- />,- );- expect(carriers()).toEqual([]);- rerender(- <MobileTokenizer- label="Tags"- searchSource={source}- value={[ITEMS[0], ITEMS[1]]}- onChange={() => {}}- />,- );- expect(carriers()).toEqual([]);- });-- it('reads the source through a ref: a source rebuilt on an unrelated render causes no new request (FR20)', async () => {- const search = vi.fn((q: string) =>- ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),- );- const bootstrap = vi.fn(() => ITEMS);- function Rebuilding() {- const [value, setValue] = useState<SearchableItem[]>([]);- // A new source object every render, as a caller writing it inline does.- const inline: SearchSource<SearchableItem> = {- search: q => search(q),- bootstrap: () => bootstrap(),- };- return (- <MobileTokenizer- label="Tags"- searchSource={inline}- value={value}- onChange={items => setValue(items)}- debounceMs={0}- />- );- }- render(<Rebuilding />);- await openSheet();- await screen.findByRole('checkbox', {name: 'Design'});- expect(bootstrap).toHaveBeenCalledTimes(1);- fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- await waitFor(() =>- expect(screen.getByRole('checkbox', {name: 'Design'})).toBeChecked(),- );- fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));- await waitFor(() =>- expect(screen.getByRole('checkbox', {name: 'Eng'})).toBeChecked(),- );- expect(bootstrap).toHaveBeenCalledTimes(1);- expect(search).not.toHaveBeenCalled();- });-- it('is pending only for a query it will search: a kept query below minQueryLength opens settled (FR20, FR18)', async () => {- let pending = () => {};- const slow: SearchSource<SearchableItem> = {- search: () =>- new Promise<SearchableItem[]>(resolve => {- pending = () => resolve([ITEMS[1]]);- }),- bootstrap: () =>- new Promise<SearchableItem[]>(resolve => {- pending = () => resolve(ITEMS);- }),- };- function Flow() {- const [isDisabled, setIsDisabled] = useState(false);- return (- <>- <button type="button" onClick={() => setIsDisabled(d => !d)}>- Toggle- </button>- <MobileTokenizer- label="Tags"- searchSource={slow}- value={[]}- onChange={() => {}}- debounceMs={0}- minQueryLength={3}- isDisabled={isDisabled}- />- </>- );- }- render(<Flow />);- const trigger = screen.getByRole('button', {name: /Tags/});- const sheet = await openSheet();- // Pending from open until the bootstrap settles.- expect(within(sheet).getByRole('img', {name: 'Loading'})).toBeTruthy();- await act(async () => {- pending();- });- expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull();- // Below the threshold: nothing is searched, nothing is pending.- fireEvent.change(screen.getByLabelText('Search Tags'), {- target: {value: 'en'},- });- expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull();- expect(screen.queryByRole('checkbox')).toBeNull();- // The field becomes disabled while open: the sheet closes and the query- // is kept; re-enabled and reopened, it starts from "en", settled.- fireEvent.click(screen.getByRole('button', {name: 'Toggle'}));- expect(trigger).toHaveAttribute('aria-expanded', 'false');- act(() => trigger.focus());- await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());- fireEvent.click(screen.getByRole('button', {name: 'Toggle'}));- const reopened = await openSheet();- expect(screen.getByLabelText('Search Tags')).toHaveValue('en');- expect(within(reopened).queryByRole('img', {name: 'Loading'})).toBeNull();- });-- it('keeps a spent Clear all in the focus order with its reason, confirms, then focuses the search field and announces inside the sheet after the confirmation has closed (FR24, AST-085 FR1, AST-086 FR14)', async () => {- presentModally();- const spy = vi.fn();- render(<Harness spy={spy} />);- const sheet = await openSheet();- await screen.findByRole('checkbox', {name: 'Design'});- const clearAll = screen.getByRole('button', {name: 'Clear all'});- expect(clearAll).not.toHaveAttribute('aria-disabled');- fireEvent.click(clearAll);- const confirmation = await screen.findByRole('alertdialog');- expect(confirmation).toHaveTextContent('Clear all selected items?');- expect(spy).not.toHaveBeenCalled();- fireEvent.click(- within(confirmation).getByRole('button', {name: 'Clear selection'}),- );- expect(spy).not.toHaveBeenCalled();- await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());- expect(screen.getByLabelText('Search Tags')).toHaveFocus();- await waitFor(() => expect(liveText(sheet)).toBe('All items removed'));- // Spent: still a tab stop, says why, opens no confirmation.- const spent = screen.getByRole('button', {name: 'Clear all'});- expect(spent).toHaveAttribute('aria-disabled', 'true');- expect(spent).not.toHaveAttribute('disabled');- expect(spent).toHaveAccessibleDescription('Nothing selected');- fireEvent.click(spent);- expect(screen.queryByRole('alertdialog')).toBeNull();- fireEvent.click(screen.getByRole('button', {name: 'Save'}));- expect(spy).toHaveBeenCalledWith(- [],- expect.objectContaining({type: 'remove'}),- );- });-- it('announces each toggle and the result count from inside the dialog (AR6, AST-086 FR14)', async () => {- presentModally();- render(<Harness />);- const sheet = await openSheet();- await screen.findByRole('checkbox', {name: 'Energizer'});- fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));- await waitFor(() => expect(liveText(sheet)).toBe('Added Energizer'));- fireEvent.change(screen.getByLabelText('Search Tags'), {- target: {value: 'eng'},- });- await waitFor(() => expect(liveText(sheet)).toBe('2 results'));- // Nothing went to the page-level region behind the modal.- for (const region of document.querySelectorAll(- 'body > [data-astryx-live-region]',- )) {- expect(region.textContent).toBe('');- }- });-- it('uses the shared catalog for the sheet strings', async () => {- render(<CreateHarness spy={() => {}} />);- await openSheet();- const search = screen.getByLabelText('Search Tags');- expect(search).toHaveAttribute('placeholder', 'Search…');- fireEvent.change(search, {target: {value: 'Ops'}});- await screen.findByTestId('mobile-tokenizer-create-row');- expect(screen.getByText('Create "Ops"')).toBeInTheDocument();- expect(screen.getByRole('button', {name: 'Add Ops'})).toBeInTheDocument();- // With `hasCreate`, an unmatched query offers the create row instead of- // the empty state; the empty state's catalog words are checked with a- // field without it, above ("searches within the same sheet").- fireEvent.change(search, {target: {value: 'zzz'}});- expect(- await screen.findByRole('button', {name: 'Add zzz'}),- ).toBeInTheDocument();- });-});diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsxdeleted file mode 100644index 2bdf677525..0000000000--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx+++ /dev/null@@ -1,1269 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file MobileTokenizer.tsx- * @input Public @astryxdesign/core components and hooks, plus private Lab- * touch-sheet confirmation and search-drag dismissal from Core's internal entry- * @output Exports MobileTokenizer — Lab prototype of the touch Tokenizer- * flow with the inline-compatible closed trigger, a searchable draft-selection- * sheet, persistent Clear all / Save footer, dirty-dismiss confirmation,- * stable checkbox ordering, and progressive long-list rendering- * @position Lab (canary) stack layer 1: the touch sheet's user-experience- * pass happens here; Core's sheet presentation (`component:Tokenizer`- * DEC-3, FR16–FR24, AR6) is implemented but not exposed. The behaviors- * below are at parity with Core's sheet where Lab's component has the same- * part: Clear all confirmed, focusable while spent, announced once the- * confirmation has closed (FR24); the bootstrap set capped at- * `maxMenuItems` and an empty one showing only the search field (FR20);- * the trigger described in the inline input's order, then the count and- * the rendered tokens by id (AR6, `spec:AST-085` FR5); form carriers only- * while enabled (`spec:AST-085` FR3, FR17); the source read through a ref and one- * `willSearchFor` rule for the pending state (FR20); the sheet mounted only- * from the press until its exit completes (INV7); announcements from inside- * the dialog (AR6, `spec:AST-086` FR14); a disabled field closing its sheet- * and keeping the query (FR17, FR18); catalog strings.- *- * API mirrors Core Tokenizer (label/isLabelHidden/searchSource/value/onChange/- * change, renderItem, hasCreate, maxEntries) so graduation is an import swap.- * Lab deltas: the filter is a bordered TextInput (Core's PanelSearchInput is- * not exported); row, Create, and Clear all changes stay in one draft until- * Save; the footer stays visible while searching; dirty dismissal asks before- * discarding; and directly dragging results blurs the search so the mobile- * keyboard leaves without clearing the query. There is no theming/spec contract- * yet.- */--import type React from 'react';-import {- useCallback,- useEffect,- useId,- useImperativeHandle,- useLayoutEffect,- useMemo,- useRef,- useState,- type ReactNode,- type RefObject,-} from 'react';-import * as stylex from '@stylexjs/stylex';-import type {BaseProps} from '@astryxdesign/core';-import {BottomSheet} from '@astryxdesign/core/BottomSheet';-import {Button} from '@astryxdesign/core/Button';-import {EmptyState} from '@astryxdesign/core/EmptyState';-import {Field, inputWrapperStyles} from '@astryxdesign/core/Field';-import {useAnnounce, useMergedRefs} from '@astryxdesign/core/hooks';-import {useTranslator} from '@astryxdesign/core/i18n';-import {Icon} from '@astryxdesign/core/Icon';-import {CheckboxIndicator} from '@astryxdesign/core/Indicator';-import {Spinner} from '@astryxdesign/core/Spinner';-import {Text} from '@astryxdesign/core/Text';-import {TextInput} from '@astryxdesign/core/TextInput';-import {Token} from '@astryxdesign/core/Token';-import {useTooltip} from '@astryxdesign/core/Tooltip';-import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';-import {composeEventHandlers, mergeProps} from '@astryxdesign/core/utils';-import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';-import {- colorVars,- radiusVars,- sizeVars,- spacingVars,-} from '@astryxdesign/core/theme/tokens.stylex';-import {- SheetConfirmation,- hasSameSelection,- nameSheetDraftChange,- useDismissSearchOnTouchDrag,- type SheetDraftChange,-} from '@astryxdesign/core/internal/touch-sheet';--export type MobileTokenizerChange<T extends SearchableItem> =- | {item: T; type: 'add'}- | {item: T; type: 'create'}- | {item: T; type: 'remove'}- | {type: 'reorder'};--export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<- BaseProps<HTMLDivElement>,- 'onChange'-> {- label: string;- /**- * Hide the visible field label; the trigger and the sheet keep `label` as- * their accessible name. Mirrors Core Tokenizer.- */- isLabelHidden?: boolean;- searchSource: SearchSource<T>;- value: T[];- onChange: (items: T[], change: MobileTokenizerChange<T>) => void;- /**- * Render function for a result row's content, shown beside the row's- * checkbox. Default: the item's label. Mirrors Core Tokenizer.- */- renderItem?: (item: T) => ReactNode;- placeholder?: string;- description?: string;- /** Status shown under the field and read with the trigger. */- status?: {type: 'error' | 'warning' | 'success'; message: string};- /**- * Why the field is disabled; exposed as the disabled trigger's description- * and shown as its tooltip (`spec:AST-085` FR5). Mirrors Core Tokenizer.- */- disabledMessage?: string;- /** Form field name: one hidden carrier per selected item while enabled. */- htmlName?: string;- isOptional?: boolean;- isDisabled?: boolean;- hasCreate?: boolean;- maxEntries?: number;- maxMenuItems?: number;- minQueryLength?: number;- debounceMs?: number;- emptySearchResultsText?: string;- onChangeQuery?: (query: string) => void;-}--const CREATABLE_ID_PREFIX = '__xds_create__';-const LIST_RENDER_BATCH_SIZE = 50;-const LIST_LOAD_MORE_THRESHOLD_PX = 200;--// The inline Tokenizer's token-row inset: a token's corners (radius-1) sit-// concentric with the field's (radius-2) when inset = radius-2 − radius-1 −-// border = 3px. The same number is the row gap, so wrapped rows read evenly.-const TOKEN_ROW_INSET = `calc(${spacingVars['--spacing-1']} - 1px)`;--const styles = stylex.create({- // The closed trigger is the inline Tokenizer field's own control box, as a- // button — the same `inputWrapperStyles.base` box Core's sheet trigger- // composes (`component:Tokenizer` FR16: same width, border, radius,- // surface and `size` block size, minus only the inline input's own row),- // so before the sheet opens the field looks the same as the desktop field.- // The 44px thumb targets belong to the sheet's rows, not to the closed- // field. These rules are the inline field's own on top of the shared box:- // tokens wrap, the row inset and gap keep token and field corners- // concentric, the block size is the `md` step, and the cursor says "press"- // since there is no input to type into.- trigger: {- width: '100%',- flexWrap: 'wrap',- gap: spacingVars['--spacing-1'],- // Row gap matches the block inset so wrapped rows look evenly spaced.- rowGap: TOKEN_ROW_INSET,- minHeight: sizeVars['--size-element-md'],- height: 'auto',- paddingBlock: TOKEN_ROW_INSET,- paddingInline: TOKEN_ROW_INSET,- 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.- triggerDisabled: {- borderColor: {- default: colorVars['--color-border-emphasized'],- '@media (forced-colors: active)': 'GrayText',- },- color: {- default: null,- '@media (forced-colors: active)': 'GrayText',- },- },- triggerPlaceholder: {- color: colorVars['--color-text-secondary'],- // The input's text inset, so the placeholder sits where typed text would.- paddingInline: spacingVars['--spacing-1'],- },- triggerPlaceholderDisabled: {- color: {- default: colorVars['--color-text-secondary'],- '@media (forced-colors: active)': 'GrayText',- },- },- sheetBody: {- display: 'flex',- flexDirection: 'column',- height: '100%',- minHeight: 0,- paddingInline: spacingVars['--spacing-3'],- paddingBlockStart: spacingVars['--spacing-8'],- paddingBlockEnd: spacingVars['--spacing-3'],- },- // The manage sheet intentionally has no dedicated close button; the sheet- // keeps its standard gesture, scrim, and Escape dismissal paths.- list: {- display: 'flex',- flexDirection: 'column',- flexGrow: 1,- overflowY: 'auto',- minHeight: 0,- },- 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'],- textAlign: 'start',- cursor: {- default: 'pointer',- ':is(:disabled,[aria-disabled="true"])': 'default',- },- },- // 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.- tokenDisabled: {- color: {- default: colorVars['--color-text-primary'],- '@media (forced-colors: active)': 'GrayText',- },- },- // 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',- },- },- rowDisabled: {- color: {- default: colorVars['--color-text-primary'],- '@media (forced-colors: active)': 'GrayText',- },- },- rowLabel: {- flexGrow: 1,- minWidth: 0,- },- 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,- },- filterRow: {- display: 'flex',- alignItems: 'flex-end',- paddingBlockEnd: spacingVars['--spacing-2'],- },- // TextInput renders Field (block, shrink-to-fit); xstyle lands on that- // root, so it must fill the available search row width.- filterInput: {- flexGrow: 1,- flexShrink: 1,- flexBasis: 0,- minWidth: 0,- height: sizeVars['--size-element-lg'],- minHeight: sizeVars['--size-element-lg'],- },- empty: {- flexGrow: 1,- },- emptyHost: {- display: 'flex',- flexDirection: 'column',- flexGrow: 1,- },- pending: {- display: 'flex',- justifyContent: 'center',- paddingBlock: spacingVars['--spacing-4'],- },-});--export function MobileTokenizer<T extends SearchableItem>({- label,- isLabelHidden,- searchSource,- value,- onChange,- renderItem,- placeholder,- description,- status,- disabledMessage,- htmlName,- isOptional,- isDisabled = false,- hasCreate = false,- maxEntries,- maxMenuItems = 10,- minQueryLength = 1,- debounceMs = 150,- emptySearchResultsText,- onChangeQuery,- xstyle,- id,- className,- style,- 'aria-label': ariaLabelProp,- 'aria-describedby': ariaDescribedByProp,- onClick: callerOnClick,- onFocus: callerOnFocus,- onBlur: callerOnBlur,- ...rest-}: MobileTokenizerProps<T>) {- const t = useTranslator();- const generatedTriggerId = useId();- const triggerId = id ?? generatedTriggerId;- const descriptionId = useId();- const statusId = useId();- const countId = 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) =>- `${countId}-${encodeURIComponent(itemId)}`;- const triggerRef = useRef<HTMLButtonElement>(null);- // Whether the caller has been told focus entered the field and not yet- // that it left: the sheet's focus hand-back is reported as the entry when- // the trigger never had focus (a tap or click that opened the sheet without- // focusing the trigger, as Safari does), so a caller never sees a blur- // without its focus.- const hasReportedFocusRef = useRef(false);- const [isSheetOpen, setIsSheetOpen] = useState(false);- // The sheet stays mounted after it closes until BottomSheet has run its- // exit and handed focus back to the trigger; at rest nothing of the sheet- // is in the DOM (`architecture:component-style-authoring` INV7).- const [isSheetPresented, setIsSheetPresented] = useState(false);- // The sheet's query between presentations: a close the person makes clears- // it, a close the field forces (becoming disabled while open) keeps it- // (`component:Tokenizer` 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],- );- // A field that becomes disabled cannot keep its sheet open, and must not- // reopen it when re-enabled (FR17). A forced close bypasses the dirty-draft- // prompt, keeps the query, and discards the in-sheet draft on the next open.- const [wasDisabled, setWasDisabled] = useState(isDisabled);- const [keepsSheetWhileDisabled, setKeepsSheetWhileDisabled] = useState(false);- if (isDisabled !== wasDisabled) {- setWasDisabled(isDisabled);- if (isDisabled && isSheetOpen) {- setIsSheetOpen(false);- setKeepsSheetWhileDisabled(true);- }- if (!isDisabled) {- setKeepsSheetWhileDisabled(false);- }- }-- const handleSheetCommit = useCallback(- (items: T[], change: SheetDraftChange<T>) => {- if (!isDisabled) {- onChange(items, change);- }- },- [isDisabled, onChange],- );-- const showsDisabledMessage = isDisabled && disabledMessage != null;- // The disabled reason as a tooltip on the trigger, for hover, focus and- // touch alike, and the element the trigger's description names- // (`spec:AST-085` FR5); the trigger is focusable while disabled, so focus- // triggering reaches keyboard users.- const disabledMessageTooltip = useTooltip({- placement: 'above',- focusTrigger: 'always',- isEnabled: showsDisabledMessage,- });- const triggerMergedRef = useMergedRefs<HTMLButtonElement>(- triggerRef,- disabledMessageTooltip.ref,- );- // The trigger's description is the inline input's, in its order — the- // caller's ids, the field description, the status message, the disabled- // reason (`spec:AST-085` FR5) — 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 (`component:Tokenizer` AR6).- const triggerDescribedBy =- [- ariaDescribedByProp,- description ? descriptionId : null,- status?.message ? statusId : null,- // The disabled reason is the tooltip's element, as for Core's trigger.- showsDisabledMessage ? disabledMessageTooltip.describedBy : null,- value.length > 0 ? countId : null,- ...value.map(item => tokenElementId(item.id)),- ]- .filter(Boolean)- .join(' ') || undefined;-- return (- <Field- label={label}- isLabelHidden={isLabelHidden}- description={description}- descriptionID={description ? descriptionId : undefined}- status={- status- ? {type: status.type, message: status.message, messageID: statusId}- : undefined- }- isOptional={isOptional}- isDisabled={isDisabled}- inputID={triggerId}- xstyle={xstyle}>- {/* The trigger is the control: the caller's base props — `id`,- `data-*`, `aria-*`, handlers, className, style — reach it, as they- reach Core's sheet trigger, not the field root; what the trigger- sets itself is composed with the caller's value, never over it. */}- <button- // Typed for a div by the base props; here the control is a button.- {...(rest as React.ButtonHTMLAttributes<HTMLButtonElement>)}- ref={triggerMergedRef}- type="button"- id={triggerId}- aria-haspopup="dialog"- aria-expanded={isSheetOpen}- // The caller's name wins over the field label.- aria-label={ariaLabelProp ?? label}- aria-disabled={isDisabled || undefined}- // Already merged with the caller's ids, first.- aria-describedby={triggerDescribedBy}- // The open runs first and the caller's onClick after it, as Core's- // trigger composes its click: a caller observes the click but cannot- // cancel the field's own handling.- onClick={composeEventHandlers<React.MouseEvent<HTMLButtonElement>>(- () => {- if (isDisabled) {- return;- }- setIsSheetPresented(true);- setSheetInitialQuery(sheetQueryRef.current);- setIsSheetOpen(true);- },- callerOnClick as unknown as- React.MouseEventHandler<HTMLButtonElement> | undefined,- )}- onFocus={event => {- // BottomSheet focuses the trigger only after its exit completes;- // that focus is the signal that the retained sheet can leave. The- // field's own sheet is part of the field, so focus coming back from- // it is not focus entering from outside: the caller's onFocus stays- // quiet for it — unless the trigger never had focus (a tap that- // opened the sheet without focusing it, as Safari does), in which- // case the hand-back is the entry, and the caller hears it before- // any blur.- const isReturningFromSheet = !isSheetOpen && isSheetPresented;- if (isReturningFromSheet) {- setIsSheetPresented(false);- }- const isInsideTheField =- isReturningFromSheet && hasReportedFocusRef.current;- if (isInsideTheField) {- return;- }- hasReportedFocusRef.current = true;- (- callerOnFocus as unknown as- React.FocusEventHandler<HTMLButtonElement> | undefined- )?.(event);- }}- onBlur={event => {- // Focus moving into the sheet is still the field's; only a blur to- // somewhere else is reported.- if (isSheetOpen) {- return;- }- hasReportedFocusRef.current = false;- (- callerOnBlur as unknown as- React.FocusEventHandler<HTMLButtonElement> | undefined- )?.(event);- }}- {...mergeProps(- stylex.props(- inputWrapperStyles.base,- styles.trigger,- isDisabled && inputWrapperStyles.disabled,- isDisabled && styles.triggerDisabled,- ),- className,- style,- )}>- {value.length > 0 ? (- value.map(item => (- <Token- key={item.id}- id={tokenElementId(item.id)}- label={item.label}- isDisabled={isDisabled}- xstyle={isDisabled ? styles.tokenDisabled : undefined}- />- ))- ) : (- <span- {...stylex.props(- styles.triggerPlaceholder,- isDisabled && styles.triggerPlaceholderDisabled,- )}>- {placeholder ?? ''}- </span>- )}- </button>- {value.length > 0 && (- <VisuallyHidden id={countId}>- {t('@astryx.tokenizer.selectedCount', {count: value.length})}- </VisuallyHidden>- )}- {showsDisabledMessage &&- disabledMessageTooltip.renderTooltip(disabledMessage)}- {/* Form carriers, gated as Core's inline field gates its own: a- disabled field submits nothing (`spec:AST-085` FR3, FR17). */}- {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: at rest the field renders its trigger- alone (INV7). */}- {(isSheetOpen || isSheetPresented) &&- (!isDisabled || keepsSheetWhileDisabled) && (- <MobileTokenizerSheet- isOpen={isSheetOpen}- onOpenChange={setIsSheetOpen}- finalFocusRef={triggerRef}- initialQuery={sheetInitialQuery}- label={label}- searchSource={searchSource}- value={value}- maxEntries={maxEntries}- hasCreate={hasCreate}- maxMenuItems={maxMenuItems}- minQueryLength={minQueryLength}- debounceMs={debounceMs}- emptySearchResultsText={emptySearchResultsText}- renderItem={renderItem}- onCommit={handleSheetCommit}- onChangeQuery={handleSheetQueryChange}- />- )}- </Field>- );-}--MobileTokenizer.displayName = 'MobileTokenizer';--interface MobileTokenizerSheetProps<T extends SearchableItem> {- isOpen: boolean;- onOpenChange: (isOpen: boolean) => void;- finalFocusRef: RefObject<HTMLElement | null>;- /** The query this presentation starts with (kept across a forced close). */- initialQuery: string;- label: string;- searchSource: SearchSource<T>;- value: T[];- maxEntries?: number;- hasCreate: boolean;- maxMenuItems: number;- minQueryLength: number;- debounceMs: number;- emptySearchResultsText?: string;- renderItem?: (item: T) => ReactNode;- onCommit: (items: T[], change: SheetDraftChange<T>) => void;- onChangeQuery: (query: string) => void;-}--/**- * The sheet: BottomSheet around the content. The content owns the query; a- * close the person makes (Save, swipe, scrim, Escape) clears it through a- * handle from the closing event, so a close the field forces (becoming- * disabled) keeps it (FR18).- */-function MobileTokenizerSheet<T extends SearchableItem>({- isOpen,- onOpenChange,- finalFocusRef,- label,- ...content-}: MobileTokenizerSheetProps<T>) {- const clearQueryRef = useRef<(() => void) | null>(null);- const requestDismissRef = useRef<(() => void) | null>(null);- const closeSheet = () => {- clearQueryRef.current?.();- onOpenChange(false);- };- return (- <BottomSheet- isOpen={isOpen}- onOpenChange={next => {- if (next) {- onOpenChange(true);- } else if (requestDismissRef.current != null) {- requestDismissRef.current();- } else {- closeSheet();- }- }}- finalFocusRef={finalFocusRef}- label={label}- height="tall"- padding={0}>- <MobileTokenizerSheetContent- {...content}- isOpen={isOpen}- label={label}- clearQueryRef={clearQueryRef}- requestDismissRef={requestDismissRef}- onCloseSheet={closeSheet}- />- </BottomSheet>- );-}--type MobileTokenizerSheetContentProps<T extends SearchableItem> = Omit<- MobileTokenizerSheetProps<T>,- 'onOpenChange' | 'finalFocusRef'-> & {- clearQueryRef: RefObject<(() => void) | null>;- requestDismissRef: RefObject<(() => void) | null>;- onCloseSheet: () => void;-};--/**- * Rendered inside the sheet's dialog, so every announcement it makes through- * `useAnnounce` is delivered inside the open modal (`spec:AST-086` FR14).- */-function MobileTokenizerSheetContent<T extends SearchableItem>({- isOpen,- initialQuery,- clearQueryRef,- requestDismissRef,- onCloseSheet,- label,- searchSource,- value,- maxEntries,- hasCreate,- maxMenuItems,- minQueryLength,- debounceMs,- emptySearchResultsText,- renderItem,- onCommit,- onChangeQuery,-}: MobileTokenizerSheetContentProps<T>) {- const t = useTranslator();- const announce = useAnnounce();- const searchRef = useRef<HTMLInputElement>(null);- const clearAllRef = useRef<HTMLButtonElement>(null);-- // One open sheet owns one selection draft. The caller's controlled value is- // unchanged until Save, so a cancelled dismissal can discard cleanly.- const [valueAtOpen, setValueAtOpen] = useState<T[]>(() => [...value]);- const [draftValue, setDraftValue] = useState<T[]>(() => [...value]);- const lastDraftChangeRef = useRef<SheetDraftChange<T> | null>(null);- const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);- const [isDiscardConfirmationOpen, setIsDiscardConfirmationOpen] =- useState(false);- const afterConfirmationRef = useRef<'search' | 'clear-all' | null>(null);- const shouldRestoreDraftFocusRef = useRef(false);- const isDraftDirty = !hasSameSelection(valueAtOpen, draftValue);- const selectedIds = useMemo(- () => new Set(draftValue.map(item => item.id)),- [draftValue],- );- const isAtMax = maxEntries != null && draftValue.length >= maxEntries;- const isDraftOverMax = maxEntries != null && draftValue.length > maxEntries;-- // ---- query and search ----- const [query, setQuery] = useState(initialQuery);- const trimmedQuery = query.trim();- // Whether a query is one the source is asked about: empty (the bootstrap- // set) or at least `minQueryLength`. One rule for every way a query comes- // to be: the initial one, a change.- const willSearchFor = (trimmed: string) =>- trimmed === '' || trimmed.length >= minQueryLength;- const isBelowMinQuery = trimmedQuery !== '' && !willSearchFor(trimmedQuery);- // Pending from open, and from each query change, until that search- // settles. The sheet mounts already open, so the initial state is derived- // from the initial query the way a change derives it: a kept query below- // the threshold starts settled, not pending for a search that never runs- // (FR20).- const [isPending, setIsPending] = useState(() =>- willSearchFor(initialQuery.trim()),- );- const [sourceResults, setSourceResults] = useState<T[]>([]);- const results = isBelowMinQuery ? [] : sourceResults;- // Each search that runs gets a number; its outcome is announced once.- const [searchId, setSearchId] = useState(0);- const searchIdRef = useRef(0);- const announcedSearchIdRef = useRef(- willSearchFor(initialQuery.trim()) ? -1 : 0,- );- const seqRef = useRef(0);- // The source is read through a ref at request time, so a caller that- // rebuilds the source object in render causes no new request on an- // unrelated render (a row toggle); the sheet asks the source only on open,- // on a query change, and on clearing (FR20). The ref is updated in a layout- // effect, before any request this commit makes. (React's own- // useLayoutEffect: this content renders only inside an open sheet, after a- // press, so it never runs on the server.)- const searchSourceRef = useRef(searchSource);- useLayoutEffect(() => {- 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 —- // and a typed query waits `debounceMs`. A layout effect, as Core's sheet- // runs it, so a source that answers synchronously settles before the- // browser paints the open commit and the Loading row never reaches the- // screen. 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).- useLayoutEffect(() => {- if (!isOpen) {- return;- }- const trimmed = query.trim();- const seq = ++seqRef.current;- if (!willSearchFor(trimmed)) {- return;- }- const settle = (items: T[]) => {- if (seqRef.current === seq) {- // The bootstrap set is capped at `maxMenuItems` as the inline field- // caps its focus bootstrap (FR20).- setSourceResults(items.slice(0, maxMenuItems));- setIsPending(false);- }- };- const run = () => {- const source = searchSourceRef.current;- let answer: T[] | PromiseLike<T[]>;- try {- answer =- trimmed === ''- ? source.bootstrap- ? source.bootstrap()- : source.search('')- : source.search(query);- } catch {- answer = [];- }- if (Array.isArray(answer)) {- settle(answer);- return;- }- void Promise.resolve(answer).then(settle, () => settle([]));- };- if (trimmed !== '' && debounceMs > 0) {- const timer = setTimeout(run, debounceMs);- return () => clearTimeout(timer);- }- run();- }, [isOpen, query, minQueryLength, maxMenuItems, debounceMs]);-- const [renderedItemCount, setRenderedItemCount] = useState(- LIST_RENDER_BATCH_SIZE,- );- const lastLoadScrollHeightRef = useRef<number | null>(null);- // Snapshot the selection and reset the rendered window in the render that- // opens the sheet (the sheet stays mounted through its exit, so a reopen- // reuses this content), so the first open frame already shows- // selected-first order; rows keep their place while the sheet is open.- const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);- const resetListWindow = () => {- lastLoadScrollHeightRef.current = null;- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);- };- const [wasOpen, setWasOpen] = useState(isOpen);- if (isOpen !== wasOpen) {- setWasOpen(isOpen);- if (isOpen) {- const snapshot = [...value];- setValueAtOpen(snapshot);- setDraftValue(snapshot);- lastDraftChangeRef.current = null;- setSelectedItemsAtOpen(snapshot);- resetListWindow();- // An open lists the bootstrap set, or searches a query kept across a- // forced close (FR18); a kept query below the threshold leaves nothing- // pending, since no search runs for it.- const willSearch = willSearchFor(trimmedQuery);- setIsPending(willSearch);- if (willSearch) {- searchIdRef.current += 1;- setSearchId(searchIdRef.current);- } else {- announcedSearchIdRef.current = searchIdRef.current;- }- } else {- // Close both confirmations in the same render that closes the sheet.- afterConfirmationRef.current = null;- shouldRestoreDraftFocusRef.current = false;- setIsClearConfirmationOpen(false);- setIsDiscardConfirmationOpen(false);- }- }- const handleQueryChange = (next: string) => {- resetListWindow();- const willSearch = willSearchFor(next.trim());- // Below the threshold nothing is searched, so nothing is pending and no- // outcome is owed: a search still unsettled from the previous query is- // retired unannounced.- setIsPending(willSearch);- if (willSearch) {- searchIdRef.current += 1;- setSearchId(searchIdRef.current);- } else {- announcedSearchIdRef.current = searchIdRef.current;- }- setQuery(next);- onChangeQuery(next);- };- useImperativeHandle(- clearQueryRef,- () => () => {- if (query !== '') {- setQuery('');- onChangeQuery('');- }- },- [query, onChangeQuery],- );-- const visibleItems = useMemo(() => {- const normalizedQuery = trimmedQuery.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 = draftValue.filter(- item =>- !selectedAtOpenIds.has(item.id) &&- !resultIds.has(item.id) &&- matchesQuery(item),- );- return [- ...selectedAtOpenMatches,- ...selectedItemsMissingFromResults,- ...results.filter(item => !selectedAtOpenIds.has(item.id)),- ];- }, [trimmedQuery, results, selectedItemsAtOpen, draftValue]);- const renderedItems = visibleItems.slice(0, renderedItemCount);-- const createItem = useMemo<T | null>(() => {- if (!hasCreate || trimmedQuery === '' || isAtMax) {- return null;- }- const lower = trimmedQuery.toLowerCase();- if (- selectedIds.has(trimmedQuery) ||- draftValue.some(item => item.label.toLowerCase() === lower) ||- results.some(r => r.label.toLowerCase() === lower)- ) {- return null;- }- return {- id: `${CREATABLE_ID_PREFIX}${trimmedQuery}`,- label: t('@astryx.tokenizer.create', {value: trimmedQuery}),- } as unknown as T;- }, [hasCreate, trimmedQuery, results, selectedIds, isAtMax, draftValue, t]);-- const isQueryEmpty = trimmedQuery === '';- // An empty state is a searched query's answer. An empty query that lists- // nothing — nothing selected and an empty bootstrap set — shows only the- // search field, no list, no message, and announces nothing (FR20).- const isSettledEmpty =- !isPending &&- !isBelowMinQuery &&- !isQueryEmpty &&- visibleItems.length === 0 &&- createItem == null;- const isSettledBlank =- !isPending &&- !isBelowMinQuery &&- isQueryEmpty &&- visibleItems.length === 0 &&- createItem == null;-- // How each search ended, once per settle (AR6): the result count for a- // searched query. The empty state announces its own words.- useEffect(() => {- if (!isOpen || isPending || announcedSearchIdRef.current === searchId) {- return;- }- announcedSearchIdRef.current = searchId;- if (!isSettledEmpty && !isQueryEmpty) {- announce(- t('@astryx.typeahead.resultCount', {- count: visibleItems.length + (createItem == null ? 0 : 1),- }),- );- }- }, [- announce,- createItem,- isOpen,- isPending,- isQueryEmpty,- isSettledEmpty,- visibleItems.length,- searchId,- t,- ]);-- // ---- confirmations and dismissal ----- const closeDiscardConfirmation = () => {- shouldRestoreDraftFocusRef.current = true;- setIsDiscardConfirmationOpen(false);- };- // Synchronize DOM focus with the closed discard dialog. Dialog restores focus- // in its own close Effect, so focus the search only after that dialog closes.- useEffect(() => {- if (- isDiscardConfirmationOpen ||- !shouldRestoreDraftFocusRef.current ||- !isOpen- ) {- return;- }- shouldRestoreDraftFocusRef.current = false;- searchRef.current?.focus({preventScroll: true});- }, [isDiscardConfirmationOpen, isOpen]);- const closeClearConfirmation = (confirmed: boolean) => {- afterConfirmationRef.current = confirmed ? 'search' : 'clear-all';- setIsClearConfirmationOpen(false);- };- // Synchronize DOM focus and the live-region announcement after the clear- // dialog closes, once Dialog's own close Effect has restored focus.- 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]);- useImperativeHandle(- requestDismissRef,- () => () => {- if (isDraftDirty) {- setIsDiscardConfirmationOpen(true);- } else {- onCloseSheet();- }- },- [isDraftDirty, onCloseSheet],- );-- const handleSave = () => {- if (isDraftOverMax) {- return;- }- const change = isDraftDirty- ? nameSheetDraftChange(- valueAtOpen,- draftValue,- lastDraftChangeRef.current,- )- : null;- if (change != null) {- onCommit([...draftValue], change);- }- onCloseSheet();- };-- const searchLabel = t('@astryx.tokenizer.search', {label});- const noResultsTitle =- emptySearchResultsText ?? t('@astryx.typeahead.emptySearchResults');- // A drag moves focus to the sheet's panel, never to the page body behind- // the open modal.- const listDragProps = useDismissSearchOnTouchDrag(- () => [searchRef.current],- () => searchRef.current?.closest<HTMLElement>('[tabindex="-1"]'),- );-- return (- <div {...stylex.props(styles.sheetBody)}>- <div {...stylex.props(styles.filterRow)}>- <TextInput- ref={searchRef}- label={searchLabel}- isLabelHidden- placeholder={t('@astryx.tokenizer.searchPlaceholder')}- startIcon="search"- value={query}- size="lg"- width="100%"- hasClear- onChange={handleQueryChange}- controlXstyle={styles.filterInput}- />- </div>- {isPending ? (- // Named busy feedback while the source works, above any rows still- // listed from the previous search (`family:input-fields` FR7).- <div {...stylex.props(styles.pending)}>- <Spinner- size="md"- role="img"- aria-label={t('@astryx.typeahead.loading')}- />- </div>- ) : null}- {isSettledEmpty ? (- <div {...stylex.props(styles.emptyHost)}>- <EmptyState- icon={<Icon icon="search" size="lg" color="secondary" />}- title={noResultsTitle}- description={t('@astryx.tokenizer.noResultsDescription')}- isCompact- xstyle={styles.empty}- />- </div>- ) : isSettledBlank ? null : (- <div- {...stylex.props(styles.list)}- role="group"- aria-label={label}- aria-busy={isPending || undefined}- data-testid="mobile-tokenizer-list"- data-rendered-count={renderedItems.length}- data-total-count={visibleItems.length}- {...listDragProps}- 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 != null && (- <div- data-testid="mobile-tokenizer-create-row"- {...stylex.props(styles.createRow)}>- <span {...stylex.props(styles.createLabel)}>- <Text type="body">{createItem.label}</Text>- </span>- <Button- label={t('@astryx.tokenizer.add')}- aria-label={t('@astryx.tokenizer.addValue', {- value: trimmedQuery,- })}- variant="secondary"- size="lg"- onClick={() => {- const item: SearchableItem = {- id: trimmedQuery,- label: trimmedQuery,- };- const createdItem = item as T;- setDraftValue(current => [...current, createdItem]);- lastDraftChangeRef.current = {- item: createdItem,- type: 'create',- };- announce(- t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),- );- handleQueryChange('');- searchRef.current?.focus();- }}- />- </div>- )}- {renderedItems.map(item => {- const isSelected = selectedIds.has(item.id);- const rowDisabled = !isSelected && isAtMax;- return (- <button- key={item.id}- type="button"- role="checkbox"- aria-checked={isSelected}- aria-label={item.label}- aria-disabled={rowDisabled || undefined}- onClick={() => {- if (rowDisabled) {- return;- }- if (isSelected) {- setDraftValue(current =>- current.filter(selected => selected.id !== item.id),- );- lastDraftChangeRef.current = {item, type: 'remove'};- announce(- t('@astryx.tokenizer.tokenRemoved', {label: item.label}),- );- } else {- setDraftValue(current => [...current, item]);- lastDraftChangeRef.current = {item, type: 'add'};- announce(- t('@astryx.tokenizer.tokenAdded', {label: item.label}),- );- }- }}- {...stylex.props(- styles.row,- rowDisabled && styles.rowDisabled,- )}>- <span {...stylex.props(styles.rowLabel)}>- {renderItem ? (- renderItem(item)- ) : (- <Text- type="body"- color={rowDisabled ? 'inherit' : undefined}>- {item.label}- </Text>- )}- </span>- <CheckboxIndicator- state={isSelected ? 'checked' : 'unchecked'}- size="md"- isDisabled={rowDisabled}- xstyle={rowDisabled ? styles.indicatorDisabled : undefined}- />- </button>- );- })}- </div>- )}- <div {...stylex.props(styles.footer)}>- <Button- ref={clearAllRef}- label={t('@astryx.tokenizer.clearAll')}- variant="secondary"- size="lg"- isDisabled={draftValue.length === 0}- tooltip={- draftValue.length === 0- ? t('@astryx.tokenizer.nothingToClear')- : undefined- }- onClick={() => setIsClearConfirmationOpen(true)}- xstyle={styles.footerAction}- />- <Button- label={t('@astryx.tokenizer.save')}- variant="primary"- size="lg"- isDisabled={isDraftOverMax}- tooltip={- isDraftOverMax- ? t('@astryx.tokenizer.selectionLimit', {- count: maxEntries ?? 0,- })- : undefined- }- onClick={handleSave}- xstyle={styles.footerAction}- />- </div>- {isClearConfirmationOpen && (- <SheetConfirmation- isOpen- onOpenChange={next => {- if (!next) {- closeClearConfirmation(false);- }- }}- title={t('@astryx.tokenizer.clearAllTitle')}- description={t('@astryx.tokenizer.clearAllDescription', {label})}- cancelLabel={t('@astryx.alertDialog.cancel')}- actionLabel={t('@astryx.tokenizer.clearSelection')}- onAction={() => {- const lastItem = draftValue[draftValue.length - 1];- if (lastItem != null) {- setDraftValue([]);- lastDraftChangeRef.current = {- item: lastItem,- type: 'remove',- };- }- closeClearConfirmation(true);- }}- />- )}- {isDiscardConfirmationOpen && (- <SheetConfirmation- isOpen- onOpenChange={next => {- if (!next) {- closeDiscardConfirmation();- }- }}- title={t('@astryx.tokenizer.discardChangesTitle')}- description={t('@astryx.tokenizer.discardChangesDescription', {- label,- })}- cancelLabel={t('@astryx.tokenizer.keepEditing')}- actionLabel={t('@astryx.tokenizer.discardChanges')}- onAction={() => {- shouldRestoreDraftFocusRef.current = false;- setIsDiscardConfirmationOpen(false);- onCloseSheet();- }}- />- )}- </div>- );-}diff --git a/packages/lab/src/MobileTokenizer/index.ts b/packages/lab/src/MobileTokenizer/index.tsdeleted file mode 100644index 5fe4999040..0000000000--- a/packages/lab/src/MobileTokenizer/index.ts+++ /dev/null@@ -1,16 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--'use client';--/**- * @file index.ts- * @input MobileTokenizer component- * @output Public MobileTokenizer entry point for @astryxdesign/lab- * @position Component barrel; re-exported by /packages/lab/src/index.ts- */--export {MobileTokenizer} from './MobileTokenizer';-export type {- MobileTokenizerProps,- MobileTokenizerChange,-} from './MobileTokenizer';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 36fb89ec84..c28ce99d49 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -324,24 +324,6 @@ export {type DiffViewerSide,} from './DiffViewer';-// MobileTokenizer — Lab prototype (stack layer 1) of the touch Tokenizer-// flow: summary trigger + stacked manage/add BottomSheets. Graduates to-// Core Tokenizer presentation="bottom-sheet" (stack layer 2).-export {- MobileTokenizer,- type MobileTokenizerProps,- type MobileTokenizerChange,-} from './MobileTokenizer';--// MobilePowerSearch — Lab prototype (stack layer 1) of the touch PowerSearch-// flow: field-wide "Manage filters" trigger with display-only tokens, a-// Filters sheet, and a field → operator → value drill-down. The caller picks-// it explicitly on touch layouts; the API mirrors Core PowerSearch.-export {- MobilePowerSearch,- type MobilePowerSearchProps,-} from './MobilePowerSearch';-// RichTextEditor (RFC meta/astryx#3899) moved out of @astryxdesign/lab into// its own package, @astryxdesign/richtext. Import it from there:// import {RichTextEditor, RichTextView} from '@astryxdesign/richtext';diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex c3c98ee101..b97ec5af95 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -239,7 +239,6 @@ const FILE_MODULE_SUBPATH_EXPORTS = [// (architecture:react-component-runtime INV13).'internal/indicatorPress.stylex','internal/touch',- 'internal/touch-sheet','internal/selectable-card',];