Skip to content

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

TypeScript

feat(lab): MobileTokenizer at parity with Core's sheet presentation (#8739)

Xinzi Zhou9d1ef5a40c5d
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
index e8f0b70d49..a9c451b82d 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
@@ -14,20 +14,24 @@ export const docs = {
{name: 'onChange', type: '(items: T[], change: MobileTokenizerChange<T>) => void', description: 'Mirrors Core Tokenizer: single-item add/create/remove, or reorder.', required: true},
{name: 'renderItem', type: '(item: T) => ReactNode', description: 'Custom content for a result row, shown beside its checkbox. Default: the item label.'},
{name: 'placeholder', type: 'string', description: 'Trigger text when nothing is selected.'},
+ {name: 'description', type: 'string', description: 'Help text under the field, read with the trigger.'},
+ {name: 'status', type: "{type: 'error' | 'warning' | 'success'; message: string}", description: 'Status shown under the field and read with the trigger.'},
+ {name: 'disabledMessage', type: 'string', description: 'Why the field is disabled: the disabled trigger exposes it as its description and tooltip.'},
+ {name: 'htmlName', type: 'string', description: 'Form field name: one hidden input per selected item while the field is enabled.'},
{name: 'hasCreate', type: 'boolean', description: 'Offer Create "<query>" for unmatched free text.', default: 'false'},
{name: 'maxEntries', type: 'number', description: 'Cap selections; add rows disable at the cap.'},
- {name: 'maxMenuItems', type: 'number', description: 'Maximum source results retained; long lists render progressively in 50-item batches.', default: '10'},
+ {name: 'maxMenuItems', type: 'number', description: 'Maximum source results retained, for a search and for the empty-query bootstrap list alike; long lists render progressively in 50-item batches.', default: '10'},
],
usage: {
description:
- 'Lab prototype for trying the touch Tokenizer flow: tap the field to open one searchable sheet where selected and available items share a full-row checkbox list. Selected items are grouped first when the sheet opens, while checkbox changes keep every existing row in place until the sheet closes; the latest selection is regrouped the next time it opens. Selected custom values stay in the list, and long result sets render progressively in 50-item batches. Custom text uses a trailing Add action, and guarded Clear all plus Done actions finish the unfiltered flow. The footer is hidden while searching.',
+ 'Lab prototype for trying the touch Tokenizer flow: tap the field to open one searchable sheet where selected and available items share a full-row checkbox list. Selected items are grouped first when the sheet opens, while checkbox changes keep every existing row in place until the sheet closes; the latest selection is regrouped the next time it opens. Selected custom values stay in the list, and long result sets render progressively in 50-item batches. Custom text uses a trailing Add action, and guarded Clear all plus Done actions finish the unfiltered flow. The footer is hidden while searching. Clear all stays in the focus order when nothing is selected and says why; a confirmed clear returns focus to the search field and is announced inside the sheet. Every announcement — additions, removals, result counts — is delivered inside the open sheet. The trigger describes its selection to assistive technology (count, then the tokens) after the field description, status, and disabled reason. Strings come from the shared Astryx catalog.',
bestPractices: [
{guidance: true, description: 'Try this in Lab/canary to validate the flow; graduate via Core Tokenizer presentation="adaptive" when it ships.'},
- {guidance: false, description: 'Do not ship stable product on this Lab API; it has no theming, i18n, or spec contract yet.'},
+ {guidance: false, description: 'Do not ship stable product on this Lab API; it has no theming or spec contract yet.'},
],
anatomy: [
{name: 'Trigger field', required: true, description: 'Button showing tokens as a summary.'},
- {name: 'Management sheet', required: true, description: 'One searchable list with trailing checkboxes for existing items, a trailing Add action for custom text, and equal-width Clear all and Done footer actions when unfiltered. Clear all requires confirmation; the footer is hidden while searching.'},
+ {name: 'Management sheet', required: true, description: 'One searchable list with trailing checkboxes for existing items, a trailing Add action for custom text, and equal-width Clear all and Done footer actions when unfiltered. Clear all requires confirmation and stays focusable with its reason when nothing is selected; the footer is hidden while searching. Nothing of the sheet is in the page while it is closed.'},
],
},
};
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
index 4b4985486a..f23125ecfb 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
@@ -14,6 +14,7 @@ import {
waitFor,
within,
} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';
@@ -512,3 +513,488 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
}
});
});
+
+/**
+ * Behaviors at parity with Core's sheet presentation (`component:Tokenizer`
+ * DEC-3, FR16–FR24, AR6), ported into the Lab prototype.
+ */
+describe('MobileTokenizer Core-sheet parity', () => {
+ // The live region the hook writes inside an open modal (AST-086 FR14);
+ // created by the first announcement, so absent means nothing was said.
+ const liveText = (root: HTMLElement) =>
+ root.querySelector('[data-astryx-modal-live-region]')?.textContent ?? '';
+ // jsdom has no showModal(), so an open dialog never matches `:modal`;
+ // stand in for the sheet the browser presents modally.
+ let matchesSpy: ReturnType<typeof vi.spyOn> | null = null;
+ const presentModally = () => {
+ const matches = Element.prototype.matches;
+ matchesSpy = vi
+ .spyOn(Element.prototype, 'matches')
+ .mockImplementation(function (this: Element, selector: string) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+ };
+ beforeEach(async () => {
+ // The page's live regions outlive a test's tree, and a previous test's
+ // announcement may still be a frame away; let it land, then start with
+ // nothing said on the page.
+ await new Promise(resolve => setTimeout(resolve, 0));
+ for (const region of document.querySelectorAll(
+ 'body > [data-astryx-live-region]',
+ )) {
+ region.textContent = '';
+ }
+ });
+ afterEach(() => {
+ matchesSpy?.mockRestore();
+ matchesSpy = null;
+ });
+ const openSheet = async (name = /Tags/) => {
+ fireEvent.click(screen.getByRole('button', {name}));
+ const sheet = await screen.findByRole('dialog');
+ return sheet;
+ };
+
+ it('mounts the sheet only from the press until its exit completes, and keeps nothing of it at rest (INV7)', async () => {
+ presentModally();
+ render(<Harness />);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.queryByLabelText('Search Tags')).toBeNull();
+ const sheet = await openSheet();
+ expect(sheet).toHaveAttribute('open');
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ // Closed but retained for its exit; the trigger's focus (BottomSheet's
+ // hand-back after the exit) releases it.
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ act(() => trigger.focus());
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ });
+
+ it('caps the empty-query bootstrap set at maxMenuItems, and an empty bootstrap shows only the search field (FR20)', async () => {
+ presentModally();
+ const many: SearchableItem[] = Array.from({length: 30}, (_, i) => ({
+ id: `i${i}`,
+ label: `Item ${i + 1}`,
+ }));
+ const bigSource: SearchSource<SearchableItem> = {
+ search: () => many,
+ bootstrap: () => many,
+ };
+ const {unmount} = render(
+ <MobileTokenizer
+ label="Items"
+ searchSource={bigSource}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ maxMenuItems={7}
+ />,
+ );
+ await openSheet(/Items/);
+ await waitFor(() =>
+ expect(screen.getAllByRole('checkbox')).toHaveLength(7),
+ );
+ unmount();
+
+ const emptySource: SearchSource<SearchableItem> = {
+ search: () => [],
+ bootstrap: () => [],
+ };
+ render(
+ <MobileTokenizer
+ label="Blank"
+ searchSource={emptySource}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+ const sheet = await openSheet(/Blank/);
+ await waitFor(() =>
+ expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull(),
+ );
+ expect(screen.getByLabelText('Search Blank')).toBeInTheDocument();
+ expect(screen.queryByTestId('mobile-tokenizer-list')).toBeNull();
+ expect(screen.queryByRole('checkbox')).toBeNull();
+ expect(screen.queryByText('No items available')).toBeNull();
+ expect(screen.queryByText('No results found')).toBeNull();
+ expect(liveText(sheet)).toBe('');
+ });
+
+ it("describes the trigger in the inline input's order — caller ids, description, status, disabled reason, count, then the tokens by id — with no label repeated (AR6, AST-085 FR5)", async () => {
+ render(
+ <>
+ <p id="hint">Pick a few</p>
+ <MobileTokenizer
+ label="Tags"
+ aria-describedby="hint"
+ description="Up to three"
+ status={{type: 'error', message: 'Pick at least one'}}
+ isDisabled
+ disabledMessage="Locked by the owner"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ />
+ </>,
+ );
+ const trigger = screen.getByRole('button', {name: 'Tags'});
+ const ids = trigger.getAttribute('aria-describedby')!.split(' ');
+ const texts = ids.map(id => document.getElementById(id)!.textContent);
+ expect(texts).toEqual([
+ 'Pick a few',
+ 'Up to three',
+ 'Pick at least one',
+ 'Locked by the owner',
+ '2 selected',
+ 'Design',
+ 'Eng',
+ ]);
+ expect(trigger).toHaveAccessibleDescription(
+ 'Pick a few Up to three Pick at least one Locked by the owner 2 selected Design Eng',
+ );
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+ // The reason is a tooltip, not a native title: it is the element the
+ // description names, and it opens on focus, so keyboard and touch users
+ // get it too.
+ expect(trigger).not.toHaveAttribute('title');
+ const tooltip = screen.getByRole('tooltip', {hidden: true});
+ expect(tooltip).toHaveTextContent('Locked by the owner');
+ expect(ids).toContain(tooltip.id);
+ // jsdom has no Popover API; the shared setup stubs showPopover, so the
+ // open is observed as the call on the tooltip's element.
+ const shown = vi.spyOn(HTMLElement.prototype, 'showPopover');
+ try {
+ // Keyboard focus: the tooltip opens for `:focus-visible` focus only.
+ await userEvent.setup().tab();
+ expect(trigger).toHaveFocus();
+ await waitFor(() => {
+ expect(shown.mock.instances).toContain(tooltip);
+ });
+ } finally {
+ shown.mockRestore();
+ }
+ });
+
+ it('paints the trigger on the input surface, so a status band behind it does not show through the tokens', () => {
+ const atoms = (style: stylex.StyleXStyles) =>
+ stylex
+ .props(style)
+ .className!.split(' ')
+ .filter(name => !name.includes('__'));
+ const surface = stylex.create({
+ trigger: {backgroundColor: colorVars['--color-background-surface']},
+ });
+ render(
+ <MobileTokenizer
+ label="Tags"
+ status={{type: 'error', message: 'Pick at least one'}}
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByRole('button', {name: 'Tags'});
+ for (const name of atoms(surface.trigger)) {
+ expect(trigger).toHaveClass(name);
+ }
+ expect(screen.getByText('Pick at least one')).toBeInTheDocument();
+ });
+
+ it("composes the trigger's own handlers and attributes with the caller's: onClick after the open, onFocus for focus from outside only, aria-label winning, aria-describedby merged, className and style on the trigger", async () => {
+ presentModally();
+ const onClick = vi.fn();
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ render(
+ <>
+ <p id="hint">Pick a few</p>
+ <button type="button">Elsewhere</button>
+ <MobileTokenizer
+ label="Tags"
+ aria-label="Project tags"
+ aria-describedby="hint"
+ className="caller-class"
+ style={{marginBlockStart: 3}}
+ onClick={onClick}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ debounceMs={0}
+ />
+ </>,
+ );
+ // The caller's name wins; the description still starts with its ids.
+ const trigger = screen.getByRole('button', {name: 'Project tags'});
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(trigger.getAttribute('aria-describedby')!.split(' ')[0]).toBe(
+ 'hint',
+ );
+ expect(trigger).toHaveAccessibleDescription(
+ /^Pick a few 1 selected Design/,
+ );
+ expect(trigger).toHaveClass('caller-class');
+ expect(trigger.style.marginBlockStart).toBe('3px');
+ // Focus from outside reports; the field's own label and tokens too.
+ act(() => trigger.focus());
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // The click opens the sheet and then reaches the caller.
+ fireEvent.click(trigger);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ const sheet = await screen.findByRole('dialog');
+ await screen.findByRole('checkbox', {name: 'Design'});
+ // Focus moving into the sheet is still the field's: no blur reported.
+ act(() => screen.getByLabelText('Search Tags').focus());
+ expect(onBlur).not.toHaveBeenCalled();
+ // Closing hands focus back to the trigger: that is not focus entering
+ // from outside, so the caller's onFocus stays quiet for it.
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ act(() => trigger.focus());
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(sheet).not.toBeInTheDocument();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // Leaving the field reports the blur once.
+ act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ it('forwards the base props — id, data-*, aria-*, handlers — to the trigger button, not the field root', () => {
+ const onPointerDown = vi.fn();
+ render(
+ <MobileTokenizer
+ label="Tags"
+ id="tags-field"
+ data-testid="tags-trigger"
+ aria-label="Project tags"
+ onPointerDown={onPointerDown}
+ searchSource={source}
+ value={[ITEMS[0]]}
+ onChange={() => {}}
+ />,
+ );
+ const trigger = screen.getByTestId('tags-trigger');
+ expect(trigger.tagName).toBe('BUTTON');
+ expect(trigger).toHaveAttribute('id', 'tags-field');
+ expect(trigger).toHaveAttribute('aria-haspopup', 'dialog');
+ // The field's label still points at the control.
+ expect(screen.getByText('Tags').closest('label')).toHaveAttribute(
+ 'for',
+ 'tags-field',
+ );
+ fireEvent.pointerDown(trigger);
+ expect(onPointerDown).toHaveBeenCalledTimes(1);
+ expect(trigger.closest('.astryx-field')).not.toHaveAttribute('id');
+ expect(trigger.closest('.astryx-field')).not.toHaveAttribute('data-testid');
+ });
+
+ it('renders one hidden form carrier per selected item only while enabled with an htmlName (FR10, FR17)', () => {
+ const {container, rerender} = render(
+ <MobileTokenizer
+ label="Tags"
+ htmlName="tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ />,
+ );
+ const carriers = () =>
+ Array.from(
+ container.querySelectorAll<HTMLInputElement>(
+ 'input[type="hidden"][name="tags"]',
+ ),
+ ).map(input => input.value);
+ expect(carriers()).toEqual(['design', 'eng']);
+ rerender(
+ <MobileTokenizer
+ label="Tags"
+ htmlName="tags"
+ isDisabled
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ />,
+ );
+ expect(carriers()).toEqual([]);
+ rerender(
+ <MobileTokenizer
+ label="Tags"
+ searchSource={source}
+ value={[ITEMS[0], ITEMS[1]]}
+ onChange={() => {}}
+ />,
+ );
+ expect(carriers()).toEqual([]);
+ });
+
+ it('reads the source through a ref: a source rebuilt on an unrelated render causes no new request (FR20)', async () => {
+ const search = vi.fn((q: string) =>
+ ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
+ );
+ const bootstrap = vi.fn(() => ITEMS);
+ function Rebuilding() {
+ const [value, setValue] = useState<SearchableItem[]>([]);
+ // A new source object every render, as a caller writing it inline does.
+ const inline: SearchSource<SearchableItem> = {
+ search: q => search(q),
+ bootstrap: () => bootstrap(),
+ };
+ return (
+ <MobileTokenizer
+ label="Tags"
+ searchSource={inline}
+ value={value}
+ onChange={items => setValue(items)}
+ debounceMs={0}
+ />
+ );
+ }
+ render(<Rebuilding />);
+ await openSheet();
+ await screen.findByRole('checkbox', {name: 'Design'});
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Design'})).toBeChecked(),
+ );
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ await waitFor(() =>
+ expect(screen.getByRole('checkbox', {name: 'Eng'})).toBeChecked(),
+ );
+ expect(bootstrap).toHaveBeenCalledTimes(1);
+ expect(search).not.toHaveBeenCalled();
+ });
+
+ it('is pending only for a query it will search: a kept query below minQueryLength opens settled (FR20, FR18)', async () => {
+ let pending = () => {};
+ const slow: SearchSource<SearchableItem> = {
+ search: () =>
+ new Promise<SearchableItem[]>(resolve => {
+ pending = () => resolve([ITEMS[1]]);
+ }),
+ bootstrap: () =>
+ new Promise<SearchableItem[]>(resolve => {
+ pending = () => resolve(ITEMS);
+ }),
+ };
+ function Flow() {
+ const [isDisabled, setIsDisabled] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsDisabled(d => !d)}>
+ Toggle
+ </button>
+ <MobileTokenizer
+ label="Tags"
+ searchSource={slow}
+ value={[]}
+ onChange={() => {}}
+ debounceMs={0}
+ minQueryLength={3}
+ isDisabled={isDisabled}
+ />
+ </>
+ );
+ }
+ render(<Flow />);
+ const sheet = await openSheet();
+ // Pending from open until the bootstrap settles.
+ expect(within(sheet).getByRole('img', {name: 'Loading'})).toBeTruthy();
+ await act(async () => {
+ pending();
+ });
+ expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull();
+ // Below the threshold: nothing is searched, nothing is pending.
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'en'},
+ });
+ expect(within(sheet).queryByRole('img', {name: 'Loading'})).toBeNull();
+ expect(screen.queryByRole('checkbox')).toBeNull();
+ // The field becomes disabled while open: the sheet closes and the query
+ // is kept; re-enabled and reopened, it starts from "en", settled.
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle'}));
+ expect(screen.getByRole('button', {name: /Tags/})).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ act(() => screen.getByRole('button', {name: /Tags/}).focus());
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ fireEvent.click(screen.getByRole('button', {name: 'Toggle'}));
+ const reopened = await openSheet();
+ expect(screen.getByLabelText('Search Tags')).toHaveValue('en');
+ expect(within(reopened).queryByRole('img', {name: 'Loading'})).toBeNull();
+ });
+
+ it('keeps a spent Clear all in the focus order with its reason, confirms, then focuses the search field and announces inside the sheet after the confirmation has closed (FR24, AST-085 FR1, AST-086 FR14)', async () => {
+ presentModally();
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ const sheet = await openSheet();
+ await screen.findByRole('checkbox', {name: 'Design'});
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+ expect(clearAll).not.toHaveAttribute('aria-disabled');
+ fireEvent.click(clearAll);
+ const confirmation = await screen.findByRole('alertdialog');
+ expect(confirmation).toHaveTextContent('Clear all selected items?');
+ expect(spy).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
+ );
+ expect(spy).toHaveBeenCalledWith(
+ [],
+ expect.objectContaining({type: 'remove'}),
+ );
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ await waitFor(() => expect(liveText(sheet)).toBe('All items removed'));
+ // Spent: still a tab stop, says why, opens no confirmation.
+ const spent = screen.getByRole('button', {name: 'Clear all'});
+ expect(spent).toHaveAttribute('aria-disabled', 'true');
+ expect(spent).not.toHaveAttribute('disabled');
+ expect(spent).toHaveAccessibleDescription('Nothing selected');
+ fireEvent.click(spent);
+ expect(screen.queryByRole('alertdialog')).toBeNull();
+ });
+
+ it('announces each toggle and the result count from inside the dialog (AR6, AST-086 FR14)', async () => {
+ presentModally();
+ render(<Harness />);
+ const sheet = await openSheet();
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
+ await waitFor(() => expect(liveText(sheet)).toBe('Added Energizer'));
+ fireEvent.change(screen.getByLabelText('Search Tags'), {
+ target: {value: 'eng'},
+ });
+ await waitFor(() => expect(liveText(sheet)).toBe('2 results'));
+ // Nothing went to the page-level region behind the modal.
+ for (const region of document.querySelectorAll(
+ 'body > [data-astryx-live-region]',
+ )) {
+ expect(region.textContent).toBe('');
+ }
+ });
+
+ it('uses the shared catalog for the sheet strings', async () => {
+ render(<CreateHarness spy={() => {}} />);
+ await openSheet();
+ const search = screen.getByLabelText('Search Tags');
+ expect(search).toHaveAttribute('placeholder', 'Search…');
+ fireEvent.change(search, {target: {value: 'Ops'}});
+ await screen.findByTestId('mobile-tokenizer-create-row');
+ expect(screen.getByText('Create "Ops"')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Add Ops'})).toBeInTheDocument();
+ // With `hasCreate`, an unmatched query offers the create row instead of
+ // the empty state; the empty state's catalog words are checked with a
+ // field without it, above ("searches within the same sheet").
+ fireEvent.change(search, {target: {value: 'zzz'}});
+ expect(
+ await screen.findByRole('button', {name: 'Add zzz'}),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
index ae1ad01fb4..e2be8f0279 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
@@ -4,30 +4,45 @@
/**
* @file MobileTokenizer.tsx
- * @input Uses public @astryxdesign/core components only (AlertDialog,
- * BottomSheet, Button, CheckboxIndicator, EmptyState,
- * Field, Icon, Text, TextInput, Token)
+ * @input Uses public @astryxdesign/core components and hooks only
+ * (AlertDialog, BottomSheet, Button, CheckboxIndicator, EmptyState, Field,
+ * Icon, Spinner, Text, TextInput, Token, VisuallyHidden, useAnnounce,
+ * useMergedRefs, useTooltip, useTranslator)
* @output Exports MobileTokenizer — Lab prototype of the touch Tokenizer
* flow with a single searchable sheet, stable in-session checkbox ordering,
* and progressive long-list rendering
- * @position Lab (canary) stack layer 1: validates the design before the
- * Core promotion (Tokenizer presentation="bottom-sheet").
+ * @position Lab (canary) stack layer 1: the touch sheet's user-experience
+ * pass happens here; Core's sheet presentation (`component:Tokenizer`
+ * DEC-3, FR16–FR24, AR6) is implemented but not exposed. The behaviors
+ * below are at parity with Core's sheet where Lab's component has the same
+ * part: Clear all confirmed, focusable while spent, announced once the
+ * confirmation has closed (FR24); the bootstrap set capped at
+ * `maxMenuItems` and an empty one showing only the search field (FR20);
+ * the trigger described in the inline input's order, then the count and
+ * the rendered tokens by id (AR6, `spec:AST-085` FR5); form carriers only
+ * while enabled (`spec:AST-085` FR3, FR17); the source read through a ref and one
+ * `willSearchFor` rule for the pending state (FR20); the sheet mounted only
+ * from the press until its exit completes (INV7); announcements from inside
+ * the dialog (AR6, `spec:AST-086` FR14); a disabled field closing its sheet
+ * and keeping the query (FR17, FR18); catalog strings.
*
* API mirrors Core Tokenizer (label/isLabelHidden/searchSource/value/onChange/
- * change, renderItem, hasCreate, maxEntries) so graduation is an import swap. Differences from
- * Core are the Lab deltas: the filter is a bordered TextInput (Core's
- * PanelSearchInput is not exported), strings are literals (no i18n keys),
- * and there is no theming/spec contract yet.
+ * change, renderItem, hasCreate, maxEntries) so graduation is an import swap.
+ * Lab deltas: the filter is a bordered TextInput (Core's PanelSearchInput is
+ * not exported), and there is no theming/spec contract yet.
*/
+import type React from 'react';
import {
+ useCallback,
useEffect,
useId,
+ useImperativeHandle,
useMemo,
useRef,
useState,
type ReactNode,
- type SVGProps,
+ type RefObject,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
@@ -36,12 +51,18 @@ import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {EmptyState} from '@astryxdesign/core/EmptyState';
import {Field} from '@astryxdesign/core/Field';
+import {useAnnounce, useMergedRefs} from '@astryxdesign/core/hooks';
+import {useTranslator} from '@astryxdesign/core/i18n';
import {Icon} from '@astryxdesign/core/Icon';
import {CheckboxIndicator} from '@astryxdesign/core/Indicator';
+import {Spinner} from '@astryxdesign/core/Spinner';
import {Text} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
import {Token} from '@astryxdesign/core/Token';
+import {useTooltip} from '@astryxdesign/core/Tooltip';
import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';
+import {composeEventHandlers, mergeProps} from '@astryxdesign/core/utils';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
import {
colorVars,
radiusVars,
@@ -75,6 +96,15 @@ export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<
renderItem?: (item: T) => ReactNode;
placeholder?: string;
description?: string;
+ /** Status shown under the field and read with the trigger. */
+ status?: {type: 'error' | 'warning' | 'success'; message: string};
+ /**
+ * Why the field is disabled; exposed as the disabled trigger's description
+ * and shown as its tooltip (`spec:AST-085` FR5). Mirrors Core Tokenizer.
+ */
+ disabledMessage?: string;
+ /** Form field name: one hidden carrier per selected item while enabled. */
+ htmlName?: string;
isOptional?: boolean;
isDisabled?: boolean;
hasCreate?: boolean;
@@ -90,22 +120,6 @@ const CREATABLE_ID_PREFIX = '__xds_create__';
const LIST_RENDER_BATCH_SIZE = 50;
const LIST_LOAD_MORE_THRESHOLD_PX = 200;
-function ListBulletIcon(props: SVGProps<SVGSVGElement>) {
- return (
- <svg viewBox="0 0 24 24" fill="none" {...props}>
- <path
- d="M8.5 6h11M8.5 12h11M8.5 18h11"
- stroke="currentColor"
- strokeWidth="1.5"
- strokeLinecap="round"
- />
- <circle cx="4.5" cy="6" r="1" fill="currentColor" />
- <circle cx="4.5" cy="12" r="1" fill="currentColor" />
- <circle cx="4.5" cy="18" r="1" fill="currentColor" />
- </svg>
- );
-}
-
const styles = stylex.create({
trigger: {
display: 'flex',
@@ -120,7 +134,10 @@ const styles = stylex.create({
borderStyle: 'solid',
borderColor: colorVars['--color-border'],
borderRadius: radiusVars['--radius-element'],
- backgroundColor: 'transparent',
+ // The input surface, as Core's sheet trigger has from the shared input
+ // wrapper: Field's attached status band sits behind the control, and a
+ // transparent trigger would show it through the tokens.
+ backgroundColor: colorVars['--color-background-surface'],
textAlign: 'start',
cursor: {
default: 'pointer',
@@ -255,6 +272,16 @@ const styles = stylex.create({
empty: {
flexGrow: 1,
},
+ emptyHost: {
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ },
+ pending: {
+ display: 'flex',
+ justifyContent: 'center',
+ paddingBlock: spacingVars['--spacing-4'],
+ },
});
export function MobileTokenizer<T extends SearchableItem>({
@@ -266,6 +293,9 @@ export function MobileTokenizer<T extends SearchableItem>({
renderItem,
placeholder,
description,
+ status,
+ disabledMessage,
+ htmlName,
isOptional,
isDisabled = false,
hasCreate = false,
@@ -273,103 +303,536 @@ export function MobileTokenizer<T extends SearchableItem>({
maxMenuItems = 10,
minQueryLength = 1,
debounceMs = 150,
- emptySearchResultsText = 'No results found',
+ emptySearchResultsText,
onChangeQuery,
xstyle,
+ id,
+ className,
+ style,
+ 'aria-label': ariaLabelProp,
+ 'aria-describedby': ariaDescribedByProp,
+ onClick: callerOnClick,
+ onFocus: callerOnFocus,
+ onBlur: callerOnBlur,
+ ...rest
}: MobileTokenizerProps<T>) {
- const triggerId = useId();
+ const t = useTranslator();
+ const generatedTriggerId = useId();
+ const triggerId = id ?? generatedTriggerId;
+ const descriptionId = useId();
+ const statusId = useId();
+ const countId = useId();
+ // Each rendered token's id, for the trigger's description; the item id is
+ // an arbitrary string, so it is encoded rather than used as is.
+ const tokenElementId = (itemId: string) =>
+ `${countId}-${encodeURIComponent(itemId)}`;
+ const triggerRef = useRef<HTMLButtonElement>(null);
const [isSheetOpen, setIsSheetOpen] = useState(false);
- const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
+ // The sheet stays mounted after it closes until BottomSheet has run its
+ // exit and handed focus back to the trigger; at rest nothing of the sheet
+ // is in the DOM (`architecture:component-style-authoring` INV7).
+ const [isSheetPresented, setIsSheetPresented] = useState(false);
+ // The sheet's query between presentations: a close the person makes clears
+ // it, a close the field forces (becoming disabled while open) keeps it
+ // (`component:Tokenizer` FR18). The ref follows every report; the press
+ // snapshots it into the state the next presentation starts from.
+ const sheetQueryRef = useRef('');
+ const [sheetInitialQuery, setSheetInitialQuery] = useState('');
+ const handleSheetQueryChange = useCallback(
+ (query: string) => {
+ sheetQueryRef.current = query;
+ onChangeQuery?.(query);
+ },
+ [onChangeQuery],
+ );
const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);
const isAtMax = maxEntries != null && value.length >= maxEntries;
- const handleAdd = (item: T) => {
- if (isAtMax || selectedIds.has(item.id)) {
- return;
+ // A field that becomes disabled cannot keep its sheet open, and must not
+ // reopen it when re-enabled (FR17). Adjusted in the render that sees the
+ // change, not an effect, so no frame shows both. A sheet that was open when
+ // the field became disabled stays mounted, closed, so it runs its exit and
+ // hands focus back to the trigger; a field disabled from the start mounts
+ // no sheet.
+ const [wasDisabled, setWasDisabled] = useState(isDisabled);
+ const [keepsSheetWhileDisabled, setKeepsSheetWhileDisabled] = useState(false);
+ if (isDisabled !== wasDisabled) {
+ setWasDisabled(isDisabled);
+ if (isDisabled && isSheetOpen) {
+ setIsSheetOpen(false);
+ setKeepsSheetWhileDisabled(true);
}
- if (
- hasCreate &&
- typeof item.id === 'string' &&
- item.id.startsWith(CREATABLE_ID_PREFIX)
- ) {
- const created = item.id.slice(CREATABLE_ID_PREFIX.length);
- if (selectedIds.has(created)) {
- return;
+ if (!isDisabled) {
+ setKeepsSheetWhileDisabled(false);
+ }
+ }
+
+ const handleAdd = useCallback(
+ (item: T): boolean => {
+ if (isDisabled || isAtMax || selectedIds.has(item.id)) {
+ return false;
+ }
+ if (
+ hasCreate &&
+ typeof item.id === 'string' &&
+ item.id.startsWith(CREATABLE_ID_PREFIX)
+ ) {
+ const created = item.id.slice(CREATABLE_ID_PREFIX.length);
+ if (selectedIds.has(created)) {
+ return false;
+ }
+ const createdItem: SearchableItem = {id: created, label: created};
+ const real = createdItem as T;
+ onChange([...value, real], {item: real, type: 'create'});
+ return true;
+ }
+ onChange([...value, item], {item, type: 'add'});
+ return true;
+ },
+ [hasCreate, isAtMax, isDisabled, onChange, selectedIds, value],
+ );
+ const handleRemove = useCallback(
+ (item: T): boolean => {
+ if (isDisabled) {
+ return false;
}
- const createdItem: SearchableItem = {id: created, label: created};
- const real = createdItem as T;
- onChange([...value, real], {item: real, type: 'create'});
+ onChange(
+ value.filter(v => v.id !== item.id),
+ {item, type: 'remove'},
+ );
+ return true;
+ },
+ [isDisabled, onChange, value],
+ );
+ const handleClearAll = useCallback(() => {
+ if (isDisabled || value.length === 0) {
return;
}
- onChange([...value, item], {item, type: 'add'});
- };
- const handleRemove = (item: T) =>
- onChange(
- value.filter(v => v.id !== item.id),
- {item, type: 'remove'},
- );
- const handleClearAll = () => {
- if (value.length > 0) {
- onChange([], {item: value[value.length - 1], type: 'remove'});
- }
+ onChange([], {item: value[value.length - 1], type: 'remove'});
+ }, [isDisabled, onChange, value]);
+
+ const showsDisabledMessage = isDisabled && disabledMessage != null;
+ // The disabled reason as a tooltip on the trigger, for hover, focus and
+ // touch alike, and the element the trigger's description names
+ // (`spec:AST-085` FR5); the trigger is focusable while disabled, so focus
+ // triggering reaches keyboard users.
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+ const triggerMergedRef = useMergedRefs<HTMLButtonElement>(
+ triggerRef,
+ disabledMessageTooltip.ref,
+ );
+ // The trigger's description is the inline input's, in its order — the
+ // caller's ids, the field description, the status message, the disabled
+ // reason (`spec:AST-085` FR5) — then the hidden count and the rendered
+ // tokens themselves, each by id: the accessible-description algorithm reads
+ // the referenced elements in order and separates them, so every label
+ // renders once (`architecture:component-style-authoring` INV7) and no
+ // locale's list punctuation is written here (`component:Tokenizer` AR6).
+ const triggerDescribedBy =
+ [
+ ariaDescribedByProp,
+ description ? descriptionId : null,
+ status?.message ? statusId : null,
+ // The disabled reason is the tooltip's element, as for Core's trigger.
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ value.length > 0 ? countId : null,
+ ...value.map(item => tokenElementId(item.id)),
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ return (
+ <Field
+ label={label}
+ isLabelHidden={isLabelHidden}
+ description={description}
+ descriptionID={description ? descriptionId : undefined}
+ status={
+ status
+ ? {type: status.type, message: status.message, messageID: statusId}
+ : undefined
+ }
+ isOptional={isOptional}
+ isDisabled={isDisabled}
+ inputID={triggerId}
+ xstyle={xstyle}>
+ {/* The trigger is the control: the caller's base props — `id`,
+ `data-*`, `aria-*`, handlers, className, style — reach it, as they
+ reach Core's sheet trigger, not the field root; what the trigger
+ sets itself is composed with the caller's value, never over it. */}
+ <button
+ // Typed for a div by the base props; here the control is a button.
+ {...(rest as React.ButtonHTMLAttributes<HTMLButtonElement>)}
+ ref={triggerMergedRef}
+ type="button"
+ id={triggerId}
+ aria-haspopup="dialog"
+ aria-expanded={isSheetOpen}
+ // The caller's name wins over the field label.
+ aria-label={ariaLabelProp ?? label}
+ aria-disabled={isDisabled || undefined}
+ // Already merged with the caller's ids, first.
+ aria-describedby={triggerDescribedBy}
+ // The open runs first and the caller's onClick after it, as Core's
+ // trigger composes its click: a caller observes the click but cannot
+ // cancel the field's own handling.
+ onClick={composeEventHandlers<React.MouseEvent<HTMLButtonElement>>(
+ () => {
+ if (isDisabled) {
+ return;
+ }
+ setIsSheetPresented(true);
+ setSheetInitialQuery(sheetQueryRef.current);
+ setIsSheetOpen(true);
+ },
+ callerOnClick as unknown as
+ React.MouseEventHandler<HTMLButtonElement> | undefined,
+ )}
+ onFocus={event => {
+ // BottomSheet focuses the trigger only after its exit completes;
+ // that focus is the signal that the retained sheet can leave. The
+ // field's own sheet is part of the field, so focus coming back from
+ // it is not focus entering from outside: the caller's onFocus stays
+ // quiet for it.
+ const isReturningFromSheet = !isSheetOpen && isSheetPresented;
+ if (isReturningFromSheet) {
+ setIsSheetPresented(false);
+ return;
+ }
+ (
+ callerOnFocus as unknown as
+ React.FocusEventHandler<HTMLButtonElement> | undefined
+ )?.(event);
+ }}
+ onBlur={event => {
+ // Focus moving into the sheet is still the field's; only a blur to
+ // somewhere else is reported.
+ if (isSheetOpen) {
+ return;
+ }
+ (
+ callerOnBlur as unknown as
+ React.FocusEventHandler<HTMLButtonElement> | undefined
+ )?.(event);
+ }}
+ {...mergeProps(
+ stylex.props(styles.trigger, isDisabled && styles.triggerDisabled),
+ className,
+ style,
+ )}>
+ {value.length > 0 ? (
+ value.map(item => (
+ <Token
+ key={item.id}
+ id={tokenElementId(item.id)}
+ label={item.label}
+ isDisabled={isDisabled}
+ xstyle={isDisabled ? styles.tokenDisabled : undefined}
+ />
+ ))
+ ) : (
+ <span
+ {...stylex.props(
+ styles.triggerPlaceholder,
+ isDisabled && styles.triggerPlaceholderDisabled,
+ )}>
+ {placeholder ?? ''}
+ </span>
+ )}
+ </button>
+ {value.length > 0 && (
+ <VisuallyHidden id={countId}>
+ {t('@astryx.tokenizer.selectedCount', {count: value.length})}
+ </VisuallyHidden>
+ )}
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ {/* Form carriers, gated as Core's inline field gates its own: a
+ disabled field submits nothing (`spec:AST-085` FR3, FR17). */}
+ {htmlName != null &&
+ !isDisabled &&
+ value.map(item => (
+ <input key={item.id} type="hidden" name={htmlName} value={item.id} />
+ ))}
+ {/* Mounted from the press until the sheet's exit has completed and
+ focus is back on the trigger: at rest the field renders its trigger
+ alone (INV7). */}
+ {(isSheetOpen || isSheetPresented) &&
+ (!isDisabled || keepsSheetWhileDisabled) && (
+ <MobileTokenizerSheet
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ finalFocusRef={triggerRef}
+ initialQuery={sheetInitialQuery}
+ label={label}
+ searchSource={searchSource}
+ value={value}
+ selectedIds={selectedIds}
+ isAtMax={isAtMax}
+ hasCreate={hasCreate}
+ maxMenuItems={maxMenuItems}
+ minQueryLength={minQueryLength}
+ debounceMs={debounceMs}
+ emptySearchResultsText={emptySearchResultsText}
+ renderItem={renderItem}
+ onAdd={handleAdd}
+ onRemove={handleRemove}
+ onClearAll={handleClearAll}
+ onChangeQuery={handleSheetQueryChange}
+ />
+ )}
+ </Field>
+ );
+}
+
+MobileTokenizer.displayName = 'MobileTokenizer';
+
+interface MobileTokenizerSheetProps<T extends SearchableItem> {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ finalFocusRef: RefObject<HTMLElement | null>;
+ /** The query this presentation starts with (kept across a forced close). */
+ initialQuery: string;
+ label: string;
+ searchSource: SearchSource<T>;
+ value: T[];
+ selectedIds: Set<string>;
+ isAtMax: boolean;
+ hasCreate: boolean;
+ maxMenuItems: number;
+ minQueryLength: number;
+ debounceMs: number;
+ emptySearchResultsText?: string;
+ renderItem?: (item: T) => ReactNode;
+ onAdd: (item: T) => boolean;
+ onRemove: (item: T) => boolean;
+ onClearAll: () => void;
+ onChangeQuery: (query: string) => void;
+}
+
+/**
+ * The sheet: BottomSheet around the content. The content owns the query; a
+ * close the person makes (Done, swipe, scrim, Escape) clears it through a
+ * handle from the closing event, so a close the field forces (becoming
+ * disabled) keeps it (FR18).
+ */
+function MobileTokenizerSheet<T extends SearchableItem>({
+ isOpen,
+ onOpenChange,
+ finalFocusRef,
+ label,
+ ...content
+}: MobileTokenizerSheetProps<T>) {
+ const clearQueryRef = useRef<(() => void) | null>(null);
+ const requestClose = () => {
+ clearQueryRef.current?.();
+ onOpenChange(false);
};
+ return (
+ <BottomSheet
+ isOpen={isOpen}
+ onOpenChange={next => {
+ if (next) {
+ onOpenChange(true);
+ } else {
+ requestClose();
+ }
+ }}
+ finalFocusRef={finalFocusRef}
+ label={label}
+ height="tall"
+ padding={0}>
+ <MobileTokenizerSheetContent
+ {...content}
+ isOpen={isOpen}
+ label={label}
+ clearQueryRef={clearQueryRef}
+ onRequestClose={requestClose}
+ />
+ </BottomSheet>
+ );
+}
- // ---- sheet search ----
- const [query, setQuery] = useState('');
- const [results, setResults] = useState<T[]>([]);
- const [isSearching, setIsSearching] = useState(false);
- const [renderedItemCount, setRenderedItemCount] = useState(
- LIST_RENDER_BATCH_SIZE,
+type MobileTokenizerSheetContentProps<T extends SearchableItem> = Omit<
+ MobileTokenizerSheetProps<T>,
+ 'onOpenChange' | 'finalFocusRef'
+> & {
+ clearQueryRef: RefObject<(() => void) | null>;
+ onRequestClose: () => void;
+};
+
+/**
+ * Rendered inside the sheet's dialog, so every announcement it makes through
+ * `useAnnounce` is delivered inside the open modal (`spec:AST-086` FR14).
+ */
+function MobileTokenizerSheetContent<T extends SearchableItem>({
+ isOpen,
+ initialQuery,
+ clearQueryRef,
+ onRequestClose,
+ label,
+ searchSource,
+ value,
+ selectedIds,
+ isAtMax,
+ hasCreate,
+ maxMenuItems,
+ minQueryLength,
+ debounceMs,
+ emptySearchResultsText,
+ renderItem,
+ onAdd,
+ onRemove,
+ onClearAll,
+ onChangeQuery,
+}: MobileTokenizerSheetContentProps<T>) {
+ const t = useTranslator();
+ const announce = useAnnounce();
+ const searchRef = useRef<HTMLInputElement>(null);
+ const clearAllRef = useRef<HTMLButtonElement>(null);
+
+ // ---- query and search ----
+ const [query, setQuery] = useState(initialQuery);
+ const trimmedQuery = query.trim();
+ // Whether a query is one the source is asked about: empty (the bootstrap
+ // set) or at least `minQueryLength`. One rule for every way a query comes
+ // to be: the initial one, a change.
+ const willSearchFor = (trimmed: string) =>
+ trimmed === '' || trimmed.length >= minQueryLength;
+ const isBelowMinQuery = trimmedQuery !== '' && !willSearchFor(trimmedQuery);
+ // Pending from open, and from each query change, until that search
+ // settles. The sheet mounts already open, so the initial state is derived
+ // from the initial query the way a change derives it: a kept query below
+ // the threshold starts settled, not pending for a search that never runs
+ // (FR20).
+ const [isPending, setIsPending] = useState(() =>
+ willSearchFor(initialQuery.trim()),
+ );
+ const [sourceResults, setSourceResults] = useState<T[]>([]);
+ const results = isBelowMinQuery ? [] : sourceResults;
+ // Each search that runs gets a number; its outcome is announced once.
+ const [searchId, setSearchId] = useState(0);
+ const searchIdRef = useRef(0);
+ const announcedSearchIdRef = useRef(
+ willSearchFor(initialQuery.trim()) ? -1 : 0,
);
const seqRef = useRef(0);
- const lastLoadScrollHeightRef = useRef<number | null>(null);
- const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);
+ // The source is read through a ref at request time, so a caller that
+ // rebuilds the source object in render causes no new request on an
+ // unrelated render (a row toggle); the sheet asks the source only on open,
+ // on a query change, and on clearing (FR20).
+ const searchSourceRef = useRef(searchSource);
useEffect(() => {
- if (!isSheetOpen) {
+ searchSourceRef.current = searchSource;
+ }, [searchSource]);
+ useEffect(() => {
+ if (!isOpen) {
return;
}
+ const trimmed = query.trim();
const seq = ++seqRef.current;
- const run = async () => {
- setIsSearching(true);
+ if (!willSearchFor(trimmed)) {
+ return;
+ }
+ const settle = (items: T[]) => {
+ if (seqRef.current === seq) {
+ // The bootstrap set is capped at `maxMenuItems` as the inline field
+ // caps its focus bootstrap (FR20).
+ setSourceResults(items.slice(0, maxMenuItems));
+ setIsPending(false);
+ }
+ };
+ const run = () => {
+ const source = searchSourceRef.current;
+ let answer: T[] | PromiseLike<T[]>;
try {
- const trimmed = query.trim();
- let items: T[];
- if (trimmed === '') {
- items = searchSource.bootstrap
- ? await searchSource.bootstrap()
- : await searchSource.search('');
- } else if (trimmed.length < minQueryLength) {
- items = [];
- } else {
- items = await searchSource.search(query);
- }
- if (seqRef.current === seq) {
- setResults(items.slice(0, maxMenuItems));
- }
- } finally {
- if (seqRef.current === seq) {
- setIsSearching(false);
- }
+ answer =
+ trimmed === ''
+ ? source.bootstrap
+ ? source.bootstrap()
+ : source.search('')
+ : source.search(query);
+ } catch {
+ answer = [];
+ }
+ if (Array.isArray(answer)) {
+ settle(answer);
+ return;
}
+ void Promise.resolve(answer).then(settle, () => settle([]));
};
- if (debounceMs > 0) {
- const timer = setTimeout(() => {
- void run();
- }, debounceMs);
+ if (trimmed !== '' && debounceMs > 0) {
+ const timer = setTimeout(run, debounceMs);
return () => clearTimeout(timer);
}
- void run();
- }, [
- isSheetOpen,
- query,
- searchSource,
- minQueryLength,
- maxMenuItems,
- debounceMs,
- ]);
+ run();
+ }, [isOpen, query, minQueryLength, maxMenuItems, debounceMs]);
+
+ const [renderedItemCount, setRenderedItemCount] = useState(
+ LIST_RENDER_BATCH_SIZE,
+ );
+ const lastLoadScrollHeightRef = useRef<number | null>(null);
+ // Snapshot the selection and reset the rendered window in the render that
+ // opens the sheet (the sheet stays mounted through its exit, so a reopen
+ // reuses this content), so the first open frame already shows
+ // selected-first order; rows keep their place while the sheet is open.
+ const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);
+ const resetListWindow = () => {
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ };
+ const [wasOpen, setWasOpen] = useState(isOpen);
+ if (isOpen !== wasOpen) {
+ setWasOpen(isOpen);
+ if (isOpen) {
+ setSelectedItemsAtOpen(value);
+ resetListWindow();
+ // An open lists the bootstrap set, or searches a query kept across a
+ // forced close (FR18); a kept query below the threshold leaves nothing
+ // pending, since no search runs for it.
+ const willSearch = willSearchFor(trimmedQuery);
+ setIsPending(willSearch);
+ if (willSearch) {
+ searchIdRef.current += 1;
+ setSearchId(searchIdRef.current);
+ } else {
+ announcedSearchIdRef.current = searchIdRef.current;
+ }
+ }
+ }
+ const handleQueryChange = (next: string) => {
+ resetListWindow();
+ const willSearch = willSearchFor(next.trim());
+ // Below the threshold nothing is searched, so nothing is pending and no
+ // outcome is owed: a search still unsettled from the previous query is
+ // retired unannounced.
+ setIsPending(willSearch);
+ if (willSearch) {
+ searchIdRef.current += 1;
+ setSearchId(searchIdRef.current);
+ } else {
+ announcedSearchIdRef.current = searchIdRef.current;
+ }
+ setQuery(next);
+ onChangeQuery(next);
+ };
+ useImperativeHandle(
+ clearQueryRef,
+ () => () => {
+ if (query !== '') {
+ setQuery('');
+ onChangeQuery('');
+ }
+ },
+ [query, onChangeQuery],
+ );
const visibleItems = useMemo(() => {
- const normalizedQuery = query.trim().toLowerCase();
+ const normalizedQuery = trimmedQuery.toLowerCase();
const matchesQuery = (item: T) =>
normalizedQuery === '' ||
item.label.toLowerCase().includes(normalizedQuery);
@@ -384,266 +847,295 @@ export function MobileTokenizer<T extends SearchableItem>({
!resultIds.has(item.id) &&
matchesQuery(item),
);
-
- // Selection changes update checkbox state without moving an existing row.
- // The next open snapshots the latest value and applies selected-first order.
return [
...selectedAtOpenMatches,
...selectedItemsMissingFromResults,
...results.filter(item => !selectedAtOpenIds.has(item.id)),
];
- }, [query, results, selectedItemsAtOpen, value]);
-
+ }, [trimmedQuery, results, selectedItemsAtOpen, value]);
const renderedItems = visibleItems.slice(0, renderedItemCount);
const createItem = useMemo<T | null>(() => {
- const trimmed = query.trim();
- if (!hasCreate || trimmed === '' || isAtMax) {
+ if (!hasCreate || trimmedQuery === '' || isAtMax) {
return null;
}
+ const lower = trimmedQuery.toLowerCase();
if (
- selectedIds.has(trimmed) ||
- value.some(item => item.label.toLowerCase() === trimmed.toLowerCase()) ||
- results.some(r => r.label.toLowerCase() === trimmed.toLowerCase())
+ selectedIds.has(trimmedQuery) ||
+ value.some(item => item.label.toLowerCase() === lower) ||
+ results.some(r => r.label.toLowerCase() === lower)
) {
return null;
}
return {
- id: `${CREATABLE_ID_PREFIX}${trimmed}`,
- label: `Create "${trimmed}"`,
+ id: `${CREATABLE_ID_PREFIX}${trimmedQuery}`,
+ label: t('@astryx.tokenizer.create', {value: trimmedQuery}),
} as unknown as T;
- }, [hasCreate, query, results, selectedIds, isAtMax, value]);
+ }, [hasCreate, trimmedQuery, results, selectedIds, isAtMax, value, t]);
- return (
- <Field
- label={label}
- isLabelHidden={isLabelHidden}
- description={description}
- isOptional={isOptional}
- isDisabled={isDisabled}
- inputID={triggerId}
- xstyle={xstyle}>
- <button
- type="button"
- id={triggerId}
- aria-haspopup="dialog"
- aria-expanded={isSheetOpen}
- aria-label={label}
- aria-disabled={isDisabled || undefined}
- onClick={() => {
- if (isDisabled) {
- return;
- }
- setSelectedItemsAtOpen(value);
- lastLoadScrollHeightRef.current = null;
- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setIsSheetOpen(true);
- }}
- {...stylex.props(styles.trigger, isDisabled && styles.triggerDisabled)}>
- {value.length > 0 ? (
- value.map(item => (
- <Token
- key={item.id}
- label={item.label}
- isDisabled={isDisabled}
- xstyle={isDisabled ? styles.tokenDisabled : undefined}
- />
- ))
- ) : (
- <span
- {...stylex.props(
- styles.triggerPlaceholder,
- isDisabled && styles.triggerPlaceholderDisabled,
- )}>
- {placeholder ?? ''}
- </span>
- )}
- </button>
+ const isQueryEmpty = trimmedQuery === '';
+ // An empty state is a searched query's answer. An empty query that lists
+ // nothing — nothing selected and an empty bootstrap set — shows only the
+ // search field, no list, no message, and announces nothing (FR20).
+ const isSettledEmpty =
+ !isPending &&
+ !isBelowMinQuery &&
+ !isQueryEmpty &&
+ visibleItems.length === 0 &&
+ createItem == null;
+ const isSettledBlank =
+ !isPending &&
+ !isBelowMinQuery &&
+ isQueryEmpty &&
+ visibleItems.length === 0 &&
+ createItem == null;
- {!isDisabled && (
- <BottomSheet
- isOpen={isSheetOpen}
- onOpenChange={setIsSheetOpen}
- label={label}
- height="tall"
- padding={0}>
- <div {...stylex.props(styles.sheetBody)}>
- <div {...stylex.props(styles.filterRow)}>
- <TextInput
- label={`Search ${label}`}
- isLabelHidden
- placeholder="Search..."
- startIcon="search"
- value={query}
+ // How each search ended, once per settle (AR6): the result count for a
+ // searched query. The empty state announces its own words.
+ useEffect(() => {
+ if (!isOpen || isPending || announcedSearchIdRef.current === searchId) {
+ return;
+ }
+ announcedSearchIdRef.current = searchId;
+ if (!isSettledEmpty && !isQueryEmpty) {
+ announce(
+ t('@astryx.typeahead.resultCount', {
+ count: visibleItems.length + (createItem == null ? 0 : 1),
+ }),
+ );
+ }
+ }, [
+ announce,
+ createItem,
+ isOpen,
+ isPending,
+ isQueryEmpty,
+ isSettledEmpty,
+ visibleItems.length,
+ searchId,
+ t,
+ ]);
+
+ // ---- Clear all ----
+ // The confirmation is in the DOM only from the Clear all press until it
+ // closes (INV7). Dialog restores focus only in its close effect, so the
+ // sheet places focus itself once the modal is gone: on the search field
+ // after a confirmed clear — the clear is spent, and the search field is
+ // where the next selection starts (FR24, `spec:AST-085` FR4) — and back on
+ // Clear all after a cancel. A confirmed clear is announced there too, after
+ // the confirmation has gone, so the words are delivered inside the sheet
+ // (`spec:AST-086` FR14).
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
+ const afterConfirmationRef = useRef<'search' | 'clear-all' | null>(null);
+ const closeClearConfirmation = (confirmed: boolean) => {
+ afterConfirmationRef.current = confirmed ? 'search' : 'clear-all';
+ setIsClearConfirmationOpen(false);
+ };
+ useEffect(() => {
+ if (isClearConfirmationOpen || afterConfirmationRef.current == null) {
+ return;
+ }
+ const destination = afterConfirmationRef.current;
+ afterConfirmationRef.current = null;
+ if (destination === 'search') {
+ searchRef.current?.focus();
+ announce(t('@astryx.tokenizer.allRemoved'));
+ } else {
+ clearAllRef.current?.focus();
+ }
+ }, [announce, isClearConfirmationOpen, t]);
+
+ const searchLabel = t('@astryx.tokenizer.search', {label});
+ const noResultsTitle =
+ emptySearchResultsText ?? t('@astryx.typeahead.emptySearchResults');
+
+ return (
+ <div {...stylex.props(styles.sheetBody)}>
+ <div {...stylex.props(styles.filterRow)}>
+ <TextInput
+ ref={searchRef}
+ label={searchLabel}
+ isLabelHidden
+ placeholder={t('@astryx.tokenizer.searchPlaceholder')}
+ startIcon="search"
+ value={query}
+ size="lg"
+ width="100%"
+ hasClear
+ onChange={handleQueryChange}
+ controlXstyle={styles.filterInput}
+ />
+ </div>
+ {isPending ? (
+ // Named busy feedback while the source works, above any rows still
+ // listed from the previous search (`family:input-fields` FR7).
+ <div {...stylex.props(styles.pending)}>
+ <Spinner
+ size="md"
+ role="img"
+ aria-label={t('@astryx.typeahead.loading')}
+ />
+ </div>
+ ) : null}
+ {isSettledEmpty ? (
+ <div {...stylex.props(styles.emptyHost)}>
+ <EmptyState
+ icon={<Icon icon="search" size="lg" color="secondary" />}
+ title={noResultsTitle}
+ description={t('@astryx.tokenizer.noResultsDescription')}
+ isCompact
+ xstyle={styles.empty}
+ />
+ </div>
+ ) : isSettledBlank ? null : (
+ <div
+ {...stylex.props(styles.list)}
+ role="group"
+ aria-label={label}
+ aria-busy={isPending || undefined}
+ data-testid="mobile-tokenizer-list"
+ data-rendered-count={renderedItems.length}
+ data-total-count={visibleItems.length}
+ onScroll={event => {
+ const list = event.currentTarget;
+ const distanceFromBottom =
+ list.scrollHeight - list.scrollTop - list.clientHeight;
+ if (
+ distanceFromBottom <= LIST_LOAD_MORE_THRESHOLD_PX &&
+ lastLoadScrollHeightRef.current !== list.scrollHeight
+ ) {
+ lastLoadScrollHeightRef.current = list.scrollHeight;
+ setRenderedItemCount(current =>
+ Math.min(current + LIST_RENDER_BATCH_SIZE, visibleItems.length),
+ );
+ }
+ }}>
+ {createItem != null && (
+ <div
+ data-testid="mobile-tokenizer-create-row"
+ {...stylex.props(styles.createRow)}>
+ <span {...stylex.props(styles.createLabel)}>
+ <Text type="body">{createItem.label}</Text>
+ </span>
+ <Button
+ label={t('@astryx.tokenizer.add')}
+ aria-label={t('@astryx.tokenizer.addValue', {
+ value: trimmedQuery,
+ })}
+ variant="secondary"
size="lg"
- width="100%"
- hasClear
- onChange={next => {
- lastLoadScrollHeightRef.current = null;
- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setQuery(next);
- onChangeQuery?.(next);
+ onClick={() => {
+ if (onAdd(createItem)) {
+ announce(
+ t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),
+ );
+ }
+ handleQueryChange('');
}}
- controlXstyle={styles.filterInput}
/>
</div>
- <div
- {...stylex.props(styles.list)}
- role="group"
- aria-label={label}
- data-testid="mobile-tokenizer-list"
- data-rendered-count={renderedItems.length}
- data-total-count={visibleItems.length}
- onScroll={event => {
- const list = event.currentTarget;
- const distanceFromBottom =
- list.scrollHeight - list.scrollTop - list.clientHeight;
- if (
- distanceFromBottom <= LIST_LOAD_MORE_THRESHOLD_PX &&
- lastLoadScrollHeightRef.current !== list.scrollHeight
- ) {
- lastLoadScrollHeightRef.current = list.scrollHeight;
- setRenderedItemCount(current =>
- Math.min(
- current + LIST_RENDER_BATCH_SIZE,
- visibleItems.length,
- ),
- );
- }
- }}>
- {createItem != null && (
- <div
- data-testid="mobile-tokenizer-create-row"
- {...stylex.props(styles.createRow)}>
- <span {...stylex.props(styles.createLabel)}>
- <Text type="body">{createItem.label}</Text>
- </span>
- <Button
- label="Add"
- aria-label={`Add ${query.trim()}`}
- variant="secondary"
- size="lg"
- onClick={() => {
- handleAdd(createItem);
- lastLoadScrollHeightRef.current = null;
- setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
- setQuery('');
- }}
- />
- </div>
- )}
- {!isSearching &&
- visibleItems.length === 0 &&
- createItem == null ? (
- <EmptyState
- icon={
- <Icon
- icon={query.trim() === '' ? ListBulletIcon : 'search'}
- size="lg"
- color="secondary"
- />
+ )}
+ {renderedItems.map(item => {
+ const isSelected = selectedIds.has(item.id);
+ const rowDisabled = !isSelected && isAtMax;
+ return (
+ <button
+ key={item.id}
+ type="button"
+ role="checkbox"
+ aria-checked={isSelected}
+ aria-label={item.label}
+ aria-disabled={rowDisabled || undefined}
+ onClick={() => {
+ if (rowDisabled) {
+ return;
}
- title={
- query.trim() === ''
- ? 'No items available'
- : emptySearchResultsText
+ if (isSelected) {
+ if (onRemove(item)) {
+ announce(
+ t('@astryx.tokenizer.tokenRemoved', {
+ label: item.label,
+ }),
+ );
+ }
+ } else if (onAdd(item)) {
+ announce(
+ t('@astryx.tokenizer.tokenAdded', {label: item.label}),
+ );
}
- description={
- query.trim() === ''
- ? 'There are no items to choose from.'
- : 'Try a different search.'
- }
- isCompact
- xstyle={styles.empty}
- />
- ) : (
- renderedItems.map(item => {
- const isSelected = selectedIds.has(item.id);
- const rowDisabled = !isSelected && isAtMax;
- return (
- <button
- key={item.id}
- type="button"
- role="checkbox"
- aria-checked={isSelected}
- aria-label={item.label}
- aria-disabled={rowDisabled || undefined}
- onClick={() => {
- if (rowDisabled) {
- return;
- }
- if (isSelected) {
- handleRemove(item);
- } else {
- handleAdd(item);
- }
- }}
- {...stylex.props(
- styles.row,
- rowDisabled && styles.rowDisabled,
- )}>
- <span {...stylex.props(styles.rowLabel)}>
- {renderItem ? (
- renderItem(item)
- ) : (
- <Text
- type="body"
- color={rowDisabled ? 'inherit' : undefined}>
- {item.label}
- </Text>
- )}
- </span>
- <CheckboxIndicator
- state={isSelected ? 'checked' : 'unchecked'}
- size="md"
- isDisabled={rowDisabled}
- xstyle={
- rowDisabled ? styles.indicatorDisabled : undefined
- }
- />
- </button>
- );
- })
- )}
- </div>
- {query.trim() === '' && (
- <div {...stylex.props(styles.footer)}>
- <Button
- label="Clear all"
- variant="secondary"
- size="lg"
- isDisabled={value.length === 0}
- onClick={() => setIsClearConfirmationOpen(true)}
- xstyle={styles.footerAction}
- />
- <Button
- label="Done"
- variant="primary"
- size="lg"
- onClick={() => {
- setQuery('');
- setIsSheetOpen(false);
- }}
- xstyle={styles.footerAction}
+ }}
+ {...stylex.props(
+ styles.row,
+ rowDisabled && styles.rowDisabled,
+ )}>
+ <span {...stylex.props(styles.rowLabel)}>
+ {renderItem ? (
+ renderItem(item)
+ ) : (
+ <Text
+ type="body"
+ color={rowDisabled ? 'inherit' : undefined}>
+ {item.label}
+ </Text>
+ )}
+ </span>
+ <CheckboxIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
+ isDisabled={rowDisabled}
+ xstyle={rowDisabled ? styles.indicatorDisabled : undefined}
/>
- </div>
- )}
- <AlertDialog
- isOpen={isClearConfirmationOpen}
- onOpenChange={setIsClearConfirmationOpen}
- title="Clear all selected items?"
- description={`This removes all selected items from ${label}.`}
- actionLabel="Clear selection"
- onAction={() => {
- handleClearAll();
- setIsClearConfirmationOpen(false);
- }}
- />
- </div>
- </BottomSheet>
+ </button>
+ );
+ })}
+ </div>
)}
- </Field>
+ {isQueryEmpty && (
+ <div {...stylex.props(styles.footer)}>
+ <Button
+ ref={clearAllRef}
+ label={t('@astryx.tokenizer.clearAll')}
+ variant="secondary"
+ size="lg"
+ isDisabled={value.length === 0}
+ // With a tooltip, Button's disabled mode is `aria-disabled`: the
+ // action keeps its focus order and says why it does nothing
+ // (`spec:AST-085` FR1), instead of leaving the tab order as a
+ // natively disabled button does (FR24).
+ tooltip={
+ value.length === 0
+ ? t('@astryx.tokenizer.nothingToClear')
+ : undefined
+ }
+ onClick={() => setIsClearConfirmationOpen(true)}
+ xstyle={styles.footerAction}
+ />
+ <Button
+ label={t('@astryx.tokenizer.done')}
+ variant="primary"
+ size="lg"
+ onClick={onRequestClose}
+ xstyle={styles.footerAction}
+ />
+ </div>
+ )}
+ {isClearConfirmationOpen && (
+ <AlertDialog
+ isOpen
+ onOpenChange={next => {
+ if (!next) {
+ closeClearConfirmation(false);
+ }
+ }}
+ title={t('@astryx.tokenizer.clearAllTitle')}
+ description={t('@astryx.tokenizer.clearAllDescription', {label})}
+ actionLabel={t('@astryx.tokenizer.clearSelection')}
+ onAction={() => {
+ onClearAll();
+ closeClearConfirmation(true);
+ }}
+ />
+ )}
+ </div>
);
}
-
-MobileTokenizer.displayName = 'MobileTokenizer';