Skip to content

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

TypeScript

Prototype single-sheet MobileTokenizer flow (#6855)

rubyycheung4fc416b03806
diff --git a/apps/storybook/stories/MobileTokenizer.stories.tsx b/apps/storybook/stories/MobileTokenizer.stories.tsx
index 9c84b37f46..5f69683e7d 100644
--- a/apps/storybook/stories/MobileTokenizer.stories.tsx
+++ b/apps/storybook/stories/MobileTokenizer.stories.tsx
@@ -1,22 +1,29 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file MobileTokenizer.stories.tsx
- * @input Uses MobileTokenizer (Lab) with the sketch's Design/Eng data
- * @output Storybook try-it story at 390px: field -> manage -> add sheets,
- * including custom item creation
- * @position Lab story; stack layer 1 try-it surface
+ * @input Uses MobileTokenizer (Lab) with a 1,000-entry searchable dataset
+ * @output Storybook try-it story at 390px: one searchable management sheet
+ * with stable checkbox rows and enough entries to evaluate progressive
+ * list rendering
+ * @position Lab story; single-sheet touch-flow prototype
*/
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react';
import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';
import {MobileTokenizer} from '@astryxdesign/lab';
-const tags: SearchableItem[] = [
- {id: 'design', label: 'Design'},
- {id: 'eng', label: 'Eng'},
- {id: 'engineer', label: 'Engineer'},
- {id: 'energizer', label: 'Energizer'},
-];
+const tags: SearchableItem[] = Array.from({length: 1000}, (_, index) => {
+ const number = index + 1;
+ return {
+ id: `tag-${number}`,
+ label:
+ number === 1
+ ? 'Design'
+ : number === 2
+ ? 'Eng'
+ : `Tag ${String(number).padStart(2, '0')}`,
+ };
+});
const source: SearchSource = {
search: (q: string) =>
tags.filter(t => t.label.toLowerCase().includes(q.toLowerCase())),
@@ -42,10 +49,11 @@ export const TouchFlow: Story = {
onChange={items => setValue(items)}
placeholder="Add tags"
hasCreate
+ maxMenuItems={1000}
debounceMs={0}
/>
</div>
);
},
- name: 'Touch flow (sketch: manage + stacked add, bottom filter)',
+ name: 'Touch flow (single searchable management sheet)',
};
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
index 356310ffff..9b5124a610 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
@@ -14,19 +14,18 @@ export const docs = {
{name: 'placeholder', type: 'string', description: 'Trigger text when nothing is selected.'},
{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: 'renderItem', type: '(item: T) => ReactNode', description: 'Custom add-sheet row content.'},
+ {name: 'maxMenuItems', type: 'number', description: 'Maximum source results retained; 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 the manage sheet (review, remove, Clear all, Add item), tap Add item for the stacked search sheet (results above, filter + Done in the bottom row above the keyboard, tap +/check to toggle immediately).',
+ '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.',
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.'},
],
anatomy: [
{name: 'Trigger field', required: true, description: 'Button showing tokens as a summary.'},
- {name: 'Manage sheet', required: true, description: 'Selected rows with remove controls, guided empty states, and equal-width footer actions.'},
- {name: 'Add sheet', required: true, description: 'Stacked sheet: result rows with +/check toggles, bottom filter + Done row.'},
+ {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.'},
],
},
};
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
index 1794df9d47..5f24c20560 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
@@ -2,12 +2,18 @@
/**
* @file MobileTokenizer.test.tsx
* @input Uses vitest, @testing-library/react, MobileTokenizer
- * @output Lab tests for the sketch flow: field -> manage -> add (bottom
- * filter) -> Done -> manage
+ * @output Lab tests for the single-sheet touch flow
* @position Lab tests; validates MobileTokenizer.tsx
*/
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {
+ act,
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ within,
+} from '@testing-library/react';
import {useState} from 'react';
import {MobileTokenizer, type MobileTokenizerChange} from './MobileTokenizer';
import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';
@@ -20,14 +26,17 @@ const ITEMS: SearchableItem[] = [
];
const source: SearchSource<SearchableItem> = {
search: q =>
- ITEMS.filter(i => i.label.toLowerCase().includes(q.toLowerCase())),
+ ITEMS.filter(item => item.label.toLowerCase().includes(q.toLowerCase())),
bootstrap: () => ITEMS,
};
function Harness({
spy,
}: {
- spy?: (i: SearchableItem[], c: MobileTokenizerChange<SearchableItem>) => void;
+ spy?: (
+ items: SearchableItem[],
+ change: MobileTokenizerChange<SearchableItem>,
+ ) => void;
}) {
const [value, setValue] = useState<SearchableItem[]>([ITEMS[0], ITEMS[1]]);
return (
@@ -35,7 +44,6 @@ function Harness({
label="Tags"
searchSource={source}
value={value}
- hasCreate
debounceMs={0}
placeholder="Add tags"
onChange={(items, change) => {
@@ -46,6 +54,23 @@ function Harness({
);
}
+function CreateHarness({spy}: {spy: ReturnType<typeof vi.fn>}) {
+ const [value, setValue] = useState<SearchableItem[]>([]);
+ return (
+ <MobileTokenizer
+ label="Tags"
+ searchSource={source}
+ value={value}
+ hasCreate
+ debounceMs={0}
+ onChange={(items, change) => {
+ setValue(items);
+ spy(items, change);
+ }}
+ />
+ );
+}
+
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
this: HTMLDialogElement,
@@ -75,6 +100,7 @@ beforeEach(() => {
dispatchEvent: vi.fn(),
}),
);
+ window.scrollTo = vi.fn();
vi.stubGlobal(
'requestAnimationFrame',
vi.fn((cb: FrameRequestCallback) => {
@@ -85,114 +111,227 @@ beforeEach(() => {
});
afterEach(() => vi.unstubAllGlobals());
-describe('MobileTokenizer (Lab, sketch flow)', () => {
- it('field -> manage -> add: filter at bottom, tap + adds, Done returns', async () => {
+describe('MobileTokenizer (Lab, single-sheet flow)', () => {
+ it('keeps rows stable while open and applies selected-first order on reopen', async () => {
const spy = vi.fn();
render(<Harness spy={spy} />);
const trigger = screen.getByRole('button', {name: /Tags/});
- expect(trigger.getAttribute('aria-haspopup')).toBe('dialog');
fireEvent.click(trigger);
+
+ const list = await screen.findByTestId('mobile-tokenizer-list');
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+ const checkboxLabels = () =>
+ within(list)
+ .getAllByRole('checkbox')
+ .map(row => row.getAttribute('aria-label'));
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+ const search = screen.getByLabelText('Search Tags');
expect(
- (await screen.findByTestId('mobile-tokenizer-manage-list')).textContent,
- ).toContain('Design');
- fireEvent.click(screen.getByRole('button', {name: 'Add item'}));
- const search = await screen.findByLabelText('Search Tags');
- fireEvent.change(search, {target: {value: 'E'}});
- const engineer = await screen.findByRole('button', {name: 'Add Engineer'});
- expect(engineer).toHaveAttribute('data-variant', 'secondary');
- fireEvent.click(engineer);
+ search.closest('.astryx-text-input')?.querySelector('.astryx-icon'),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Add item'}),
+ ).not.toBeInTheDocument();
+ const design = screen.getByRole('checkbox', {name: 'Design'});
+ expect(design).toBeChecked();
+ expect(design.lastElementChild).toHaveAttribute('aria-hidden', 'true');
+ expect(design.lastElementChild).toHaveAttribute('data-size', 'md');
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
expect(spy).toHaveBeenCalledWith(
- [ITEMS[0], ITEMS[1], ITEMS[2]],
+ [ITEMS[0], ITEMS[1], ITEMS[3]],
expect.objectContaining({type: 'add'}),
);
await waitFor(() =>
- expect(
- screen.getByRole('button', {name: 'Remove Engineer'}),
- ).toBeInTheDocument(),
+ expect(screen.getByRole('checkbox', {name: 'Energizer'})).toBeChecked(),
+ );
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
+ expect(spy).toHaveBeenLastCalledWith(
+ [ITEMS[0], ITEMS[3]],
+ expect.objectContaining({type: 'remove'}),
);
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Eng',
+ 'Engineer',
+ 'Energizer',
+ ]);
+
fireEvent.click(screen.getByRole('button', {name: 'Done'}));
- expect(
- (await screen.findByTestId('mobile-tokenizer-manage-list')).textContent,
- ).toContain('Engineer');
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+
+ await act(async () => {
+ fireEvent.click(trigger);
+ });
+ expect(checkboxLabels()).toEqual([
+ 'Design',
+ 'Energizer',
+ 'Eng',
+ 'Engineer',
+ ]);
});
- it('creates custom items and shows them in the field and manage sheet', async () => {
+
+ it('creates a custom entry with a trailing Add action', async () => {
const spy = vi.fn();
- render(<Harness spy={spy} />);
+ render(<CreateHarness spy={spy} />);
const trigger = screen.getByRole('button', {name: /Tags/});
fireEvent.click(trigger);
- fireEvent.click(screen.getByRole('button', {name: 'Add item'}));
const search = await screen.findByLabelText('Search Tags');
fireEvent.change(search, {target: {value: 'Custom'}});
- const create = await screen.findByRole('button', {
- name: 'Create "Custom"',
+ expect(
+ screen.queryByRole('checkbox', {name: 'Create "Custom"'}),
+ ).not.toBeInTheDocument();
+ const create = await screen.findByRole('button', {name: 'Add Custom'});
+ expect(
+ screen.queryByRole('button', {name: 'Clear all'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Done'}),
+ ).not.toBeInTheDocument();
+ expect(create).toHaveAttribute('data-size', 'lg');
+ expect(screen.getByTestId('mobile-tokenizer-create-row')).toHaveTextContent(
+ 'Create "Custom"',
+ );
+ await act(async () => {
+ fireEvent.click(create);
});
- fireEvent.click(create);
expect(spy).toHaveBeenCalledWith(
- [ITEMS[0], ITEMS[1], {id: 'Custom', label: 'Custom'}],
+ [{id: 'Custom', label: 'Custom'}],
expect.objectContaining({type: 'create'}),
);
await waitFor(() => expect(trigger).toHaveTextContent('Custom'));
-
- fireEvent.click(screen.getByRole('button', {name: 'Done'}));
- expect(
- await screen.findByTestId('mobile-tokenizer-manage-list'),
- ).toHaveTextContent('Custom');
+ expect(search).toHaveValue('');
+ const custom = await screen.findByRole('checkbox', {name: 'Custom'});
+ expect(custom).toBeChecked();
});
- it('uses guided empty states and large actions', async () => {
+ it('renders long lists in 50-item batches and resets the window for search', async () => {
+ const longItems: SearchableItem[] = Array.from(
+ {length: 120},
+ (_, index) => ({
+ id: `item-${index + 1}`,
+ label: `Item ${String(index + 1).padStart(3, '0')}`,
+ }),
+ );
+ const longSource: SearchSource<SearchableItem> = {
+ bootstrap: () => longItems,
+ search: query =>
+ longItems.filter(item =>
+ item.label.toLowerCase().includes(query.toLowerCase()),
+ ),
+ };
render(
<MobileTokenizer
- label="Tags"
- searchSource={source}
+ label="Items"
+ searchSource={longSource}
value={[]}
- debounceMs={0}
onChange={() => {}}
+ maxMenuItems={120}
+ debounceMs={0}
/>,
);
- fireEvent.click(screen.getByRole('button', {name: /Tags/}));
- const manageTitle = await screen.findByRole('heading', {
- name: 'No items yet',
+ fireEvent.click(screen.getByRole('button', {name: 'Items'}));
+ const list = await screen.findByTestId('mobile-tokenizer-list');
+ await waitFor(() => {
+ expect(list).toHaveAttribute('data-rendered-count', '50');
+ expect(list).toHaveAttribute('data-total-count', '120');
});
+ expect(screen.getAllByRole('checkbox')).toHaveLength(50);
expect(
- manageTitle.closest('[role="status"]')?.querySelector('.astryx-icon'),
- ).toHaveAttribute('data-size', 'lg');
- expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute(
- 'data-size',
- 'lg',
- );
- expect(
- screen.queryByRole('button', {name: 'Close'}),
+ screen.queryByRole('checkbox', {name: 'Item 051'}),
).not.toBeInTheDocument();
- fireEvent.click(screen.getByRole('button', {name: 'Add item'}));
- const search = await screen.findByLabelText('Search Tags');
- expect(search.closest('.astryx-text-input')).toHaveAttribute(
- 'data-size',
- 'lg',
- );
- expect(screen.getByRole('button', {name: 'Done'})).toHaveAttribute(
- 'data-size',
- 'lg',
+
+ Object.defineProperties(list, {
+ clientHeight: {configurable: true, value: 600},
+ scrollHeight: {configurable: true, value: 2400},
+ scrollTop: {configurable: true, value: 1700, writable: true},
+ });
+ fireEvent.scroll(list);
+ expect(list).toHaveAttribute('data-rendered-count', '100');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(100);
+ expect(
+ screen.getByRole('checkbox', {name: 'Item 100'}),
+ ).toBeInTheDocument();
+
+ Object.defineProperties(list, {
+ scrollHeight: {configurable: true, value: 4400},
+ scrollTop: {
+ configurable: true,
+ value: 3600,
+ writable: true,
+ },
+ });
+ fireEvent.scroll(list);
+ expect(list).toHaveAttribute('data-rendered-count', '120');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(120);
+
+ fireEvent.change(screen.getByLabelText('Search Items'), {
+ target: {value: 'Item'},
+ });
+ await waitFor(() =>
+ expect(list).toHaveAttribute('data-rendered-count', '50'),
);
+ expect(screen.getAllByRole('checkbox')).toHaveLength(50);
+
+ fireEvent.scroll(list);
+ expect(list).toHaveAttribute('data-rendered-count', '100');
+ expect(screen.getAllByRole('checkbox')).toHaveLength(100);
+ });
+
+ it('searches within the same sheet and centers the no-results state', async () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: /Tags/}));
+ const search = await screen.findByLabelText('Search Tags');
fireEvent.change(search, {target: {value: 'zzz'}});
- const searchTitle = await screen.findByRole('heading', {
+
+ const title = await screen.findByRole('heading', {
name: 'No results found',
});
- expect(searchTitle.closest('[role="status"]')).toHaveTextContent(
- 'Try a different search.',
+ const emptyState = title.closest('[role="status"]');
+ expect(emptyState).toHaveTextContent('Try a different search.');
+ expect(emptyState?.querySelector('.astryx-icon')).toHaveAttribute(
+ 'data-size',
+ 'lg',
);
});
- it('manage sheet removes and clears', async () => {
+
+ it('keeps large equal-width Clear all and Done footer actions while guarding the bulk clear', async () => {
const spy = vi.fn();
render(<Harness spy={spy} />);
fireEvent.click(screen.getByRole('button', {name: /Tags/}));
- await screen.findByTestId('mobile-tokenizer-manage-list');
- fireEvent.click(screen.getByRole('button', {name: 'Remove Eng'}));
- expect(spy).toHaveBeenCalledWith(
- [ITEMS[0]],
- expect.objectContaining({type: 'remove'}),
+ const list = await screen.findByTestId('mobile-tokenizer-list');
+
+ const clearAll = screen.getByRole('button', {name: 'Clear all'});
+ const done = screen.getByRole('button', {name: 'Done'});
+ expect(clearAll).toHaveAttribute('data-size', 'lg');
+ expect(clearAll).toHaveAttribute('data-variant', 'secondary');
+ expect(done).toHaveAttribute('data-size', 'lg');
+ expect(list.compareDocumentPosition(clearAll)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ expect(list.compareDocumentPosition(done)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING,
+ );
+ fireEvent.click(clearAll);
+ const confirmation = screen.getByRole('alertdialog');
+ expect(confirmation).toHaveTextContent('Clear all selected items?');
+ expect(spy).not.toHaveBeenCalled();
+ fireEvent.click(
+ within(confirmation).getByRole('button', {name: 'Clear selection'}),
);
- fireEvent.click(screen.getByRole('button', {name: 'Clear all'}));
expect(spy).toHaveBeenLastCalledWith(
[],
expect.objectContaining({type: 'remove'}),
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
index 9288ba4867..48285f5705 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
@@ -4,13 +4,14 @@
/**
* @file MobileTokenizer.tsx
- * @input Uses public @astryxdesign/core components only (BottomSheet,
- * BottomSheetSwitcher, Button, EmptyState, Field, Icon, IconButton, Text,
- * TextInput, Token)
+ * @input Uses public @astryxdesign/core components only (AlertDialog,
+ * BottomSheet, BottomSheetSwitcher, Button, CheckboxIndicator, EmptyState,
+ * Field, Icon, Text, TextInput, Token)
* @output Exports MobileTokenizer — Lab prototype of the touch Tokenizer
- * flow (stacked manage + add sheets)
+ * 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") stacked after it.
+ * Core promotion (Tokenizer presentation="bottom-sheet").
*
* API mirrors Core Tokenizer (label/searchSource/value/onChange/change,
* hasCreate, maxEntries) so graduation is an import swap. Differences from
@@ -25,18 +26,18 @@ import {
useMemo,
useRef,
useState,
- type ReactNode,
type SVGProps,
} from 'react';
import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
+import {AlertDialog} from '@astryxdesign/core/AlertDialog';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
import {EmptyState} from '@astryxdesign/core/EmptyState';
import {Field} from '@astryxdesign/core/Field';
import {Icon} from '@astryxdesign/core/Icon';
-import {IconButton} from '@astryxdesign/core/IconButton';
+import {CheckboxIndicator} from '@astryxdesign/core/Indicator';
import {Text} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
import {Token} from '@astryxdesign/core/Token';
@@ -62,7 +63,6 @@ export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<
searchSource: SearchSource<T>;
value: T[];
onChange: (items: T[], change: MobileTokenizerChange<T>) => void;
- renderItem?: (item: T) => ReactNode;
placeholder?: string;
description?: string;
isOptional?: boolean;
@@ -76,8 +76,10 @@ export interface MobileTokenizerProps<T extends SearchableItem> extends Omit<
onChangeQuery?: (query: string) => void;
}
-type SheetId = 'manage' | 'add';
+type SheetId = 'manage';
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 (
@@ -125,7 +127,7 @@ const styles = stylex.create({
height: '100%',
minHeight: 0,
paddingInline: spacingVars['--spacing-3'],
- paddingBlockStart: spacingVars['--spacing-3'],
+ paddingBlockStart: spacingVars['--spacing-8'],
paddingBlockEnd: spacingVars['--spacing-3'],
},
// The manage sheet intentionally has no dedicated close button; the sheet
@@ -133,27 +135,46 @@ const styles = stylex.create({
list: {
display: 'flex',
flexDirection: 'column',
+ flexGrow: 1,
overflowY: 'auto',
minHeight: 0,
},
- addList: {
- flexGrow: 1,
- },
row: {
display: 'flex',
alignItems: 'center',
+ justifyContent: 'space-between',
gap: spacingVars['--spacing-2'],
width: '100%',
minHeight: 44,
paddingBlock: spacingVars['--spacing-2'],
paddingInline: spacingVars['--spacing-1'],
- textAlign: 'start',
- backgroundColor: 'transparent',
borderWidth: 0,
+ borderRadius: radiusVars['--radius-element'],
+ backgroundColor: 'transparent',
color: colorVars['--color-text-primary'],
+ textAlign: 'start',
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ },
+ rowLabel: {
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ createRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ width: '100%',
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-1'],
+ },
+ createLabel: {
+ flexGrow: 1,
+ minWidth: 0,
},
- rowDisabled: {opacity: 0.5},
- rowLabel: {flexGrow: 1, minWidth: 0},
footer: {
display: 'flex',
alignItems: 'center',
@@ -168,12 +189,10 @@ const styles = stylex.create({
filterRow: {
display: 'flex',
alignItems: 'flex-end',
- gap: spacingVars['--spacing-2'],
- paddingBlockStart: spacingVars['--spacing-2'],
- marginTop: 'auto',
+ paddingBlockEnd: spacingVars['--spacing-2'],
},
// TextInput renders Field (block, shrink-to-fit); xstyle lands on that
- // root, so it must flex — the filter takes all row space minus Done+gap.
+ // root, so it must fill the available search row width.
filterInput: {
flexGrow: 1,
flexShrink: 1,
@@ -182,8 +201,7 @@ const styles = stylex.create({
height: sizeVars['--size-element-lg'],
minHeight: sizeVars['--size-element-lg'],
},
- empty: {paddingBlock: spacingVars['--spacing-4']},
- searchEmpty: {
+ empty: {
flexGrow: 1,
},
});
@@ -193,7 +211,6 @@ export function MobileTokenizer<T extends SearchableItem>({
searchSource,
value,
onChange,
- renderItem,
placeholder,
description,
isOptional,
@@ -209,6 +226,7 @@ export function MobileTokenizer<T extends SearchableItem>({
}: MobileTokenizerProps<T>) {
const triggerId = useId();
const [activeSheet, setActiveSheet] = useState<SheetId | null>(null);
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);
const isAtMax = maxEntries != null && value.length >= maxEntries;
@@ -243,14 +261,19 @@ export function MobileTokenizer<T extends SearchableItem>({
}
};
- // ---- add-sheet search ----
+ // ---- sheet search ----
const [query, setQuery] = useState('');
const [results, setResults] = useState<T[]>([]);
const [isSearching, setIsSearching] = useState(false);
+ const [renderedItemCount, setRenderedItemCount] = useState(
+ LIST_RENDER_BATCH_SIZE,
+ );
const seqRef = useRef(0);
- const isAddOpen = activeSheet === 'add';
+ const lastLoadScrollHeightRef = useRef<number | null>(null);
+ const [selectedItemsAtOpen, setSelectedItemsAtOpen] = useState<T[]>(value);
+ const isSheetOpen = activeSheet === 'manage';
useEffect(() => {
- if (!isAddOpen) {
+ if (!isSheetOpen) {
return;
}
const seq = ++seqRef.current;
@@ -285,7 +308,7 @@ export function MobileTokenizer<T extends SearchableItem>({
}
void run();
}, [
- isAddOpen,
+ isSheetOpen,
query,
searchSource,
minQueryLength,
@@ -293,6 +316,34 @@ export function MobileTokenizer<T extends SearchableItem>({
debounceMs,
]);
+ const visibleItems = useMemo(() => {
+ const normalizedQuery = query.trim().toLowerCase();
+ const matchesQuery = (item: T) =>
+ normalizedQuery === '' ||
+ item.label.toLowerCase().includes(normalizedQuery);
+ const selectedAtOpenMatches = selectedItemsAtOpen.filter(matchesQuery);
+ const selectedAtOpenIds = new Set(
+ selectedAtOpenMatches.map(item => item.id),
+ );
+ const resultIds = new Set(results.map(item => item.id));
+ const selectedItemsMissingFromResults = value.filter(
+ item =>
+ !selectedAtOpenIds.has(item.id) &&
+ !resultIds.has(item.id) &&
+ matchesQuery(item),
+ );
+
+ // Selection changes update checkbox state without moving an existing row.
+ // The next open snapshots the latest value and applies selected-first order.
+ return [
+ ...selectedAtOpenMatches,
+ ...selectedItemsMissingFromResults,
+ ...results.filter(item => !selectedAtOpenIds.has(item.id)),
+ ];
+ }, [query, results, selectedItemsAtOpen, value]);
+
+ const renderedItems = visibleItems.slice(0, renderedItemCount);
+
const createItem = useMemo<T | null>(() => {
const trimmed = query.trim();
if (!hasCreate || trimmed === '' || isAtMax) {
@@ -300,6 +351,7 @@ export function MobileTokenizer<T extends SearchableItem>({
}
if (
selectedIds.has(trimmed) ||
+ value.some(item => item.label.toLowerCase() === trimmed.toLowerCase()) ||
results.some(r => r.label.toLowerCase() === trimmed.toLowerCase())
) {
return null;
@@ -308,7 +360,7 @@ export function MobileTokenizer<T extends SearchableItem>({
id: `${CREATABLE_ID_PREFIX}${trimmed}`,
label: `Create "${trimmed}"`,
} as unknown as T;
- }, [hasCreate, query, results, selectedIds, isAtMax]);
+ }, [hasCreate, query, results, selectedIds, isAtMax, value]);
return (
<Field
@@ -325,7 +377,12 @@ export function MobileTokenizer<T extends SearchableItem>({
aria-expanded={activeSheet != null}
aria-label={label}
disabled={isDisabled}
- onClick={() => setActiveSheet('manage')}
+ onClick={() => {
+ setSelectedItemsAtOpen(value);
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ setActiveSheet('manage');
+ }}
{...stylex.props(styles.trigger)}>
{value.length > 0 ? (
value.map(item => (
@@ -342,153 +399,158 @@ export function MobileTokenizer<T extends SearchableItem>({
<BottomSheetSwitcher
activeSheet={activeSheet}
onActiveSheetChange={id => setActiveSheet(id as SheetId | null)}>
- <BottomSheet sheetId="manage" label={label} height="hug">
+ <BottomSheet sheetId="manage" label={label} height="tall">
<div {...stylex.props(styles.sheetBody)}>
- <div
- {...stylex.props(styles.list)}
- data-testid="mobile-tokenizer-manage-list">
- {value.length === 0 ? (
- <EmptyState
- icon={
- <Icon icon={ListBulletIcon} size="lg" color="secondary" />
- }
- title="No items yet"
- description="Add an item to get started."
- isCompact
- xstyle={styles.empty}
- />
- ) : (
- value.map(item => (
- <div key={item.id}>
- <div {...stylex.props(styles.row)}>
- <span {...stylex.props(styles.rowLabel)}>
- <Text type="body">{item.label}</Text>
- </span>
- <IconButton
- label={`Remove ${item.label}`}
- icon={<Icon icon="close" />}
- variant="ghost"
- size="sm"
- onClick={() => handleRemove(item)}
- />
- </div>
- </div>
- ))
- )}
- </div>
- <div {...stylex.props(styles.footer)}>
- <Button
- label="Clear all"
- variant="secondary"
- size="lg"
- isDisabled={value.length === 0}
- onClick={handleClearAll}
- xstyle={styles.footerAction}
- />
- <Button
- label="Add item"
- variant="primary"
+ <div {...stylex.props(styles.filterRow)}>
+ <TextInput
+ label={`Search ${label}`}
+ isLabelHidden
+ placeholder="Search..."
+ startIcon="search"
+ value={query}
size="lg"
- isDisabled={isAtMax}
- onClick={() => setActiveSheet('add')}
- xstyle={styles.footerAction}
+ width="100%"
+ hasClear
+ onChange={next => {
+ lastLoadScrollHeightRef.current = null;
+ setRenderedItemCount(LIST_RENDER_BATCH_SIZE);
+ setQuery(next);
+ onChangeQuery?.(next);
+ }}
+ xstyle={styles.filterInput}
/>
</div>
- </div>
- </BottomSheet>
-
- <BottomSheet sheetId="add" label="Add item" height="tall">
- <div {...stylex.props(styles.sheetBody)}>
<div
- {...stylex.props(styles.list, styles.addList)}
- role="list"
+ {...stylex.props(styles.list)}
+ role="group"
aria-label={label}
- data-testid="mobile-tokenizer-add-list">
+ 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 role="listitem" {...stylex.props(styles.row)}>
- <span {...stylex.props(styles.rowLabel)}>
+ <div
+ data-testid="mobile-tokenizer-create-row"
+ {...stylex.props(styles.createRow)}>
+ <span {...stylex.props(styles.createLabel)}>
<Text type="body">{createItem.label}</Text>
</span>
- <IconButton
- label={createItem.label}
- icon={<span aria-hidden="true">+</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 && results.length === 0 && createItem == null ? (
+ {!isSearching &&
+ visibleItems.length === 0 &&
+ createItem == null ? (
<EmptyState
- icon={<Icon icon="search" size="lg" color="secondary" />}
- title={emptySearchResultsText}
- description="Try a different search."
+ icon={
+ <Icon
+ icon={query.trim() === '' ? ListBulletIcon : 'search'}
+ size="lg"
+ color="secondary"
+ />
+ }
+ title={
+ query.trim() === ''
+ ? 'No items available'
+ : emptySearchResultsText
+ }
+ description={
+ query.trim() === ''
+ ? 'There are no items to choose from.'
+ : 'Try a different search.'
+ }
isCompact
- xstyle={styles.searchEmpty}
+ xstyle={styles.empty}
/>
) : (
- results.map(item => {
+ renderedItems.map(item => {
const isSelected = selectedIds.has(item.id);
const rowDisabled = !isSelected && isAtMax;
return (
- <div
+ <button
key={item.id}
- role="listitem"
- {...stylex.props(
- styles.row,
- rowDisabled && styles.rowDisabled,
- )}>
+ type="button"
+ role="checkbox"
+ aria-checked={isSelected}
+ aria-label={item.label}
+ disabled={rowDisabled}
+ onClick={() =>
+ isSelected ? handleRemove(item) : handleAdd(item)
+ }
+ {...stylex.props(styles.row)}>
<span {...stylex.props(styles.rowLabel)}>
- {renderItem ? (
- renderItem(item)
- ) : (
- <Text type="body">{item.label}</Text>
- )}
+ <Text type="body">{item.label}</Text>
</span>
- <IconButton
- label={`${isSelected ? 'Remove' : 'Add'} ${item.label}`}
- icon={
- isSelected ? (
- <Icon icon="close" size="sm" />
- ) : (
- <span aria-hidden="true">+</span>
- )
- }
- variant={isSelected ? 'ghost' : 'secondary'}
+ <CheckboxIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
isDisabled={rowDisabled}
- onClick={() =>
- isSelected ? handleRemove(item) : handleAdd(item)
- }
/>
- </div>
+ </button>
);
})
)}
</div>
- <div {...stylex.props(styles.filterRow)}>
- <TextInput
- label={`Search ${label}`}
- isLabelHidden
- placeholder="Search..."
- value={query}
- size="lg"
- width="100%"
- hasClear
- onChange={next => {
- setQuery(next);
- onChangeQuery?.(next);
- }}
- xstyle={styles.filterInput}
- />
- <Button
- label="Done"
- variant="primary"
- size="lg"
- onClick={() => setActiveSheet('manage')}
- />
- </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('');
+ setActiveSheet(null);
+ }}
+ xstyle={styles.footerAction}
+ />
+ </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>
</BottomSheetSwitcher>