An open source design system that's fully customizable and agent ready
TypeScript
fix(Tokenizer): the sheet presentation renders endContent and renderToken (#9902)
Xinzi Zhou12f63f5d0131
diff --git a/.changeset/tokenizer-sheet-end-content-render-token.md b/.changeset/tokenizer-sheet-end-content-render-token.mdnew file mode 100644index 0000000000..ddca761e4d--- /dev/null+++ b/.changeset/tokenizer-sheet-end-content-render-token.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Tokenizer: in the sheet presentation, `endContent` renders at the field's inline end and `renderToken` renders the field's tokens, as in the inline field, so the same props work on a phone under the `'adaptive'` default. Their own controls act without opening the sheet: an end-content button runs its handler, and a custom token's remove control commits `onChange` at once and moves focus to the trigger. A tap on a token, the placeholder or the field's empty space still opens the sheet. Before, the sheet dropped both props with a development warning. `renderItem`, `hasClear` (the sheet has its own Clear all), `hasEntriesOnFocus`, `menuWidth`, `tokenOverflowBehavior` and `hasAutoFocus` still apply to the inline field only.++@imdreamrunnerdiff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsxindex c833852ad3..ade7221ca4 100644--- a/apps/storybook/stories/Tokenizer.stories.tsx+++ b/apps/storybook/stories/Tokenizer.stories.tsx@@ -923,6 +923,51 @@ export const AdaptivePresentation: Story = {name: 'Adaptive (default)',};+/**+ * The sheet presentation keeps `endContent` at the field's inline end and+ * renders its tokens through `renderToken`, as the inline field does. The end+ * content's buttons and a token's own remove control act at once; a tap+ * anywhere else on the field opens the sheet. The grid column sizes the field,+ * so a test can narrow it.+ */+export const SheetPresentationEndContent: Story = {+ render: () => {+ const [value, setValue] = useState<SearchableItem[]>([+ sheetTags[0],+ sheetTags[1],+ sheetTags[2],+ sheetTags[3],+ ]);+ const [copies, setCopies] = useState(0);+ return (+ <div style={{display: 'grid', gridTemplateColumns: 'minmax(0, 400px)'}}>+ <Tokenizer+ label="Recipients"+ searchSource={sheetTagSource}+ value={value}+ onChange={items => setValue(items)}+ debounceMs={0}+ placeholder="Add recipients"+ presentation="bottom-sheet"+ renderToken={(item, onRemove) => (+ <Token label={item.label} onRemove={onRemove} />+ )}+ endContent={+ <Button+ label={`Cc (${copies})`}+ variant="ghost"+ size="sm"+ onClick={() => setCopies(count => count + 1)}+ />+ }+ />+ </div>+ );+ },+ name: 'Bottom sheet with end content and custom tokens',+ parameters: {viewport: {defaultViewport: 'mobile2'}},+};+/*** Disabled and at-limit states of the sheet presentation: the disabled* trigger stays focusable and does not open; at `maxEntries` the sheet'sdiff --git a/docs/specs/components/Tokenizer/Tokenizer.spec.md b/docs/specs/components/Tokenizer/Tokenizer.spec.mdindex ad9362b085..2518720201 100644--- a/docs/specs/components/Tokenizer/Tokenizer.spec.md+++ b/docs/specs/components/Tokenizer/Tokenizer.spec.md@@ -20,6 +20,7 @@ verified_by:packages/core/src/internal/sheetDraft.test.ts,packages/core/src/Tokenizer/Tokenizer.props-type.test.tsx,packages/core/src/Tokenizer/Tokenizer.composites.test.tsx,+ packages/core/src/Tokenizer/__tests__/TokenizerSheetField.a11y.chromium.spec.ts,packages/core/src/PowerSearch/PowerSearch.test.tsx,packages/core/src/Typeahead/Typeahead.test.tsx,packages/core/src/Layer/useLayer.test.tsx,@@ -61,9 +62,9 @@ system_specs:| Area | Contract || ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || Public contract | A stable `presentation` prop, `'popover' \| 'bottom-sheet' \| 'adaptive'` with `adaptive` the default, selects the surface (DEC-3); the sheet edits a draft committed by Save (DEC-4). `TokenizerProps` stays an interface whose `ref` keeps its released `Ref<HTMLInputElement>` type; the component also accepts `Ref<HTMLInputElement \| HTMLButtonElement>`, because the ref reaches the sheet's trigger. 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 sheet presentation — `bottom-sheet`, and the default `adaptive` on a compact coarse-pointer screen — 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). |+| 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 sheet presentation — `bottom-sheet`, and the default `adaptive` on a compact coarse-pointer screen — replaces the inline combobox with a field whose trigger 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, the field offers thumb-sized rows and a search field the keyboard does not cover. |-| Builder impact | None with a fine pointer or on a screen that is not compact. On a compact coarse-pointer screen a Tokenizer without `presentation` opens the sheet: `onChange` fires on Save, `ref` reaches the trigger, and the props of the inline combobox are not rendered. `presentation="popover"` keeps the inline combobox on every device. |+| Builder impact | None with a fine pointer or on a screen that is not compact. On a compact coarse-pointer screen a Tokenizer without `presentation` opens the sheet: `onChange` fires on Save, `ref` reaches the trigger, `endContent` and `renderToken` render as in the inline field, and the inline combobox's other props (`renderItem`, `hasClear`, `hasEntriesOnFocus`, `menuWidth`, `tokenOverflowBehavior`, `hasAutoFocus`) are not rendered. `presentation="popover"` keeps the inline combobox on every device. || Compatibility/readiness | The stable prop and its `adaptive` default ship together in a patch as `[feat]` (Compatibility and migration, DEC-3). With a fine pointer, on a screen that is not compact, on the server, and while hydrating, a field without `presentation` is the inline combobox, unchanged; the default `hasEntriesOnFocus={false}` path keeps 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 a fine pointer or a screen that is not compact gets by default, that `presentation="popover"` does not prevent, that 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-is-a-stable-presentation-and-adaptive-is-the-default), and [DEC-4](#dec-4--the-sheet-edits-a-draft-that-save-commits). |@@ -111,8 +112,7 @@ record.hydrating, a field without `presentation` renders the inline comboboxexactly as before (`spec:AST-017/FR59`). On a compact coarse-pointer screenit renders the sheet: `onChange` fires once on Save in place of once per- selection, `ref` receives the trigger button, and the props of the inline- combobox are not rendered. `presentation="popover"` keeps the previous+ selection, `ref` receives the trigger button, and the inline combobox's props other than `endContent` and `renderToken` are not rendered. `presentation="popover"` keeps the previousbehavior everywhere. Thestable prop and this default ship together in a patch as `[feat]`: thatrelease tier is a product decision of the engineering owner, with the@@ -190,21 +190,21 @@ usage remain in `Tokenizer.doc.mjs`. The existing`hasEntriesOnFocus` mode includes the component-owned post-selection behaviorin FR13–FR15.-In the sheet presentation the trigger is the control: `ref`, `id`, `data-*`,-`aria-*`, and the other base props reach it (`family:input-fields/FR10`,+In the sheet presentation the field's control box holds the trigger button, the tokens, and `endContent`, and carries the `tokenizer` theming target, its `data-*` state attributes, and the focus ring (`:focus-within`), as the inline field's box does. The trigger is the control: `ref`, `id`, the caller's `data-*` and `aria-*`, and the other base props reach it (`family:input-fields/FR10`,`architecture:public-component-api/INV8`), `handleRef.focus()` and `blur()`-act on it, and `onFocus`, `onBlur`, and `onKeyDown` report its events. The+act on it, and `onKeyDown` reports its events. `onFocus` and `onBlur` report focus entering and leaving the field's box, which also holds `endContent` and a custom token's controls, as the inline field reports its wrapper. Theexported `TokenizerProps` remains an interface and keeps `ref?:Ref<HTMLInputElement>` as released, so `interface X extends TokenizerProps<T>`and `Omit<TokenizerProps<T>, …>` wrappers keep compiling; the component's ownparameter type also accepts `Ref<HTMLInputElement | HTMLButtonElement>`. Theref receives the trigger button in the sheet presentation and the combobox-input otherwise, so a ref typed for both elements describes what it holds. The-props that describe the inline combobox have no surface in the sheet-presentation: `renderItem`, `renderToken`, `endContent`, `hasClear` (the-sheet's own Clear all replaces it), `hasEntriesOnFocus` (the sheet always-lists the bootstrap set), `menuWidth`, `tokenOverflowBehavior`, and-`hasAutoFocus`. Passing one of them with the sheet presentation emits one+input otherwise, so a ref typed for both elements describes what it holds. In the sheet+presentation `endContent` renders at the field's inline end and `renderToken`+renders the field's tokens, as in the inline field. The props that describe+only the inline combobox have no surface in the sheet presentation:+`renderItem`, `hasClear` (the sheet's own Clear all replaces it), `hasEntriesOnFocus` (the sheet always+lists the bootstrap set), `menuWidth`, `tokenOverflowBehavior` (the field+wraps its tokens), and `hasAutoFocus`. Passing one of them with the sheet presentation emits onedevelopment-mode warning naming the prop and `presentation="popover"`, so itis not silently dropped(`architecture:public-component-api/INV3`); every other prop keeps its@@ -221,38 +221,38 @@ Each requirement identifies its basis. This current record defines the approvedpackage-internal contract while implementation and focused verification remainpending. FR1–FR15 and FR25 describe the `popover` presentation, the inline combobox;FR16–FR24, FR26, and FR27 describe the `presentation` prop and its sheet-presentation, which has no inline combobox, suggestion menu, or-end lane.--| ID | Invariant | Basis | Status |-| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1 | Tokenizer MUST keep one native combobox input mounted across token addition, removal, clear, ordinary wrapping, and maximum-entry states. Reaching `maxEntries` may make the input zero-width, transparent, and out of flow, but MUST NOT replace its identity. | Current source and tests | Verified current behavior |-| FR2 | Tokenizer's suggestion menu MUST remain associated with the outer field/control surface. Existing `menuWidth` behavior remains an exact preferred pixel width plus the outer field's minimum width; it is not a maximum. | Current BaseTypeahead/Tokenizer source and docs | Verified current behavior; preserve |-| FR3 | `unfocusedInline` MAY replace direct token layout with OverflowList while blurred. `unfocusedLayer` MAY keep the real wrapper/input mounted in a context layer while an ordinary-flow placeholder represents the collapsed field. | Current source, tests, and stories | Verified current behavior |-| FR4 | Tokenizer MUST provide Core peers one package-internal descriptor with stable identities for its outer field/control surface and active opening control. Layer consumes the descriptor; public consumers cannot observe or configure it. | Approved package-internal contract; #5804 evidence; `spec:AST-002/DEC-1` | Current contract; implementation pending |-| FR5 | Add/search opens MUST identify the stable inner input as the opening control before the result row disappears. Selection, query clearing, result removal, refocus, or later input collapse MUST NOT substitute the transient result row or a pointer coordinate. | Current selection order plus approved descriptor contract | Current contract; implementation pending |-| FR6 | Edit opens MUST capture the actual activated token/control before state removes or replaces it. The Tokenizer-owned capture path MUST include custom `renderToken` output when activation originates from an identifiable descendant control; it MUST NOT require a new public ref contract. | Current owned wrapper plus approved capture contract | Current contract; implementation pending |-| FR7 | A non-null element is usable only while connected, rendered, and geometrically meaningful for the open being prepared. A disconnected, stale, hidden-layer, zero-width, or otherwise unusable opening control MUST fall back safely to the outer field at logical start before show. | Current max/overflow states plus approved safety rule | Current contract; implementation pending |-| FR8 | The descriptor MUST remain valid across focus movement, token add/remove/clear, wrapping, and `unfocusedLayer` reparenting. It MUST clear on unmount, perform no DOM work during SSR, and never retain an element beyond the open preparation that uses it. | Approved identity/lifetime contract | Current contract; implementation pending |-| FR9 | A consuming surface MUST resolve its preferred width before choosing horizontal placement. A surface at least as wide as the outer field MUST use outer-field logical-start alignment. Only a surface narrower than the outer field may use opening-control geometry. | Approved conditional-placement contract | Current contract; implementation pending |-| FR10 | For a narrower surface, Layer MUST compare the opening control with the outer field's physical start/end geometry, choose the nearer physical edge, map that result to logical start/end, and use logical start on a tie. Viewport collision runs last. | Approved Layer-consumer contract | Current contract; implementation pending |-| FR11 | Opening placement MUST be modality-neutral and latched for one open lifetime. Pointer, keyboard, touch, and programmatic activation of the same control MUST produce the same preferred edge. Pointer movement, later focus movement, resize, or target collapse MUST NOT recompute it. | `architecture:interaction-modality` plus approved stability contract | Current contract; implementation pending |-| FR12 | Placement state MUST commit while the surface is hidden, and Layer MUST show it on the next animation frame only after anchor, alignment, and width styles exist. A stale or invalid descriptor MUST never cause a visible wrong-position or first-frame flash. | Approved no-flash contract | Current contract; implementation pending |-| FR13 | Tokenizer MUST exclude every choice whose `SearchableItem.id` is already present in its committed `value` from displayed bootstrap and search cohorts, including results that settle after the controlled value changes. A caller-rejected proposed value remains eligible because it was not committed. Distinct IDs remain eligible even when their labels match. | Approved Tokenizer multi-selection contract | Current contract; implementation and verification pending |-| FR14 | With `hasEntriesOnFocus` enabled, committing a choice from the current settled empty-query bootstrap cohort MUST keep the input focused and the popup open when another eligible loaded choice remains. The active option advances to the next remaining choice in displayed order; when the committed choice was last, the nearest preceding choice becomes active. `aria-activedescendant` MUST reference that rendered option. | Approved rapid multi-select lifecycle | Current contract; implementation and verification pending |-| FR15 | The retained popup MUST close and clear its active descendant when no eligible loaded choice remains, `maxEntries` is reached, the control becomes disabled, focus leaves, or the person dismisses it. Disabled Tokenizer remains non-interactive. Pending or stale source work MUST NOT reopen a terminal popup or expose stale choices; loading has no selectable placeholder and its busy state clears when work is cancelled or settles. | Approved terminal-state safety boundary | Current contract; implementation and verification pending |-| FR16 | `presentation` selects the surface. `adaptive`, the value when `presentation` is omitted, 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; with a fine pointer or on a screen that is not compact it renders exactly the `popover` presentation. `popover` is the inline combobox with its anchored suggestion menu on every device, unchanged. `bottom-sheet` is the trigger and modal sheet of FR17–FR24, FR26, and FR27 on every device. `adaptive` renders on the server, and hydrates, as the inline field, because the resolver answers `popover` where there is no `matchMedia` and in the hydrating render; on a compact coarse-pointer client the field swaps to the trigger in the first render after hydration; nothing is focused before interaction, so focus is undisturbed (`document.activeElement` stays the body), except with `hasAutoFocus`, whose server-rendered `autofocus` focuses the inline input on load: then the swap moves that focus to the trigger — the same element and visit for the caller, so no `onBlur`/`onFocus` pair is reported. The trigger keeps the field's box — the same width, top, label, and `size` block size — except the inline input's own row: when the tokens leave the input no room on their row, the inline field wraps the input onto a row of its own, and the trigger, which has no input, drops that row (one `md` row, 27px, on a 390 and a 414px phone with five tokens); with room for the input beside the tokens, nothing shifts. A resolution change while the sheet is open takes effect after it closes and focus has returned to the trigger — the presentation hold `architecture:layer-runtime/INV14` assigns to the layer runtime; INV14 gap: the runtime does not yet provide one (its record names INV14 as ownership not yet met), so until it does the field keeps its own hold, to be replaced by the runtime's when it exists. Whenever the presentation changes while its control holds focus — then, or while the sheet is closed — focus moves to the new presentation's control, the combobox input or the trigger, so it never lands on the page body (`spec:AST-085/FR4`). | DEC-3; touch-flow evidence | Verified current behavior. |-| FR17 | In the sheet presentation the control surface is one button, named by the field label, with `aria-haspopup="dialog"` and `aria-expanded`. It shows the selected tokens without remove controls, or the placeholder when empty, wraps tokens onto further lines, and is the inline field's control box: the shared input box — its 1px border, focus ring, surface and radius — the inline field's token inset and row gap, and the `size` block size, so before the sheet opens the field looks the same as the inline field; the touch-sized targets belong to the sheet's rows and actions, not to the closed field. Activating it opens one tall modal BottomSheet named by the field label; the suggestion popover, inline input, and end lane do not render. While disabled the trigger stays focusable with `aria-disabled="true"`, does not open, and shows `disabledMessage` as the inline field does (`spec:AST-085/FR1`); a field that becomes disabled while its sheet is open closes the sheet and returns focus to the trigger (`spec:AST-085/FR2`). | DEC-3; touch-flow evidence; `spec:AST-085` | Verified current behavior. |-| FR18 | The sheet is a single surface: a search field at the top, a scrolling list of rows, and a footer with Clear all and Save pinned below the list. There is no second sheet. The search field is the shared panel search field drawn as a bordered input box (the input border and surface, element radius, the `lg` input height — 36px — above the sheet's 44px rows) rather than the borderless field a dropdown panel draws; it does not scroll with the list. The footer is rendered in every state of the sheet — while searching, while pending, with an empty query — so Clear all and Save are reachable without clearing the query. On open, focus moves to the sheet's panel, not the search field, so the reading order starts at the top of the sheet and the on-screen keyboard rises only when the person reaches for the search (WCAG 2.2 SC 2.4.3 Focus Order and 3.2.1 On Focus through `spec:AST-020/FR1`). Save commits the draft and closes the sheet (FR26); swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"` and close directly while the draft is unchanged, and ask first while it is changed (FR27). Each close the person makes — Save, a clean dismissal, a confirmed discard — clears the query and reports it through `onChangeQuery`, so the next open lists the bootstrap set, while a close the field forces (becoming disabled, FR17) keeps the query, since nothing the person did changed it; focus returns to the trigger after the sheet closes. While the search field holds focus on a touch screen, a direct vertical finger drag on the results of at least 8px moves focus from it to the sheet's panel, without clearing the query — a focus rule of the sheet's, so the rows the person reaches for come into view and focus never rests on the page body behind the open modal (`spec:AST-085/FR4`); what the on-screen keyboard does when the field loses focus is `spec:AST-099`'s. A tap, a shorter move, a multi-touch gesture, and a scroll event the list fires on its own (filtering can clamp its scroll position while the person is typing) leave focus where it is. | DEC-3; touch-flow evidence; `component:BottomSheet` | Verified current behavior. |-| FR19 | Each row is a `checkbox` named by the item label whose `aria-checked` mirrors membership in the sheet's draft (FR26): the selection the person is editing, which starts as `value` when the sheet opens. Activating an unchecked row adds the item to the draft; a checked row removes it; both apply to the draft at once and are announced with the inline field's words through the sheet's own live region (AR6); `value` and `onChange` are untouched until Save. Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then draft-selected items absent from the results, then the results in source order; a toggle never moves an existing row. The next open takes a fresh snapshot. The query filters the selected rows by case-insensitive label substring. A row renders an item without its `action` and warns once in development that the sheet does not render it, as the inline panel does (`spec:AST-058/FR9`). | DEC-3; touch-flow evidence | Verified current behavior. |-| FR20 | An empty query lists the source's bootstrap set, capped at `maxMenuItems` as the inline field caps its focus bootstrap (the prop keeps its meaning in the sheet), requested at once on open and on clearing the query, so an instant source shows no busy feedback and announces no busy start; a query shorter than `minQueryLength` is not searched: it lists only the selected rows it matches and, with `hasCreate`, the create row, with no busy feedback, no empty state, and no outcome announcement, as the inline field shows nothing for such a query; otherwise the source is searched `debounceMs` after the query change and the results are capped at `maxMenuItems`. `onChangeQuery` fires on every query change. From open, and from each query change, until that search settles, the list is pending: it shows named busy feedback above any rows still listed from the previous search, the list element carries the busy semantics (`aria-busy`), since the sheet has no combobox (`family:input-fields/FR7`, which places busy semantics on the list a presentation without a combobox updates), and no empty state shows; when the settled search removes the row that holds focus, focus moves to the search field (`spec:AST-085/FR4`). Once settled, the outcome is announced through the sheet's live region (AR6): the result count for a searched query, or the rendered text of the empty state when it shows (`spec:AST-056/FR3`). A source that rejects settles the search to no results, as the inline field does. With no rows and no create row, a searched query shows the `emptySearchText` empty state (its default message when omitted); an empty query shows no list, no message, and announces nothing — only the search field, above the footer — as the inline field opens no menu and reports nothing for a bootstrap set that is empty: nothing has failed, and typing is what finds items (a search-only source, `bootstrap: () => []`, is such a source). | DEC-3; touch-flow evidence; `family:input-fields` | Verified current behavior. |-| FR21 | Long lists render progressively: 50 rows at a time, the next batch when the list scrolls within 200px of its end, with the window reset to the first batch on open and on each query change. The rendered and total counts are exposed as `data-rendered-count` and `data-total-count` on the list, and the rows sit in a `list` whose `listitem` wrappers carry `aria-setsize` with the total and `aria-posinset` with the row's position — the `checkbox` role itself admits neither — so a person moving through the rows can learn that more exist before the list has scrolled; whether a screen reader speaks the position ("n of total") from the focused checkbox depends on the screen reader (`spec:AST-009/FR8`), and the accessibility tree proves the `list`, `listitem`, `aria-setsize`, and `aria-posinset` exposure; focus reaching the last rendered row renders the next batch (WCAG 2.2 SC 1.3.1 Info and Relationships and 4.1.2 Name, Role, Value through `spec:AST-020/FR1`). | DEC-3; touch-flow evidence | Verified current behavior. |-| FR22 | With `hasCreate`, a non-empty trimmed query that matches no draft-selected id, no draft-selected label, and no result label (case-insensitive) adds a create row above the list showing `Create "{text}"` with a trailing Add action named `Add {text}`. Activating it adds to the draft an item with the text as both id and label — reported by Save as a `create` when that create is the last edit that still holds (FR26) — announces it, clears the query, and moves focus to the sheet's search field, since the row it was on is gone. The create row is absent while the draft is at `maxEntries`. | DEC-3; touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior. |-| FR23 | `maxEntries` is enforced on the draft: while the draft holds `maxEntries` items, unchecked rows carry `aria-disabled="true"`, stay focusable, and ignore activation; checked rows remain toggleable so the person can make room (`spec:AST-085/FR1`). While the draft holds more than `maxEntries` — a `value` over the limit when the sheet opened, or `maxEntries` lowered while the sheet is open — Save is `aria-disabled`, still in the focus order, with a tooltip naming the limit ("Select up to {count} items"), and does nothing until the draft is within it. | DEC-3; touch-flow evidence; `spec:AST-085` | Verified current behavior. |-| FR24 | Clear all is disabled while the draft is empty: `aria-disabled`, still in the focus order, with a tooltip saying nothing is selected, and a click opens nothing (`spec:AST-085/FR1`). Otherwise it opens the sheet's confirmation (FR27) naming the field, with Cancel as the safe action and Clear selection as the destructive one; confirming empties the draft — recorded as a removal of the draft's last item, which Save names in its `remove` when the clear is the last edit that holds (FR26); `value` is untouched until Save, so a discard restores it — closes the confirmation, and, once the confirmation has closed, returns focus to Clear all, which is now `aria-disabled` and still in the focus order, so it keeps focus as a control that becomes disabled does (`spec:AST-085/FR4`, WCAG 2.2 SC 2.4.3 through `spec:AST-020/FR1`); focus never moves to the search field, which would raise the on-screen keyboard over the rows just cleared; and announces "All items removed" inside the sheet (AR6); cancelling changes nothing and focus returns to Clear all the same way. Clear all stays visible and reachable while searching, since the footer is pinned (FR18). | DEC-3; touch-flow evidence | Verified current behavior. |-| FR25 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 | Verified current behavior |-| FR26 | One open sheet edits one draft. The draft starts as `value` when the sheet opens and takes every row toggle, create, and Clear all (FR19, FR22, FR24); `value` and `onChange` are untouched while the sheet is open. Save closes the sheet; with an unchanged draft it reports nothing, and with a changed one it reports the whole draft once through `onChange(items, change)`, where `change` names the last edit that still holds: the last toggle, create, or clear when its item is in the draft and was not selected at open (`add`, or `create` for an item created in this sheet) or was selected at open and is not in the draft (`remove`); otherwise, when the last edit was a removal and some item selected at open is gone, a `remove` naming one such item; otherwise an `add` (`create` when the last edit created that item) naming an item in the draft that was not selected at open; otherwise a `remove` naming an item gone since open. A field that is disabled when Save fires reports nothing. A toggle is announced when it happens (AR6), not again on Save. | DEC-4 | Verified current behavior. |-| FR27 | Swipe, scrim, and Escape dismissal of the sheet close it directly while the draft equals the selection at open. While the draft differs, they open a discard confirmation inside the sheet — "Discard changes?", "Your changes to {label} haven't been saved." — with Discard changes as the destructive action and Keep editing as the safe one, which is focused first; Discard changes closes the sheet without reporting the draft, and Keep editing closes the confirmation and moves focus to the search field so editing resumes where the sheet's own reading order starts (`spec:AST-085/FR4`). The sheet's confirmations (this one and Clear all's, FR24) are one modal dialog shape: a title, a description, and two full-width large actions stacked in reading order — the destructive action, then the safe action, which takes focus first; the two actions are one action group (`family:action-groups`) while keeping their separated, full-width, stacked look; scrim and Escape take the safe action. A close the field forces (becoming disabled, FR17) asks nothing and reports nothing: the draft is dropped. | DEC-4 | Verified current behavior, with one implementation gap: the confirmation's two actions are separated Buttons, not yet one action group (`family:action-groups`). |+presentation, which has no inline combobox or suggestion menu; its end lane+holds only `endContent` (FR17).++| 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 | `presentation` selects the surface. `adaptive`, the value when `presentation` is omitted, 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; with a fine pointer or on a screen that is not compact it renders exactly the `popover` presentation. `popover` is the inline combobox with its anchored suggestion menu on every device, unchanged. `bottom-sheet` is the trigger and modal sheet of FR17–FR24, FR26, and FR27 on every device. `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 sheet field 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 sheet field keeps the inline 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 sheet field, 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 field holds focus — on its control, a token's remove, the inline Clear all, or the sheet field's `endContent` — then, or while the sheet is closed, focus moves to the new presentation's control, the combobox input or the trigger, so it never lands on the page body (`spec:AST-085/FR4`). | DEC-3; touch-flow evidence | Verified current behavior. |+| FR17 | In the sheet presentation the field's control is one button, named by the field label, with `aria-haspopup="dialog"` and `aria-expanded`, inside the field's control box. The box shows the selected tokens, or the placeholder when empty, wraps tokens onto further lines, and keeps `endContent` at its inline end, where token rows and the placeholder stop short of it. The default tokens are display-only, with no remove control; `renderToken` renders the tokens instead when given, and a control inside a custom token acts at once, as in the inline field: its remove commits `onChange` and moves focus to the trigger. A tap on a token, the placeholder, or the empty space opens the sheet; `endContent` and a custom token's own controls act without opening it, and follow the trigger in the focus order. The box 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 the trigger opens one tall modal BottomSheet named by the field label; the suggestion popover and inline input do not render, and the end lane holds `endContent` only, with no clear button and no busy indicator. While disabled the trigger stays focusable with `aria-disabled="true"`, does not open, and shows `disabledMessage` as the inline field does (`spec:AST-085/FR1`); a field that becomes disabled while its sheet is open closes the sheet and returns focus to the trigger (`spec:AST-085/FR2`). | DEC-3; touch-flow evidence; `spec:AST-085` | Verified current behavior. |+| FR18 | The sheet is a single surface: a search field at the top, a scrolling list of rows, and a footer with Clear all and Save pinned below the list. There is no second sheet. The search field is the shared panel search field drawn as a bordered input box (the input border and surface, element radius, the `lg` input height — 36px — above the sheet's 44px rows) rather than the borderless field a dropdown panel draws; it does not scroll with the list. The footer is rendered in every state of the sheet — while searching, while pending, with an empty query — so Clear all and Save are reachable without clearing the query. On open, focus moves to the sheet's panel, not the search field, so the reading order starts at the top of the sheet and the on-screen keyboard rises only when the person reaches for the search (WCAG 2.2 SC 2.4.3 Focus Order and 3.2.1 On Focus through `spec:AST-020/FR1`). Save commits the draft and closes the sheet (FR26); swipe, scrim, and Escape dismissal follow BottomSheet `purpose="info"` and close directly while the draft is unchanged, and ask first while it is changed (FR27). Each close the person makes — Save, a clean dismissal, a confirmed discard — clears the query and reports it through `onChangeQuery`, so the next open lists the bootstrap set, while a close the field forces (becoming disabled, FR17) keeps the query, since nothing the person did changed it; focus returns to the trigger after the sheet closes. While the search field holds focus on a touch screen, a direct vertical finger drag on the results of at least 8px moves focus from it to the sheet's panel, without clearing the query — a focus rule of the sheet's, so the rows the person reaches for come into view and focus never rests on the page body behind the open modal (`spec:AST-085/FR4`); what the on-screen keyboard does when the field loses focus is `spec:AST-099`'s. A tap, a shorter move, a multi-touch gesture, and a scroll event the list fires on its own (filtering can clamp its scroll position while the person is typing) leave focus where it is. | DEC-3; touch-flow evidence; `component:BottomSheet` | Verified current behavior. |+| FR19 | Each row is a `checkbox` named by the item label whose `aria-checked` mirrors membership in the sheet's draft (FR26): the selection the person is editing, which starts as `value` when the sheet opens. Activating an unchecked row adds the item to the draft; a checked row removes it; both apply to the draft at once and are announced with the inline field's words through the sheet's own live region (AR6); `value` and `onChange` are untouched until Save. Row order is stable while the sheet is open: the items selected when it opened, in `value` order, then draft-selected items absent from the results, then the results in source order; a toggle never moves an existing row. The next open takes a fresh snapshot. The query filters the selected rows by case-insensitive label substring. A row renders an item without its `action` and warns once in development that the sheet does not render it, as the inline panel does (`spec:AST-058/FR9`). | DEC-3; touch-flow evidence | Verified current behavior. |+| FR20 | An empty query lists the source's bootstrap set, capped at `maxMenuItems` as the inline field caps its focus bootstrap (the prop keeps its meaning in the sheet), requested at once on open and on clearing the query, so an instant source shows no busy feedback and announces no busy start; a query shorter than `minQueryLength` is not searched: it lists only the selected rows it matches and, with `hasCreate`, the create row, with no busy feedback, no empty state, and no outcome announcement, as the inline field shows nothing for such a query; otherwise the source is searched `debounceMs` after the query change and the results are capped at `maxMenuItems`. `onChangeQuery` fires on every query change. From open, and from each query change, until that search settles, the list is pending: it shows named busy feedback above any rows still listed from the previous search, the list element carries the busy semantics (`aria-busy`), since the sheet has no combobox (`family:input-fields/FR7`, which places busy semantics on the list a presentation without a combobox updates), and no empty state shows; when the settled search removes the row that holds focus, focus moves to the search field (`spec:AST-085/FR4`). Once settled, the outcome is announced through the sheet's live region (AR6): the result count for a searched query, or the rendered text of the empty state when it shows (`spec:AST-056/FR3`). A source that rejects settles the search to no results, as the inline field does. With no rows and no create row, a searched query shows the `emptySearchText` empty state (its default message when omitted); an empty query shows no list, no message, and announces nothing — only the search field, above the footer — as the inline field opens no menu and reports nothing for a bootstrap set that is empty: nothing has failed, and typing is what finds items (a search-only source, `bootstrap: () => []`, is such a source). | DEC-3; touch-flow evidence; `family:input-fields` | Verified current behavior. |+| FR21 | Long lists render progressively: 50 rows at a time, the next batch when the list scrolls within 200px of its end, with the window reset to the first batch on open and on each query change. The rendered and total counts are exposed as `data-rendered-count` and `data-total-count` on the list, and the rows sit in a `list` whose `listitem` wrappers carry `aria-setsize` with the total and `aria-posinset` with the row's position — the `checkbox` role itself admits neither — so a person moving through the rows can learn that more exist before the list has scrolled; whether a screen reader speaks the position ("n of total") from the focused checkbox depends on the screen reader (`spec:AST-009/FR8`), and the accessibility tree proves the `list`, `listitem`, `aria-setsize`, and `aria-posinset` exposure; focus reaching the last rendered row renders the next batch (WCAG 2.2 SC 1.3.1 Info and Relationships and 4.1.2 Name, Role, Value through `spec:AST-020/FR1`). | DEC-3; touch-flow evidence | Verified current behavior. |+| FR22 | With `hasCreate`, a non-empty trimmed query that matches no draft-selected id, no draft-selected label, and no result label (case-insensitive) adds a create row above the list showing `Create "{text}"` with a trailing Add action named `Add {text}`. Activating it adds to the draft an item with the text as both id and label — reported by Save as a `create` when that create is the last edit that still holds (FR26) — announces it, clears the query, and moves focus to the sheet's search field, since the row it was on is gone. The create row is absent while the draft is at `maxEntries`. | DEC-3; touch-flow evidence; `hasCreate` contract of the inline field | Verified current behavior. |+| FR23 | `maxEntries` is enforced on the draft: while the draft holds `maxEntries` items, unchecked rows carry `aria-disabled="true"`, stay focusable, and ignore activation; checked rows remain toggleable so the person can make room (`spec:AST-085/FR1`). While the draft holds more than `maxEntries` — a `value` over the limit when the sheet opened, or `maxEntries` lowered while the sheet is open — Save is `aria-disabled`, still in the focus order, with a tooltip naming the limit ("Select up to {count} items"), and does nothing until the draft is within it. | DEC-3; touch-flow evidence; `spec:AST-085` | Verified current behavior. |+| FR24 | Clear all is disabled while the draft is empty: `aria-disabled`, still in the focus order, with a tooltip saying nothing is selected, and a click opens nothing (`spec:AST-085/FR1`). Otherwise it opens the sheet's confirmation (FR27) naming the field, with Cancel as the safe action and Clear selection as the destructive one; confirming empties the draft — recorded as a removal of the draft's last item, which Save names in its `remove` when the clear is the last edit that holds (FR26); `value` is untouched until Save, so a discard restores it — closes the confirmation, and, once the confirmation has closed, returns focus to Clear all, which is now `aria-disabled` and still in the focus order, so it keeps focus as a control that becomes disabled does (`spec:AST-085/FR4`, WCAG 2.2 SC 2.4.3 through `spec:AST-020/FR1`); focus never moves to the search field, which would raise the on-screen keyboard over the rows just cleared; and announces "All items removed" inside the sheet (AR6); cancelling changes nothing and focus returns to Clear all the same way. Clear all stays visible and reachable while searching, since the footer is pinned (FR18). | DEC-3; touch-flow evidence | Verified current behavior. |+| FR25 | The result list follows `component:BaseTypeahead` FR12: a press on the field's input or its buttons, or in the list, keeps it open, and a press anywhere else closes it. | `component:BaseTypeahead` FR12 | Verified current behavior |+| FR26 | One open sheet edits one draft. The draft starts as `value` when the sheet opens and takes every row toggle, create, and Clear all (FR19, FR22, FR24); `value` and `onChange` are untouched while the sheet is open. Save closes the sheet; with an unchanged draft it reports nothing, and with a changed one it reports the whole draft once through `onChange(items, change)`, where `change` names the last edit that still holds: the last toggle, create, or clear when its item is in the draft and was not selected at open (`add`, or `create` for an item created in this sheet) or was selected at open and is not in the draft (`remove`); otherwise, when the last edit was a removal and some item selected at open is gone, a `remove` naming one such item; otherwise an `add` (`create` when the last edit created that item) naming an item in the draft that was not selected at open; otherwise a `remove` naming an item gone since open. A field that is disabled when Save fires reports nothing. A toggle is announced when it happens (AR6), not again on Save. | DEC-4 | Verified current behavior. |+| FR27 | Swipe, scrim, and Escape dismissal of the sheet close it directly while the draft equals the selection at open. While the draft differs, they open a discard confirmation inside the sheet — "Discard changes?", "Your changes to {label} haven't been saved." — with Discard changes as the destructive action and Keep editing as the safe one, which is focused first; Discard changes closes the sheet without reporting the draft, and Keep editing closes the confirmation and moves focus to the search field so editing resumes where the sheet's own reading order starts (`spec:AST-085/FR4`). The sheet's confirmations (this one and Clear all's, FR24) are one modal dialog shape: a title, a description, and two full-width large actions stacked in reading order — the destructive action, then the safe action, which takes focus first; the two actions are one action group (`family:action-groups`) while keeping their separated, full-width, stacked look; scrim and Escape take the safe action. A close the field forces (becoming disabled, FR17) asks nothing and reports nothing: the draft is dropped. | DEC-4 | Verified current behavior, with one implementation gap: the confirmation's two actions are separated Buttons, not yet one action group (`family:action-groups`). |### Allowed variation@@ -284,36 +284,35 @@ end lane.attributes and styles on the same elements; open, in INV7's words, "theopen layer under a coarse pointer has at most as many elements as under afine pointer (beyond that, only by the open-layer allowance `spec:AST-017`- FR60 and DEC-29 set)". The closed `adaptive` trigger (a different element,- which no allowance covers) and the open sheet (more than the five extra+ FR60 and DEC-29 set)". The closed `adaptive` sheet field (different elements, which no allowance covers) and the open sheet (more than the five extraelements FR60 allows) are owner exceptions DEC-3 records, beyond thatallowance, with their before and after counts.### Representative states-| State | Required invariant | Allowed variation |-| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |-| Empty field | The mounted inner input is the opening control; a full-width menu stays aligned to the outer field. | Placeholder and bootstrap results may vary. |-| Focus bootstrap, choices remain | A committed selection is removed from the displayed cohort; the input and popup remain active on the next valid remaining choice. | Internal cohort storage and projection may vary. |-| Focus bootstrap, selected choice was last | The nearest preceding remaining choice becomes active without changing the displayed order. | Option identity representation may vary. |-| Focus bootstrap, no choices or max reached | The popup closes and no active descendant remains; pending work cannot reopen it. | Source cancellation mechanism may vary. |-| Source pending or replaced | Busy semantics identify pending work; stale work cannot add choices or reopen a terminal popup. | A settled current cohort may be retained internally. |-| Disabled | No choice can be committed; an open popup closes and clears its active descendant while disabled-reason focusability remains available where configured. | The disabled representation follows `spec:AST-085`. |-| One or many tokens | The same input remains after tokens and moves with wrapping; full-width placement does not follow that movement. | Token labels, wrapping rows, and custom content may vary. |-| At `maxEntries` | The input identity remains mounted but its zero-width/hidden box is unusable as geometry; opening falls back to the outer field. | Search remains unavailable under current behavior. |-| Token removal or clear | Input identity survives and current refocus behavior remains. | Token count and input position change. |-| `unfocusedInline` | Blurred OverflowList and focused direct-token layouts resolve the same live input identity; a collapsed input is not used as geometry. | Visible token count may vary with width. |-| `unfocusedLayer`, focused | The live wrapper/input may be reparented into the context layer without descriptor churn. | Corrective portal location may vary. |-| `unfocusedLayer`, unfocused | The hidden-layer input is unusable for a new open; the ordinary-flow outer-field fallback is used. | Placeholder token count may vary. |-| Default or custom token edit | The actual activated token/control is captured before edit state changes; if no usable descendant control exists, input then outer-field fallback applies. | Custom token markup may vary. |-| LTR or RTL | Physical proximity selects an edge only for a narrower surface; logical start wins ties and full-width placement. | Collision may move the final rendered surface. |-| SSR, hydration, or unmount | No server geometry read occurs; first client open prepares normally; unmount clears identities and pending show work. | Hydration timing may vary. |-| Sheet presentation, closed | The trigger shows the tokens or placeholder at the inline field's height for its `size`, `aria-expanded="false"`; no sheet content is interactive. | Token wrapping and placeholder text may vary. |-| Sheet presentation, open | One tall modal sheet named by the label: a bordered search field on top, stable-order checkbox rows editing a draft, and Clear all and Save pinned below in every state. Focus is on the sheet's panel, not the search field. | Row count, batches, and empty states may vary. |-| Sheet presentation, searching | The footer stays pinned below the list with Clear all and Save; the list is busy until the search settles; rows filter to the query; the create row leads when `hasCreate` applies; a dead end shows the no-results empty state. | Debounce and result cap follow the props. |-| Sheet presentation, at `maxEntries` | Unchecked rows are `aria-disabled` and inert; checked rows toggle; no create row. | The disabled representation follows `spec:AST-085`. |-| Sheet presentation, dismissed | After Save, a clean swipe, scrim, or Escape close, or a confirmed discard, the query is empty and reported, so the next open lists the bootstrap set; focus is back on the trigger; only Save changed `value`. A close forced by disabling keeps the query and drops the draft. | A dismissal that keeps a typed query for the next open, or that leaves focus on the page body, fails. |-| Sheet presentation, `adaptive` resolution (the default) | Server and hydrating renders are the inline field; a compact coarse-pointer client swaps to the trigger in the first render after hydration, focus undisturbed, the box kept except an inline input row the tokens had wrapped. While closed the surface follows the shared compact-touch query; an open surface keeps its presentation until it closes. | The query is shared, not Tokenizer-owned. |+| State | Required invariant | Allowed variation |+| ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |+| Empty field | The mounted inner input is the opening control; a full-width menu stays aligned to the outer field. | Placeholder and bootstrap results may vary. |+| Focus bootstrap, choices remain | A committed selection is removed from the displayed cohort; the input and popup remain active on the next valid remaining choice. | Internal cohort storage and projection may vary. |+| Focus bootstrap, selected choice was last | The nearest preceding remaining choice becomes active without changing the displayed order. | Option identity representation may vary. |+| Focus bootstrap, no choices or max reached | The popup closes and no active descendant remains; pending work cannot reopen it. | Source cancellation mechanism may vary. |+| Source pending or replaced | Busy semantics identify pending work; stale work cannot add choices or reopen a terminal popup. | A settled current cohort may be retained internally. |+| Disabled | No choice can be committed; an open popup closes and clears its active descendant while disabled-reason focusability remains available where configured. | The disabled representation follows `spec:AST-085`. |+| One or many tokens | The same input remains after tokens and moves with wrapping; full-width placement does not follow that movement. | Token labels, wrapping rows, and custom content may vary. |+| At `maxEntries` | The input identity remains mounted but its zero-width/hidden box is unusable as geometry; opening falls back to the outer field. | Search remains unavailable under current behavior. |+| Token removal or clear | Input identity survives and current refocus behavior remains. | Token count and input position change. |+| `unfocusedInline` | Blurred OverflowList and focused direct-token layouts resolve the same live input identity; a collapsed input is not used as geometry. | Visible token count may vary with width. |+| `unfocusedLayer`, focused | The live wrapper/input may be reparented into the context layer without descriptor churn. | Corrective portal location may vary. |+| `unfocusedLayer`, unfocused | The hidden-layer input is unusable for a new open; the ordinary-flow outer-field fallback is used. | Placeholder token count may vary. |+| Default or custom token edit | The actual activated token/control is captured before edit state changes; if no usable descendant control exists, input then outer-field fallback applies. | Custom token markup may vary. |+| LTR or RTL | Physical proximity selects an edge only for a narrower surface; logical start wins ties and full-width placement. | Collision may move the final rendered surface. |+| SSR, hydration, or unmount | No server geometry read occurs; first client open prepares normally; unmount clears identities and pending show work. | Hydration timing may vary. |+| Sheet presentation, closed | The field box shows the tokens or placeholder, and any `endContent`, at the inline field's height for its `size`; the trigger has `aria-expanded="false"`; no sheet content is interactive. | Token wrapping and placeholder text may vary. |+| Sheet presentation, open | One tall modal sheet named by the label: a bordered search field on top, stable-order checkbox rows editing a draft, and Clear all and Save pinned below in every state. Focus is on the sheet's panel, not the search field. | Row count, batches, and empty states may vary. |+| Sheet presentation, searching | The footer stays pinned below the list with Clear all and Save; the list is busy until the search settles; rows filter to the query; the create row leads when `hasCreate` applies; a dead end shows the no-results empty state. | Debounce and result cap follow the props. |+| Sheet presentation, at `maxEntries` | Unchecked rows are `aria-disabled` and inert; checked rows toggle; no create row. | The disabled representation follows `spec:AST-085`. |+| Sheet presentation, dismissed | After Save, a clean swipe, scrim, or Escape close, or a confirmed discard, the query is empty and reported, so the next open lists the bootstrap set; focus is back on the trigger; only Save changed `value`. A close forced by disabling keeps the query and drops the draft. | A dismissal that keeps a typed query for the next open, or that leaves focus on the page body, fails. |+| Sheet presentation, `adaptive` resolution (the default) | Server and hydrating renders are the inline field; a compact coarse-pointer client swaps to the sheet field in the first render after hydration, focus undisturbed, the box kept except an inline input row the tokens had wrapped. While closed the surface follows the shared compact-touch query; an open surface keeps its presentation until it closes. | The query is shared, not Tokenizer-owned. |### Transformation and precedence order@@ -384,10 +383,7 @@ presentation.disabled (a disabled control exposes its description and its reason onitself, `spec:AST-085/FR5`) — followed by the selected count and theselected token labels, so the selection the sighted person sees is exposed- to assistive technology as the trigger's description; the labels are the- rendered tokens themselves, each referenced by id from `aria-describedby`- after a hidden count, so no label renders twice- (`architecture:component-style-authoring` INV7); whether a screen reader+ to assistive technology as the trigger's description; the labels are the rendered tokens themselves, each referenced by id from `aria-describedby` after a hidden count, so no label renders twice (`architecture:component-style-authoring` INV7); a custom token from `renderToken` can hold controls whose names would join the description, and the caller's markup cannot be referenced without them, so each custom token is described instead by a copy of its item label carrying the `hidden` attribute, which `aria-describedby` reads and the accessibility tree leaves out, so each label is in the accessibility tree once (the INV7 exception below records the copies); whether a screen readerreads a description with the button depends on the screen reader(`spec:AST-009/FR8`), and the DOM and accessibility tree prove the`aria-describedby` exposure (WCAG 2.2 SC 1.3.1 and 4.1.2 through@@ -442,14 +438,14 @@ the sheet presentation.| Suggestion menu | Retains current outer-field anchoring and exact preferred `menuWidth`; focus bootstrap keeps only eligible choices and a valid active option. | Current BaseTypeahead source | Prominent | FR2, FR13–FR15, AR5 || Overflow placeholder/layer | Preserves a usable outer-field fallback while live content may reparent or collapse. | Current Tokenizer/Layer composition | Supporting | FR3, FR7–FR8 || Dependent narrower surface | Uses the descriptor only after its owning component resolves a width narrower than the field. | Consuming component plus Layer | Prominent | FR9–FR12 |-| Sheet trigger | The field's control surface in the sheet presentation: tokens or placeholder, the inline field's size step, opens the sheet. | Tokenizer source; Token | Prominent | FR17, AR6 |+| Sheet field | The field's control box in the sheet presentation, with the inline field's size step, theming target, and focus ring: the trigger button, the tokens (default or `renderToken`) or the placeholder, and `endContent` in the end lane; the trigger opens the sheet. | Tokenizer source; Token | Prominent | FR17, AR6 || Sheet search row | The shared panel search field at the top of the sheet, drawn as a bordered input box and fixed above the scrolling list; filters rows and the create row. | Shared panel search field | Prominent | FR18, FR20, FR22 || Sheet rows | Full-width checkbox rows with a trailing indicator, editing the sheet's draft; stable order while open; disabled at the limit. | Tokenizer source; checkbox indicator | Prominent | FR19, FR21, FR23, FR26 || Sheet footer | Equal-width large Clear all and Save, pinned below the list in every state; Clear all confirms through the sheet's confirmation; Save commits the draft. | Button; the sheet's confirmation dialog | Supporting | FR18, FR24, FR26 || Sheet confirmation | One dialog shape for Clear all and for discarding a changed draft: title, description, and one action group (`family:action-groups`) of two separated full-width actions — the destructive action then the safe action in reading order, the safe action focused first. | Dialog; Button | Supporting | FR24, FR27 |This contract adds no target, state, or visual styling contract. The sheet-presentation exposes the field's existing `tokenizer` target on the trigger;+presentation exposes the field's existing `tokenizer` target on the field's control box, as the inline field does;the sheet's own parts carry no Tokenizer theming targets (DEC-3), and arethemed through the targets of the components they compose.@@ -498,18 +494,18 @@ become Tokenizer policy.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |-| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |-| FR1–FR3 | Existing Tokenizer/BaseTypeahead unit tests plus source inspection | empty, tokens, remove, clear, max, wrapping, both overflow modes | Input remounts, suggestion menu changes anchor/width semantics, or overflow ownership is misstated. | `audit:Tokenizer/current` |-| FR4–FR8 | Focused descriptor identity/capture tests when implemented | add, default/custom token edit, max, hidden layer, reparent, stale node, unmount, SSR | Descriptor leaks publicly, captures a transient result/pointer, misses custom controls, or uses unusable geometry. | `audit:Tokenizer/opening-anchor` |-| FR9–FR12 | Layer unit tests and real-Chromium geometry checks when implemented | full/equal/narrow surface, start/end/tie, LTR/RTL, collision, stale fallback | Full-width follows inner input, tie is physical, collision runs early, or stale identity flashes. | `audit:Tokenizer/placement` |-| FR13–FR15, AR5 | Focused Tokenizer/BaseTypeahead tests and exact-head Chromium interaction evidence | pointer/keyboard commit, first/middle/last choice, rejected/deferred control, loading, disabled, max, exhaustion, Escape, Tab, outside focus | Selected values remain available, order changes, focus leaves the combobox, active descendant names no option, stale work reopens, or a terminal state stays interactive. | `audit:Tokenizer/multi-select` |-| PR1–PR5 | Instrumented reads, pending-frame cleanup tests, and first-frame Chromium capture | open, close before frame, reopen opposite side, resize while open | Render-time/repeated reads, observer/pointer tracking, uncancelled frame, or first-frame jump occurs. | `audit:Tokenizer/performance` |-| AR1–AR5 | Existing interaction suites plus focused pointer/keyboard/browser checks; native-disabled assertions pending conformance (`spec:AST-085`) | add/edit, focus/refocus, overflow, disabled, dismissal, retained bootstrap selection | Modality changes placement, semantics/focus regress, active descendant becomes invalid, or visible placement is wrong before fallback. | `audit:Tokenizer/accessibility` |-| AR7 | Focused Tokenizer tests, inline and sheet, and the PowerSearch test | inline Clear all; a localized catalog; a Clear all confirmed in the sheet counted across every live region; PowerSearch's own words | The inline Clear all is silent, speaks words other than its catalog message, a sheet Clear all is announced twice, or PowerSearch speaks Tokenizer's words. | `audit:Tokenizer/accessibility` |-| FR16–FR24, FR26, FR27, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, the sheet's draft, Save, pinned footer, discard confirmation and results-drag tests with the draft rule's unit tests, plus real-engine touch evidence | the default resolving both ways, `popover` kept on a compact coarse-pointer screen, Core's composites that render Tokenizer inline — PowerSearch's field and list value editors and Table's list filter — staying inline on a compact coarse-pointer screen, forced sheet, `adaptive` server-rendered as the combobox with the same markup as `popover` and hydrated without a recoverable error, then the trigger on a coarse-pointer client with the body still active, with `hasAutoFocus` the autofocused input's focus on the trigger after the swap and no `onBlur`/`onFocus` reported, the trigger's box against the hydrating field's at 390 and 414px, base props and ref on the trigger, the trigger's description in the inline input's order — a disabled trigger with `disabledMessage`, `description` and a status exposing the caller's ids, the description, the status message and the reason before the count and the tokens —, inert-prop warning, pending search, in-sheet announcements of toggles, busy start, result count and the rendered empty outcome, the confirmed Clear all announced once the confirmation has closed, a below-threshold query, a rejecting source, focus on the panel at open, the query cleared by a swipe, scrim, or Escape close, focus after a presentation change with the sheet closed, focus after the create row, focus after a confirmed Clear all, a spent Clear all focusable with `aria-disabled` and no action, focus after a settled search removes the focused row, no busy feedback or busy-start announcement on open with an instant source, only the search field — no list, no message, no announcement — for an empty query with nothing to list (a search-only source, nothing selected), and the list once a query finds items, element counts under a fine and a coarse pointer at rest and open (Chromium, the Adaptive (default) and Bottom sheet stories: adaptive 154/120 at rest — the closed trigger in place of the inline field, a different element that stays under the fine count — and 157/165 open at the query "e" with no footer, the coarse total reconciled as rest − the re-hosted surfaces host + the dialog of 47 by part, forced sheet 114/114 and 165/165; the two owner exceptions DEC-3 records beyond the FR60 allowance, with before and after counts), no confirmation dialog in the DOM while none is pending, the query kept across a disabled-forced close, `aria-setsize`/`aria-posinset` on each row's `listitem` and the next batch on focus reaching the last rendered row, open/toggle/reopen order, create, batches, limit, Clear all, disabled while open, focus return, `value` unchanged through toggles, create, and Clear all until Save, Save with an unchanged draft reporting nothing and with a changed one reporting the whole draft and the last holding edit, a clean dismissal closing directly, a dirty dismissal asking — Keep editing back to the search field, Discard changes closing without a report —, the footer present while searching, Save disabled over the limit, a results drag moving focus off the search with the query kept | A field with a fine pointer or on a screen that is not compact changes by default, `presentation="popover"` presents the sheet, a Core composite's inline Tokenizer becomes a sheet trigger, a toggle moves a row, a toggle, the create row, or a confirmed Clear all changes `value` before Save, Save reports more than one change or reports when the draft is unchanged, a swipe, scrim, or Escape closes a changed draft without the discard confirmation or asks on an unchanged one, Save or Clear all leaves while the query is non-empty, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |-| FR25 | `Tokenizer.test.tsx` press-inside case; `component:BaseTypeahead` FR12's verification | Press in the input, press elsewhere | A press in the input that closes the list, or a press elsewhere that leaves it open, fails. | — |-| Record structure | `scripts/check-knowledge.mjs` | Template-v3 current record and current-only frontmatter links | Invalid metadata, authority, or relationship references fail repository validation. | `audit:Tokenizer/knowledge` |+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |+| FR1–FR3 | Existing Tokenizer/BaseTypeahead unit tests plus source inspection | empty, tokens, remove, clear, max, wrapping, both overflow modes | Input remounts, suggestion menu changes anchor/width semantics, or overflow ownership is misstated. | `audit:Tokenizer/current` |+| FR4–FR8 | Focused descriptor identity/capture tests when implemented | add, default/custom token edit, max, hidden layer, reparent, stale node, unmount, SSR | Descriptor leaks publicly, captures a transient result/pointer, misses custom controls, or uses unusable geometry. | `audit:Tokenizer/opening-anchor` |+| FR9–FR12 | Layer unit tests and real-Chromium geometry checks when implemented | full/equal/narrow surface, start/end/tie, LTR/RTL, collision, stale fallback | Full-width follows inner input, tie is physical, collision runs early, or stale identity flashes. | `audit:Tokenizer/placement` |+| FR13–FR15, AR5 | Focused Tokenizer/BaseTypeahead tests and exact-head Chromium interaction evidence | pointer/keyboard commit, first/middle/last choice, rejected/deferred control, loading, disabled, max, exhaustion, Escape, Tab, outside focus | Selected values remain available, order changes, focus leaves the combobox, active descendant names no option, stale work reopens, or a terminal state stays interactive. | `audit:Tokenizer/multi-select` |+| PR1–PR5 | Instrumented reads, pending-frame cleanup tests, and first-frame Chromium capture | open, close before frame, reopen opposite side, resize while open | Render-time/repeated reads, observer/pointer tracking, uncancelled frame, or first-frame jump occurs. | `audit:Tokenizer/performance` |+| AR1–AR5 | Existing interaction suites plus focused pointer/keyboard/browser checks; native-disabled assertions pending conformance (`spec:AST-085`) | add/edit, focus/refocus, overflow, disabled, dismissal, retained bootstrap selection | Modality changes placement, semantics/focus regress, active descendant becomes invalid, or visible placement is wrong before fallback. | `audit:Tokenizer/accessibility` |+| AR7 | Focused Tokenizer tests, inline and sheet, and the PowerSearch test | inline Clear all; a localized catalog; a Clear all confirmed in the sheet counted across every live region; PowerSearch's own words | The inline Clear all is silent, speaks words other than its catalog message, a sheet Clear all is announced twice, or PowerSearch speaks Tokenizer's words. | `audit:Tokenizer/accessibility` |+| FR16–FR24, FR26, FR27, AR6, PR6 | Focused Tokenizer sheet tests with the compact-touch query stubbed both ways, a server-render-then-hydrate test, the sheet's draft, Save, pinned footer, discard confirmation and results-drag tests with the draft rule's unit tests, plus real-engine touch evidence | the default resolving both ways, `popover` kept on a compact coarse-pointer screen, Core's composites that render Tokenizer inline — PowerSearch's field and list value editors and Table's list filter — staying inline on a compact coarse-pointer screen, forced sheet, `adaptive` server-rendered as the combobox with the same markup as `popover` and hydrated without a recoverable error, then the sheet field on a coarse-pointer client with the body still active, with `hasAutoFocus` the autofocused input's focus on the trigger after the swap and no `onBlur`/`onFocus` reported, the sheet field's box against the hydrating field's at 390 and 414px, base props and ref on the trigger, the trigger's description in the inline input's order — a disabled trigger with `disabledMessage`, `description` and a status exposing the caller's ids, the description, the status message and the reason before the count and the tokens —, inert-prop warning, pending search, in-sheet announcements of toggles, busy start, result count and the rendered empty outcome, the confirmed Clear all announced once the confirmation has closed, a below-threshold query, a rejecting source, focus on the panel at open, the query cleared by a swipe, scrim, or Escape close, focus after a presentation change with the sheet closed, focus after the create row, focus after a confirmed Clear all, a spent Clear all focusable with `aria-disabled` and no action, focus after a settled search removes the focused row, no busy feedback or busy-start announcement on open with an instant source, only the search field — no list, no message, no announcement — for an empty query with nothing to list (a search-only source, nothing selected), and the list once a query finds items, element counts under a fine and a coarse pointer at rest and open (Chromium, the Adaptive (default) and Bottom sheet stories: adaptive 154/121 at rest — the closed sheet field in place of the inline field, different elements that stay under the fine count — and 157/166 open at the query "e" with no footer, the coarse total reconciled as rest − the re-hosted surfaces host + the dialog of 47 by part, forced sheet 115/115 and 166/166; the two owner exceptions DEC-3 records beyond the FR60 allowance, with before and after counts), no confirmation dialog in the DOM while none is pending, the query kept across a disabled-forced close, `aria-setsize`/`aria-posinset` on each row's `listitem` and the next batch on focus reaching the last rendered row, open/toggle/reopen order, create, batches, limit, Clear all, disabled while open, focus return, `value` unchanged through toggles, create, and Clear all until Save, Save with an unchanged draft reporting nothing and with a changed one reporting the whole draft and the last holding edit, a clean dismissal closing directly, a dirty dismissal asking — Keep editing back to the search field, Discard changes closing without a report —, the footer present while searching, Save disabled over the limit, a results drag moving focus off the search with the query kept | A field with a fine pointer or on a screen that is not compact changes by default, `presentation="popover"` presents the sheet, a Core composite's inline Tokenizer becomes a sheet trigger, a toggle moves a row, a toggle, the create row, or a confirmed Clear all changes `value` before Save, Save reports more than one change or reports when the draft is unchanged, a swipe, scrim, or Escape closes a changed draft without the discard confirmation or asks on an unchanged one, Save or Clear all leaves while the query is non-empty, Clear all skips confirmation, the limit disables checked rows, or the popover bundle carries the sheet. | `audit:Tokenizer/sheet` |+| FR25 | `Tokenizer.test.tsx` press-inside case; `component:BaseTypeahead` FR12's verification | Press in the input, press elsewhere | A press in the input that closes the list, or a press elsewhere that leaves it open, fails. | — |+| Record structure | `scripts/check-knowledge.mjs` | Template-v3 current record and current-only frontmatter links | Invalid metadata, authority, or relationship references fail repository validation. | `audit:Tokenizer/knowledge` |## Decision log@@ -580,8 +576,7 @@ Rejected: the date and time fields' `PickerPresentation` value set withsheet's parts expose no Tokenizer theming targets; they are themed through thecomponents they compose.-The sheet surface is one tall modal BottomSheet opened by a trigger that shows-the selected tokens in the inline field's box: a bordered search field on top,+The sheet surface is one tall modal BottomSheet opened by a trigger in the inline field's box, which shows the selected tokens and keeps `endContent`: a bordered search field on top,checkbox rows whose order is fixed while the sheet is open and regroupedselected-first on the next open, progressive rendering of long lists, a createrow with a trailing Add action, and a pinned footer with a confirmed Clear all@@ -590,17 +585,13 @@ standalone BottomSheet driven by `isOpen`. Rejected: separate manage and add sheloses their place). Rejected: hosting the one sheet in a BottomSheetSwitcher.**INV7 owner exception** (`architecture:component-style-authoring` INV7;-`spec:AST-017/FR60`), in two parts, both beyond the FR60/DEC-29 allowance —-which admits an open layer five extra elements and a closed control none —-and recorded here with their measured counts as FR60 asks. _The closed field under `adaptive`._ INV7's+`spec:AST-017/FR60`), in three parts, all beyond the FR60/DEC-29 allowance — which admits an open layer five extra elements and a closed control none — and recorded here with their measured counts as FR60 asks. _The closed field under `adaptive`._ INV7'ssurface budget says a pointer-specific presentation is a change of attributesand styles on the same elements; under `adaptive` on a compact coarse-pointer-client the closed field instead renders a different element — the trigger-button showing the selected tokens — in place of the inline combobox input,+client the closed field instead renders different elements — the field box holding the trigger button and the selected tokens — in place of the inline combobox input,its token remove actions, and its overflow handling, because the touch surfaceis a sheet opened by a button, not a menu anchored to an input (DEC-3, FR16).-The swap removes elements rather than adding them: at rest 154 elements under a-fine pointer against 120 under a coarse one, measured as below, so the coarse+The swap removes elements rather than adding them: at rest 154 elements under a fine pointer against 121 under a coarse one, measured as below, so the coarsepointer stays under the fine count at rest. _The open layer._ The open sheethas more elements than the open popover menu it replaces under a fine pointer,because it is a different surface, not the same one restyled: a full-height modal with a@@ -611,25 +602,22 @@ plain options; the Clear all confirmation is in the DOM only from the Clearall press until it closes. Measured in Chromium 149 on theAdaptive (default) story (five tokens selected), elements under `body`,fine = desktop 1280×800 `pointer: fine`, coarse = iPhone 13 profile-`pointer: coarse`. At rest: 154 fine / 120 coarse (the trigger with its tokens-is smaller than the inline field with its token remove actions and input).+`pointer: coarse`. At rest: 154 fine / 121 coarse (the field box with its trigger and tokens is smaller than the inline field with its token remove actions and input).Open, at the query "e" — a searching state: 157 fine — the inline field with its anchored menu open on the onestory item matching "e", plus the two shared page live regions the first-announcement creates — and 165 coarse. The coarse total reconciles exactly:-120 at rest, minus the 2 elements of the app-global surfaces host (the+announcement creates — and 166 coarse. The coarse total reconciles exactly:+121 at rest, minus the 2 elements of the app-global surfaces host (thetoast host the open modal re-hosts inside itself, `spec:AST-003/FR18`), plusthe 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. Apending 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",+in every state (FR18), adds 9, so the open coarse count at the query "e" is 175 with it; the counts are re-measured when either surface changes. The forced `bottom-sheet` presentation+renders the same elements under either pointer (115 at rest, 175 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 DOM-until a press. The exception covers the closed `adaptive` trigger and the open sheet; its-counts are re-measured when either surface changes.+until a press. _Custom-token label copies._ With `renderToken`, the closed sheet field renders one extra element per selected token: a `hidden` span holding the item label, which the trigger's description references in place of the caller's token markup (AR6). The copy is outside the accessibility tree, so its label is announced once. Measured in Chromium 149 on the Bottom sheet with end content and custom tokens story (four tokens) at 390px: 153 elements under `body` at rest, four of them the copies, and each label once in the story's accessibility tree. The exception covers the closed `adaptive` trigger, the open sheet, and the custom-token copies; its counts are re-measured when either surface changes.### DEC-4 — The sheet edits a draft that Save commits@@ -645,7 +633,7 @@ state, so the actions do not leave while the person searches, and the searchfield is a bordered input fixed above the list, so the sheet reads as a form:a field, a list, two actions. On a touch screen a direct drag on the resultsmoves focus off the search field without clearing the query, so the rows the-person reaches for come into view (the keyboard follows, `spec:AST-099`). The closed trigger is the inline field's own box,+person reaches for come into view (the keyboard follows, `spec:AST-099`). The closed sheet field is the inline field's own box,so a page that uses the inline field on desktop and the sheet on touch showsone field. Rejected: committing each toggle at once (a mis-tap is live beforethe person has seen the result, a dismissal has nothing to discard, and a@@ -657,9 +645,9 @@ on a results drag (the person loses the search they made to reach those rows).## Open questions-- Should the sheet rows and trigger honor `renderItem` and `renderToken`, or- stay with the default row and token rendering they have now? Today they stay- with the defaults, as the Public concepts section records.+- Should the sheet rows honor `renderItem`, or stay with the default row+ rendering they have now? Today they stay with the default, as the Public+ concepts section records.- The opening-control descriptor implementation remains pending; thepost-selection lifecycle has no unresolved decision.diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjsindex e48efa7239..32fe2187d6 100644--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs@@ -296,7 +296,7 @@ export const docs = {name: 'presentation',type: "'popover' | 'bottom-sheet' | 'adaptive'",description:- 'How the field presents its choices. adaptive (the default) uses the bottom sheet on compact touch screens and the popover otherwise, resolved the same way Selector resolves it; the server render and the hydrating render are the popover. popover is the inline combobox with its anchored suggestion menu on every device. bottom-sheet replaces it on every device 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. In the sheet presentation the trigger is the control: ref, id, aria-* and data-* reach it, and ref receives the trigger button there, so type it Ref<HTMLInputElement | HTMLButtonElement>, which the component accepts (TokenizerProps keeps its released input ref type). renderItem, renderToken, endContent, hasClear, hasEntriesOnFocus, menuWidth, tokenOverflowBehavior and hasAutoFocus have no surface in the sheet, and the field warns once in development when they are passed. Pass presentation="popover" to keep the inline field and those props on every device.',+ 'How the field presents its choices. adaptive (the default) uses the bottom sheet on compact touch screens and the popover otherwise, resolved the same way Selector resolves it; the server render and the hydrating render are the popover. popover is the inline combobox with its anchored suggestion menu on every device. bottom-sheet replaces it on every device with a field showing the selected tokens, whose trigger 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. In the sheet presentation the field box holds the trigger, the tokens and endContent, and keeps the box, theming target and focus ring of the inline field; the trigger is the control: ref, id, aria-* and data-* reach it, and ref receives the trigger button there, so type it Ref<HTMLInputElement | HTMLButtonElement>, which the component accepts (TokenizerProps keeps its released input ref type). endContent sits at the inline end of the field and renderToken renders its tokens, as in the inline field; their own controls act without opening the sheet. renderItem, hasClear (the sheet has its own Clear all), hasEntriesOnFocus, menuWidth, tokenOverflowBehavior (the field wraps its tokens) and hasAutoFocus have no surface in the sheet, and the field warns once in development when they are passed. Pass presentation="popover" to keep the inline field and those props on every device.',default: "'adaptive'",},],@@ -642,7 +642,7 @@ export const docsZh = {name: 'presentation',type: "'popover' | 'bottom-sheet' | 'adaptive'",description:- '字段如何呈现选项。adaptive(默认)在紧凑触摸屏上使用底部面板,其他情况使用 popover,解析方式与 Selector 相同;服务端渲染和水合期间的渲染均为 popover。popover 在所有设备上为内联组合框及其锚定建议菜单。bottom-sheet 在所有设备上改为一个显示已选标记的触发按钮,点按后打开一个高的模态底部面板——顶部为搜索行,下方为整行复选框行(面板打开期间位置保持不变),hasCreate 时有「创建」行,底部固定显示需确认的「全部清除」和「保存」;面板编辑的是草稿,onChange 仅在「保存」提交时触发一次,草稿有改动时滑动、点击遮罩或按 Escape 关闭会先询问是否放弃。在底部面板呈现中,触发按钮即为控件:ref、id、aria-* 和 data-* 都作用于它,ref 在该呈现中收到的是触发按钮,因此请将其类型声明为组件所接受的 Ref<HTMLInputElement | HTMLButtonElement>(TokenizerProps 保留已发布的输入框 ref 类型)。renderItem、renderToken、endContent、hasClear、hasEntriesOnFocus、menuWidth、tokenOverflowBehavior 和 hasAutoFocus 在底部面板中没有作用对象,传入时开发模式下会警告一次。传入 presentation="popover" 可在所有设备上保留内联字段和这些属性。',+ '字段如何呈现选项。adaptive(默认)在紧凑触摸屏上使用底部面板,其他情况使用 popover,解析方式与 Selector 相同;服务端渲染和水合期间的渲染均为 popover。popover 在所有设备上为内联组合框及其锚定建议菜单。bottom-sheet 在所有设备上改为一个显示已选标记的字段,点按其中的触发按钮后打开一个高的模态底部面板——顶部为搜索行,下方为整行复选框行(面板打开期间位置保持不变),hasCreate 时有「创建」行,底部固定显示需确认的「全部清除」和「保存」;面板编辑的是草稿,onChange 仅在「保存」提交时触发一次,草稿有改动时滑动、点击遮罩或按 Escape 关闭会先询问是否放弃。在底部面板呈现中,字段框包含触发按钮、标记和 endContent,并保留内联字段的外框、主题目标和焦点环;触发按钮即为控件:ref、id、aria-* 和 data-* 都作用于它,ref 在该呈现中收到的是触发按钮,因此请将其类型声明为组件所接受的 Ref<HTMLInputElement | HTMLButtonElement>(TokenizerProps 保留已发布的输入框 ref 类型)。endContent 位于字段的行内末端,renderToken 渲染字段中的标记,与内联字段相同;其中的控件可直接操作,不会打开底部面板。renderItem、hasClear(底部面板自带“全部清除”)、hasEntriesOnFocus、menuWidth、tokenOverflowBehavior(字段会换行显示标记)和 hasAutoFocus 在底部面板中没有作用对象,传入时开发模式下会警告一次。传入 presentation="popover" 可在所有设备上保留内联字段和这些属性。',default: "'adaptive'",},],@@ -845,6 +845,6 @@ export const docsDense = {endContent: 'Content at input row end. For buttons, counts, controls.',handleRef: 'Imperative handle for focus() and blur() control.',presentation:- "'adaptive' (default: sheet on compact touch, else popover; SSR/hydration render popover) | 'popover' (inline combobox, every device) | 'bottom-sheet' (trigger + one searchable modal sheet of checkbox rows editing a draft that Save commits; onChange fires once, on Save). Sheet: ref reaches the trigger button; renderItem/renderToken/endContent/hasClear/hasEntriesOnFocus/menuWidth/tokenOverflowBehavior/hasAutoFocus inert (dev warning). presentation=\"popover\" keeps them on every device.",+ "'adaptive' (default: sheet on compact touch, else popover; SSR/hydration render popover) | 'popover' (inline combobox, every device) | 'bottom-sheet' (field box with trigger + one searchable modal sheet of checkbox rows editing a draft that Save commits; onChange fires once, on Save). Sheet: field box keeps the inline box, theming target and focus ring; ref reaches the trigger button; endContent (field end) and renderToken (field tokens) work as inline; renderItem/hasClear/hasEntriesOnFocus/menuWidth/tokenOverflowBehavior/hasAutoFocus inert (dev warning). presentation=\"popover\" keeps them on every device.",},};diff --git a/packages/core/src/Tokenizer/Tokenizer.tsx b/packages/core/src/Tokenizer/Tokenizer.tsxindex 95141fb739..dc146e1182 100644--- a/packages/core/src/Tokenizer/Tokenizer.tsx+++ b/packages/core/src/Tokenizer/Tokenizer.tsx@@ -8,8 +8,8 @@* useAdaptivePresentation, and TokenizerBottomSheet (lazy)* @output Exports Tokenizer multi-select typeahead component* @position Composed component; forwards DOM ref and exposes focus control via- * handleRef. The `presentation` prop swaps the inline combobox for a- * trigger that opens TokenizerBottomSheet.+ * handleRef. The `presentation` prop swaps the inline combobox for a field+ * box whose trigger opens TokenizerBottomSheet.** SYNC: When modified, update:* - /packages/core/src/Tokenizer/index.ts@@ -48,6 +48,7 @@ import {} from '../Field/fieldParts';import {inputDisabledFocusStyles} from '../Field/inputDisabledFocus';import {useMergedRefs} from '../hooks/useMergedRefs';+import {hasInteractiveAncestor} from '../hooks/useClickableContainer';import {TokenizerClearAllMessageContext} from './TokenizerClearAllMessageContext';import {TokenizerItemRemovableContext} from './TokenizerItemRemovableContext';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';@@ -303,8 +304,8 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<* How the field presents its choices.* - `'popover'`: the inline combobox with its anchored suggestion menu, on* every device.- * - `'bottom-sheet'`: a trigger showing the selected tokens that opens one- * tall modal sheet: a search row on top, full-width checkbox rows that+ * - `'bottom-sheet'`: a field showing the selected tokens, whose trigger+ * 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@@ -315,12 +316,16 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<* otherwise the popover — the same resolution Selector uses. The server* render and the hydrating render are the popover.*- * 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. Pass `'popover'` to keep the inline field- * and those props on every device.+ * In the sheet presentation the field's box keeps the inline field's box,+ * theming target and focus ring, and holds the trigger, the tokens and+ * `endContent`. The trigger is the control: `ref`, `id`, `aria-*`, and+ * `data-*` reach it. `endContent` renders at the field's+ * inline end and `renderToken` renders the field's tokens, as in the inline+ * field. `renderItem`, `hasClear` (the sheet has its own Clear all),+ * `hasEntriesOnFocus`, `menuWidth`, `tokenOverflowBehavior` (the field+ * wraps its tokens), and `hasAutoFocus` have no surface to act on and warn+ * once in development. Pass `'popover'` to keep the inline field and those+ * props on every device.* @default 'adaptive'*/presentation?: TokenizerPresentation;@@ -487,20 +492,52 @@ const styles = stylex.create({color: colorVars['--color-text-secondary'],paddingInline: spacingVars['--spacing-1'],},- // The sheet presentation's trigger: the field's own control box, as a- // button. It wraps tokens like the inline field, but there is no input to- // type into, so the cursor says "press".- sheetTrigger: {+ // The sheet presentation's field: the inline field's own control box. A+ // button cannot contain controls, so the trigger, the tokens and the end lane+ // are siblings in this box. `endContent` and a custom token can then hold their+ // own controls. There is no input to type into, so the cursor says "press".+ sheetField: {width: '100%',+ cursor: {+ default: 'pointer',+ ':is(:disabled,[aria-disabled="true"])': 'default',+ },+ },+ // The box carries no aria-disabled: that would expose a caller's operable+ // `endContent` as disabled. The trigger carries it, so the box keys its+ // disabled cursor on the prop.+ sheetFieldDisabled: {+ cursor: 'default',+ },+ // With tokens, the button covers the box beneath them. A tap on a token or+ // on empty space then opens the sheet. The box draws the focus ring, so the+ // button draws none.+ sheetTrigger: {+ appearance: 'none',+ flexGrow: 1,+ alignSelf: 'stretch',+ display: 'flex',+ alignItems: 'center',+ minWidth: 0,+ padding: 0,+ margin: 0,+ borderWidth: 0,+ borderStyle: 'none',+ backgroundColor: 'transparent',fontFamily: 'inherit',fontSize: 'inherit',+ lineHeight: 'inherit',color: 'inherit',textAlign: 'start',- appearance: 'none',cursor: {default: 'pointer',':is(:disabled,[aria-disabled="true"])': 'default',},+ outline: 'none',+ },+ sheetTriggerWithTokens: {+ position: 'absolute',+ inset: 0,},// An aria-disabled button gets no system disabled paint in forced colors;// GrayText is the platform's disabled affordance there. Defaults repeat the@@ -906,8 +943,6 @@ export function Tokenizer<T extends SearchableItem>({? ([['renderItem', renderItem],- ['renderToken', renderToken],- ['endContent', endContent],['hasClear', hasClear || undefined],['hasEntriesOnFocus', hasEntriesOnFocus || undefined],['menuWidth', menuWidth],@@ -989,12 +1024,32 @@ export function Tokenizer<T extends SearchableItem>({[tooltipAnchorRef],);+ // A swap also removes `endContent` and a custom token's remove. If focus is+ // in the box when it detaches, the new control takes it. The box also anchors+ // the disabled-message tooltip.+ const sheetFieldCallbackRef = useCallback(+ (el: HTMLDivElement | null) => {+ tooltipAnchorRef(el);+ if (el == null) {+ return;+ }+ return () => {+ if (el.contains(el.ownerDocument.activeElement)) {+ isFocusPendingHandOffRef.current = true;+ }+ tooltipAnchorRef(null);+ };+ },+ [tooltipAnchorRef],+ );+// The sheet presentation has no input; the public ref reaches the trigger,- // the control it stands for (`family:input-fields` FR10).+ // the control it stands for (`family:input-fields` FR10). The+ // disabled-message tooltip anchors to the field box around it, as it+ // anchors to the inline field's wrapper.const triggerMergedRef = useMergedRefs<HTMLButtonElement>(triggerRef,ref as React.Ref<HTMLButtonElement> | undefined,- disabledMessageTooltip.ref,handOffFocusRef,);@@ -1019,6 +1074,14 @@ export function Tokenizer<T extends SearchableItem>({// `endContent`, a clear button, or all three — so its width is measured// rather than assumed, and the input reserves it.const [laneRef, laneReserve] = useEndLaneReserve(END_LANE_INSET);+ // `laneRef` publishes the lane's width, so token rows and the placeholder+ // stop short of it. `sheetLaneRef` tells a tap in the lane from a tap on the+ // field.+ const sheetLaneRef = useRef<HTMLDivElement | null>(null);+ const sheetLaneMergedRef = useMergedRefs<HTMLDivElement>(+ laneRef,+ sheetLaneRef,+ );// A composing component can lock tokens (PowerSearch's read-only filters// and read-only field). No remove path removes a locked token.const isItemRemovable = use(TokenizerItemRemovableContext);@@ -1556,92 +1619,91 @@ export function Tokenizer<T extends SearchableItem>({</div>);+ // A `renderToken` token's own remove control in the sheet field removes at+ // once, as it does in the inline field. Its control leaves with it, so+ // focus moves to the trigger.+ const handleSheetTokenRemove = (item: T) => {+ if (handleRemove(item)) {+ triggerRef.current?.focus();+ }+ };+ // A tap on a token, the placeholder or empty space opens the sheet, as a tap+ // on the trigger does. The trigger, `endContent` and a custom token's+ // controls handle their own clicks.+ const handleSheetFieldClick = (event: React.MouseEvent<HTMLDivElement>) => {+ const trigger = triggerRef.current;+ const target = event.target;+ if (trigger == null || !(target instanceof Element)) {+ return;+ }+ if (+ trigger.contains(target) ||+ sheetLaneRef.current?.contains(target) ||+ hasInteractiveAncestor(target, event.currentTarget)+ ) {+ return;+ }+ trigger.click();+ };++ // The caller's onFocus and onBlur report focus entering and leaving the whole+ // box, as for the inline wrapper. A move between the trigger, `endContent`+ // and a custom token's controls stays inside the field.+ const handleSheetFieldFocus = (event: React.FocusEvent<HTMLDivElement>) => {+ // BottomSheet focuses the trigger only after its exit completes; that+ // focus is the signal that the retained sheet can leave. If the+ // resolution moved to the popover meanwhile, the inline input takes the+ // focus over once it mounts.+ const isReturningFromSheet =+ (event.target as EventTarget) === triggerRef.current &&+ !isSheetOpen &&+ isSheetPresented;+ if (isReturningFromSheet) {+ setIsSheetPresented(false);+ }+ const relatedTarget = event.relatedTarget;+ if (+ relatedTarget instanceof Node &&+ event.currentTarget.contains(relatedTarget)+ ) {+ return;+ }+ // Focus that returns from the field's own sheet, or that a presentation swap+ // hands over, does not enter from outside. The caller's onFocus stays quiet+ // for it (`family:input-fields` FR10).+ const isInsideTheField =+ (isReturningFromSheet && hasReportedFocusRef.current) ||+ isHandingOffFocusRef.current;+ if (!isInsideTheField) {+ hasReportedFocusRef.current = true;+ onFocus?.(event);+ }+ };+ const handleSheetFieldBlur = (event: React.FocusEvent<HTMLDivElement>) => {+ // Focus moving into the sheet, or to another control in the box, is+ // still the field's. Only a blur to somewhere else reports.+ const relatedTarget = event.relatedTarget;+ if (+ isSheetOpen ||+ (relatedTarget instanceof Node &&+ event.currentTarget.contains(relatedTarget))+ ) {+ return;+ }+ hasReportedFocusRef.current = false;+ isFocusPendingHandOffRef.current = false;+ onBlur?.(event);+ };+let tokenizerContent: ReactNode;if (isSheetPresentation) {tokenizerContent = (<>- <button- // The field-level pass-through props (`data-*`, `aria-*`) were typed- // for the inline input; here the control is a button.- {...(restWithoutClick as React.ButtonHTMLAttributes<HTMLButtonElement>)}- ref={triggerMergedRef}- type="button"- id={inputId}- aria-labelledby={fieldLabelledBy}- aria-haspopup="dialog"- aria-expanded={isSheetOpen}- aria-disabled={isDisabled || undefined}- // The description is what the inline input's is, in its order —- // the caller's ids, the field description, the status message, the- // disabled reason (`spec:AST-085` FR5: a disabled control exposes- // its description and reason on itself) — then the hidden count and- // the rendered tokens themselves, each by id: the- // accessible-description algorithm reads the referenced elements in- // order and separates them, so every label renders once- // (`architecture:component-style-authoring` INV7) and no locale's- // list punctuation is written here (AR6).- aria-describedby={- [- ariaDescribedByProp,- ariaDescribedBy,- value.length > 0 ? triggerTokensId : null,- ...value.map(item => tokenElementId(item.id)),- ]- .filter(Boolean)- .join(' ') || undefined- }- // The open runs first and the caller's onClick after it, as the- // inline input composes its click: a caller observes the click but- // cannot cancel the field's own handling- // (`family:input-fields` FR10).- onClick={composeEventHandlers<React.MouseEvent<HTMLButtonElement>>(- () => {- if (isDisabled) {- return;- }- setIsSheetPresented(true);- setSheetInitialQuery(sheetQueryRef.current);- setIsSheetOpen(true);- },- // Typed for the input by the base props; here the control is the- // trigger button, and the handler only reads the event.- callerOnClick as unknown as- React.MouseEventHandler<HTMLButtonElement> | undefined,- )}- onFocus={event => {- // BottomSheet focuses the trigger only after its exit completes;- // that focus is the signal that the retained sheet can leave. If- // the resolution moved to the popover meanwhile, the inline input- // takes the focus over once it mounts. The field's own sheet is- // part of the field: focus coming back from it, or handed over by- // a presentation swap, is not focus entering from outside, so the- // caller's onFocus — "when focus enters the tokenizer from- // outside" — stays quiet for it (`family:input-fields` FR10).- const isReturningFromSheet = !isSheetOpen && isSheetPresented;- if (isReturningFromSheet) {- setIsSheetPresented(false);- }- const isInsideTheField =- (isReturningFromSheet && hasReportedFocusRef.current) ||- isHandingOffFocusRef.current;- if (!isInsideTheField) {- hasReportedFocusRef.current = true;- onFocus?.(event);- }- }}- onBlur={event => {- // Focus moving into the sheet is still the field's: the flag- // stays, and the caller's onBlur — "when focus leaves the- // tokenizer entirely" — stays quiet. Only a blur to somewhere- // else reports.- if (isSheetOpen) {- return;- }- hasReportedFocusRef.current = false;- isFocusPendingHandOffRef.current = false;- onBlur?.(event);- }}- onKeyDown={onKeyDown}+ <div+ ref={sheetFieldCallbackRef}+ onClick={handleSheetFieldClick}+ onFocus={handleSheetFieldFocus}+ onBlur={handleSheetFieldBlur}{...mergeProps(themeProps('tokenizer', {size,@@ -1651,8 +1713,9 @@ export function Tokenizer<T extends SearchableItem>({stylex.props(inputWrapperStyles.base,styles.wrapper,- styles.sheetTrigger,- // The trigger keeps the inline field's height for its size step,+ styles.sheetField,+ isDisabled && styles.sheetFieldDisabled,+ // The field keeps the inline field's height for its size step,// as Selector's bottom-sheet trigger does; the sheet's own rows// and search field carry the touch-sized targets.sizeStyles[size],@@ -1675,8 +1738,77 @@ export function Tokenizer<T extends SearchableItem>({{renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}</span>)}- {value.length > 0 ? (- value.map(item => (+ <button+ // The field-level pass-through props (`data-*`, `aria-*`) were typed+ // for the inline input; here the control is a button.+ {...(restWithoutClick as React.ButtonHTMLAttributes<HTMLButtonElement>)}+ ref={triggerMergedRef}+ type="button"+ id={inputId}+ aria-labelledby={fieldLabelledBy}+ aria-haspopup="dialog"+ aria-expanded={isSheetOpen}+ aria-disabled={isDisabled || undefined}+ // The description follows the inline input's order: the caller's+ // ids, the field description, the status message, then the+ // disabled reason (`spec:AST-085` FR5). The hidden count and the+ // token labels follow, each by id. The algorithm separates+ // referenced elements, so no list punctuation is written here+ // (AR6). A default token is display-only and is its own label. A+ // custom token can hold controls, so a hidden copy of its item+ // label stands in.+ aria-describedby={+ [+ ariaDescribedByProp,+ ariaDescribedBy,+ value.length > 0 ? triggerTokensId : null,+ ...value.map(item => tokenElementId(item.id)),+ ]+ .filter(Boolean)+ .join(' ') || undefined+ }+ // The open runs first and the caller's onClick after it, as the+ // inline input composes its click: a caller observes the click but+ // cannot cancel the field's own handling+ // (`family:input-fields` FR10).+ onClick={composeEventHandlers<React.MouseEvent<HTMLButtonElement>>(+ () => {+ if (isDisabled) {+ return;+ }+ setIsSheetPresented(true);+ setSheetInitialQuery(sheetQueryRef.current);+ setIsSheetOpen(true);+ },+ // Typed for the input by the base props; here the control is the+ // trigger button, and the handler only reads the event.+ callerOnClick as unknown as+ React.MouseEventHandler<HTMLButtonElement> | undefined,+ )}+ onKeyDown={onKeyDown}+ {...stylex.props(+ styles.sheetTrigger,+ value.length > 0 && styles.sheetTriggerWithTokens,+ // With no token the placeholder stops short of the end lane, as+ // the inline input's text does.+ value.length === 0 && laneReserve,+ )}>+ {value.length === 0 && (+ <span+ {...stylex.props(+ styles.sheetTriggerPlaceholder,+ isDisabled && styles.sheetTriggerPlaceholderDisabled,+ )}>+ {placeholder ?? ''}+ </span>+ )}+ </button>+ {value.map(item =>+ renderToken ? (+ <span key={item.id} {...stylex.props(styles.token)}>+ {renderToken(item, () => handleSheetTokenRemove(item))}+ </span>+ ) : (<Tokenkey={item.id}id={tokenElementId(item.id)}@@ -1685,22 +1817,27 @@ export function Tokenizer<T extends SearchableItem>({isDisabled={isDisabled}xstyle={isDisabled ? styles.sheetTokenDisabled : undefined}/>- ))- ) : (- <span- {...stylex.props(- styles.sheetTriggerPlaceholder,- isDisabled && styles.sheetTriggerPlaceholderDisabled,- )}>- {placeholder ?? ''}- </span>+ ),+ )}+ {isRenderable(endContent) && (+ <div+ ref={sheetLaneMergedRef}+ {...stylex.props(styles.endSection, endSectionSizeStyles[size])}>+ {endContent}+ </div>)}- </button>+ </div>{value.length > 0 && (<VisuallyHidden id={triggerTokensId}>{t('@astryx.tokenizer.selectedCount', {count: value.length})}</VisuallyHidden>)}+ {renderToken != null &&+ value.map(item => (+ <span key={item.id} id={tokenElementId(item.id)} hidden>+ {item.label}+ </span>+ ))}{/* Form carriers, gated exactly as the inline branch gates its own: adisabled field submits nothing. */}{htmlName != null &&diff --git a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsxindex c7d7ee1d7d..a258302412 100644--- a/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx+++ b/packages/core/src/Tokenizer/TokenizerBottomSheet.test.tsx@@ -25,13 +25,14 @@ import {waitFor,within,} from '@testing-library/react';-import {StrictMode, createRef, useState} from 'react';+import {StrictMode, createRef, useState, type ReactNode} from 'react';import * as stylex from '@stylexjs/stylex';import {Tokenizer,type TokenizerChange,type TokenizerProps,} from './Tokenizer';+import {Token} from '../Token/Token';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {__resetDevWarnings} from '../utils/devWarning';import {colorVars, sizeVars, spacingVars} from '../theme/tokens.stylex';@@ -89,6 +90,8 @@ function Harness({debounceMs?: number;onFocus?: (event: React.FocusEvent) => void;onBlur?: (event: React.FocusEvent) => void;+ endContent?: ReactNode;+ renderToken?: (item: SearchableItem, onRemove: () => void) => ReactNode;}) {const [value, setValue] = useState<SearchableItem[]>(initial);return (@@ -145,6 +148,10 @@ function stubEnvironment() {}const openTrigger = () => screen.getByRole('button', {name: 'Tags'});+// The sheet field's control box: it holds the trigger button, the tokens and+// the end lane.+const sheetField = () =>+ openTrigger().closest<HTMLElement>('.astryx-tokenizer')!;// The row list carries the progressive-rendering counters (FR21).const list = () => document.querySelector<HTMLElement>('[data-total-count]')!;@@ -214,10 +221,11 @@ describe('Tokenizer presentation (FR16)', () => {const trigger = openTrigger();expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');expect(trigger).toHaveAttribute('aria-expanded', 'false');- expect(trigger).toHaveTextContent('Design');- expect(trigger).toHaveTextContent('Eng');- // Tokens in the trigger are display-only (FR17).- expect(within(trigger).queryAllByRole('button')).toHaveLength(0);+ expect(sheetField()).toHaveTextContent('Design');+ expect(sheetField()).toHaveTextContent('Eng');+ // The field's tokens are display-only (FR17): the trigger is its only+ // button.+ expect(within(sheetField()).getAllByRole('button')).toEqual([trigger]);fireEvent.click(trigger);expect(trigger).toHaveAttribute('aria-expanded', 'true');@@ -453,7 +461,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// 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(sheetField()).not.toHaveTextContent('Custom');expect(search).toHaveValue('');const custom = await screen.findByRole('checkbox', {name: 'Custom'});expect(custom).toBeChecked();@@ -478,7 +486,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {item: {id: 'Custom', label: 'Custom'},type: 'create',});- await waitFor(() => expect(trigger).toHaveTextContent('Custom'));+ await waitFor(() => expect(sheetField()).toHaveTextContent('Custom'));} finally {modalSpy.mockRestore();}@@ -1352,23 +1360,24 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {// algorithm's, not a literal (i18n INV1a).expect(trigger).toHaveAccessibleDescription('2 selected Design Eng');// The labels come from the rendered tokens themselves, referenced by id:- // in the trigger and its description, each label is in the DOM once- // (component-style-authoring INV7); the only hidden text is the count.+ // in the field and the trigger's description, each label is in the DOM+ // once (component-style-authoring INV7); the only hidden text is the+ // count.const ids = trigger.getAttribute('aria-describedby')!.split(' ');expect(ids).toHaveLength(3);const described = ids.map(id => document.getElementById(id)!);expect(described[0]).toHaveTextContent('2 selected');expect(described[1]).toBe(- within(trigger).getByText('Design').closest('.astryx-token'),+ within(sheetField()).getByText('Design').closest('.astryx-token'),);expect(described[2]).toBe(- within(trigger).getByText('Eng').closest('.astryx-token'),+ within(sheetField()).getByText('Eng').closest('.astryx-token'),);const leaves = (root: Element) =>Array.from(root.querySelectorAll('*')).filter(el => el.children.length === 0 && el.textContent?.trim() !== '',);- const texts = [...leaves(trigger), ...leaves(described[0])].map(+ const texts = [...leaves(sheetField()), ...leaves(described[0])].map(el => el.textContent,);expect(texts.filter(text => text === 'Design')).toHaveLength(1);@@ -1540,6 +1549,239 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(order).toEqual(['false']);});+ it("renders endContent at the sheet field's inline end; its controls work without opening the sheet (FR17)", async () => {+ const onApply = vi.fn();+ render(+ <Harness+ endContent={+ <button type="button" onClick={onApply}>+ Apply+ </button>+ }+ />,+ );+ const trigger = openTrigger();+ const apply = screen.getByRole('button', {name: 'Apply'});+ expect(sheetField()).toContainElement(apply);+ expect(trigger).not.toContainElement(apply);+ // A control of its own, after the trigger in the focus order.+ expect(+ trigger.compareDocumentPosition(apply) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ apply.focus();+ expect(apply).toHaveFocus();+ fireEvent.click(apply);+ expect(onApply).toHaveBeenCalledTimes(1);+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ // A tap on the field around it still opens the sheet.+ fireEvent.click(sheetField());+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(+ await screen.findByRole('dialog', {name: 'Tags'}),+ ).toBeInTheDocument();+ });++ it('keeps endContent operable and exposed as enabled in a disabled sheet field (FR17)', () => {+ const onApply = vi.fn();+ render(+ <Harness+ isDisabled+ endContent={+ <button type="button" onClick={onApply}>+ Apply+ </button>+ }+ />,+ );+ const trigger = openTrigger();+ expect(trigger).toHaveAttribute('aria-disabled', 'true');+ const apply = screen.getByRole('button', {name: 'Apply'});+ // aria-disabled on an ancestor would expose the caller's button as+ // disabled while a press still runs it.+ expect(apply.closest('[aria-disabled="true"]')).toBeNull();+ fireEvent.click(apply);+ expect(onApply).toHaveBeenCalledTimes(1);+ // The disabled field itself still does not open.+ fireEvent.click(sheetField());+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });++ it('renders endContent beside the placeholder of an empty sheet field (FR17)', () => {+ render(+ <Harness initial={[]} endContent={<button type="button">Cc</button>} />,+ );+ expect(sheetField()).toHaveTextContent('Add tags');+ expect(+ within(sheetField()).getByRole('button', {name: 'Cc'}),+ ).toBeInTheDocument();+ expect(openTrigger()).toHaveTextContent('Add tags');+ });++ it("renders the sheet field's tokens through renderToken; a token's own remove control removes at once (FR17)", async () => {+ const spy = vi.fn();+ render(+ <Harness+ spy={spy}+ renderToken={(item, onRemove) => (+ <Token label={item.label} onRemove={onRemove} />+ )}+ />,+ );+ const trigger = openTrigger();+ const removeDesign = within(sheetField()).getByRole('button', {+ name: 'Remove Design',+ });+ expect(trigger).not.toContainElement(removeDesign);+ // A custom token's controls follow the trigger in the focus order.+ expect(+ trigger.compareDocumentPosition(removeDesign) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy();+ // The description names the count and the item labels only: no+ // referenced element holds a custom token's control.+ const described = trigger+ .getAttribute('aria-describedby')!+ .split(' ')+ .map(id => document.getElementById(id)!);+ expect(described.map(el => el.textContent)).toEqual([+ '2 selected',+ 'Design',+ 'Eng',+ ]);+ expect(described.filter(el => el.querySelector('button'))).toEqual([]);+ // The label copies stay out of the accessibility tree.+ expect(described.slice(1).every(el => el.hidden)).toBe(true);+ fireEvent.click(removeDesign);+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy).toHaveBeenCalledWith([ITEMS[1]], {+ item: ITEMS[0],+ type: 'remove',+ });+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ // The removed token's control is gone, so focus moves to the trigger.+ expect(trigger).toHaveFocus();+ // A tap on a custom token's label opens the sheet, as on the default+ // token.+ fireEvent.click(within(sheetField()).getByText('Eng'));+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ expect(+ await screen.findByRole('dialog', {name: 'Tags'}),+ ).toBeInTheDocument();+ });++ it('reports onFocus and onBlur for the whole sheet field, not for moves between its controls (FR17; input-fields FR10)', () => {+ const onFocus = vi.fn();+ const onBlur = vi.fn();+ render(+ <>+ <Harness+ onFocus={onFocus}+ onBlur={onBlur}+ endContent={<button type="button">Cc</button>}+ renderToken={(item, onRemove) => (+ <Token label={item.label} onRemove={onRemove} />+ )}+ />+ <button type="button">Outside</button>+ </>,+ );+ const trigger = openTrigger();+ act(() => trigger.focus());+ expect(onFocus).toHaveBeenCalledTimes(1);+ // Moving among the trigger, the end content and a token's own control+ // stays inside the field.+ act(() => screen.getByRole('button', {name: 'Cc'}).focus());+ act(() => screen.getByRole('button', {name: 'Remove Eng'}).focus());+ act(() => trigger.focus());+ expect(onFocus).toHaveBeenCalledTimes(1);+ expect(onBlur).not.toHaveBeenCalled();+ act(() => screen.getByRole('button', {name: 'Outside'}).focus());+ expect(onBlur).toHaveBeenCalledTimes(1);+ // Entering at the end content is focus entering the field.+ act(() => screen.getByRole('button', {name: 'Cc'}).focus());+ expect(onFocus).toHaveBeenCalledTimes(2);+ });++ it('hands focus to the inline input when a swap removes a focused end-content or custom-token control (FR16)', () => {+ let compact = true;+ const listeners = new Set<() => void>();+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockImplementation((query: string) => ({+ get matches() {+ return query === COMPACT_TOUCH_QUERY ? compact : false;+ },+ media: query,+ onchange: null,+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),+ removeEventListener: (_: string, cb: () => void) =>+ listeners.delete(cb),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })),+ );+ const turn = (next: boolean) => {+ compact = next;+ act(() => {+ for (const cb of listeners) {+ cb();+ }+ });+ };+ const view = (+ <Harness+ presentation="adaptive"+ endContent={<button type="button">Cc</button>}+ renderToken={(item, onRemove) => (+ <Token label={item.label} onRemove={onRemove} />+ )}+ />+ );+ render(view);+ // The sheet field: the end content holds focus, then the screen stops+ // being compact-touch.+ act(() => openTrigger().focus());+ const cc = screen.getByRole('button', {name: 'Cc'});+ act(() => cc.focus());+ expect(cc).toHaveFocus();+ turn(false);+ expect(screen.getByRole('combobox')).toHaveFocus();+ // Back to the sheet field, then a custom token's remove holds focus.+ turn(true);+ const remove = within(sheetField()).getByRole('button', {+ name: 'Remove Design',+ });+ act(() => remove.focus());+ expect(remove).toHaveFocus();+ turn(false);+ expect(screen.getByRole('combobox')).toHaveFocus();+ });++ it('does not warn about endContent or renderToken in the sheet presentation', () => {+ __resetDevWarnings();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ render(+ <Tokenizer+ label="Tags"+ searchSource={source}+ value={[ITEMS[0]]}+ onChange={() => {}}+ endContent={<button type="button">Apply</button>}+ renderToken={item => <span>{item.label}</span>}+ hasClear+ presentation="bottom-sheet"+ />,+ );+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toMatch(/`hasClear` has no surface/);+ expect(warn.mock.calls[0][0]).not.toMatch(/endContent|renderToken/);+ warn.mockRestore();+ });+it('warns once in development about props with no sheet surface (INV3)', () => {__resetDevWarnings();const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});@@ -1748,11 +1990,11 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {},});const {unmount} = render(<Harness isDisabled />);- const trigger = openTrigger();+ const field = sheetField();for (const name of atoms(forced.trigger)) {- expect(trigger).toHaveClass(name);+ expect(field).toHaveClass(name);}- const tokens = trigger.querySelectorAll('.astryx-token');+ const tokens = field.querySelectorAll('.astryx-token');expect(tokens).toHaveLength(2);for (const token of tokens) {for (const name of atoms(forced.token)) {@@ -2783,9 +3025,7 @@ describe('Tokenizer sheet presentation (single-sheet touch flow)', () => {expect(hidden).toHaveLength(2);expect(hidden[0]).toHaveAttribute('name', 'tags');expect(hidden[0]).toHaveValue('design');- const trigger = openTrigger();- expect(trigger).toHaveClass('astryx-tokenizer');- expect(trigger).toHaveAttribute('data-status', 'error');+ expect(sheetField()).toHaveAttribute('data-status', 'error');expect(screen.getByText('Pick at least three')).toBeInTheDocument();});diff --git a/packages/core/src/Tokenizer/__tests__/TokenizerSheetField.a11y.chromium.spec.ts b/packages/core/src/Tokenizer/__tests__/TokenizerSheetField.a11y.chromium.spec.tsnew file mode 100644index 0000000000..8a842c965c--- /dev/null+++ b/packages/core/src/Tokenizer/__tests__/TokenizerSheetField.a11y.chromium.spec.ts@@ -0,0 +1,204 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Tokenizer ^apps/storybook/stories/Tokenizer++/**+ * @file TokenizerSheetField.a11y.chromium.spec.ts+ * @input The `Core/Tokenizer` sheet story with end content and custom tokens+ * in a built Storybook.+ * @output Real-engine proof that the sheet field keeps its tokens clear of+ * the end lane across widths and both writing directions, that the end+ * content and a custom token's remove control act without opening the+ * sheet, and that a tap on a token opens it.+ * @position Run with `pnpm test:a11y-contract`. The lane is absolutely+ * positioned, so whether a token reaches it depends on how rows wrap at a+ * given width, which only a shipping layout engine can show.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++type Direction = 'ltr' | 'rtl';++const STORY = 'core-tokenizer--sheet-presentation-end-content';++async function open(page: Page, direction: Direction = 'ltr'): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=direction:${direction}`,+ {waitUntil: 'load'},+ );+ await page+ .getByRole('button', {name: 'Recipients'})+ .waitFor({state: 'visible'});+ await page.evaluate(async () => {+ await document.fonts.ready;+ });+}++const trigger = (page: Page) => page.getByRole('button', {name: 'Recipients'});++/**+ * Sizes the story's grid column to `width` and returns every token that+ * paints under the end lane, plus a field whose content is wider than its+ * box.+ */+async function overlapsAt(page: Page, width: number): Promise<string[]> {+ return page.evaluate(async width => {+ const host = document.querySelector<HTMLElement>(+ '#storybook-root [style*="grid-template-columns"]',+ );+ if (host == null) {+ throw new Error('No sizing grid in the story');+ }+ host.style.gridTemplateColumns = `minmax(0, ${width}px)`;+ for (let frame = 0; frame < 4; frame++) {+ await new Promise(resolve => requestAnimationFrame(resolve));+ }+ const field = host.querySelector<HTMLElement>('.astryx-tokenizer');+ const cc = [...host.querySelectorAll('button')].find(button =>+ button.textContent?.startsWith('Cc'),+ );+ const lane = cc?.parentElement;+ if (field == null || lane == null) {+ throw new Error('The story has no sheet field with an end lane');+ }+ const l = lane.getBoundingClientRect();+ const found: string[] = [];+ for (const token of field.querySelectorAll('.astryx-token')) {+ const t = token.getBoundingClientRect();+ const crosses =+ t.right > l.left + 0.5 &&+ t.left < l.right - 0.5 &&+ t.bottom > l.top + 0.5 &&+ t.top < l.bottom - 0.5;+ if (crosses) {+ found.push(`${width}px: "${token.textContent}" paints under the lane`);+ }+ }+ if (field.scrollWidth > field.clientWidth + 1) {+ found.push(+ `${width}px: the field's content is ${field.scrollWidth}px in a ${field.clientWidth}px box`,+ );+ }+ return found;+ }, width);+}++for (const direction of ['ltr', 'rtl'] as const) {+ test(`${direction}: the sheet field's tokens stay clear of the end lane`, async ({+ page,+ }) => {+ await open(page, direction);+ const found: string[] = [];+ for (let width = 180; width <= 400; width += 20) {+ found.push(...(await overlapsAt(page, width)));+ }+ expect(found).toEqual([]);+ });+}++test("Tab moves from the trigger through the custom tokens' controls to the end content", async ({+ page,+}) => {+ await open(page);+ await trigger(page).focus();+ const names: string[] = [];+ for (let step = 0; step < 5; step++) {+ await page.keyboard.press('Tab');+ names.push(+ await page.evaluate(+ () =>+ document.activeElement?.getAttribute('aria-label') ??+ document.activeElement?.textContent ??+ '',+ ),+ );+ }+ expect(names.slice(0, 4).every(name => name.startsWith('Remove '))).toBe(+ true,+ );+ expect(names[4]).toBe('Cc (0)');+});++test("the trigger's description is the count and the custom tokens' labels, without their controls' names", async ({+ page,+}) => {+ await open(page);+ const labels = await page+ .locator('.astryx-tokenizer .astryx-token')+ .evaluateAll(tokens =>+ tokens.map(+ token =>+ token+ .querySelector('button')+ ?.getAttribute('aria-label')+ ?.replace(/^Remove /, '') ?? '',+ ),+ );+ expect(labels).toHaveLength(4);+ await expect(trigger(page)).toHaveAccessibleDescription(+ `4 selected ${labels.join(' ')}`,+ );+ // The label copies the description reads are hidden, so the+ // accessibility tree holds each label once: the custom token's own text.+ const tree = (await page.locator('#storybook-root').ariaSnapshot()).split(+ '\n',+ );+ for (const label of labels) {+ expect(+ tree.filter(line => line.trim() === `- text: ${label}`),+ label,+ ).toHaveLength(1);+ }+});++test('the end content acts without opening the sheet', async ({page}) => {+ await open(page);+ await page.getByRole('button', {name: 'Cc (0)'}).click();+ await expect(page.getByRole('button', {name: 'Cc (1)'})).toBeVisible();+ await expect(trigger(page)).toHaveAttribute('aria-expanded', 'false');+ await expect(page.getByRole('dialog')).toHaveCount(0);+});++test("a custom token's remove control removes it without opening the sheet", async ({+ page,+}) => {+ await open(page);+ const remove = page.getByRole('button', {name: /^Remove /}).first();+ const label = (await remove.getAttribute('aria-label'))!.replace(+ /^Remove /,+ '',+ );+ await remove.click();+ await expect(page.getByRole('button', {name: `Remove ${label}`})).toHaveCount(+ 0,+ );+ await expect(trigger(page)).toHaveAttribute('aria-expanded', 'false');+ await expect(trigger(page)).toBeFocused();+ await expect(page.getByRole('dialog')).toHaveCount(0);+});++test('a tap on a token opens the sheet', async ({page}) => {+ await open(page);+ const token = page.locator('.astryx-tokenizer .astryx-token').first();+ const box = (await token.boundingBox())!;+ // The token's label, clear of its remove control at the inline end.+ await page.mouse.click(box.x + 8, box.y + box.height / 2);+ await expect(trigger(page)).toHaveAttribute('aria-expanded', 'true');+ await expect(page.getByRole('dialog', {name: 'Recipients'})).toBeVisible();+});