An open source design system that's fully customizable and agent ready
TypeScript
feat(Tokenizer): the touch sheet presentation is public behind experimental.presentation, and the sheet edits a draft that Save commits (#9708)
Xinzi Zhou4f452f927f7b
diff --git a/.changeset/tokenizer-experimental-bottom-sheet.md b/.changeset/tokenizer-experimental-bottom-sheet.mdnew file mode 100644index 0000000000..473f25eed6--- /dev/null+++ b/.changeset/tokenizer-experimental-bottom-sheet.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[experimental] Tokenizer gains a touch surface behind `experimental={{presentation: 'bottom-sheet' | 'adaptive'}}`. `bottom-sheet` replaces the inline combobox with a trigger that shows the selected tokens and opens one tall modal sheet: a bordered search field on top, full-width checkbox rows that keep their place while the sheet is open and regroup selected-first on the next open, 50-row progressive rendering for long lists, a `Create "…"` row with a trailing Add action under `hasCreate`, and a footer pinned in every state with a confirmed Clear all and Save. The sheet edits a draft: rows, the create row and Clear all change the selection the sheet shows, and `value` changes once, when Save reports the draft through `onChange` with the last edit that still holds as its `change`; a swipe, scrim or Escape close of a changed draft asks before discarding, and a clean one closes directly. On a touch screen a direct drag on the results dismisses the keyboard without clearing the query. `adaptive` uses the sheet on compact coarse-pointer screens and the popover otherwise, resolved the same way Selector resolves it. The sheet surface loads on demand, so a Tokenizer that does not opt in does not carry it. The trigger describes its selected tokens to assistive technology, announcements made while the sheet is open reach assistive technology through a live region inside the sheet, with `experimental` passed the component also accepts a `Ref<HTMLInputElement | HTMLButtonElement>` because `ref` reaches the trigger in the sheet presentation (`TokenizerProps` keeps its released `ref` type and gains only the optional `experimental`), and in development the field warns once about props that have no surface in the sheet presentation (`renderItem`, `renderToken`, `endContent`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`, `tokenOverflowBehavior`, `hasAutoFocus`). The sheet's strings come from the `@astryx.tokenizer.*` catalog; the sheet's parts expose no theming targets while the option is experimental. Anything inside Tokenizer's `experimental` prop may change or be removed in a patch release; omitting it keeps the stable behavior.++@imdreamrunnerdiff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsxindex a589fabcc6..dc25854701 100644--- a/apps/storybook/stories/Tokenizer.stories.tsx+++ b/apps/storybook/stories/Tokenizer.stories.tsx@@ -816,3 +816,144 @@ export const CaretPlacement: Story = {}},};+// A long, searchable dataset for the sheet presentation: enough entries to+// see the 50-row batches of progressive rendering.+const sheetTags: SearchableItem[] = Array.from({length: 1000}, (_, index) => {+ const number = index + 1;+ return {+ id: `tag-${number}`,+ label:+ number === 1+ ? 'Design'+ : number === 2+ ? 'Eng'+ : `Tag ${String(number).padStart(2, '0')}`,+ };+});++const sheetTagSource: SearchSource = {+ search: (query: string) =>+ sheetTags.filter(tag =>+ tag.label.toLowerCase().includes(query.toLowerCase()),+ ),+ bootstrap: () => sheetTags,+};++/**+ * The experimental touch surface, forced on every device so it is reviewable+ * on a laptop: `experimental.presentation="bottom-sheet"`. The trigger shows+ * the selected tokens; tapping it opens one tall sheet with the search row on+ * top, checkbox rows that keep their place while the sheet is open, a Create+ * row for typed text, and a pinned footer with a confirmed Clear all beside+ * Save, which commits the draft; `onChange` fires once, on Save.+ */+export const ExperimentalBottomSheet: Story = {+ render: args => {+ const [value, setValue] = useState<SearchableItem[]>([+ sheetTags[0],+ sheetTags[1],+ ]);+ return (+ <Tokenizer+ {...args}+ searchSource={sheetTagSource}+ value={value}+ onChange={items => setValue(items)}+ hasCreate+ maxMenuItems={1000}+ debounceMs={0}+ experimental={{presentation: 'bottom-sheet'}}+ />+ );+ },+ args: {+ label: 'Tags',+ placeholder: 'Add tags',+ },+ name: 'Experimental: bottom sheet',+};++/**+ * `experimental.presentation="adaptive"`: the sheet on a compact+ * coarse-pointer screen (narrow the viewport and emulate touch), otherwise the+ * inline combobox — the same resolution Selector uses.+ */+export const ExperimentalAdaptive: Story = {+ render: args => {+ // Enough tokens to wrap the inline field's row on a phone, so the box+ // the trigger keeps at the swap is the wrapped one (FR16, FR17).+ const [value, setValue] = useState<SearchableItem[]>([+ sheetTags[0],+ sheetTags[1],+ sheetTags[2],+ sheetTags[3],+ sheetTags[4],+ ]);+ return (+ <Tokenizer+ {...args}+ searchSource={sheetTagSource}+ value={value}+ onChange={items => setValue(items)}+ maxMenuItems={1000}+ debounceMs={0}+ experimental={{presentation: 'adaptive'}}+ />+ );+ },+ args: {+ label: 'Tags',+ placeholder: 'Add tags',+ },+ name: 'Experimental: adaptive',+};++/**+ * Disabled and at-limit states of the sheet presentation: the disabled+ * trigger stays focusable and does not open; at `maxEntries` the sheet's+ * unchecked rows are inert while checked rows still toggle.+ */+export const ExperimentalBottomSheetStates: Story = {+ render: args => {+ const [value, setValue] = useState<SearchableItem[]>([+ sheetTags[0],+ sheetTags[1],+ ]);+ return (+ <div style={{display: 'grid', gap: 16}}>+ <Tokenizer+ {...args}+ label="Disabled"+ searchSource={sheetTagSource}+ value={[sheetTags[0], sheetTags[1]]}+ onChange={() => {}}+ isDisabled+ experimental={{presentation: 'bottom-sheet'}}+ />+ <Tokenizer+ {...args}+ label="Disabled and empty"+ searchSource={sheetTagSource}+ value={[]}+ onChange={() => {}}+ isDisabled+ experimental={{presentation: 'bottom-sheet'}}+ />+ <Tokenizer+ {...args}+ label="At the limit"+ searchSource={sheetTagSource}+ value={value}+ onChange={items => setValue(items)}+ maxEntries={2}+ debounceMs={0}+ experimental={{presentation: 'bottom-sheet'}}+ />+ </div>+ );+ },+ args: {+ placeholder: 'Add tags',+ },+ name: 'Experimental: bottom sheet states',+};diff --git a/docs/specs/components/Tokenizer/Tokenizer.spec.md b/docs/specs/components/Tokenizer/Tokenizer.spec.mdindex 1201ef2351..fdf2e7a1fa 100644--- a/docs/specs/components/Tokenizer/Tokenizer.spec.md+++ b/docs/specs/components/Tokenizer/Tokenizer.spec.md@@ -15,12 +15,11 @@ verified_by:packages/core/src/Tokenizer/Tokenizer.test.tsx,packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx,packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx,+ packages/core/src/internal/SheetConfirmation.test.tsx,+ packages/core/src/internal/useDismissSearchOnTouchDrag.test.tsx,packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx,- packages/lab/src/internal/MobileSheetConfirmation.test.tsx,- packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsx,packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx,packages/core/src/PowerSearch/PowerSearch.test.tsx,- packages/core/src/internal/tokenizer-presentation.test.ts,packages/core/src/Typeahead/Typeahead.test.tsx,packages/core/src/Layer/useLayer.test.tsx,scripts/check-knowledge.mjs,@@ -56,15 +55,15 @@ system_specs:# Tokenizer component contract-| Area | Contract |-| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Public contract | One optional `experimental` prop object whose `presentation` option selects the surface (DEC-3), a sheet that edits a draft committed by Save (DEC-4); the stable props, exports, and syntax are unchanged, and `TokenizerProps` stays an interface whose `ref` is `Ref<HTMLInputElement>`; only with `experimental` passed does the component accept a wider `ref`. The existing `hasEntriesOnFocus` mode has a defined post-selection lifecycle (DEC-2). |-| Behavior | A committed empty-query bootstrap choice keeps remaining eligible loaded choices open, filters committed IDs, and advances the active option; terminal states close safely. The `bottom-sheet` presentation replaces the inline combobox with a trigger that opens one searchable modal sheet of checkbox rows that edit a draft committed by Save (FR16–FR24, FR26, FR27). |-| End-user impact | People selecting several loaded values can continue without reopening the menu, while disabled, loading, exhausted, and dismissed states remain non-interactive. On a compact touch screen, an opted-in field offers thumb-sized rows and a search field the keyboard does not cover. |-| Builder impact | None for existing callers. A caller opts into the touch surface with `experimental={{presentation: 'adaptive'}}` or `'bottom-sheet'`, accepting that the option may change or be removed in a patch release. |-| Compatibility/readiness | Omitting `experimental`, and the default `hasEntriesOnFocus={false}` path, keep today's inline combobox and direct single-select BaseTypeahead unchanged. DEC-2 is current and owner-approved with implementation and exact-head evidence pending; DEC-3 is current and implemented, with the implementation gap that the sheet presentation is not yet exposed: `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. DEC-4 is current with the implementation gap that Core's sheet commits each edit at once; the draft, Save, pinned footer, and discard confirmation of FR18, FR19, FR22–FR24, FR26, and FR27 are verified in the Lab prototype. |-| Review checks | Reject implementations that filter by label instead of ID, reorder eligible choices, lose focus or a valid active descendant, refetch unnecessarily, or let disabled, exhausted, dismissed, or stale-loading states remain interactive or reopen. Reject a sheet presentation that switches without `experimental`, moves an existing row on toggle, clears every token without confirmation, changes `value` before Save, closes a changed draft without asking, or hides Clear all or Save while the person searches. |-| Governing rules | This canonical `component:Tokenizer` record: [FR13–FR27](#behavioral-and-layout-contract), [AR5–AR6](#accessibility-contract), [DEC-2](#dec-2--focus-bootstrap-supports-consecutive-committed-selections), [DEC-3](#dec-3--the-touch-sheet-presentation-is-an-experimental-option), and [DEC-4](#dec-4--the-sheet-edits-a-draft-that-save-commits). |+| Area | Contract |+| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | One optional `experimental` prop object whose `presentation` option selects the surface (DEC-3), a sheet that edits a draft committed by Save (DEC-4); the stable props, exports, and syntax are unchanged, and `TokenizerProps` stays an interface whose `ref` is `Ref<HTMLInputElement>`; only with `experimental` passed does the component accept a wider `ref`. The existing `hasEntriesOnFocus` mode has a defined post-selection lifecycle (DEC-2). |+| Behavior | A committed empty-query bootstrap choice keeps remaining eligible loaded choices open, filters committed IDs, and advances the active option; terminal states close safely. The `bottom-sheet` presentation replaces the inline combobox with a trigger that opens one searchable modal sheet of checkbox rows that edit a draft committed by Save (FR16–FR24, FR26, FR27). |+| End-user impact | People selecting several loaded values can continue without reopening the menu, while disabled, loading, exhausted, and dismissed states remain non-interactive. On a compact touch screen, an opted-in field offers thumb-sized rows and a search field the keyboard does not cover. |+| Builder impact | None for existing callers. A caller opts into the touch surface with `experimental={{presentation: 'adaptive'}}` or `'bottom-sheet'`, accepting that the option may change or be removed in a patch release. |+| Compatibility/readiness | Omitting `experimental`, and the default `hasEntriesOnFocus={false}` path, keep today's inline combobox and direct single-select BaseTypeahead unchanged. DEC-2 is current and owner-approved with implementation and exact-head evidence pending; DEC-3 is current and implemented. DEC-4 is current and implemented; the confirmation's actions are not yet one action group (FR27). |+| Review checks | Reject implementations that filter by label instead of ID, reorder eligible choices, lose focus or a valid active descendant, refetch unnecessarily, or let disabled, exhausted, dismissed, or stale-loading states remain interactive or reopen. Reject a sheet presentation that switches without `experimental`, moves an existing row on toggle, clears every token without confirmation, changes `value` before Save, closes a changed draft without asking, or hides Clear all or Save while the person searches. |+| Governing rules | This canonical `component:Tokenizer` record: [FR13–FR27](#behavioral-and-layout-contract), [AR5–AR6](#accessibility-contract), [DEC-2](#dec-2--focus-bootstrap-supports-consecutive-committed-selections), [DEC-3](#dec-3--the-touch-sheet-presentation-is-an-experimental-option), and [DEC-4](#dec-4--the-sheet-edits-a-draft-that-save-commits). |## Intent@@ -123,7 +122,9 @@ Consumer migration instructions belong in consumer docs and release notes.presentations.- The touch sheet presentation: its trigger, the single searchable sheet, thein-session row order, progressive long-list rendering, the create row, the- confirmed Clear all, and which Tokenizer props the sheet honors.+ confirmed Clear all, the draft with Save and the guard that asks before a+ changed draft is discarded (FR26, FR27, DEC-4), and which Tokenizer props+ the sheet honors.**Does not own / non-goals**@@ -150,8 +151,10 @@ Consumer migration instructions belong in consumer docs and release notes.- The sheet's dialog, scrim, gestures, snap behavior, and dismissal paths —owned by `component:BottomSheet` and `family:overlay-dismissal`; itson-screen keyboard behavior — owned by `spec:AST-099`. This record owns- only which touch on the results moves focus off the sheet's search field- (FR18), not what the keyboard does when it does.+ which touch on the results moves focus off the sheet's search field and+ where it goes (FR18), not what the keyboard does when it does, and what the+ sheet does with a dismissal while its draft is changed (FR27), not the+ gesture or its paths.## Public concepts@@ -159,13 +162,8 @@ One public concept is introduced, as an experimental surface: the optional`experimental` prop object and its `presentation` option, `'popover' |'bottom-sheet' | 'adaptive'` (DEC-3). The option type is inlined on the prop;no experimental hook or type is exported. Declarations carry `@experimental`-and consumer docs carry `stability: 'experimental'` metadata. Implementation-gap: the option is not yet exposed — `TokenizerProps` offers no `experimental`-while the sheet's user experience is being finished, consumer docs carry no-`experimental` entry, and the sheet-capable signature is reachable only-through `@astryxdesign/core/internal/tokenizer-presentation`, an internal entry-reserved for Astryx's own packages (`architecture:react-component-runtime`-INV13). Existing consumer props and usage remain in `Tokenizer.doc.mjs`. The existing+and consumer docs carry `stability: 'experimental'` metadata. Existing+consumer props and usage remain in `Tokenizer.doc.mjs`. The existing`hasEntriesOnFocus` mode includes the component-owned post-selection behaviorin FR13–FR15.@@ -203,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 through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 off it without clearing the query — a focus rule of the sheet's, so the rows the person reaches for come into view; 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` | Implementation gap: Core's sheet does not match this row yet — its footer renders only while the query is empty, its closing action is Done, its search field is the borderless panel field, and a results drag does not move focus off the search; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 | Implementation gap: Core's sheet does not match this row yet — a toggle commits an `add` or `remove` change through `onChange` at once; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 through the internal entry. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 | Implementation gap: Core's sheet does not match this row yet — the Add action commits a `create` change through `onChange` at once; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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` | Implementation gap: Core's sheet does not match this row yet — the limit is read against `value`, since there is no draft, and Save does not exist; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 | Implementation gap: Core's sheet does not match this row yet — confirming commits `[]` through `onChange` at once, the confirmation is an AlertDialog, and Clear all leaves with the footer while searching; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 | Implementation gap: Core's sheet does not match this row yet — there is no draft: every edit commits through `onChange` at once and the closing action is Done; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |-| 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 | Implementation gap: Core's sheet does not match this row yet — a dismissal always closes, and the sheet's confirmation is an AlertDialog with a ghost safe action and no scrim dismissal; the Lab prototype's confirmation has the shape, order, and focus of this row but renders its two actions as plain buttons, so the action-group sentence is met by neither yet; the row's behavior is the Lab prototype's, verified in `packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx`. Implementation gap: the sheet presentation is implemented but not yet exposed; `TokenizerProps` offers no `experimental.presentation` while its user experience is being finished, and every field renders the popover presentation. |+| 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. |### Allowed variation@@ -537,14 +535,6 @@ single-select BaseTypeahead behavior.**Reference:** `component:Tokenizer/DEC-3`**Decider:** `imdreamrunner`, `2026-10-23`-Implementation gap: the sheet presentation is implemented but not yet-exposed; `TokenizerProps` offers no `experimental.presentation` while its user-experience is being finished, and every field renders the popover-presentation. Astryx's own packages reach the implementation through the-internal entry `@astryxdesign/core/internal/tokenizer-presentation`-(`architecture:react-component-runtime` INV13); the rows below are verified-through it.-Tokenizer offers its touch surface through the `presentation` option of theoptional `experimental` prop object, with the values `popover`, `bottom-sheet`,and `adaptive` that the selection controls use. The option is marked@@ -605,13 +595,11 @@ the sheet's dialog of 47 — BottomSheet's dialog, panel, handle and edge tint7; the sheet body 2; the search row with its clear action 19; the list 16(the list element, its scroll host, and two checkbox rows of 7 with indicatorand position); the sheet's live region 1; the re-hosted surfaces host 2. A-pending Clear all confirmation adds 20 while it is open; the footer adds 9-(the counts above are of the implementation as it stands, whose footer-renders only while the query is empty; with the pinned footer of FR18 the open-coarse count includes those 9 in every state, and the counts are re-measured-when the implementation matches). The forced `bottom-sheet` presentation-renders the same elements under either pointer (114 at rest, 165 open at "e",-its dialog 53 with the story's create row of 6). At rest the coarse pointer+pending Clear all confirmation adds 20 while it is open; the footer, pinned+in every state (FR18), adds 9, so the open coarse count at the query "e" is+174 with it; the counts are re-measured when either surface changes. The forced `bottom-sheet` presentation+renders the same elements under either pointer (114 at rest, 174 open at "e",+its dialog 62 with the create row of 6 and the pinned footer of 9). At rest the coarse pointernever has more elements than the fine one: nothing of the sheet is in the DOMuntil a press. The exception covers the closed `adaptive` trigger and the open sheet; itscounts are re-measured when either surface changes.@@ -621,12 +609,6 @@ counts are re-measured when either surface changes.**Reference:** `component:Tokenizer/DEC-4`**Decider:** `imdreamrunner`, `2026-11-02`-Implementation gap: Core's sheet commits each edit at once and closes with-Done; the draft, Save, the pinned footer, and the discard confirmation are the-Lab prototype's behavior, which this record states as the contract-(FR18, FR19, FR22–FR24, FR26, FR27). The hold-back of DEC-3 stands until the-implementation matches.-The sheet edits a draft: every row toggle, create, and Clear all changes theselection the sheet shows, and `value` changes once, when Save reports thedraft through `onChange` with the last net edit as its `change` (FR26). Adiff --git a/packages/core/package.json b/packages/core/package.jsonindex 7fbaca35f2..4f14c57f6b 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -829,10 +829,10 @@"types": "./dist/internal/touch.d.ts","default": "./dist/internal/touch.js"},- "./internal/tokenizer-presentation": {- "source": "./src/internal/tokenizer-presentation.ts",- "types": "./dist/internal/tokenizer-presentation.d.ts",- "default": "./dist/internal/tokenizer-presentation.js"+ "./internal/touch-sheet": {+ "source": "./src/internal/touch-sheet.ts",+ "types": "./dist/internal/touch-sheet.d.ts",+ "default": "./dist/internal/touch-sheet.js"}},"files": [diff --git a/packages/core/src/Field/PanelSearchInput.tsx b/packages/core/src/Field/PanelSearchInput.tsxindex 521a62b428..db6d3fff73 100644--- a/packages/core/src/Field/PanelSearchInput.tsx+++ b/packages/core/src/Field/PanelSearchInput.tsx@@ -58,6 +58,7 @@ import {} from '../theme/tokens.stylex';import type {BaseProps} from '../BaseProps';import {textEntryTraitAttributes} from './textEntryTraits';+import {inputWrapperStyles} from './inputStyles.stylex';const styles = stylex.create({// Gutter only. Matches the option list's own padding so the field below@@ -185,6 +186,14 @@ export interface PanelSearchInputProps extends Omit<* the field to the same height as its rows.*/fieldXstyle?: StyleXStyles;+ /**+ * Draw the field as the shared input box — the input border, accent while+ * focused, surface and radius — instead of the borderless panel row. A+ * touch sheet is a full-width surface, not a bordered panel, so its field+ * reads as a form input.+ * @default false+ */+ hasInputBox?: boolean;}/**@@ -208,6 +217,7 @@ export function PanelSearchInput({onBlur,onContainerKeyDown,fieldXstyle,+ hasInputBox = false,xstyle,className,style,@@ -268,6 +278,7 @@ export function PanelSearchInput({{...stylex.props(styles.field,isKeyboardFocus && styles.fieldKeyboardFocus,+ hasInputBox && inputWrapperStyles.base,fieldXstyle,)}><Icon icon="search" size="sm" color="secondary" xstyle={styles.icon} />diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjsindex b7e698cf90..17a60d4835 100644--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs@@ -292,6 +292,13 @@ export const docs = {type: 'CSSProperties',description: 'Inline styles for the visual control box.',},+ {+ name: 'experimental',+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",+ stability: 'experimental',+ description:+ "Experimental options: anything in this object may change or be removed in a patch release, and omitting it keeps the stable behavior. presentation (default 'popover') chooses how the field presents its choices. popover is the inline combobox with its anchored suggestion menu. bottom-sheet replaces it with a trigger showing the selected tokens that opens one tall modal sheet: a search row on top, full-width checkbox rows that keep their place while the sheet is open, a Create row with hasCreate, and a footer pinned in every state with a confirmed Clear all and Save; the sheet edits a draft, so onChange fires once, when Save commits it, and a swipe, scrim or Escape close of a changed draft asks before discarding. adaptive uses the bottom sheet on compact touch screens and the popover otherwise, resolved the same way Selector resolves it. In the sheet presentation the trigger is the control (ref, id, aria-* and data-* reach it; with experimental passed, ref also accepts a Ref<HTMLInputElement | HTMLButtonElement> — an input-only ref still type-checks against that wider type, but with adaptive or bottom-sheet it receives the trigger button at runtime, so type the ref for both elements; TokenizerProps keeps its released ref type and gains only the optional experimental), and renderItem, renderToken, endContent, hasClear, hasEntriesOnFocus, menuWidth, tokenOverflowBehavior and hasAutoFocus have no surface to act on; the field warns once in development when they are passed. For example: <Tokenizer label=\"Tags\" searchSource={tagSource} value={tags} onChange={setTags} hasCreate experimental={{presentation: 'adaptive'}} />.",+ },],theming: {targets: [@@ -631,6 +638,13 @@ export const docsZh = {type: 'CSSProperties',description: '可视控件框的内联样式。',},+ {+ name: 'experimental',+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",+ stability: 'experimental',+ description:+ "实验性选项:此对象中的任何内容都可能在补丁版本中更改或移除;省略它即保持稳定行为。presentation(默认 'popover')决定字段如何呈现选项:popover 为内联组合框及其锚定建议菜单;bottom-sheet 改为一个显示已选标记的触发按钮,点按后打开一个高的模态底部面板——顶部为搜索行,下方为整行复选框行(面板打开期间位置保持不变),hasCreate 时有「创建」行,底部固定显示需确认的「全部清除」和「保存」;面板编辑的是草稿,onChange 仅在「保存」提交时触发一次,草稿有改动时滑动、点击遮罩或按 Escape 关闭会先询问是否放弃;adaptive 在紧凑触摸屏上使用底部面板,其他情况使用 popover,解析方式与 Selector 相同。在底部面板呈现中,触发按钮即为控件(ref、id、aria-* 和 data-* 都作用于它;传入 experimental 后,ref 也接受 Ref<HTMLInputElement | HTMLButtonElement>——仅为输入框类型的 ref 在这个更宽的类型下仍能通过类型检查,但在 adaptive 或 bottom-sheet 下运行时收到的是触发按钮,因此请为两种元素声明 ref 的类型;TokenizerProps 保留已发布的 ref 类型,仅新增可选的 experimental);renderItem、renderToken、endContent、hasClear、hasEntriesOnFocus、menuWidth、tokenOverflowBehavior 和 hasAutoFocus 没有作用对象,传入时开发模式下会警告一次。例如:<Tokenizer label=\"标签\" searchSource={tagSource} value={tags} onChange={setTags} hasCreate experimental={{presentation: 'adaptive'}} />。",+ },],theming: {targets: [@@ -830,5 +844,7 @@ export const docsDense = {'Icon at input start, before tokens. Icon name, SVG component, or ReactNode.',endContent: 'Content at input row end. For buttons, counts, controls.',handleRef: 'Imperative handle for focus() and blur() control.',+ experimental:+ "Experimental; may change in a patch. presentation: 'popover' (default, inline combobox) | 'bottom-sheet' (trigger + one searchable modal sheet of checkbox rows editing a draft that Save commits; onChange fires once, on Save) | 'adaptive' (sheet on compact touch, else popover).",},};diff --git a/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx b/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsxindex be6ccc66f3..5e7ca712b5 100644--- a/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx@@ -4,10 +4,8 @@* @input Uses vitest, TokenizerProps and Tokenizer* @output Type-level proof that the exported `TokenizerProps` stays an* interface callers can extend and `Omit` (its `ref` typed for the combobox- * input as released), that the public component names no `experimental`- * presentation, and that only the internal `TokenizerWithPresentation`- * admits the presentation options and a `ref` that also accepts the sheet- * presentation's trigger button+ * input as released), and that only the experimental opt-in admits a `ref`+ * that also accepts the sheet presentation's trigger button* @position Core type tests; checked by `tsc`, with `@ts-expect-error`* marking the shapes that must keep failing*/@@ -15,7 +13,6 @@ import {createRef, type ComponentProps} from 'react';import {describe, it, expect} from 'vitest';import type {SearchableItem} from '../Typeahead/types';import {Tokenizer, type TokenizerProps} from './Tokenizer';-import {TokenizerWithPresentation} from '../internal/tokenizer-presentation';type Item = SearchableItem;const source = {search: () => [], bootstrap: () => []};@@ -65,22 +62,13 @@ export function compiles() {onChange={() => {}}ref={inputRef}/>- {/* The public props name no presentation. */}<TagsFieldsearchSource={source}value={[]}onChange={() => {}}- // @ts-expect-error -- `experimental` is not on TokenizerProps+ ref={inputRef}experimental={{presentation: 'adaptive'}}/>- <Tokenizer- label="Tags"- searchSource={source}- value={[]}- onChange={() => {}}- // @ts-expect-error -- nor on the public component- experimental={{presentation: 'bottom-sheet'}}- />{/* The stable shape: ref is the combobox input's. */}<Tokenizerlabel="Tags"@@ -89,8 +77,8 @@ export function compiles() {onChange={() => {}}ref={inputRef}/>- {/* The internal signature admits the presentation and the wider ref. */}- <TokenizerWithPresentation+ {/* The experimental opt-in admits the wider ref. */}+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -98,8 +86,8 @@ export function compiles() {ref={wideRef}experimental={{presentation: 'adaptive'}}/>- {/* An input-typed ref is still fine there. */}- <TokenizerWithPresentation+ {/* An input-typed ref is still fine with the opt-in. */}+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -107,12 +95,12 @@ export function compiles() {ref={inputRef}experimental={{}}/>+ {/* @ts-expect-error -- without experimental, ref keeps the released input-only type */}<Tokenizerlabel="Tags"searchSource={source}value={[]}onChange={() => {}}- // @ts-expect-error -- the public ref keeps the released input-only typeref={wideRef}/></>@@ -120,7 +108,7 @@ export function compiles() {}describe('Tokenizer props type', () => {- it('keeps TokenizerProps an interface that extends and Omit-wraps, with no presentation option on the public component (type-checked above)', () => {+ it('keeps TokenizerProps an interface that extends and Omit-wraps (type-checked above)', () => {expect(typeof compiles).toBe('function');});});diff --git a/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx b/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsxindex 54de7b82d0..64a91b1b28 100644--- a/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.ssr.test.tsx@@ -20,7 +20,7 @@ import type {SearchableItem, SearchSource} from '../Typeahead/types';// their whole module graph, which takes seconds, and many times that on a// busy machine. Each fresh module graph below runs these modules again// without that cost.-import '../internal/tokenizer-presentation';+import './Tokenizer';import './TokenizerBottomSheet';const ITEMS: SearchableItem[] = [@@ -89,10 +89,9 @@ async function hydrateFreshTokenizer(options: HydrationOptions,) {vi.resetModules();- const {TokenizerWithPresentation} =- await import('../internal/tokenizer-presentation');+ const {Tokenizer} = await import('./Tokenizer');const tree = (- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex b1337692dc..5b4d9a1293 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -6,16 +6,10 @@* @file Tokenizer.tsx* @input Uses React, BaseTypeahead, Field, Token, useAnnounce,* useAdaptivePresentation, and TokenizerBottomSheet (lazy)- * @output Exports Tokenizer multi-select typeahead component, and the- * internal TokenizerWithPresentation signature the `internal/tokenizer-presentation`- * entry re-exports+ * @output Exports Tokenizer multi-select typeahead component* @position Composed component; forwards DOM ref and exposes focus control via- * handleRef. The sheet presentation — a trigger that opens- * TokenizerBottomSheet — is implemented but not exposed: `TokenizerProps`- * offers no `experimental.presentation` while its user experience is being- * finished (`component:Tokenizer` DEC-3, implementation gap), and only- * Astryx's own packages reach it through the internal entry- * (`architecture:react-component-runtime` INV13).+ * handleRef. The experimental `presentation` option swaps the inline+ * combobox for a trigger that opens TokenizerBottomSheet.** SYNC: When modified, update:* - /packages/core/src/Tokenizer/index.ts@@ -96,6 +90,7 @@ import {composeEventHandlers, mergeProps} from '../utils';import {joinAriaIDs} from '../utils/inputAria';import {isFocusDetached} from '../utils/focusReturn';import {themeProps} from '../utils/themeProps';+import type {SheetDraftChange} from '../internal/sheetDraft';import type {TokenizerBottomSheetProps} from './TokenizerBottomSheet';import {useResolvedRequired} from '../hooks/useResolvedRequired';import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';@@ -148,36 +143,6 @@ export interface TokenizerHandle {blur(): void;}-/**- * The presentation options the sheet-capable signature admits. Not public:- * `TokenizerProps` has no `experimental` while the sheet's user experience is- * being finished; Astryx's own packages reach the sheet through- * `@astryxdesign/core/internal/tokenizer-presentation`.- */-export interface TokenizerPresentationOptions {- /**- * How the field presents its choices.- * - `'popover'`: the inline combobox with its anchored suggestion menu —- * the stable behavior.- * - `'bottom-sheet'`: a trigger showing the selected tokens that opens one- * tall modal sheet: a search row on top, full-width checkbox rows that- * keep their place while the sheet is open, a create row with- * `hasCreate`, and a footer with a confirmed Clear all and Done. Suited- * to compact touch screens, where the inline combobox competes with the- * software keyboard.- * - `'adaptive'`: the bottom sheet on compact coarse-pointer screens,- * otherwise the popover — the same resolution Selector uses.- *- * In the sheet presentation the trigger is the control: `ref`, `id`,- * `aria-*`, and `data-*` reach it. `renderItem`, `renderToken`,- * `endContent`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`,- * `tokenOverflowBehavior`, and `hasAutoFocus` have no surface to act on- * and warn once in development.- * @default 'popover'- */- presentation?: 'popover' | 'bottom-sheet' | 'adaptive';-}-export interface TokenizerProps<T extends SearchableItem> extends Omit<FieldInputBaseProps<HTMLInputElement>,'onChange' | 'onFocus' | 'onBlur' | 'onKeyDown'@@ -335,26 +300,58 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<ref?: React.Ref<HTMLInputElement>;/** Imperative handle ref for focus/blur control. */handleRef?: React.Ref<TokenizerHandle>;+ /**+ * Experimental options, outside the stable compatibility promise: anything+ * in this object may change or be removed in a patch release. Omit it for+ * the stable behavior.+ * @experimental+ */+ experimental?: {+ /**+ * How the field presents its choices.+ * - `'popover'`: the inline combobox with its anchored suggestion menu —+ * the stable behavior.+ * - `'bottom-sheet'`: a trigger showing the selected tokens that opens one+ * tall modal sheet: a search row on top, full-width checkbox rows that+ * keep their place while the sheet is open, a create row with+ * `hasCreate`, and a footer pinned in every state with a confirmed Clear+ * all and Save. The sheet edits a draft: `onChange` fires once, when Save+ * commits it, and a swipe, scrim or Escape close of a changed draft asks+ * before discarding. Suited to compact touch screens, where the inline+ * combobox competes with the software keyboard.+ * - `'adaptive'`: the bottom sheet on compact coarse-pointer screens,+ * otherwise the popover — the same resolution Selector uses.+ *+ * In the sheet presentation the trigger is the control: `ref`, `id`,+ * `aria-*`, and `data-*` reach it. `renderItem`, `renderToken`,+ * `endContent`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`,+ * `tokenOverflowBehavior`, and `hasAutoFocus` have no surface to act on+ * and warn once in development.+ * @experimental+ * @default 'popover'+ */+ presentation?: 'popover' | 'bottom-sheet' | 'adaptive';+ };}/**- * The props of the sheet-capable signature: `TokenizerProps` plus the- * presentation options and a `ref` that also accepts the sheet presentation's- * trigger button, the control it stands for there. Not public: reached only- * as `TokenizerWithPresentation` through the internal entry, so the released- * `TokenizerProps` — an interface, so `interface X extends TokenizerProps<T>`,- * `Omit<TokenizerProps<T>, …>` and `ComponentProps<typeof Tokenizer>` keep- * their released shapes — names no presentation.+ * The props the experimental opt-in admits. `experimental` is present, and+ * `ref` also accepts the sheet presentation's trigger button, the control it+ * stands for there. Only the overload below reaches this type. `TokenizerProps`+ * stays the component's declared props type: it is an interface, so+ * `interface X extends TokenizerProps<T>`, `Omit<TokenizerProps<T>, …>` and+ * `ComponentProps<typeof Tokenizer>` keep their released shapes.*/-export type TokenizerWithPresentationProps<T extends SearchableItem> = Omit<+type TokenizerExperimentalProps<T extends SearchableItem> = Omit<TokenizerProps<T>,- 'ref'+ 'ref' | 'experimental'> & {- /** How the field presents its choices; see `TokenizerPresentationOptions`. */- experimental?: TokenizerPresentationOptions;+ /** @experimental */+ experimental: NonNullable<TokenizerProps<T>['experimental']>;/*** Ref forwarded to the control: the combobox input in the popover* presentation, the trigger button in the sheet presentation.+ * @experimental*/ref?: React.Ref<HTMLInputElement | HTMLButtonElement>;};@@ -724,10 +721,13 @@ function EndLane({);}-// The public signature names no presentation: `ComponentProps<typeof-// Tokenizer>` and every public call resolve against `TokenizerProps`. The-// implementation also reads the presentation options, reached only through-// `TokenizerWithPresentation` below.+// Keep this overload first. TypeScript resolves `ComponentProps<typeof+// Tokenizer>` against the last overload, so that type stays the stable props.+// A call that passes `experimental` matches this one and may pass the wider+// `ref`.+export function Tokenizer<T extends SearchableItem>(+ props: TokenizerExperimentalProps<T>,+): React.JSX.Element;export function Tokenizer<T extends SearchableItem>(props: TokenizerProps<T>,): React.JSX.Element;@@ -781,7 +781,7 @@ export function Tokenizer<T extends SearchableItem>({'aria-describedby': ariaDescribedByProp,'aria-labelledby': ariaLabelledByProp,...restProps-}: TokenizerWithPresentationProps<T>): React.JSX.Element {+}: TokenizerProps<T> | TokenizerExperimentalProps<T>): React.JSX.Element {const isEffectivelyRequired = useResolvedRequired({isRequired, isOptional});const {rest, container} = useFieldInputStyling('Tokenizer', restProps, {containerXstyle,@@ -844,6 +844,17 @@ export function Tokenizer<T extends SearchableItem>({},[onChangeQuery],);+ // Save's one report. The sheet announced each edit as it happened, so+ // nothing is announced here; a field that is disabled at Save reports+ // nothing.+ const handleSheetCommit = useCallback(+ (items: T[], change: SheetDraftChange<T>) => {+ if (!isDisabled) {+ onChange(items, change);+ }+ },+ [isDisabled, onChange],+ );// Set around a focus move the field makes itself — a presentation swap// handing focus from one control to the other — so the receiving control// does not report it as focus entering from outside.@@ -1717,15 +1728,13 @@ export function Tokenizer<T extends SearchableItem>({label={label}searchSource={searchSource}value={value}- isAtMax={isAtMax}+ maxEntries={maxEntries}hasCreate={hasCreate}maxMenuItems={maxMenuItems ?? 10}minQueryLength={minQueryLength ?? 1}debounceMs={debounceMs ?? 150}emptySearchText={emptySearchText}- onAdd={handleAdd}- onRemove={handleRemove}- onClearAll={() => handleClearAll({silent: true})}+ onCommit={handleSheetCommit}onChangeQuery={handleSheetQueryChange}/>)}@@ -1832,19 +1841,3 @@ export function Tokenizer<T extends SearchableItem>({}Tokenizer.displayName = 'Tokenizer';--/**- * The same component with the sheet presentation reachable: `experimental`- * (`presentation: 'popover' | 'bottom-sheet' | 'adaptive'`) and a `ref` that- * also takes the trigger button. Not public — re-exported only by- * `@astryxdesign/core/internal/tokenizer-presentation`, the entry reserved- * for Astryx's own packages (`architecture:react-component-runtime` INV13),- * while the sheet's user experience is being finished (`component:Tokenizer`- * DEC-3). The public `Tokenizer` renders the popover presentation for every- * field.- */-export const TokenizerWithPresentation = Tokenizer as <- T extends SearchableItem,->(- props: TokenizerWithPresentationProps<T>,-) => React.JSX.Element;diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsxindex 9abd8f8d36..6aec0631f6 100644--- a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx@@ -28,11 +28,11 @@ import {} from '@testing-library/react';import {createRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';-import type {TokenizerChange} from './Tokenizer';-import {TokenizerWithPresentation} from '../internal/tokenizer-presentation';+import {Tokenizer, type TokenizerChange} from './Tokenizer';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {__resetDevWarnings} from '../utils/devWarning';-import {colorVars} from '../theme/tokens.stylex';+import {colorVars, sizeVars, spacingVars} from '../theme/tokens.stylex';+import {inputWrapperStyles} from '../Field/inputStyles.stylex';import type {SearchSource, SearchableItem} from '../Typeahead/types';import {COMPACT_TOUCH_PRESENTATION_QUERY as COMPACT_TOUCH_QUERY} from '../hooks/useAdaptivePresentation';@@ -83,7 +83,7 @@ function Harness({}) {const [value, setValue] = useState<SearchableItem[]>(initial);return (- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={value}@@ -164,7 +164,7 @@ afterEach(() => vi.unstubAllGlobals());describe('Tokenizer experimental.presentation (FR16)', () => {it('keeps the inline combobox when experimental is omitted', () => {render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -179,7 +179,7 @@ describe('Tokenizer experimental.presentation (FR16)', () => {it('keeps the inline combobox for an empty experimental object and for popover', () => {const {unmount} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -277,10 +277,8 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(design.lastElementChild).toHaveAttribute('data-size', 'md');fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));- expect(spy).toHaveBeenCalledWith(- [ITEMS[0], ITEMS[1], ITEMS[3]],- expect.objectContaining({type: 'add'}),- );+ // The draft changed; `value` and `onChange` wait for Save (FR26).+ expect(spy).not.toHaveBeenCalled();await waitFor(() =>expect(screen.getByRole('checkbox', {name: 'Energizer'})).toBeChecked(),);@@ -292,10 +290,8 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {]);fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));- expect(spy).toHaveBeenLastCalledWith(- [ITEMS[0], ITEMS[3]],- expect.objectContaining({type: 'remove'}),- );+ expect(spy).not.toHaveBeenCalled();+ expect(screen.getByRole('checkbox', {name: 'Eng'})).not.toBeChecked();expect(checkboxLabels()).toEqual(['Design','Eng',@@ -303,7 +299,13 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {'Energizer',]);- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ // Save reports the whole draft once, with the last edit that holds.+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith([ITEMS[0], ITEMS[3]], {+ item: ITEMS[1],+ type: 'remove',+ });expect(trigger).toHaveAttribute('aria-expanded', 'false');await act(async () => {@@ -380,7 +382,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('keeps the inline popover presentation on the shared live region', async () => {render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0], ITEMS[1]]}@@ -426,22 +428,20 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {screen.queryByRole('checkbox', {name: 'Create "Custom"'}),).not.toBeInTheDocument();const create = await screen.findByRole('button', {name: 'Add Custom'});+ // The footer stays pinned while searching (FR18).expect(- screen.queryByRole('button', {name: 'Clear all'}),- ).not.toBeInTheDocument();- expect(- screen.queryByRole('button', {name: 'Done'}),- ).not.toBeInTheDocument();+ screen.getByRole('button', {name: 'Clear all'}),+ ).toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();expect(create).toHaveAttribute('data-size', 'lg');expect(screen.getByText('Create "Custom"')).toBeInTheDocument();await act(async () => {fireEvent.click(create);});- expect(spy).toHaveBeenCalledWith(- [{id: 'Custom', label: 'Custom'}],- expect.objectContaining({type: 'create'}),- );- await waitFor(() => expect(trigger).toHaveTextContent('Custom'));+ // The created item joins the draft; the trigger and `onChange` wait+ // for Save (FR22, FR26), which then reports the create.+ expect(spy).not.toHaveBeenCalled();+ expect(trigger).not.toHaveTextContent('Custom');expect(search).toHaveValue('');const custom = await screen.findByRole('checkbox', {name: 'Custom'});expect(custom).toBeChecked();@@ -460,6 +460,13 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {':scope > [data-astryx-modal-live-region="polite"]',),).not.toHaveTextContent('Create');+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith([{id: 'Custom', label: 'Custom'}], {+ item: {id: 'Custom', label: 'Custom'},+ type: 'create',+ });+ await waitFor(() => expect(trigger).toHaveTextContent('Custom'));} finally {modalSpy.mockRestore();}@@ -496,7 +503,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {),};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Items"searchSource={longSource}value={[]}@@ -599,7 +606,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('searches within the same sheet and shows the no-results state (FR18, FR20)', async () => {const onChangeQuery = vi.fn();const {rerender} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -630,7 +637,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// A string emptySearchText becomes the empty state's title.rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -664,7 +671,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {});try {render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={searchOnly}value={[]}@@ -698,7 +705,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {?.textContent ?? '',).toBe('');// The footer still closes the sheet (FR18); Clear all is spent.- expect(within(dialog).getByRole('button', {name: 'Done'})).toBeVisible();+ expect(within(dialog).getByRole('button', {name: 'Save'})).toBeVisible();expect(within(dialog).getByRole('button', {name: 'Clear all'}),).toHaveAttribute('aria-disabled', 'true');@@ -745,7 +752,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {await screen.findByRole('dialog', {name: 'Tags'});expect(sheetDom().dialog).not.toBeNull();- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});@@ -822,14 +829,14 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {}});- it('keeps large equal-width Clear all and Done footer actions while guarding the bulk clear (FR24)', async () => {+ it('keeps large equal-width Clear all and Save footer actions while guarding the bulk clear (FR24)', async () => {const spy = vi.fn();render(<Harness spy={spy} />);fireEvent.click(openTrigger());await screen.findByRole('checkbox', {name: 'Energizer'});const clearAll = screen.getByRole('button', {name: 'Clear all'});- const done = screen.getByRole('button', {name: 'Done'});+ const done = screen.getByRole('button', {name: 'Save'});expect(clearAll).toHaveAttribute('data-size', 'lg');expect(clearAll).toHaveAttribute('data-variant', 'secondary');expect(done).toHaveAttribute('data-size', 'lg');@@ -849,16 +856,16 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {fireEvent.click(within(confirmation).getByRole('button', {name: 'Clear selection'}),);- expect(spy).toHaveBeenLastCalledWith(- [],- expect.objectContaining({type: 'remove', item: ITEMS[1]}),- );+ // The clear empties the draft; `value` waits for Save (FR24, FR26).+ expect(spy).not.toHaveBeenCalled();await waitFor(() =>expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute('aria-disabled','true',),);+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenLastCalledWith([], {item: ITEMS[1], type: 'remove'});});it('keeps a disabled trigger focusable without opening the sheet (FR17; AST-085 FR1, FR2)', () => {@@ -911,7 +918,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {bootstrap: () => many,};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={manySource}value={[many[1], many[15]]}@@ -956,7 +963,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// "Enzo" is a created value the source never returns; the source has// three "en" matches (Eng, Engineer, Energizer), capped to two rows.render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[{id: 'Enzo', label: 'Enzo'}]}@@ -1064,7 +1071,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {function InlineSourceHarness() {const [value, setValue] = useState<SearchableItem[]>([ITEMS[0]]);return (- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"// A new object every render, as a caller writing the source inline// produces; the selection change on each toggle re-renders.@@ -1157,21 +1164,21 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {debounceMs: 0,experimental: {presentation: 'bottom-sheet' as const},};- const {rerender} = render(<TokenizerWithPresentation {...props} />);+ const {rerender} = render(<Tokenizer {...props} />);fireEvent.click(openTrigger());await screen.findByRole('dialog', {name: 'Tags'});fireEvent.change(screen.getByLabelText('Search Tags'), {target: {value: 'En'},});onChangeQuery.mockClear();- rerender(<TokenizerWithPresentation {...props} isDisabled />);+ rerender(<Tokenizer {...props} isDisabled />);fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});// Nothing the person did changed the query, so nothing is reported, and// the caller's mirror and the sheet agree on the next open.expect(onChangeQuery).not.toHaveBeenCalled();- rerender(<TokenizerWithPresentation {...props} />);+ rerender(<Tokenizer {...props} />);fireEvent.click(openTrigger());await screen.findByRole('dialog', {name: 'Tags'});expect(screen.getByLabelText('Search Tags')).toHaveValue('En');@@ -1188,7 +1195,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {minQueryLength: 3,experimental: {presentation: 'bottom-sheet' as const},};- const {rerender} = render(<TokenizerWithPresentation {...props} />);+ const {rerender} = render(<Tokenizer {...props} />);fireEvent.click(openTrigger());await screen.findByRole('dialog', {name: 'Tags'});// Two characters: below the threshold, so nothing is searched.@@ -1196,7 +1203,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {target: {value: 'En'},});// The field becomes disabled: the sheet closes, keeping the query.- rerender(<TokenizerWithPresentation {...props} isDisabled />);+ rerender(<Tokenizer {...props} isDisabled />);fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});@@ -1204,7 +1211,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {await waitFor(() =>expect(screen.queryByRole('dialog')).not.toBeInTheDocument(),);- rerender(<TokenizerWithPresentation {...props} />);+ rerender(<Tokenizer {...props} />);fireEvent.click(openTrigger());const dialog = await screen.findByRole('dialog', {name: 'Tags'});expect(screen.getByLabelText('Search Tags')).toHaveValue('En');@@ -1236,7 +1243,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('closes the sheet and returns focus to the trigger when the field becomes disabled (FR17; AST-085 FR2)', async () => {const {rerender} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1253,7 +1260,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(search).toHaveFocus();rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1273,7 +1280,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(trigger).toHaveAttribute('aria-disabled', 'true');// Re-enabling does not reopen it.rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1290,7 +1297,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {render(<><span id="hint">Up to five</span>- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0], ITEMS[1]]}@@ -1361,7 +1368,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const onFocus = vi.fn();const onKeyDown = vi.fn();render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1398,7 +1405,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const onBlur = vi.fn();render(<>- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1421,7 +1428,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {screen.getByLabelText('Search Tags').focus();expect(onBlur).not.toHaveBeenCalled();// Done: focus returns from the sheet, not from outside.- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});@@ -1436,7 +1443,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(onFocus).toHaveBeenCalledTimes(2);fireEvent.click(trigger);await screen.findByRole('dialog', {name: 'Tags'});- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});@@ -1449,7 +1456,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const onBlur = vi.fn();render(<>- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1471,7 +1478,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(onBlur).not.toHaveBeenCalled();// Done: BottomSheet's return focus is the one focus the trigger gets in// this visit, so it is the entry, and is reported.- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));fireEvent.transitionEnd(document.querySelector('.astryx-bottom-sheet')!, {propertyName: 'transform',});@@ -1494,7 +1501,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {event.preventDefault();});render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1522,7 +1529,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {__resetDevWarnings();const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});const {rerender} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -1537,7 +1544,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(warn.mock.calls[0][0]).toMatch(/`hasClear`, `menuWidth`/);expect(warn.mock.calls[0][0]).toMatch(/bottom-sheet presentation/);rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0], ITEMS[1]]}@@ -1550,7 +1557,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(warn).toHaveBeenCalledTimes(1);warn.mockClear();render(- <TokenizerWithPresentation+ <Tokenizerlabel="Other"searchSource={source}value={[]}@@ -1586,7 +1593,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// Default debounceMs (150), so the debounce window is under test too.// hasCreate, so the create row's timing is under test as well.render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={slow}value={[]}@@ -1689,11 +1696,13 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(indicator).toHaveClass(name);}// The checked row still toggles, making room (FR23).+ // Unchecking the selected row makes room in the draft: the limit is read+ // against the draft, so the inert row becomes selectable before Save.fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));- expect(spy).toHaveBeenLastCalledWith(- [],- expect.objectContaining({type: 'remove'}),- );+ expect(spy).not.toHaveBeenCalled();+ expect(row).not.toHaveAttribute('aria-disabled');+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenLastCalledWith([], {item: ITEMS[0], type: 'remove'});});it('paints a disabled trigger, its placeholder, and its tokens GrayText in forced colors (AST-085 FR6)', () => {@@ -1758,7 +1767,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {],};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={withAction}value={[]}@@ -1815,7 +1824,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(trigger).toBeInTheDocument();expect(screen.queryByRole('combobox')).not.toBeInTheDocument();- fireEvent.click(screen.getByRole('button', {name: 'Done'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));// The sheet is closing; the trigger stays mounted to take focus back,// and the inline input does not appear yet.expect(trigger).toBeInTheDocument();@@ -1837,7 +1846,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('types ref for the control it reaches: the input without experimental, input or trigger with it', () => {const inputRef = createRef<HTMLInputElement>();const {unmount} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -1849,7 +1858,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {unmount();const wideRef = createRef<HTMLInputElement | HTMLButtonElement>();const {rerender} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -1860,7 +1869,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {);expect(wideRef.current).toBe(screen.getByRole('combobox'));rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -1876,7 +1885,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const search = vi.fn(source.search);const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={{...source, search}}value={[ITEMS[0]]}@@ -1927,7 +1936,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {});try {render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2029,7 +2038,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {},};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={flaky}value={[]}@@ -2096,7 +2105,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {),};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={slow}value={[]}@@ -2161,7 +2170,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {),};render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={slow}value={[]}@@ -2253,7 +2262,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const onChangeQuery = vi.fn();const search = vi.fn(source.search);render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={{...source, search}}value={[]}@@ -2309,7 +2318,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const [query, setQuery] = useState('');return (<>- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2355,7 +2364,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {try {// Default debounceMs (150): the open must not wait for it.render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0]]}@@ -2432,7 +2441,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const errors = vi.spyOn(console, 'error').mockImplementation(() => {});try {render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={thenable}value={[]}@@ -2477,7 +2486,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// The default popover, with and without the experimental object: no// query is evaluated and no listener is registered.const {unmount} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2630,7 +2639,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {const onFocus = vi.fn();const stableRef = () => {};const field = (isDisabled: boolean, ref: () => void = stableRef) => (- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2666,7 +2675,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('moves no focus when a control re-attaches without a swap, such as a new ref callback (FR16; react-component-runtime INV6)', () => {const onFocus = vi.fn();const {rerender} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2682,7 +2691,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// A new inline ref detaches and re-attaches the same input while it// holds focus: nothing is handed off, and no focus is reported again.rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2697,7 +2706,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// Focus elsewhere: a later re-attach takes nothing back.input.blur();rerender(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}@@ -2712,7 +2721,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {it('carries hidden form inputs and the field chrome in the sheet presentation', () => {const {container} = render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0], ITEMS[1]]}@@ -2738,7 +2747,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {isDisabled: boolean,) => (<form>- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[ITEMS[0], ITEMS[1]]}@@ -2764,6 +2773,188 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {});});+describe('Tokenizer sheet draft, Save and dismissal (FR18, FR23, FR24, FR26, FR27)', () => {+ it('draws the search field as the shared input box at the lg input height above the 44px rows — the input border with its forced-colors branch, accent on focus, element radius, surface — unlike the borderless panel field the dropdowns share (FR18)', () => {+ const atoms = (className: string | undefined) =>+ (className ?? '').split(' ').filter(name => !name.includes('__'));+ // The same shared box the inline field composes, then the sheet's own+ // height and padding on top (later wins per property, as in the sheet).+ const own = stylex.create({+ field: {+ minHeight: sizeVars['--size-element-lg'],+ paddingBlock: spacingVars['--spacing-1'],+ },+ touch: {minHeight: 44},+ });+ render(<Harness />);+ fireEvent.click(openTrigger());+ const input = screen.getByLabelText('Search Tags');+ const field = input.parentElement!;+ for (const name of atoms(+ stylex.props(inputWrapperStyles.base, own.field).className,+ )) {+ expect(field).toHaveClass(name);+ }+ for (const name of atoms(stylex.props(own.touch).className)) {+ expect(field).not.toHaveClass(name);+ }+ });++ it('keeps Clear all and Save pinned while searching, while pending and with an empty query (FR18)', async () => {+ render(<Harness />);+ fireEvent.click(openTrigger());+ await screen.findByRole('checkbox', {name: 'Energizer'});+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();+ fireEvent.change(screen.getByLabelText('Search Tags'), {+ target: {value: 'zzz'},+ });+ await screen.findByText('No results found');+ expect(screen.getByRole('button', {name: 'Clear all'})).toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();+ });++ it('Save with an unchanged draft reports nothing and closes (FR26)', async () => {+ const spy = vi.fn();+ render(<Harness spy={spy} />);+ const trigger = openTrigger();+ fireEvent.click(trigger);+ await screen.findByRole('checkbox', {name: 'Energizer'});+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).not.toHaveBeenCalled();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ });++ it("Save's change is the last edit that still holds: a create then an add reports the add; an add then its own undo falls back to the other net edit (FR26)", async () => {+ const spy = vi.fn();+ render(<Harness spy={spy} hasCreate initial={[]} />);+ fireEvent.click(openTrigger());+ const search = await screen.findByLabelText('Search Tags');+ fireEvent.change(search, {target: {value: 'Custom'}});+ await act(async () => {+ fireEvent.click(await screen.findByRole('button', {name: 'Add Custom'}));+ });+ await screen.findByRole('checkbox', {name: 'Design'});+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith(+ [{id: 'Custom', label: 'Custom'}, ITEMS[0]],+ {item: ITEMS[0], type: 'add'},+ );+ });++ it('an add that is undone before Save does not hold: Save names the edit that does (FR26)', async () => {+ const spy = vi.fn();+ render(<Harness spy={spy} initial={[ITEMS[0]]} />);+ fireEvent.click(openTrigger());+ await screen.findByRole('checkbox', {name: 'Energizer'});+ // Remove Design (holds), add Eng, then undo the add: the last edit is a+ // removal of Eng, which was never selected at open, so it does not hold;+ // the removal of Design does.+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenCalledWith([], {item: ITEMS[0], type: 'remove'});+ });++ it('a clean swipe, scrim or Escape dismissal closes directly; a changed draft asks first, Keep editing returns focus to the search field, Discard changes closes without a report (FR27)', async () => {+ const spy = vi.fn();+ render(<Harness spy={spy} />);+ const trigger = openTrigger();+ fireEvent.click(trigger);+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});+ await screen.findByRole('checkbox', {name: 'Energizer'});+ // Clean: Escape closes at once, nothing asked — also after a row is+ // unchecked and checked again, which leaves the selection as it was.+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));+ fireEvent.keyDown(sheet, {key: 'Escape'});+ expect(screen.queryByRole('alertdialog')).toBeNull();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(spy).not.toHaveBeenCalled();+ // Reopen, change the draft, Escape: the confirmation, safe action first.+ await act(async () => {+ fireEvent.click(trigger);+ });+ await screen.findByRole('checkbox', {name: 'Energizer'});+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));+ fireEvent.keyDown(screen.getByRole('dialog', {name: 'Tags'}), {+ key: 'Escape',+ });+ const confirmation = await screen.findByRole('alertdialog');+ expect(confirmation).toHaveTextContent('Discard changes?');+ expect(confirmation).toHaveTextContent(+ "Your changes to Tags haven't been saved.",+ );+ const [destructive, safe] = within(confirmation).getAllByRole('button');+ expect(destructive).toHaveAccessibleName('Discard changes');+ expect(safe).toHaveAccessibleName('Keep editing');+ expect(safe).toHaveAttribute('data-autofocus');+ // Keep editing: still open, the draft intact, focus on the search field.+ fireEvent.click(safe);+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();+ expect(screen.getByRole('checkbox', {name: 'Energizer'})).toBeChecked();+ expect(spy).not.toHaveBeenCalled();+ // Discard changes: closes without a report; `value` unchanged.+ fireEvent.keyDown(screen.getByRole('dialog', {name: 'Tags'}), {+ key: 'Escape',+ });+ fireEvent.click(+ within(await screen.findByRole('alertdialog')).getByRole('button', {+ name: 'Discard changes',+ }),+ );+ expect(spy).not.toHaveBeenCalled();+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(trigger).toHaveAccessibleDescription(/2 selected Design Eng/);+ });++ it('Save over the limit is aria-disabled with the limit as its reason, and works again once the draft is within it (FR23)', async () => {+ const spy = vi.fn();+ render(<Harness spy={spy} initial={[ITEMS[0], ITEMS[1]]} maxEntries={1} />);+ fireEvent.click(openTrigger());+ await screen.findByRole('checkbox', {name: 'Energizer'});+ const save = screen.getByRole('button', {name: 'Save'});+ expect(save).toHaveAttribute('aria-disabled', 'true');+ expect(save).not.toHaveAttribute('disabled');+ expect(save).toHaveAccessibleDescription('Select up to 1 item');+ fireEvent.click(save);+ expect(spy).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));+ expect(screen.getByRole('button', {name: 'Save'})).not.toHaveAttribute(+ 'aria-disabled',+ );+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));+ expect(spy).toHaveBeenCalledWith([ITEMS[0]], {+ item: ITEMS[1],+ type: 'remove',+ });+ });++ it('a direct vertical drag on the results moves focus from the search field to the sheet panel, keeping the query; a tap or a short move does not (FR18; AST-085 FR4)', async () => {+ render(<Harness />);+ fireEvent.click(openTrigger());+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});+ await screen.findByRole('checkbox', {name: 'Energizer'});+ const search = screen.getByLabelText('Search Tags');+ fireEvent.change(search, {target: {value: 'En'}});+ search.focus();+ const results = list();+ const touches = (clientY: number) => [{clientY}];+ fireEvent.touchStart(results, {touches: touches(100)});+ fireEvent.touchMove(results, {touches: touches(104)});+ expect(search).toHaveFocus();+ fireEvent.touchMove(results, {touches: touches(110)});+ expect(search).not.toHaveFocus();+ expect(document.activeElement).not.toBe(document.body);+ expect(sheet.contains(document.activeElement)).toBe(true);+ expect(document.activeElement).toHaveAttribute('tabindex', '-1');+ expect(search).toHaveValue('En');+ });+});+describe('Tokenizer sheet under the BottomSheet stack (component:BottomSheet FR8, FR9; AST-003 FR18)', () => {const stackSummary = () =>getBottomSheetStackForTests().map(({element, isOpen, view}) => {@@ -2793,7 +2984,7 @@ describe('Tokenizer sheet under the BottomSheet stack (component:BottomSheet FR8isOpen={isHostOpen}onOpenChange={setIsHostOpen}label="Value">- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={value}@@ -2829,10 +3020,16 @@ describe('Tokenizer sheet under the BottomSheet stack (component:BottomSheet FR8await waitFor(() =>expect(within(sheet).getByRole('checkbox', {name: 'Eng'})).toBeChecked(),);- // Escape reaches only the top sheet: the field sheet closes, the host- // stays open and is the top again; focus returns to the trigger inside- // the host (FR9: the opener, inside the revealed sheet).+ // Escape reaches only the top sheet. The draft is changed, so the field+ // sheet asks first (FR27); Discard changes closes it, the host stays open+ // and is the top again; focus returns to the trigger inside the host+ // (FR9: the opener, inside the revealed sheet).fireEvent.keyDown(sheet, {key: 'Escape'});+ const confirmation = await screen.findByRole('alertdialog');+ expect(stackSummary()).toEqual(['Value:covered:1', 'Tags:top:0']);+ fireEvent.click(+ within(confirmation).getByRole('button', {name: 'Discard changes'}),+ );finishExit(sheet);await waitFor(() =>expect(@@ -2843,8 +3040,8 @@ describe('Tokenizer sheet under the BottomSheet stack (component:BottomSheet FR8expect(host).not.toHaveAttribute('data-sheet-stack');expect(host).toHaveAttribute('open');await waitFor(() => expect(openTrigger()).toHaveFocus());- // The field's selection survived the dismissal.- expect(openTrigger()).toHaveAccessibleDescription(/2 selected Design Eng/);+ // The discarded toggle never reached the field's value.+ expect(openTrigger()).toHaveAccessibleDescription(/1 selected Design/);});it("the Clear all confirmation opens over the field's sheet and returns into it; a toast raised meanwhile lands in the field's dialog (AST-003 FR18)", async () => {diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsxindex d281618293..5d3755e159 100644--- a/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.tsx@@ -37,7 +37,6 @@ import {} from 'react';import {flushSync} from 'react-dom';import * as stylex from '@stylexjs/stylex';-import {AlertDialog} from '../AlertDialog/AlertDialog';import {BottomSheet} from '../BottomSheet/BottomSheet';import {Button} from '../Button/Button';import {EmptyState} from '../EmptyState/EmptyState';@@ -50,9 +49,21 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {useAnnounce} from '../hooks/useAnnounce';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';import {Text} from '../Text/Text';+import {SheetConfirmation} from '../internal/SheetConfirmation';+import {+ hasSameSelection,+ nameSheetDraftChange,+ type SheetDraftChange,+} from '../internal/sheetDraft';+import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';import {warnOnce} from '../utils/devWarning';import type {SearchableItem, SearchSource} from '../Typeahead/types';-import {colorVars, radiusVars, spacingVars} from '../theme/tokens.stylex';+import {+ colorVars,+ radiusVars,+ sizeVars,+ spacingVars,+} from '../theme/tokens.stylex';import {registerEnglishFallback,useComponentTranslator,@@ -88,12 +99,12 @@ const styles = stylex.create({searchRow: {paddingBlockEnd: spacingVars['--spacing-2'],},- // PanelSearchInput sizes its field to the 32px option rows of a dropdown- // panel. The sheet's rows are 44px thumb targets, so the field grows to- // match them and the query reads as the first row of the list.+ // A dropdown panel is already a bordered box, so its search field has no+ // border. The sheet is not, so its field takes the shared input box at the+ // `lg` height.searchField: {- minHeight: 44,- paddingBlock: spacingVars['--spacing-2'],+ minHeight: sizeVars['--size-element-lg'],+ paddingBlock: spacingVars['--spacing-1'],},list: {display: 'flex',@@ -192,7 +203,10 @@ const styles = stylex.create({export interface TokenizerBottomSheetProps<T extends SearchableItem> {/** Whether the sheet is open. */isOpen: boolean;- /** Called with `false` when the sheet dismisses or Done is pressed. */+ /**+ * Called with `false` when the sheet closes: Save, a clean dismissal, or a+ * confirmed discard.+ */onOpenChange: (isOpen: boolean) => void;/** The trigger, which takes focus back after the sheet closes. */finalFocusRef: RefObject<HTMLElement | null>;@@ -208,10 +222,10 @@ export interface TokenizerBottomSheetProps<T extends SearchableItem> {/** The field label; names the sheet, the search field, and the list. */label: string;searchSource: SearchSource<T>;- /** The committed selection. */+ /** The committed selection; the draft the sheet edits starts from it. */value: T[];- /** Whether `maxEntries` is reached. */- isAtMax: boolean;+ /** The selection limit, enforced on the draft. */+ maxEntries: number | undefined;hasCreate: boolean;maxMenuItems: number;minQueryLength: number;@@ -219,38 +233,35 @@ export interface TokenizerBottomSheetProps<T extends SearchableItem> {/** The no-results message; a string becomes the empty state's title. */emptySearchText: ReactNode;/**- * Tokenizer's add path — duplicate checks and the create sentinel — asked- * to stay silent: the sheet announces the change itself, from inside its- * dialog, where `useAnnounce` routes it (`spec:AST-086` FR14). Returns- * whether the item was added.+ * Save's one report: the whole draft and the last edit that still holds.+ * The sheet announces each edit itself when it happens, from inside its+ * dialog, where `useAnnounce` routes it; nothing is announced on Save.*/- onAdd: (item: T, options: {silent: true}) => boolean;- /** Tokenizer's remove path, silent for the same reason. */- onRemove: (item: T, options: {silent: true}) => boolean;- /** Tokenizer's clear-all path. */- onClearAll: () => void;+ onCommit: (items: T[], change: SheetDraftChange<T>) => void;onChangeQuery?: (query: string) => void;}/*** The touch surface of Tokenizer's `bottom-sheet` presentation.*- * Rows keep their position while the sheet is open: the items selected when it- * opened lead, in `value` order, then selected items the results do not carry,- * then the results. Toggling a row changes its checkbox and nothing else; the- * next open takes a fresh snapshot and regroups selected-first.- */-/**- * The sheet: BottomSheet around the content. Split in two so the content —+ * One open sheet edits one draft that starts as `value`; rows, the create row+ * and Clear all change the draft, and Save reports it once. Rows keep their+ * position while the sheet is open: the items selected when it opened lead,+ * in `value` order, then draft-selected items the results do not carry, then+ * the results; the next open takes a fresh snapshot and regroups+ * selected-first.+ *+ * The sheet is BottomSheet around the content, split in two so the content —* search, rows, footer, and every announcement about them — is rendered* inside the sheet's dialog, where `useAnnounce` routes into it while it is- * open (`spec:AST-086` FR14): a component that renders a modal and announces- * about its content is inside that modal only when the announcing code is.+ * open: a component that renders a modal and announces about its content is+ * inside that modal only when the announcing code is.** The outer part also tells the content how a close came about: a close the- * person made (Done, swipe, scrim, Escape) clears the query so the next open+ * person made (Save, swipe, scrim, Escape) clears the query so the next open* lists the bootstrap set, while a close the field forced (becoming disabled- * while open) keeps it (`component:Tokenizer` FR18).+ * while open) keeps it. A swipe, scrim or Escape close of a changed draft is+ * routed to the content first, which asks before discarding.*/export function TokenizerBottomSheet<T extends SearchableItem>({isOpen,@@ -263,7 +274,9 @@ export function TokenizerBottomSheet<T extends SearchableItem>({// this handle, from the closing event, so a close the field forces by// becoming disabled (which never comes through here) keeps it.const clearQueryRef = useRef<(() => void) | null>(null);- const requestClose = () => {+ // Set by the content: a dismissal asks first while the draft is changed.+ const requestDismissRef = useRef<(() => void) | null>(null);+ const closeSheet = () => {clearQueryRef.current?.();onOpenChange(false);};@@ -273,8 +286,10 @@ export function TokenizerBottomSheet<T extends SearchableItem>({onOpenChange={next => {if (next) {onOpenChange(true);+ } else if (requestDismissRef.current != null) {+ requestDismissRef.current();} else {- requestClose();+ closeSheet();}}}finalFocusRef={finalFocusRef}@@ -286,7 +301,8 @@ export function TokenizerBottomSheet<T extends SearchableItem>({isOpen={isOpen}label={label}clearQueryRef={clearQueryRef}- onRequestClose={requestClose}+ requestDismissRef={requestDismissRef}+ onCloseSheet={closeSheet}/></BottomSheet>);@@ -300,27 +316,28 @@ type TokenizerSheetContentProps<T extends SearchableItem> = Omit<> & {/** Set by the content: clears and reports its query; called on a user close. */clearQueryRef: RefObject<(() => void) | null>;- /** Close the sheet as the person's own act (Done). */- onRequestClose: () => void;+ /** Set by the content: a swipe, scrim or Escape close, which asks first while the draft is changed. */+ requestDismissRef: RefObject<(() => void) | null>;+ /** Close the sheet as the person's own act. */+ onCloseSheet: () => void;};function TokenizerSheetContent<T extends SearchableItem>({isOpen,initialQuery,clearQueryRef,- onRequestClose,+ requestDismissRef,+ onCloseSheet,label,searchSource,value,- isAtMax,+ maxEntries,hasCreate,maxMenuItems,minQueryLength,debounceMs,emptySearchText,- onAdd,- onRemove,- onClearAll,+ onCommit,onChangeQuery,}: TokenizerSheetContentProps<T>) {const t = useComponentTranslator();@@ -348,6 +365,8 @@ function TokenizerSheetContent<T extends SearchableItem>({// sheet makes goes through `useAnnounce`, called inside the sheet's// dialog, so FR14 routes the words into it while the sheet is open.const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);+ const [isDiscardConfirmationOpen, setIsDiscardConfirmationOpen] =+ useState(false);const clearAllRef = useRef<HTMLButtonElement>(null);const announce = useAnnounce();const closeClearConfirmation = (confirmed: boolean) => {@@ -360,7 +379,28 @@ function TokenizerSheetContent<T extends SearchableItem>({clearAllRef.current?.focus();}};- const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);+ // Keep editing: the confirmation is gone, and focus returns to the search+ // field, where the sheet's own reading order starts.+ const closeDiscardConfirmation = () => {+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the confirmation must be gone before focus moves back into the sheet+ flushSync(() => setIsDiscardConfirmationOpen(false));+ searchRef.current?.focus({preventScroll: true});+ };++ // ---- draft ----+ // One open sheet edits one draft. The caller's `value` is unchanged until+ // Save, so a dismissal can discard cleanly; `lastDraftChangeRef` is the+ // edit Save names when it still holds.+ const [valueAtOpen, setValueAtOpen] = useState<T[]>(() => [...value]);+ const [draftValue, setDraftValue] = useState<T[]>(() => [...value]);+ const lastDraftChangeRef = useRef<SheetDraftChange<T> | null>(null);+ const isDraftDirty = !hasSameSelection(valueAtOpen, draftValue);+ const selectedIds = useMemo(+ () => new Set(draftValue.map(v => v.id)),+ [draftValue],+ );+ const isAtMax = maxEntries != null && draftValue.length >= maxEntries;+ const isDraftOverMax = maxEntries != null && draftValue.length > maxEntries;// ---- sheet session ----// Starts from the field's copy, which `onChangeQuery` keeps current, so the@@ -421,7 +461,12 @@ function TokenizerSheetContent<T extends SearchableItem>({setWasOpen(isOpen);if (isOpen) {setSelectedItemsAtOpen(value);+ setValueAtOpen([...value]);+ setDraftValue([...value]);+ lastDraftChangeRef.current = null;setRenderedItemCount(LIST_RENDER_BATCH_SIZE);+ setIsClearConfirmationOpen(false);+ setIsDiscardConfirmationOpen(false);// An open lists the bootstrap set, or searches a query kept across a// close the field forced (FR18), and that load is pending; a kept// query below the threshold leaves nothing pending, since no search@@ -533,7 +578,7 @@ function TokenizerSheetContent<T extends SearchableItem>({selectedAtOpenMatches.map(item => item.id),);const resultIds = new Set(results.map(item => item.id));- const selectedItemsMissingFromResults = value.filter(+ const selectedItemsMissingFromResults = draftValue.filter(item =>!selectedAtOpenIds.has(item.id) &&!resultIds.has(item.id) &&@@ -547,7 +592,7 @@ function TokenizerSheetContent<T extends SearchableItem>({...selectedItemsMissingFromResults,...results.filter(item => !selectedAtOpenIds.has(item.id)),];- }, [query, results, selectedItemsAtOpen, value]);+ }, [query, results, selectedItemsAtOpen, draftValue]);const renderedItems = visibleItems.slice(0, renderedItemCount);@@ -601,7 +646,7 @@ function TokenizerSheetContent<T extends SearchableItem>({const lowered = trimmedQuery.toLowerCase();if (selectedIds.has(trimmedQuery) ||- value.some(item => item.label.toLowerCase() === lowered) ||+ draftValue.some(item => item.label.toLowerCase() === lowered) ||results.some(item => item.label.toLowerCase() === lowered)) {return null;@@ -616,7 +661,7 @@ function TokenizerSheetContent<T extends SearchableItem>({isAtMax,isPending,selectedIds,- value,+ draftValue,results,t,]);@@ -642,6 +687,43 @@ function TokenizerSheetContent<T extends SearchableItem>({onChangeQuery?.(next);};+ // A swipe, scrim or Escape close: asks first while the draft is changed.+ 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();+ };++ // Focus moves to the sheet's panel, not the page body behind the modal.+ // The keyboard then leaves and the query stays.+ const listDragProps = useDismissSearchOnTouchDrag(+ () => [searchRef.current],+ () => listRef.current?.closest<HTMLElement>('[tabindex="-1"]'),+ );+const searchLabel = t('@astryx.tokenizer.search', {label});// An empty state only once the search has settled; while pending the busy// row above stands in for it.@@ -725,6 +807,7 @@ function TokenizerSheetContent<T extends SearchableItem>({placeholder={t('@astryx.tokenizer.searchPlaceholder')}value={query}onValueChange={handleQueryChange}+ hasInputBoxfieldXstyle={styles.searchField}/></div>@@ -736,6 +819,7 @@ function TokenizerSheetContent<T extends SearchableItem>({aria-busy={isPending || undefined}data-rendered-count={renderedItems.length}data-total-count={visibleItems.length}+ {...listDragProps}onFocusCapture={event => {isRowFocusedRef.current =event.target instanceof HTMLElement &&@@ -775,13 +859,18 @@ function TokenizerSheetContent<T extends SearchableItem>({variant="secondary"size="lg"onClick={() => {- if (onAdd(createItem, {silent: true})) {- // The created value, as the inline field announces it; the- // item's label is the row's caption ("Create …").- announce(- t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),- );- }+ const base = {id: trimmedQuery, label: trimmedQuery};+ const createdItem = base as T;+ setDraftValue(current => [...current, createdItem]);+ lastDraftChangeRef.current = {+ item: createdItem,+ type: 'create',+ };+ // The created value, as the inline field announces it; the+ // item's label is the row's caption ("Create …").+ announce(+ t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),+ );// The same path a typed change takes, so the bootstrap// reload shows its pending state and reports the change.handleQueryChange('');@@ -863,14 +952,18 @@ function TokenizerSheetContent<T extends SearchableItem>({return;}if (isSelected) {- if (onRemove(item, {silent: true})) {- announce(- t('@astryx.tokenizer.tokenRemoved', {- label: item.label,- }),- );- }- } else if (onAdd(item, {silent: true})) {+ 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,@@ -903,38 +996,44 @@ function TokenizerSheetContent<T extends SearchableItem>({</div>)}</div>- {isQueryEmpty && (- <div {...stylex.props(styles.footer)}>- <Button- label={t('@astryx.tokenizer.clearAll')}- variant="secondary"- size="lg"- isDisabled={value.length === 0}- // With a tooltip, Button's disabled mode is `aria-disabled`: the- // action keeps its focus order and says why it does nothing- // (`spec:AST-085` FR1), instead of leaving the tab order as a- // natively disabled button does — a confirmed Clear all returns- // focus here before the search field takes it (FR24).- tooltip={- value.length === 0- ? t('@astryx.tokenizer.nothingToClear')- : undefined- }- ref={clearAllRef}- onClick={() => setIsClearConfirmationOpen(true)}- xstyle={styles.footerAction}- />- <Button- label={t('@astryx.tokenizer.done')}- variant="primary"- size="lg"- onClick={onRequestClose}- xstyle={styles.footerAction}- />- </div>- )}+ <div {...stylex.props(styles.footer)}>+ <Button+ label={t('@astryx.tokenizer.clearAll')}+ variant="secondary"+ size="lg"+ isDisabled={draftValue.length === 0}+ // With a tooltip, Button's disabled mode is `aria-disabled`: the+ // action keeps its focus order and says why it does nothing+ // (`spec:AST-085` FR1), instead of leaving the tab order as a+ // natively disabled button does — a confirmed Clear all returns+ // focus here before the search field takes it (FR24).+ tooltip={+ draftValue.length === 0+ ? t('@astryx.tokenizer.nothingToClear')+ : undefined+ }+ ref={clearAllRef}+ onClick={() => setIsClearConfirmationOpen(true)}+ xstyle={styles.footerAction}+ />+ <Button+ label={t('@astryx.tokenizer.save')}+ variant="primary"+ size="lg"+ isDisabled={isDraftOverMax}+ // Over the limit (a `value` already over it at open, or a lowered+ // limit while open) Save keeps its tab stop and says why it waits.+ tooltip={+ isDraftOverMax+ ? t('@astryx.tokenizer.selectionLimit', {count: maxEntries ?? 0})+ : undefined+ }+ onClick={handleSave}+ xstyle={styles.footerAction}+ />+ </div>{isClearConfirmationOpen && (- <AlertDialog+ <SheetConfirmationisOpenonOpenChange={next => {if (!next) {@@ -943,13 +1042,40 @@ function TokenizerSheetContent<T extends SearchableItem>({}}title={t('@astryx.tokenizer.clearAllTitle')}description={t('@astryx.tokenizer.clearAllDescription', {label})}+ cancelLabel={t('@astryx.alertDialog.cancel')}actionLabel={t('@astryx.tokenizer.clearSelection')}onAction={() => {- onClearAll();+ // A clear is a removal of the draft's last item, for Save's+ // `remove` when it is the last edit that holds.+ 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={() => {+ setIsDiscardConfirmationOpen(false);+ onCloseSheet();+ }}+ />+ )}</div>);}diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsxindex 7272ea33ea..b02be2cb40 100644--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx@@ -65,8 +65,7 @@ const {Selector} = await import('../Selector');const {MultiSelector} = await import('../MultiSelector');const {CommandPalette} = await import('../CommandPalette');const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');-const {TokenizerWithPresentation} =- await import('../internal/tokenizer-presentation');+const {Tokenizer} = await import('../Tokenizer/Tokenizer');const {createStaticSource} = await import('../Typeahead/createStaticSource');const {TooltipWithTriggerBehavior} = await import('../Tooltip/Tooltip');@@ -189,7 +188,7 @@ const ADOPTERS: Record<string, () => Promise<void>> = {// module's load alone outlasts it.await import('../Tokenizer/TokenizerBottomSheet');render(- <TokenizerWithPresentation+ <Tokenizerlabel="Tags"searchSource={source}value={[]}diff --git a/packages/lab/src/internal/MobileSheetConfirmation.test.tsx b/packages/core/src/internal/SheetConfirmation.test.tsxsimilarity index 94%rename from packages/lab/src/internal/MobileSheetConfirmation.test.tsxrename to packages/core/src/internal/SheetConfirmation.test.tsxindex 1e9534e26b..82b77e6e0f 100644--- a/packages/lab/src/internal/MobileSheetConfirmation.test.tsx+++ b/packages/core/src/internal/SheetConfirmation.test.tsx@@ -2,7 +2,7 @@import {fireEvent, render, screen, within} from '@testing-library/react';import {beforeEach, describe, expect, it, vi} from 'vitest';-import {MobileSheetConfirmation} from './MobileSheetConfirmation';+import {SheetConfirmation} from './SheetConfirmation';// jsdom has no native modal presentation; keep the public Dialog path active.beforeEach(() => {@@ -21,7 +21,7 @@ function setup() {const onAction = vi.fn();const onOpenChange = vi.fn();render(- <MobileSheetConfirmation+ <SheetConfirmationisOpenonOpenChange={onOpenChange}title="Discard changes?"@@ -35,7 +35,7 @@ function setup() {return {dialog, onAction, onOpenChange};}-describe('MobileSheetConfirmation', () => {+describe('SheetConfirmation', () => {it('keeps the alert-dialog theme target and accessible copy', () => {const {dialog} = setup();expect(dialog).toHaveClass('astryx-alert-dialog');diff --git a/packages/lab/src/internal/MobileSheetConfirmation.tsx b/packages/core/src/internal/SheetConfirmation.tsxsimilarity index 60%rename from packages/lab/src/internal/MobileSheetConfirmation.tsxrename to packages/core/src/internal/SheetConfirmation.tsxindex d84b810906..11193c59f7 100644--- a/packages/lab/src/internal/MobileSheetConfirmation.tsx+++ b/packages/core/src/internal/SheetConfirmation.tsx@@ -3,28 +3,32 @@'use client';/**- * @file MobileSheetConfirmation.tsx- * @input Public Core Dialog, layout, text and action primitives; caller-owned copy- * @output Private confirmation shared by MobileTokenizer and MobilePowerSearch- * @position Lab-only mobile sheet confirmation owner; not a public export+ * @file SheetConfirmation.tsx+ * @input Dialog, Layout, Heading, Text, Button; caller-owned copy+ * @output SheetConfirmation — the confirmation a touch sheet opens over+ * itself for Clear all and for discarding a changed draft+ * @position Core-internal, shared by the Tokenizer sheet and the PowerSearch+ * sheets; not a public export*- * Core AlertDialog fixes its purpose to form and its safe action to ghost.- * These Lab flows instead allow scrim dismissal and use separated, full-width- * large actions with the secondary safe action focused first. Keep that- * difference here, while preserving the existing alert-dialog theme target.+ * AlertDialog fixes its purpose to form and its safe action to ghost. A touch+ * sheet's confirmation allows scrim dismissal. Its two full-width large+ * actions are stacked and separated: the destructive action first in reading+ * order, the safe action focused first. The alert-dialog theme target stays.*/import {useId} from 'react';import * as stylex from '@stylexjs/stylex';-import {Button} from '@astryxdesign/core/Button';-import {Dialog} from '@astryxdesign/core/Dialog';-import {Heading} from '@astryxdesign/core/Heading';-import {Layout, LayoutContent, LayoutFooter} from '@astryxdesign/core/Layout';-import {Stack} from '@astryxdesign/core/Stack';-import {Text} from '@astryxdesign/core/Text';-import {themeProps} from '@astryxdesign/core/utils';+import {Button} from '../Button/Button';+import {Dialog} from '../Dialog/Dialog';+import {Heading} from '../Heading/Heading';+import {Layout} from '../Layout/Layout';+import {LayoutContent} from '../Layout/LayoutContent';+import {LayoutFooter} from '../Layout/LayoutFooter';+import {Stack} from '../Stack/Stack';+import {Text} from '../Text/Text';+import {themeProps} from '../utils/themeProps';-interface MobileSheetConfirmationProps {+export interface SheetConfirmationProps {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;title: string;@@ -38,7 +42,7 @@ const styles = stylex.create({action: {width: '100%'},});-export function MobileSheetConfirmation({+export function SheetConfirmation({isOpen,onOpenChange,title,@@ -46,7 +50,7 @@ export function MobileSheetConfirmation({cancelLabel,actionLabel,onAction,-}: MobileSheetConfirmationProps) {+}: SheetConfirmationProps) {const titleId = useId();const descriptionId = useId();return (diff --git a/packages/core/src/internal/sheetDraft.test.ts b/packages/core/src/internal/sheetDraft.test.tsnew file mode 100644index 0000000000..30ccbd2392--- /dev/null+++ b/packages/core/src/internal/sheetDraft.test.ts@@ -0,0 +1,60 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+import {describe, expect, it} from 'vitest';+import {hasSameSelection, nameSheetDraftChange} from './sheetDraft';++const a = {id: 'a', label: 'A'};+const b = {id: 'b', label: 'B'};+const c = {id: 'c', label: 'C'};++describe('hasSameSelection', () => {+ it('ignores order, so a row unchecked and checked again is no change', () => {+ expect(hasSameSelection([a, b], [b, a])).toBe(true);+ expect(hasSameSelection([a, b], [a])).toBe(false);+ expect(hasSameSelection([a], [a, b])).toBe(false);+ expect(hasSameSelection([], [])).toBe(true);+ });+});++describe('nameSheetDraftChange', () => {+ it('returns null for an unchanged draft', () => {+ expect(nameSheetDraftChange([a], [a], {item: b, type: 'add'})).toBeNull();+ });++ it('names the last edit while it still holds', () => {+ expect(+ nameSheetDraftChange([a], [a, b, c], {item: c, type: 'add'}),+ ).toEqual({item: c, type: 'add'});+ expect(+ nameSheetDraftChange([a], [a, c], {item: c, type: 'create'}),+ ).toEqual({item: c, type: 'create'});+ expect(+ nameSheetDraftChange([a, b], [a], {item: b, type: 'remove'}),+ ).toEqual({item: b, type: 'remove'});+ });++ it('after an undone edit, falls back to a removal when the last edit removed, else to the net add, else to the net removal', () => {+ // Removed a, added b, removed b again: the last edit (remove b) does not+ // hold, b was never selected at open; the net removal of a does.+ expect(nameSheetDraftChange([a], [], {item: b, type: 'remove'})).toEqual({+ item: a,+ type: 'remove',+ });+ // Added c, then re-added a after unchecking it: a was selected at open,+ // so that add does not hold; c is the net add.+ expect(nameSheetDraftChange([a], [c, a], {item: a, type: 'add'})).toEqual({+ item: c,+ type: 'add',+ });+ // The create of c is the net add; a later add that no longer holds keeps+ // the create type for c only when the last edit was that create.+ expect(nameSheetDraftChange([a], [a, c], {item: a, type: 'add'})).toEqual({+ item: c,+ type: 'add',+ });+ // Nothing added; a removal that is not the last edit.+ expect(nameSheetDraftChange([a, b], [b], {item: b, type: 'add'})).toEqual({+ item: a,+ type: 'remove',+ });+ });+});diff --git a/packages/core/src/internal/sheetDraft.ts b/packages/core/src/internal/sheetDraft.tsnew file mode 100644index 0000000000..7e24b489ff--- /dev/null+++ b/packages/core/src/internal/sheetDraft.ts@@ -0,0 +1,80 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file sheetDraft.ts+ * @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+ *+ * 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. A+ * dismissal asks before discarding only while the draft differs from the+ * selection at open, as a set: a row unchecked and checked again is no change.+ */++interface SheetDraftItem {+ id: string | number;+}++/** An edit of a sheet's draft, and the shape Save reports. */+export type SheetDraftChange<T> = {+ item: T;+ type: 'add' | 'create' | 'remove';+};++/** Whether two selections hold the same items, in any order. */+export function hasSameSelection<T extends SheetDraftItem>(+ a: ReadonlyArray<T>,+ b: ReadonlyArray<T>,+): boolean {+ if (a.length !== b.length) {+ return false;+ }+ const ids = new Set(a.map(item => item.id));+ return b.every(item => ids.has(item.id));+}++/**+ * The change Save reports for a draft that differs from the selection at+ * open, or `null` when nothing differs. The last edit names it when it still+ * holds: its item is in the draft and was not selected at open, or was+ * selected at open and is gone. Otherwise, after a removal, a `remove` names+ * an item that is gone; otherwise an `add` (`create` when the last edit+ * created that item) names an item that is new; otherwise a `remove` names+ * an item that is gone.+ */+export function nameSheetDraftChange<T extends SheetDraftItem>(+ valueAtOpen: ReadonlyArray<T>,+ draftValue: ReadonlyArray<T>,+ lastDraftChange: SheetDraftChange<T> | null,+): SheetDraftChange<T> | null {+ const wasSelected = (id: T['id']) => valueAtOpen.some(item => item.id === id);+ const isSelected = (id: T['id']) => draftValue.some(item => item.id === id);+ const added = draftValue.find(item => !wasSelected(item.id));+ const removed = valueAtOpen.find(item => !isSelected(item.id));+ const lastChangeIsNet =+ lastDraftChange != null &&+ (lastDraftChange.type === 'remove'+ ? wasSelected(lastDraftChange.item.id) &&+ !isSelected(lastDraftChange.item.id)+ : isSelected(lastDraftChange.item.id) &&+ !wasSelected(lastDraftChange.item.id));+ if (lastChangeIsNet) {+ return lastDraftChange;+ }+ if (lastDraftChange?.type === 'remove' && removed != null) {+ return {item: removed, type: 'remove'};+ }+ if (added != null) {+ const type: SheetDraftChange<T>['type'] =+ lastDraftChange?.item.id === added.id && lastDraftChange.type === 'create'+ ? 'create'+ : 'add';+ return {item: added, type};+ }+ if (removed != null) {+ return {item: removed, type: 'remove'};+ }+ return null;+}diff --git a/packages/core/src/internal/tokenizer-presentation.test.ts b/packages/core/src/internal/tokenizer-presentation.test.tsdeleted file mode 100644index 8425c192e3..0000000000--- a/packages/core/src/internal/tokenizer-presentation.test.ts+++ /dev/null@@ -1,29 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.-/**- * @file tokenizer-presentation.test.ts- * @input The internal `internal/tokenizer-presentation` entry and the- * Tokenizer module- * @output Proof that the entry re-exports the same component the public- * Tokenizer entry ships, by name, and that the public Tokenizer barrel- * names no presentation- * @position Unit tests of packages/core/src/internal/tokenizer-presentation.ts- */-import {describe, expect, it} from 'vitest';--describe('internal/tokenizer-presentation', () => {- it('re-exports the one Tokenizer component under the sheet-capable name, the same value the public entry ships', async () => {- const entry: Record<string, unknown> =- await import('./tokenizer-presentation');- const tokenizer = await import('../Tokenizer/Tokenizer');- expect(entry.TokenizerWithPresentation).toBe(tokenizer.Tokenizer);- // Named re-exports only, nothing else.- expect(Object.keys(entry).sort()).toEqual(['TokenizerWithPresentation']);- });-- it('the public Tokenizer barrel exports no presentation surface', async () => {- const pub: Record<string, unknown> = await import('../Tokenizer');- expect(Object.keys(pub).sort()).toEqual(['Tokenizer']);- expect(pub).not.toHaveProperty('TokenizerWithPresentation');- expect(pub).not.toHaveProperty('TokenizerBottomSheet');- });-});diff --git a/packages/core/src/internal/tokenizer-presentation.ts b/packages/core/src/internal/tokenizer-presentation.tsdeleted file mode 100644index e2373db119..0000000000--- a/packages/core/src/internal/tokenizer-presentation.ts+++ /dev/null@@ -1,25 +0,0 @@-// Copyright (c) Meta Platforms, Inc. and affiliates.--/**- * @file tokenizer-presentation.ts- * @input Tokenizer's sheet-capable signature- * @output `@astryxdesign/core/internal/tokenizer-presentation`: the Tokenizer- * with its `presentation` options reachable, for Astryx's own packages- * @position An internal entry reserved for Astryx's own packages:- * undocumented, outside the public API and its compatibility promise- * (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in- * Core and Lab by the `@astryx/no-core-internal-import` lint rule- * (architecture:react-component-runtime INV13). The sheet presentation is- * implemented but not yet exposed: the public `TokenizerProps` offers no- * `experimental.presentation` while its user experience is being finished- * (`component:Tokenizer` DEC-3, implementation gap), and every public field- * renders the popover presentation. Named re-exports only.- *- * SYNC: When modified, update tokenizer-presentation.test.ts and- * scripts/sync-exports.js.- */-export {TokenizerWithPresentation} from '../Tokenizer/Tokenizer';-export type {- TokenizerPresentationOptions,- TokenizerWithPresentationProps,-} from '../Tokenizer/Tokenizer';diff --git a/packages/core/src/internal/touch-sheet.ts b/packages/core/src/internal/touch-sheet.tsnew file mode 100644index 0000000000..970353ccd9--- /dev/null+++ b/packages/core/src/internal/touch-sheet.ts@@ -0,0 +1,21 @@+// 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/internal/useDismissSearchOnTouchDrag.test.tsx b/packages/core/src/internal/useDismissSearchOnTouchDrag.test.tsxsimilarity index 78%rename from packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsxrename to packages/core/src/internal/useDismissSearchOnTouchDrag.test.tsxindex 33a834753b..4e8b1d413a 100644--- a/packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsx+++ b/packages/core/src/internal/useDismissSearchOnTouchDrag.test.tsx@@ -6,20 +6,27 @@ import userEvent from '@testing-library/user-event';import {describe, expect, it, vi} from 'vitest';import {useDismissSearchOnTouchDrag} from './useDismissSearchOnTouchDrag';-function Harness({hasSecondSearch = false}: {hasSecondSearch?: boolean}) {+function Harness({+ hasSecondSearch = false,+ hasFocusTarget = false,+}: {+ hasSecondSearch?: boolean;+ hasFocusTarget?: boolean;+}) {const firstRef = useRef<HTMLInputElement>(null);const secondRef = useRef<HTMLInputElement>(null);- const dragProps = useDismissSearchOnTouchDrag(() => [- firstRef.current,- secondRef.current,- ]);+ const panelRef = useRef<HTMLDivElement>(null);+ const dragProps = useDismissSearchOnTouchDrag(+ () => [firstRef.current, secondRef.current],+ hasFocusTarget ? () => panelRef.current : undefined,+ );return (- <>+ <div ref={panelRef} tabIndex={-1} aria-label="Panel"><input ref={firstRef} aria-label="First search" />{hasSecondSearch && <input ref={secondRef} aria-label="Second search" />}<input aria-label="Unrelated field" /><div role="group" aria-label="Results" {...dragProps} />- </>+ </div>);}@@ -34,6 +41,17 @@ function setup() {}describe('useDismissSearchOnTouchDrag', () => {+ it("moves focus to the caller's target at the drag threshold, so focus never lands on the page body behind an open modal", () => {+ render(<Harness hasFocusTarget />);+ const search = screen.getByRole('textbox', {name: 'First search'});+ const results = screen.getByRole('group', {name: 'Results'});+ search.focus();+ fireEvent.touchStart(results, {touches: touches(100)});+ fireEvent.touchMove(results, {touches: touches(108)});+ expect(screen.getByLabelText('Panel')).toHaveFocus();+ expect(document.activeElement).not.toBe(document.body);+ });+it('preserves typing across programmatic result scrolling', async () => {const {search, results} = setup();fireEvent.scroll(results, {target: {scrollTop: 300}});diff --git a/packages/lab/src/internal/useDismissSearchOnTouchDrag.ts b/packages/core/src/internal/useDismissSearchOnTouchDrag.tssimilarity index 51%rename from packages/lab/src/internal/useDismissSearchOnTouchDrag.tsrename to packages/core/src/internal/useDismissSearchOnTouchDrag.tsindex 1683a5c58c..b913e5cf88 100644--- a/packages/lab/src/internal/useDismissSearchOnTouchDrag.ts+++ b/packages/core/src/internal/useDismissSearchOnTouchDrag.ts@@ -4,14 +4,17 @@/*** @file useDismissSearchOnTouchDrag.ts- * @input Caller-owned search inputs and touch events from a separate results list- * @output Private touch handlers shared by the Lab mobile search sheets- * @position One owner for results-drag keyboard dismissal; not a public export+ * @input Caller-owned search inputs, a focus target, and touch events from a+ * separate results list+ * @output useDismissSearchOnTouchDrag — touch handlers for the results list+ * @position Core-internal, shared by the touch sheets; not a public export*- * A direct vertical touch drag dismisses only a focused caller-owned search.- * Scroll events are deliberately not observed: filtering can clamp scrollTop- * and fire scroll while someone is typing. Small moves, taps and multi-touch- * gestures leave focus alone. The hook acquires no external resource.+ * A direct vertical touch drag on the results moves focus off a focused+ * search input. The on-screen keyboard then leaves and the rows come into+ * view; the query stays. Focus goes to the caller's target (the sheet's+ * panel), never to the page body behind an open modal. Scroll events are not+ * observed: filtering can clamp scrollTop and fire scroll while someone is+ * typing. Small moves, taps and multi-touch gestures leave focus alone.*/import {useRef, type TouchEvent} from 'react';@@ -21,7 +24,8 @@ const DRAG_THRESHOLD_PX = 8;type SearchInput = HTMLInputElement | null | undefined;export function useDismissSearchOnTouchDrag(- getSearchInputs: () => readonly SearchInput[],+ getSearchInputs: () => ReadonlyArray<SearchInput>,+ getFocusTarget?: () => HTMLElement | null | undefined,) {const startYRef = useRef<number | null>(null);const reset = () => {@@ -49,7 +53,15 @@ export function useDismissSearchOnTouchDrag(const focusedSearch = getSearchInputs().find(input => input != null && input === document.activeElement,);- focusedSearch?.blur();+ if (focusedSearch == null) {+ return;+ }+ const target = getFocusTarget?.();+ if (target != null) {+ target.focus({preventScroll: true});+ } else {+ focusedSearch.blur();+ }},onTouchEnd: reset,onTouchCancel: reset,diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsxindex 5dee70905e..4d39081b4e 100644--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx@@ -142,8 +142,11 @@ import {typographyVars,} from '@astryxdesign/core/theme/tokens.stylex';import {isImeKeyEvent, isRenderable, rtlStyles} from '@astryxdesign/core/utils';-import {MobileSheetConfirmation} from '../internal/MobileSheetConfirmation';-import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';++import {+ SheetConfirmation,+ useDismissSearchOnTouchDrag,+} from '@astryxdesign/core/internal/touch-sheet';import {MobilePowerSearchValueEditor} from './MobilePowerSearchValueEditor';import {createContentSearchSource,@@ -889,10 +892,18 @@ export function MobilePowerSearch({// ------------------------------------------------------------------ focus --- const fieldPickerDragProps = useDismissSearchOnTouchDrag(() => [- contentSearchRef.current?.querySelector('input'),- fieldSearchRef.current?.querySelector('input'),- ]);+ // 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;@@ -2356,7 +2367,7 @@ export function MobilePowerSearch({</div></BottomSheet>- <MobileSheetConfirmation+ <SheetConfirmationisOpen={isClearConfirmationOpen}onOpenChange={setIsClearConfirmationOpen}title="Clear all filters?"diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsxindex 9c94a56100..2bdf677525 100644--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx@@ -5,7 +5,7 @@/*** @file MobileTokenizer.tsx* @input Public @astryxdesign/core components and hooks, plus private Lab- * mobile-sheet confirmation and search-drag dismissal owners+ * 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,@@ -72,8 +72,13 @@ import {sizeVars,spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';-import {MobileSheetConfirmation} from '../internal/MobileSheetConfirmation';-import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';+import {+ SheetConfirmation,+ hasSameSelection,+ nameSheetDraftChange,+ useDismissSearchOnTouchDrag,+ type SheetDraftChange,+} from '@astryxdesign/core/internal/touch-sheet';export type MobileTokenizerChange<T extends SearchableItem> =| {item: T; type: 'add'}@@ -130,18 +135,6 @@ const LIST_LOAD_MORE_THRESHOLD_PX = 200;// border = 3px. The same number is the row gap, so wrapped rows read evenly.const TOKEN_ROW_INSET = `calc(${spacingVars['--spacing-1']} - 1px)`;-type SheetDraftChange<T> = {- item: T;- type: 'add' | 'create' | 'remove';-};--function hasSameSelection<T extends SearchableItem>(a: T[], b: T[]): boolean {- return (- a.length === b.length &&- a.every(item => b.some(candidate => candidate.id === item.id))- );-}-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@@ -1018,39 +1011,15 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({if (isDraftOverMax) {return;}- if (isDraftDirty) {- const added = draftValue.find(- item => !valueAtOpen.some(openItem => openItem.id === item.id),- );- const removed = valueAtOpen.find(- item => !draftValue.some(draftItem => draftItem.id === item.id),- );- const lastDraftChange = lastDraftChangeRef.current;- const lastChangeIsNet =- lastDraftChange != null &&- (lastDraftChange.type === 'remove'- ? valueAtOpen.some(item => item.id === lastDraftChange.item.id) &&- !draftValue.some(item => item.id === lastDraftChange.item.id)- : draftValue.some(item => item.id === lastDraftChange.item.id) &&- !valueAtOpen.some(item => item.id === lastDraftChange.item.id));- let change: SheetDraftChange<T> | null = null;- if (lastChangeIsNet) {- change = lastDraftChange;- } else if (lastDraftChange?.type === 'remove' && removed != null) {- change = {item: removed, type: 'remove'};- } else if (added != null) {- const type: SheetDraftChange<T>['type'] =- lastDraftChange?.item.id === added.id &&- lastDraftChange.type === 'create'- ? 'create'- : 'add';- change = {item: added, type};- } else if (removed != null) {- change = {item: removed, type: 'remove'};- }- if (change != null) {- onCommit([...draftValue], change);- }+ const change = isDraftDirty+ ? nameSheetDraftChange(+ valueAtOpen,+ draftValue,+ lastDraftChangeRef.current,+ )+ : null;+ if (change != null) {+ onCommit([...draftValue], change);}onCloseSheet();};@@ -1058,7 +1027,12 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({const searchLabel = t('@astryx.tokenizer.search', {label});const noResultsTitle =emptySearchResultsText ?? t('@astryx.typeahead.emptySearchResults');- const listDragProps = useDismissSearchOnTouchDrag(() => [searchRef.current]);+ // 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)}>@@ -1245,7 +1219,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({/></div>{isClearConfirmationOpen && (- <MobileSheetConfirmation+ <SheetConfirmationisOpenonOpenChange={next => {if (!next) {@@ -1270,7 +1244,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({/>)}{isDiscardConfirmationOpen && (- <MobileSheetConfirmation+ <SheetConfirmationisOpenonOpenChange={next => {if (!next) {diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex e42eb6a13e..d9d8dabb44 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -238,7 +238,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [// public API, and allowed by lint only in Core and Lab// (architecture:react-component-runtime INV13).'internal/touch',- 'internal/tokenizer-presentation',+ 'internal/touch-sheet',];/**