Skip to content

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

TypeScript

fix(MobileTokenizer): refine touch sheet editing flow (#8742)

rubyycheung0df41f1238d9
diff --git a/.changeset/mobile-tokenizer-keyboard-recovery.md b/.changeset/mobile-tokenizer-keyboard-recovery.md
new file mode 100644
index 0000000000..d697f7c1c5
--- /dev/null
+++ b/.changeset/mobile-tokenizer-keyboard-recovery.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Restore a Tall BottomSheet's internal position after keyboard dismissal.
+
+@rubyycheung
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index c84d240b92..49cf7dbbb3 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -1713,7 +1713,31 @@
},
"@astryx.tokenizer.done": {
"defaultMessage": "Done",
- "description": "Label of the primary footer button inside a Tokenizer's bottom sheet; pressing it closes the sheet. Selections are already applied, so this is not a confirm."
+ "description": "Label for immediate-apply Tokenizer bottom-sheet flows. Draft selection flows use tokenizer.save."
+ },
+ "@astryx.tokenizer.save": {
+ "defaultMessage": "Save",
+ "description": "Label of the primary footer button inside a Tokenizer's bottom sheet; pressing it commits the current selection draft and closes the sheet. Imperative verb; short."
+ },
+ "@astryx.tokenizer.selectionLimit": {
+ "defaultMessage": "Select up to {count, plural, one {# item} other {# items}}",
+ "description": "Tooltip on the disabled Save action when a Tokenizer selection draft exceeds a maxEntries limit that changed while the sheet was open. `{count}` is the current maximum."
+ },
+ "@astryx.tokenizer.discardChangesTitle": {
+ "defaultMessage": "Discard changes?",
+ "description": "Title of the confirmation dialog shown when someone tries to dismiss a Tokenizer bottom sheet after changing its selection draft. A question."
+ },
+ "@astryx.tokenizer.discardChangesDescription": {
+ "defaultMessage": "Your changes to {label} haven't been saved.",
+ "description": "Body of the dirty-dismiss confirmation inside a Tokenizer bottom sheet. `{label}` is the field label, e.g. `Your changes to Tags haven't been saved.`"
+ },
+ "@astryx.tokenizer.keepEditing": {
+ "defaultMessage": "Keep editing",
+ "description": "Label of the safe cancel action in the Tokenizer dirty-dismiss confirmation. It closes the confirmation and returns to the unchanged draft."
+ },
+ "@astryx.tokenizer.discardChanges": {
+ "defaultMessage": "Discard changes",
+ "description": "Label of the destructive action in the Tokenizer dirty-dismiss confirmation. It closes the sheet without committing its selection draft."
},
"@astryx.tokenizer.clearAllTitle": {
"defaultMessage": "Clear all selected items?",
diff --git a/packages/core/src/BottomSheet/BottomSheet.test.tsx b/packages/core/src/BottomSheet/BottomSheet.test.tsx
index 1a6ec95d24..e32c6994bc 100644
--- a/packages/core/src/BottomSheet/BottomSheet.test.tsx
+++ b/packages/core/src/BottomSheet/BottomSheet.test.tsx
@@ -2189,10 +2189,151 @@ describe('BottomSheet', () => {
expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
'0px',
);
+ expect(body.scrollTop).toBe(0);
expect(sheet.getBoundingClientRect()).toEqual(initialRect);
expect(sheet.style.height).toBe('');
});
+ it('restores a top field when interactive keyboard dismissal leaves only the accessory bar', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Search items"
+ height="tall">
+ <input aria-label="Search" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Search'});
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({top: 150 - body.scrollTop, bottom: 190 - body.scrollTop}),
+ );
+
+ input.focus();
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '348px',
+ );
+ expect(body.scrollTop).toBe(0);
+
+ // Safari can move the sheet body during the interactive dismissal. The
+ // main keyboard has gone, but its accessory bar still shortens the visual
+ // viewport, so this is recovery without a full-height viewport yet.
+ body.scrollTop = 300;
+ viewport.height = 720;
+ void act(() => viewport.dispatchEvent(new Event('resize')));
+
+ expect(body.scrollTop).toBe(0);
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '128px',
+ );
+
+ // Once that recovery step has been consumed, later layout work at the
+ // same visual-viewport height must not overwrite the person's scrolling.
+ body.scrollTop = 80;
+ void act(() => window.dispatchEvent(new Event('resize')));
+ // The ordinary safe-area pass may clamp scrolling just enough to keep
+ // the still-focused top field visible, but it must not reset to the old
+ // pre-keyboard position again.
+ expect(body.scrollTop).toBe(50);
+ });
+
+ it('re-reveals a later focused field after full keyboard recovery restores the opening scroll position', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Edit details"
+ height="tall">
+ <input aria-label="First" />
+ <input aria-label="Later" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const first = screen.getByRole('textbox', {name: 'First'});
+ const later = screen.getByRole('textbox', {name: 'Later'});
+ Object.defineProperty(body, 'scrollBy', {
+ configurable: true,
+ value: ({top = 0}: ScrollToOptions) => {
+ body.scrollTop += top;
+ },
+ });
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(first, 'getBoundingClientRect').mockImplementation(() =>
+ rect({top: 150 - body.scrollTop, bottom: 190 - body.scrollTop}),
+ );
+ vi.spyOn(later, 'getBoundingClientRect').mockImplementation(() =>
+ rect({top: 860 - body.scrollTop, bottom: 900 - body.scrollTop}),
+ );
+
+ first.focus();
+ expect(body.scrollTop).toBe(0);
+ later.focus();
+ expect(body.scrollTop).toBe(448);
+
+ viewport.height = 800;
+ void act(() => viewport.dispatchEvent(new Event('resize')));
+
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '0px',
+ );
+ // Cleanup restores 0, then the unobstructed safe-area pass reveals the
+ // still-focused later field at the bottom of the 100–800 body viewport.
+ expect(body.scrollTop).toBe(100);
+ });
+
+ it('retains the accommodated body scroll through partial viewport recovery while focus is leaving', () => {
+ const viewport = mockVisualViewport(500);
+ render(
+ <BottomSheet
+ isOpen
+ onOpenChange={() => {}}
+ label="Add a comment"
+ height="tall">
+ <input aria-label="Comment" />
+ </BottomSheet>,
+ );
+ const body = getBody();
+ const input = screen.getByRole('textbox', {name: 'Comment'});
+ Object.defineProperty(body, 'scrollBy', {
+ configurable: true,
+ value: ({top = 0}: ScrollToOptions) => {
+ body.scrollTop += top;
+ },
+ });
+ vi.spyOn(body, 'getBoundingClientRect').mockReturnValue(
+ rect({top: 100, bottom: 800}),
+ );
+ vi.spyOn(input, 'getBoundingClientRect').mockImplementation(() =>
+ rect({top: 660 - body.scrollTop, bottom: 700 - body.scrollTop}),
+ );
+
+ input.focus();
+ expect(body.scrollTop).toBe(248);
+ input.blur();
+ viewport.height = 720;
+ void act(() => viewport.dispatchEvent(new Event('resize')));
+
+ expect(body.scrollTop).toBe(248);
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '128px',
+ );
+
+ viewport.height = 800;
+ void act(() => viewport.dispatchEvent(new Event('resize')));
+ expect(body.scrollTop).toBe(0);
+ expect(body.style.getPropertyValue('--_sheet-keyboard-inset')).toBe(
+ '0px',
+ );
+ });
+
it('smoothly scrolls a focused Tall control above the keyboard', () => {
mockVisualViewport(500);
render(
diff --git a/packages/core/src/BottomSheet/useMobileKeyboard.ts b/packages/core/src/BottomSheet/useMobileKeyboard.ts
index a6f03cbcbb..90c73d3a82 100644
--- a/packages/core/src/BottomSheet/useMobileKeyboard.ts
+++ b/packages/core/src/BottomSheet/useMobileKeyboard.ts
@@ -175,12 +175,19 @@ export function useMobileKeyboard({
}
let keyboardGeometry: KeyboardGeometry | null = null;
+ let keyboardObstructionTop: number | null = null;
+ let bodyScrollTopAtKeyboard: number | null = null;
let documentScrollAtKeyboard: {x: number; y: number} | null = null;
const ownsFocusTransitions = isIOSWebKit();
const clearKeyboardLayout = () => {
body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, '0px');
+ if (bodyScrollTopAtKeyboard != null) {
+ body.scrollTop = bodyScrollTopAtKeyboard;
+ }
keyboardGeometry = null;
+ keyboardObstructionTop = null;
+ bodyScrollTopAtKeyboard = null;
documentScrollAtKeyboard = null;
hasKeyboardLayoutRef.current = false;
retainKeyboardLayoutRef.current = false;
@@ -292,13 +299,28 @@ export function useMobileKeyboard({
};
const revealFocusedControl = () => {
+ const obstructionTop = getObstructionTop();
const activeElement = document.activeElement;
- if (
- !isFullyExpandedRef.current ||
- !(activeElement instanceof HTMLElement) ||
- !body.contains(activeElement) ||
- !isTextEntryControl(activeElement)
- ) {
+ const focusedControl =
+ activeElement instanceof HTMLElement &&
+ body.contains(activeElement) &&
+ isTextEntryControl(activeElement)
+ ? activeElement
+ : null;
+ // The keyboard may close while the text field remains focused (for
+ // example, a downward keyboard dismissal gesture on iOS). Run the full
+ // cleanup path so the temporary spacer and the body scroll it enabled
+ // are both restored. Then reveal the still-focused control against the
+ // recovered sheet, because it may not be the field that opened the
+ // keyboard and therefore may sit outside the restored scroll position.
+ if (hasKeyboardLayoutRef.current && isVisualViewportRecovered()) {
+ clearKeyboardLayout();
+ if (isFullyExpandedRef.current && focusedControl) {
+ scrollControlIntoSafeArea(focusedControl, false);
+ }
+ return;
+ }
+ if (!isFullyExpandedRef.current || focusedControl == null) {
if (retainKeyboardLayoutRef.current && keyboardGeometry) {
applyKeyboardGeometry(keyboardGeometry);
return;
@@ -307,10 +329,25 @@ export function useMobileKeyboard({
return;
}
+ // An interactively dismissed iOS keyboard can leave the accessory bar
+ // visible, so the visual viewport grows without reaching full height.
+ // Restore the pre-keyboard body position as soon as that recovery starts;
+ // the ordinary safe-area pass below may still scroll a low focused field
+ // just enough for whatever obstruction remains. Advance the remembered
+ // obstruction so later content mutations do not repeat this recovery.
+ if (
+ hasKeyboardLayoutRef.current &&
+ keyboardObstructionTop != null &&
+ obstructionTop > keyboardObstructionTop + 0.5 &&
+ bodyScrollTopAtKeyboard != null
+ ) {
+ body.scrollTop = bodyScrollTopAtKeyboard;
+ keyboardObstructionTop = obstructionTop;
+ }
+
retainKeyboardLayoutRef.current = false;
const measuredBodyRect = body.getBoundingClientRect();
- const obstructionTop = getObstructionTop();
const overlap = Math.max(0, measuredBodyRect.bottom - obstructionTop);
// The extra clearance leaves room for mobile suggestion UI, but only
// while the visual viewport actually overlaps the sheet. With no
@@ -327,8 +364,12 @@ export function useMobileKeyboard({
// the position handleDocumentScroll returns to. Captured on the
// transition only — a reveal that runs after the browser has already
// scrolled would otherwise record the shifted position as correct.
- if (isPageScrollLocked && overlap > 0 && !hasKeyboardLayoutRef.current) {
- documentScrollAtKeyboard = {x: window.scrollX, y: window.scrollY};
+ if (overlap > 0 && !hasKeyboardLayoutRef.current) {
+ keyboardObstructionTop = obstructionTop;
+ bodyScrollTopAtKeyboard = body.scrollTop;
+ if (isPageScrollLocked) {
+ documentScrollAtKeyboard = {x: window.scrollX, y: window.scrollY};
+ }
}
hasKeyboardLayoutRef.current = overlap > 0;
@@ -338,7 +379,7 @@ export function useMobileKeyboard({
: 0;
body.style.setProperty(MOBILE_KEYBOARD_INSET_VAR, `${inset}px`);
- scrollControlIntoSafeArea(activeElement, overlap > 0);
+ scrollControlIntoSafeArea(focusedControl, overlap > 0);
};
let animationFrame = 0;
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
index ae7d229dcf..4e83290e8e 100644
--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
@@ -107,7 +107,7 @@ export const docs = {
],
usage: {
description:
- 'Lab prototype for trying the touch PowerSearch flow. Choose it explicitly on touch layouts (for example `const Search = isTouch ? MobilePowerSearch : PowerSearch`); it never switches on pointer type by itself. The whole field is one Manage filters trigger showing display-only tokens. Tapping it opens a tall Filters sheet listing each filter with its value in bold and a direct trailing remove action, an Add filter icon button at the top right, and sticky Clear all and Done actions. One-tap boolean filters use the same trailing remove action as every other removable filter. When there are no filters, the centered Add filter action stands alone; the duplicate header add and footer Done controls are hidden. Clear all asks for confirmation, removes editable filters without closing the sheet, and preserves read-only filters. Opening the rest of a row edits that filter with Cancel and Apply. Add filter opens directly when no filter exists and leaves search unfocused until the user chooses it; when the config names a content-search field it carries that search with inline suggestions. Creating a filter drills field → operator (radios, only when a field has more than one) → value. A value editor that is the sheet’s only section sits directly on the sheet surface; multiple sections use separate muted containers. The previous step remains open beneath the current standalone BottomSheet, so Escape, a scrim press, or a downward swipe dismisses the current sheet and reveals that retained step; the Add filter header stays action-free. the stack keeps one scrim and blocks covered sheets. Single-value choices use persistent radio indicators and multi-value choices use persistent checkbox indicators. Searchable string and entity lists and date calendars remain inline in the value sheet; date-only and date-range selections honor timezoneID, while date-time operators keep their date-and-time input. Announcements made while a sheet is open are delivered inside that dialog. Filters remain keyed by identity across controlled reorder, stale filters stay visible and removable, and controlled removals re-home focus. The scroll viewport reaches the sheet edge while padded inner content aligns with the fixed header. Fields whose only operators are nested are left out with a development warning.',
+ 'Lab prototype for trying the touch PowerSearch flow. Choose it explicitly on touch layouts (for example `const Search = isTouch ? MobilePowerSearch : PowerSearch`); it never switches on pointer type by itself. The whole field is one Manage filters trigger showing display-only tokens. Tapping it opens a tall Filters sheet listing each filter with its value in bold and a direct trailing remove action, an Add filter icon button at the top right, and sticky Clear all and Done actions. One-tap boolean filters use the same trailing remove action as every other removable filter. When there are no filters, the centered Add filter action stands alone; the duplicate header add and footer Done controls are hidden. Clear all asks for confirmation, removes editable filters without closing the sheet, and preserves read-only filters. Opening the rest of a row edits that filter with Cancel and Apply. Add filter opens directly when no filter exists and leaves search unfocused until the user chooses it; when the config names a content-search field it carries that search with inline suggestions. Creating a filter drills field → operator (radios, only when a field has more than one) → value. A value editor that is the sheet’s only section sits directly on the sheet surface; multiple sections use separate muted containers. The previous step remains open beneath the current standalone BottomSheet, so Escape, a scrim press, or a downward swipe dismisses the current sheet and reveals that retained step; the Add filter header stays action-free. the stack keeps one scrim and blocks covered sheets. Single-value choices use persistent radio indicators and multi-value choices use persistent checkbox indicators. Searchable string and entity lists and date calendars remain inline in the value sheet; date-only and date-range selections honor timezoneID, while date-time operators keep their date-and-time input. Announcements made while a sheet is open are delivered inside that dialog. Filters remain keyed by identity across controlled reorder, stale filters stay visible and removable, and controlled removals re-home focus. The scroll viewport reaches the sheet edge while padded inner content aligns with the fixed header. Dragging the results dismisses the search keyboard without clearing the query; filtering keeps search focused. Fields whose only operators are nested are left out with a development warning.',
bestPractices: [
{
guidance: true,
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
index de9f11d305..0e15df6675 100644
--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
@@ -1009,11 +1009,16 @@ describe('MobilePowerSearch Add filter', () => {
sheet().querySelectorAll<HTMLElement>('div'),
).find(element => getComputedStyle(element).overflowY === 'auto')!;
fireEvent.scroll(scrollBody);
+ expect(search).toHaveFocus();
+ fireEvent.touchStart(scrollBody, {touches: [{clientY: 100}]});
+ fireEvent.touchMove(scrollBody, {touches: [{clientY: 107}]});
+ expect(search).toHaveFocus();
+ fireEvent.touchMove(scrollBody, {touches: [{clientY: 109}]});
expect(search).not.toHaveFocus();
search.focus();
- fireEvent.touchMove(scrollBody);
- expect(search).not.toHaveFocus();
fireEvent.change(search, {target: {value: 'Field'}});
+ fireEvent.scroll(scrollBody);
+ expect(search).toHaveFocus();
expect(
within(sheet()).getAllByRole('button', {name: /^Field/}),
).toHaveLength(2);
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx
index 9b11636504..5dee70905e 100644
--- a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx
@@ -5,11 +5,8 @@
/**
* @file MobilePowerSearch.tsx
* @input Core PowerSearch config, filters and onChange (the same props as
- * @astryxdesign/core PowerSearch); public @astryxdesign/core components only
- * (BottomSheet, Button, Field, Heading, Icon, List,
- * RadioList, Text, TextInput, Token, Tooltip hooks, i18n, hooks —
- * useAnnounce for every announcement — utils, Layout container-padding
- * styles)
+ * @astryxdesign/core PowerSearch); public Core primitives and private Lab
+ * mobile-sheet confirmation and search-drag dismissal owners
* @output Exports MobilePowerSearch — Lab prototype of the touch PowerSearch
* flow: the whole field is one "Manage filters" trigger with display-only
* tokens, a Filters sheet with editable rows and direct remove actions, Add
@@ -93,7 +90,6 @@ import * as stylex from '@stylexjs/stylex';
import type {BaseProps} from '@astryxdesign/core';
import {BottomSheet} from '@astryxdesign/core/BottomSheet';
import {Button} from '@astryxdesign/core/Button';
-import {Dialog} from '@astryxdesign/core/Dialog';
import {EmptyState} from '@astryxdesign/core/EmptyState';
import {
Field,
@@ -107,7 +103,6 @@ import {
import {Heading} from '@astryxdesign/core/Heading';
import {Icon, renderIconSlot, type IconType} from '@astryxdesign/core/Icon';
import {IconButton} from '@astryxdesign/core/IconButton';
-import {Layout, LayoutContent, LayoutFooter} from '@astryxdesign/core/Layout';
import {containerPaddingInlineVarStyles} from '@astryxdesign/core/Layout/padding.stylex';
import {List, ListItem} from '@astryxdesign/core/List';
import {resolveOperatorLabel} from '@astryxdesign/core/PowerSearch';
@@ -126,7 +121,6 @@ import {formatFilterValue} from '@astryxdesign/core/PowerSearch/utils';
import type {InternalConfig} from '@astryxdesign/core/PowerSearch/utils';
import {RadioList, RadioListItem} from '@astryxdesign/core/RadioList';
import {useSize} from '@astryxdesign/core/SizeContext';
-import {Stack} from '@astryxdesign/core/Stack';
import {Text} from '@astryxdesign/core/Text';
import {TextInput} from '@astryxdesign/core/TextInput';
import {Token} from '@astryxdesign/core/Token';
@@ -148,6 +142,8 @@ import {
typographyVars,
} from '@astryxdesign/core/theme/tokens.stylex';
import {isImeKeyEvent, isRenderable, rtlStyles} from '@astryxdesign/core/utils';
+import {MobileSheetConfirmation} from '../internal/MobileSheetConfirmation';
+import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';
import {MobilePowerSearchValueEditor} from './MobilePowerSearchValueEditor';
import {
createContentSearchSource,
@@ -257,63 +253,6 @@ function PlusIcon(props: SVGProps<SVGSVGElement>) {
);
}
-function ClearFiltersConfirmation({
- isOpen,
- onOpenChange,
- onConfirm,
-}: {
- isOpen: boolean;
- onOpenChange: (isOpen: boolean) => void;
- onConfirm: () => void;
-}) {
- const titleId = useId();
- const descriptionId = useId();
- return (
- <Dialog
- isOpen={isOpen}
- onOpenChange={onOpenChange}
- purpose="info"
- role="alertdialog"
- aria-labelledby={titleId}
- aria-describedby={descriptionId}
- width={400}>
- <Layout
- content={
- <LayoutContent>
- <Heading level={2} id={titleId}>
- Clear all filters?
- </Heading>
- <Text type="body" color="secondary" id={descriptionId}>
- This removes all editable filters from this search.
- </Text>
- </LayoutContent>
- }
- footer={
- <LayoutFooter>
- <Stack direction="vertical" gap={4} hAlign="stretch">
- <Button
- label="Clear filters"
- variant="destructive"
- size="lg"
- onClick={onConfirm}
- xstyle={styles.confirmationAction}
- />
- <Button
- label="Keep filters"
- variant="secondary"
- size="lg"
- onClick={() => onOpenChange(false)}
- data-autofocus
- xstyle={styles.confirmationAction}
- />
- </Stack>
- </LayoutFooter>
- }
- />
- </Dialog>
- );
-}
-
const sizeStyles = stylex.create({
sm: {minHeight: sizeVars['--size-element-sm']},
md: {minHeight: sizeVars['--size-element-md']},
@@ -520,9 +459,6 @@ const styles = stylex.create({
trailingControlRow: {
flexDirection: 'row-reverse',
},
- confirmationAction: {
- width: '100%',
- },
rowValue: {
fontWeight: fontWeightVars['--font-weight-bold'],
},
@@ -953,14 +889,10 @@ export function MobilePowerSearch({
// ------------------------------------------------------------------ focus --
- const blurFieldPickerSearch = useCallback(() => {
- const activeElement = document.activeElement;
- const contentSearch = contentSearchRef.current?.querySelector('input');
- const fieldSearch = fieldSearchRef.current?.querySelector('input');
- if (activeElement === contentSearch || activeElement === fieldSearch) {
- (activeElement as HTMLInputElement).blur();
- }
- }, []);
+ const fieldPickerDragProps = useDismissSearchOnTouchDrag(() => [
+ contentSearchRef.current?.querySelector('input'),
+ fieldSearchRef.current?.querySelector('input'),
+ ]);
const focusPendingSheetTarget = useCallback(() => {
const target = pendingSheetFocusRef.current;
@@ -2132,10 +2064,7 @@ export function MobilePowerSearch({
</div>
) : null}
</div>
- <div
- {...scrollViewportProps}
- onScroll={blurFieldPickerSearch}
- onTouchMove={blurFieldPickerSearch}>
+ <div {...scrollViewportProps} {...fieldPickerDragProps}>
<div {...scrollContentProps}>
{hasContentSearch ? (
contentResults.length > 0 ? (
@@ -2427,10 +2356,14 @@ export function MobilePowerSearch({
</div>
</BottomSheet>
- <ClearFiltersConfirmation
+ <MobileSheetConfirmation
isOpen={isClearConfirmationOpen}
onOpenChange={setIsClearConfirmationOpen}
- onConfirm={() => {
+ title="Clear all filters?"
+ description="This removes all editable filters from this search."
+ actionLabel="Clear filters"
+ cancelLabel="Keep filters"
+ onAction={() => {
handleClearAll();
setIsClearConfirmationOpen(false);
}}
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
index eab19a5388..27a086b612 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.doc.mjs
@@ -11,7 +11,7 @@ export const docs = {
{name: 'isLabelHidden', type: 'boolean', description: 'Hide the visible label; the trigger and the sheet keep it as their accessible name.', default: 'false'},
{name: 'searchSource', type: 'SearchSource<T>', description: 'Core Typeahead search source (search + bootstrap).', required: true},
{name: 'value', type: 'T[]', description: 'Selected items (Core SearchableItem).', required: true},
- {name: 'onChange', type: '(items: T[], change: MobileTokenizerChange<T>) => void', description: 'Mirrors Core Tokenizer: single-item add/create/remove, or reorder.', required: true},
+ {name: 'onChange', type: '(items: T[], change: MobileTokenizerChange<T>) => void', description: 'Called by Save when the selection draft differs from the opening value. Receives the complete committed selection plus the latest add/create/remove metadata.', required: true},
{name: 'renderItem', type: '(item: T) => ReactNode', description: 'Custom content for a result row, shown beside its checkbox. Default: the item label.'},
{name: 'placeholder', type: 'string', description: 'Trigger text when nothing is selected.'},
{name: 'description', type: 'string', description: 'Help text under the field, read with the trigger.'},
@@ -24,14 +24,14 @@ export const docs = {
],
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. 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.',
+ 'Lab prototype for trying the touch Tokenizer flow: tap the field to open one searchable sheet where selected and available items share a full-row checkbox list. Selection changes remain in a draft until Save commits them; swipe, scrim, or Escape dismissal asks before discarding a dirty draft, while a clean dismissal closes directly. Selected items are grouped first when the sheet opens, while checkbox changes keep every existing row in place until the sheet closes; the latest selection is regrouped the next time it opens. Selected custom values stay in the list, and long result sets render progressively in 50-item batches. Custom text uses a trailing Add action. The bordered large search stays above the list, and scrolling or dragging results dismisses the software keyboard without clearing the query. Clear all and Save remain visible while searching. Clear all updates the draft only and requires confirmation; a confirmed clear returns focus to the search field and is announced inside the sheet. Every announcement — additions, removals, result counts — is delivered inside the open sheet. The trigger describes its committed selection to assistive technology (count, then the tokens) after the field description, status, and disabled reason. Strings come from the shared Astryx catalog.',
bestPractices: [
{guidance: true, description: 'Try this in Lab/canary to validate the flow; graduate via Core Tokenizer presentation="adaptive" when it ships.'},
{guidance: false, description: 'Do not ship stable product on this Lab API; it has no theming or spec contract yet.'},
],
anatomy: [
{name: 'Trigger field', required: true, description: 'Button showing tokens as a summary, in the inline Tokenizer field\'s own box: same border, radius, surface, block size and token inset as the desktop field.'},
- {name: 'Management sheet', required: true, description: 'One searchable list with trailing checkboxes for existing items, a trailing Add action for custom text, and 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.'},
+ {name: 'Management sheet', required: true, description: 'One searchable list with trailing checkboxes for existing items, a trailing Add action for custom text, and persistent equal-width Clear all and Save footer actions. Save commits the draft; dirty dismissal asks before discarding. Nothing of the sheet is in the page while it is closed.'},
],
},
};
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
index 029f79aec8..9fa9d6b47c 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.test.tsx
@@ -129,6 +129,200 @@ beforeEach(() => {
afterEach(() => vi.unstubAllGlobals());
describe('MobileTokenizer (Lab, single-sheet flow)', () => {
+ it('keeps the bordered large search and footer actions visible while searching, and dismisses the keyboard without clearing the query when results move', async () => {
+ render(<Harness />);
+ fireEvent.click(screen.getByRole('button', {name: /Tags/}));
+ const search = await screen.findByLabelText('Search Tags');
+ const list = await screen.findByTestId('mobile-tokenizer-list');
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+
+ expect(search.closest('.astryx-text-input')).toBeInTheDocument();
+ act(() => search.focus());
+ fireEvent.change(search, {target: {value: 'En'}});
+ await screen.findByRole('checkbox', {name: 'Eng'});
+ expect(screen.getByRole('button', {name: 'Clear all'})).toBeVisible();
+ expect(screen.getByRole('button', {name: 'Save'})).toBeVisible();
+
+ fireEvent.scroll(list);
+ expect(search).toHaveFocus();
+ expect(search).toHaveValue('En');
+
+ // Filtering a scrolled list can produce its own scroll event as the
+ // browser clamps scrollTop; typing must continue to own focus.
+ fireEvent.change(search, {target: {value: 'Eng'}});
+ fireEvent.scroll(list);
+ expect(search).toHaveFocus();
+ fireEvent.change(search, {target: {value: 'Engi'}});
+ expect(search).toHaveValue('Engi');
+ expect(search).toHaveFocus();
+
+ fireEvent.touchStart(list, {
+ touches: [{identifier: 1, target: list, clientY: 120}],
+ });
+ fireEvent.touchMove(list, {
+ touches: [{identifier: 1, target: list, clientY: 115}],
+ });
+ expect(search).toHaveFocus();
+ fireEvent.touchMove(list, {
+ touches: [{identifier: 1, target: list, clientY: 100}],
+ });
+ expect(search).not.toHaveFocus();
+ expect(search).toHaveValue('Engi');
+ });
+
+ it('guards dirty Escape, scrim, and swipe dismissal; keeps the draft after confirmation scrim or Keep editing; and discards only on request', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ fireEvent.click(trigger);
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ const energizer = await screen.findByRole('checkbox', {name: 'Energizer'});
+ fireEvent.click(energizer);
+ expect(energizer).toBeChecked();
+ expect(spy).not.toHaveBeenCalled();
+
+ fireEvent.keyDown(sheet, {key: 'Escape'});
+ let discard = await screen.findByRole('alertdialog', {
+ name: 'Discard changes?',
+ });
+ fireEvent.click(discard);
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ expect(energizer).toBeChecked();
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.click(sheet);
+ discard = await screen.findByRole('alertdialog', {
+ name: 'Discard changes?',
+ });
+ fireEvent.click(
+ within(discard).getByRole('button', {name: 'Keep editing'}),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ expect(energizer).toBeChecked();
+ expect(screen.getByLabelText('Search Tags')).toHaveFocus();
+
+ const handle = sheet.querySelector<HTMLElement>(
+ '.astryx-bottom-sheet > div[aria-hidden="true"]',
+ )!;
+ fireEvent.pointerDown(handle, {
+ pointerId: 1,
+ clientY: 0,
+ button: 0,
+ isPrimary: true,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerMove(handle, {
+ pointerId: 1,
+ clientY: 40,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerMove(handle, {
+ pointerId: 1,
+ clientY: 120,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerUp(handle, {
+ pointerId: 1,
+ clientY: 120,
+ pointerType: 'touch',
+ });
+ discard = await screen.findByRole('alertdialog', {
+ name: 'Discard changes?',
+ });
+ const actions = within(discard).getAllByRole('button');
+ expect(actions.map(action => action.textContent)).toEqual([
+ 'Discard changes',
+ 'Keep editing',
+ ]);
+ expect(actions[0]).toHaveAttribute('data-variant', 'destructive');
+ expect(actions[1]).toHaveAttribute('data-variant', 'secondary');
+ fireEvent.click(actions[0]);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('forced disabled closure also closes a dirty-discard confirmation', async () => {
+ const spy = vi.fn();
+ const props = {
+ label: 'Tags',
+ searchSource: source,
+ value: [ITEMS[0]],
+ debounceMs: 0,
+ onChange: spy,
+ };
+ const {rerender} = render(<MobileTokenizer {...props} />);
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ fireEvent.click(trigger);
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ fireEvent.click(await screen.findByRole('checkbox', {name: 'Energizer'}));
+ fireEvent.keyDown(sheet, {key: 'Escape'});
+ expect(
+ await screen.findByRole('alertdialog', {name: 'Discard changes?'}),
+ ).toBeInTheDocument();
+
+ rerender(<MobileTokenizer {...props} isDisabled />);
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ await waitFor(() =>
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument(),
+ );
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('blocks Save if maxEntries drops below the current draft until the draft returns within the limit', async () => {
+ const spy = vi.fn();
+ const props = {
+ label: 'Tags',
+ searchSource: source,
+ value: [] as SearchableItem[],
+ debounceMs: 0,
+ onChange: spy,
+ };
+ const {rerender} = render(<MobileTokenizer {...props} maxEntries={2} />);
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ fireEvent.click(trigger);
+ const design = await screen.findByRole('checkbox', {name: 'Design'});
+ const eng = await screen.findByRole('checkbox', {name: 'Eng'});
+ fireEvent.click(design);
+ fireEvent.click(eng);
+
+ rerender(<MobileTokenizer {...props} maxEntries={1} />);
+ const save = screen.getByRole('button', {name: 'Save'});
+ expect(save).toHaveAttribute('aria-disabled', 'true');
+ expect(save).toHaveAccessibleDescription('Select up to 1 item');
+ fireEvent.click(save);
+ expect(trigger).toHaveAttribute('aria-expanded', 'true');
+ expect(spy).not.toHaveBeenCalled();
+
+ fireEvent.click(eng);
+ expect(save).not.toHaveAttribute('aria-disabled');
+ fireEvent.click(save);
+ expect(spy).toHaveBeenCalledWith(
+ [ITEMS[0]],
+ expect.objectContaining({item: ITEMS[0], type: 'add'}),
+ );
+ });
+
+ it('closes directly when edits return the draft to its opening selection', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ fireEvent.click(trigger);
+ const sheet = await screen.findByRole('dialog', {name: 'Tags'});
+ const energizer = await screen.findByRole('checkbox', {name: 'Energizer'});
+ fireEvent.click(energizer);
+ fireEvent.click(energizer);
+
+ fireEvent.keyDown(sheet, {key: 'Escape'});
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
+ expect(trigger).toHaveAttribute('aria-expanded', 'false');
+ expect(spy).not.toHaveBeenCalled();
+ });
+
it('keeps rows stable while open and applies selected-first order on reopen', async () => {
const spy = vi.fn();
render(<Harness spy={spy} />);
@@ -160,10 +354,7 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
expect(design.lastElementChild).toHaveAttribute('data-size', 'md');
fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
- expect(spy).toHaveBeenCalledWith(
- [ITEMS[0], ITEMS[1], ITEMS[3]],
- expect.objectContaining({type: 'add'}),
- );
+ expect(spy).not.toHaveBeenCalled();
await waitFor(() =>
expect(screen.getByRole('checkbox', {name: 'Energizer'})).toBeChecked(),
);
@@ -175,10 +366,7 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
]);
fireEvent.click(screen.getByRole('checkbox', {name: 'Eng'}));
- expect(spy).toHaveBeenLastCalledWith(
- [ITEMS[0], ITEMS[3]],
- expect.objectContaining({type: 'remove'}),
- );
+ expect(spy).not.toHaveBeenCalled();
expect(checkboxLabels()).toEqual([
'Design',
'Eng',
@@ -186,7 +374,11 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
'Energizer',
]);
- fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ expect(spy).toHaveBeenCalledWith(
+ [ITEMS[0], ITEMS[3]],
+ expect.objectContaining({item: ITEMS[1], type: 'remove'}),
+ );
expect(trigger).toHaveAttribute('aria-expanded', 'false');
await act(async () => {
@@ -200,6 +392,38 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
]);
});
+ it('reports the net changed item when draft actions cancel each other', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ const trigger = screen.getByRole('button', {name: /Tags/});
+ fireEvent.click(trigger);
+ await screen.findByRole('checkbox', {name: 'Energizer'});
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Energizer'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith([ITEMS[1]], {
+ item: ITEMS[0],
+ type: 'remove',
+ });
+ });
+
+ it('does not commit a selection toggled back to its opening value', async () => {
+ const spy = vi.fn();
+ render(<Harness spy={spy} />);
+ fireEvent.click(screen.getByRole('button', {name: /Tags/}));
+ await screen.findByRole('checkbox', {name: 'Design'});
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+
+ expect(spy).not.toHaveBeenCalled();
+ });
+
it('creates a custom entry with a trailing Add action', async () => {
const spy = vi.fn();
render(<CreateHarness spy={spy} />);
@@ -212,12 +436,8 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
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(screen.getByRole('button', {name: 'Clear all'})).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Save'})).toBeInTheDocument();
expect(create).toHaveAttribute('data-size', 'lg');
expect(screen.getByTestId('mobile-tokenizer-create-row')).toHaveTextContent(
'Create "Custom"',
@@ -225,14 +445,18 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
await act(async () => {
fireEvent.click(create);
});
+ expect(spy).not.toHaveBeenCalled();
+ expect(trigger).not.toHaveTextContent('Custom');
+ expect(search).toHaveValue('');
+ const custom = await screen.findByRole('checkbox', {name: 'Custom'});
+ expect(custom).toBeChecked();
+
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
expect(spy).toHaveBeenCalledWith(
[{id: 'Custom', label: 'Custom'}],
expect.objectContaining({type: 'create'}),
);
await waitFor(() => expect(trigger).toHaveTextContent('Custom'));
- expect(search).toHaveValue('');
- const custom = await screen.findByRole('checkbox', {name: 'Custom'});
- expect(custom).toBeChecked();
});
it('renders long lists in 50-item batches and resets the window for search', async () => {
@@ -325,30 +549,49 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
);
});
- it('keeps large equal-width Clear all and Done footer actions while guarding the bulk clear', async () => {
+ it('keeps large equal-width Clear all and Save footer actions while guarding the bulk clear', async () => {
const spy = vi.fn();
render(<Harness spy={spy} />);
fireEvent.click(screen.getByRole('button', {name: /Tags/}));
const list = await screen.findByTestId('mobile-tokenizer-list');
const clearAll = screen.getByRole('button', {name: 'Clear all'});
- const done = screen.getByRole('button', {name: 'Done'});
+ const save = screen.getByRole('button', {name: 'Save'});
expect(clearAll).toHaveAttribute('data-size', 'lg');
expect(clearAll).toHaveAttribute('data-variant', 'secondary');
- expect(done).toHaveAttribute('data-size', 'lg');
+ expect(save).toHaveAttribute('data-size', 'lg');
expect(list.compareDocumentPosition(clearAll)).toBe(
Node.DOCUMENT_POSITION_FOLLOWING,
);
- expect(list.compareDocumentPosition(done)).toBe(
+ expect(list.compareDocumentPosition(save)).toBe(
Node.DOCUMENT_POSITION_FOLLOWING,
);
fireEvent.click(clearAll);
const confirmation = screen.getByRole('alertdialog');
+ expect(confirmation).toHaveClass('astryx-alert-dialog');
expect(confirmation).toHaveTextContent('Clear all selected items?');
+ const confirmationActions = within(confirmation).getAllByRole('button');
+ expect(confirmationActions.map(action => action.textContent)).toEqual([
+ 'Clear selection',
+ 'Cancel',
+ ]);
+ expect(confirmationActions[0]).toHaveAttribute(
+ 'data-variant',
+ 'destructive',
+ );
+ expect(confirmationActions[1]).toHaveAttribute('data-variant', 'secondary');
expect(spy).not.toHaveBeenCalled();
fireEvent.click(
within(confirmation).getByRole('button', {name: 'Clear selection'}),
);
+ expect(spy).not.toHaveBeenCalled();
+ await waitFor(() =>
+ expect(screen.getByRole('button', {name: 'Clear all'})).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ ),
+ );
+ fireEvent.click(save);
expect(spy).toHaveBeenLastCalledWith(
[],
expect.objectContaining({type: 'remove'}),
@@ -441,6 +684,17 @@ describe('MobileTokenizer (Lab, single-sheet flow)', () => {
for (const name of indicatorClasses) {
expect(indicator).toHaveClass(name);
}
+
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Design'}));
+ expect(row).not.toHaveAttribute('aria-disabled');
+ fireEvent.click(row);
+ expect(row).toBeChecked();
+ expect(spy).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ expect(spy).toHaveBeenCalledWith(
+ [ITEMS[3]],
+ expect.objectContaining({item: ITEMS[3], type: 'add'}),
+ );
});
it('paints the placeholder of a disabled empty trigger GrayText in forced colors (AST-085 FR6)', () => {
@@ -569,7 +823,7 @@ describe('MobileTokenizer Core-sheet parity', () => {
expect(screen.queryByLabelText('Search Tags')).toBeNull();
const sheet = await openSheet();
expect(sheet).toHaveAttribute('open');
- fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
// Closed but retained for its exit; the trigger's focus (BottomSheet's
// hand-back after the exit) releases it.
const trigger = screen.getByRole('button', {name: /Tags/});
@@ -798,7 +1052,7 @@ describe('MobileTokenizer Core-sheet parity', () => {
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'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
act(() => trigger.focus());
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(sheet).not.toBeInTheDocument();
@@ -832,9 +1086,9 @@ describe('MobileTokenizer Core-sheet parity', () => {
await screen.findByRole('checkbox', {name: 'Design'});
expect(trigger).not.toHaveFocus();
expect(events).toEqual([]);
- // Done: BottomSheet hands focus to the trigger. The trigger never had
+ // Save: BottomSheet hands focus to the trigger. The trigger never had
// focus, so this is the entry.
- fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
act(() => trigger.focus());
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(events).toEqual(['focus']);
@@ -846,7 +1100,7 @@ describe('MobileTokenizer Core-sheet parity', () => {
act(() => trigger.focus());
fireEvent.click(trigger);
await screen.findByRole('dialog');
- fireEvent.click(screen.getByRole('button', {name: 'Done'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
act(() => trigger.focus());
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
act(() => screen.getByRole('button', {name: 'Elsewhere'}).focus());
@@ -1034,10 +1288,7 @@ describe('MobileTokenizer Core-sheet parity', () => {
fireEvent.click(
within(confirmation).getByRole('button', {name: 'Clear selection'}),
);
- expect(spy).toHaveBeenCalledWith(
- [],
- expect.objectContaining({type: 'remove'}),
- );
+ expect(spy).not.toHaveBeenCalled();
await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
expect(screen.getByLabelText('Search Tags')).toHaveFocus();
await waitFor(() => expect(liveText(sheet)).toBe('All items removed'));
@@ -1048,6 +1299,11 @@ describe('MobileTokenizer Core-sheet parity', () => {
expect(spent).toHaveAccessibleDescription('Nothing selected');
fireEvent.click(spent);
expect(screen.queryByRole('alertdialog')).toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Save'}));
+ expect(spy).toHaveBeenCalledWith(
+ [],
+ expect.objectContaining({type: 'remove'}),
+ );
});
it('announces each toggle and the result count from inside the dialog (AR6, AST-086 FR14)', async () => {
diff --git a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
index 0eb21faab4..9c94a56100 100644
--- a/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
+++ b/packages/lab/src/MobileTokenizer/MobileTokenizer.tsx
@@ -4,13 +4,12 @@
/**
* @file MobileTokenizer.tsx
- * @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)
+ * @input Public @astryxdesign/core components and hooks, plus private Lab
+ * mobile-sheet confirmation and search-drag dismissal owners
* @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
+ * flow with the inline-compatible closed trigger, a searchable draft-selection
+ * sheet, persistent Clear all / Save footer, dirty-dismiss confirmation,
+ * stable checkbox ordering, and progressive long-list rendering
* @position Lab (canary) stack layer 1: the touch sheet's user-experience
* pass happens here; Core's sheet presentation (`component:Tokenizer`
* DEC-3, FR16–FR24, AR6) is implemented but not exposed. The behaviors
@@ -29,7 +28,11 @@
* API mirrors Core Tokenizer (label/isLabelHidden/searchSource/value/onChange/
* change, renderItem, hasCreate, maxEntries) so graduation is an import swap.
* Lab deltas: the filter is a bordered TextInput (Core's PanelSearchInput is
- * not exported), and there is no theming/spec contract yet.
+ * not exported); row, Create, and Clear all changes stay in one draft until
+ * Save; the footer stays visible while searching; dirty dismissal asks before
+ * discarding; and directly dragging results blurs the search so the mobile
+ * keyboard leaves without clearing the query. There is no theming/spec contract
+ * yet.
*/
import type React from 'react';
@@ -47,7 +50,6 @@ import {
} 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 {Button} from '@astryxdesign/core/Button';
import {EmptyState} from '@astryxdesign/core/EmptyState';
@@ -70,6 +72,8 @@ import {
sizeVars,
spacingVars,
} from '@astryxdesign/core/theme/tokens.stylex';
+import {MobileSheetConfirmation} from '../internal/MobileSheetConfirmation';
+import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';
export type MobileTokenizerChange<T extends SearchableItem> =
| {item: T; type: 'add'}
@@ -126,6 +130,18 @@ const LIST_LOAD_MORE_THRESHOLD_PX = 200;
// border = 3px. The same number is the row gap, so wrapped rows read evenly.
const TOKEN_ROW_INSET = `calc(${spacingVars['--spacing-1']} - 1px)`;
+type SheetDraftChange<T> = {
+ item: T;
+ type: 'add' | 'create' | 'remove';
+};
+
+function hasSameSelection<T extends SearchableItem>(a: T[], b: T[]): boolean {
+ return (
+ a.length === b.length &&
+ a.every(item => b.some(candidate => candidate.id === item.id))
+ );
+}
+
const styles = stylex.create({
// The closed trigger is the inline Tokenizer field's own control box, as a
// button — the same `inputWrapperStyles.base` box Core's sheet trigger
@@ -366,15 +382,9 @@ export function MobileTokenizer<T extends SearchableItem>({
},
[onChangeQuery],
);
- const selectedIds = useMemo(() => new Set(value.map(v => v.id)), [value]);
- const isAtMax = maxEntries != null && value.length >= maxEntries;
-
// 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.
+ // reopen it when re-enabled (FR17). A forced close bypasses the dirty-draft
+ // prompt, keeps the query, and discards the in-sheet draft on the next open.
const [wasDisabled, setWasDisabled] = useState(isDisabled);
const [keepsSheetWhileDisabled, setKeepsSheetWhileDisabled] = useState(false);
if (isDisabled !== wasDisabled) {
@@ -388,49 +398,14 @@ export function MobileTokenizer<T extends SearchableItem>({
}
}
- const handleAdd = useCallback(
- (item: T): boolean => {
- if (isDisabled || isAtMax || selectedIds.has(item.id)) {
- return false;
+ const handleSheetCommit = useCallback(
+ (items: T[], change: SheetDraftChange<T>) => {
+ if (!isDisabled) {
+ onChange(items, change);
}
- 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],
+ [isDisabled, onChange],
);
- const handleRemove = useCallback(
- (item: T): boolean => {
- if (isDisabled) {
- return false;
- }
- 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([], {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
@@ -606,17 +581,14 @@ export function MobileTokenizer<T extends SearchableItem>({
label={label}
searchSource={searchSource}
value={value}
- selectedIds={selectedIds}
- isAtMax={isAtMax}
+ maxEntries={maxEntries}
hasCreate={hasCreate}
maxMenuItems={maxMenuItems}
minQueryLength={minQueryLength}
debounceMs={debounceMs}
emptySearchResultsText={emptySearchResultsText}
renderItem={renderItem}
- onAdd={handleAdd}
- onRemove={handleRemove}
- onClearAll={handleClearAll}
+ onCommit={handleSheetCommit}
onChangeQuery={handleSheetQueryChange}
/>
)}
@@ -635,23 +607,20 @@ interface MobileTokenizerSheetProps<T extends SearchableItem> {
label: string;
searchSource: SearchSource<T>;
value: T[];
- selectedIds: Set<string>;
- isAtMax: boolean;
+ maxEntries?: number;
hasCreate: boolean;
maxMenuItems: number;
minQueryLength: number;
debounceMs: number;
emptySearchResultsText?: string;
renderItem?: (item: T) => ReactNode;
- onAdd: (item: T) => boolean;
- onRemove: (item: T) => boolean;
- onClearAll: () => void;
+ onCommit: (items: T[], change: SheetDraftChange<T>) => void;
onChangeQuery: (query: string) => void;
}
/**
* The sheet: BottomSheet around the content. The content owns the query; a
- * close the person makes (Done, swipe, scrim, Escape) clears it through a
+ * close the person makes (Save, swipe, scrim, Escape) clears it through a
* handle from the closing event, so a close the field forces (becoming
* disabled) keeps it (FR18).
*/
@@ -663,7 +632,8 @@ function MobileTokenizerSheet<T extends SearchableItem>({
...content
}: MobileTokenizerSheetProps<T>) {
const clearQueryRef = useRef<(() => void) | null>(null);
- const requestClose = () => {
+ const requestDismissRef = useRef<(() => void) | null>(null);
+ const closeSheet = () => {
clearQueryRef.current?.();
onOpenChange(false);
};
@@ -673,8 +643,10 @@ function MobileTokenizerSheet<T extends SearchableItem>({
onOpenChange={next => {
if (next) {
onOpenChange(true);
+ } else if (requestDismissRef.current != null) {
+ requestDismissRef.current();
} else {
- requestClose();
+ closeSheet();
}
}}
finalFocusRef={finalFocusRef}
@@ -686,7 +658,8 @@ function MobileTokenizerSheet<T extends SearchableItem>({
isOpen={isOpen}
label={label}
clearQueryRef={clearQueryRef}
- onRequestClose={requestClose}
+ requestDismissRef={requestDismissRef}
+ onCloseSheet={closeSheet}
/>
</BottomSheet>
);
@@ -697,7 +670,8 @@ type MobileTokenizerSheetContentProps<T extends SearchableItem> = Omit<
'onOpenChange' | 'finalFocusRef'
> & {
clearQueryRef: RefObject<(() => void) | null>;
- onRequestClose: () => void;
+ requestDismissRef: RefObject<(() => void) | null>;
+ onCloseSheet: () => void;
};
/**
@@ -708,21 +682,19 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
isOpen,
initialQuery,
clearQueryRef,
- onRequestClose,
+ requestDismissRef,
+ onCloseSheet,
label,
searchSource,
value,
- selectedIds,
- isAtMax,
+ maxEntries,
hasCreate,
maxMenuItems,
minQueryLength,
debounceMs,
emptySearchResultsText,
renderItem,
- onAdd,
- onRemove,
- onClearAll,
+ onCommit,
onChangeQuery,
}: MobileTokenizerSheetContentProps<T>) {
const t = useTranslator();
@@ -730,6 +702,24 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
const searchRef = useRef<HTMLInputElement>(null);
const clearAllRef = useRef<HTMLButtonElement>(null);
+ // One open sheet owns one selection draft. The caller's controlled value is
+ // unchanged until Save, so a cancelled dismissal can discard cleanly.
+ const [valueAtOpen, setValueAtOpen] = useState<T[]>(() => [...value]);
+ const [draftValue, setDraftValue] = useState<T[]>(() => [...value]);
+ const lastDraftChangeRef = useRef<SheetDraftChange<T> | null>(null);
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
+ const [isDiscardConfirmationOpen, setIsDiscardConfirmationOpen] =
+ useState(false);
+ const afterConfirmationRef = useRef<'search' | 'clear-all' | null>(null);
+ const shouldRestoreDraftFocusRef = useRef(false);
+ const isDraftDirty = !hasSameSelection(valueAtOpen, draftValue);
+ const selectedIds = useMemo(
+ () => new Set(draftValue.map(item => item.id)),
+ [draftValue],
+ );
+ const isAtMax = maxEntries != null && draftValue.length >= maxEntries;
+ const isDraftOverMax = maxEntries != null && draftValue.length > maxEntries;
+
// ---- query and search ----
const [query, setQuery] = useState(initialQuery);
const trimmedQuery = query.trim();
@@ -838,7 +828,11 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
if (isOpen !== wasOpen) {
setWasOpen(isOpen);
if (isOpen) {
- setSelectedItemsAtOpen(value);
+ const snapshot = [...value];
+ setValueAtOpen(snapshot);
+ setDraftValue(snapshot);
+ lastDraftChangeRef.current = null;
+ setSelectedItemsAtOpen(snapshot);
resetListWindow();
// An open lists the bootstrap set, or searches a query kept across a
// forced close (FR18); a kept query below the threshold leaves nothing
@@ -851,6 +845,12 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
} else {
announcedSearchIdRef.current = searchIdRef.current;
}
+ } else {
+ // Close both confirmations in the same render that closes the sheet.
+ afterConfirmationRef.current = null;
+ shouldRestoreDraftFocusRef.current = false;
+ setIsClearConfirmationOpen(false);
+ setIsDiscardConfirmationOpen(false);
}
}
const handleQueryChange = (next: string) => {
@@ -890,7 +890,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
selectedAtOpenMatches.map(item => item.id),
);
const resultIds = new Set(results.map(item => item.id));
- const selectedItemsMissingFromResults = value.filter(
+ const selectedItemsMissingFromResults = draftValue.filter(
item =>
!selectedAtOpenIds.has(item.id) &&
!resultIds.has(item.id) &&
@@ -901,7 +901,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
...selectedItemsMissingFromResults,
...results.filter(item => !selectedAtOpenIds.has(item.id)),
];
- }, [trimmedQuery, results, selectedItemsAtOpen, value]);
+ }, [trimmedQuery, results, selectedItemsAtOpen, draftValue]);
const renderedItems = visibleItems.slice(0, renderedItemCount);
const createItem = useMemo<T | null>(() => {
@@ -911,7 +911,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
const lower = trimmedQuery.toLowerCase();
if (
selectedIds.has(trimmedQuery) ||
- value.some(item => item.label.toLowerCase() === lower) ||
+ draftValue.some(item => item.label.toLowerCase() === lower) ||
results.some(r => r.label.toLowerCase() === lower)
) {
return null;
@@ -920,7 +920,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
id: `${CREATABLE_ID_PREFIX}${trimmedQuery}`,
label: t('@astryx.tokenizer.create', {value: trimmedQuery}),
} as unknown as T;
- }, [hasCreate, trimmedQuery, results, selectedIds, isAtMax, value, t]);
+ }, [hasCreate, trimmedQuery, results, selectedIds, isAtMax, draftValue, t]);
const isQueryEmpty = trimmedQuery === '';
// An empty state is a searched query's answer. An empty query that lists
@@ -965,21 +965,30 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
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);
+ // ---- confirmations and dismissal ----
+ const closeDiscardConfirmation = () => {
+ shouldRestoreDraftFocusRef.current = true;
+ setIsDiscardConfirmationOpen(false);
+ };
+ // Synchronize DOM focus with the closed discard dialog. Dialog restores focus
+ // in its own close Effect, so focus the search only after that dialog closes.
+ useEffect(() => {
+ if (
+ isDiscardConfirmationOpen ||
+ !shouldRestoreDraftFocusRef.current ||
+ !isOpen
+ ) {
+ return;
+ }
+ shouldRestoreDraftFocusRef.current = false;
+ searchRef.current?.focus({preventScroll: true});
+ }, [isDiscardConfirmationOpen, isOpen]);
const closeClearConfirmation = (confirmed: boolean) => {
afterConfirmationRef.current = confirmed ? 'search' : 'clear-all';
setIsClearConfirmationOpen(false);
};
+ // Synchronize DOM focus and the live-region announcement after the clear
+ // dialog closes, once Dialog's own close Effect has restored focus.
useEffect(() => {
if (isClearConfirmationOpen || afterConfirmationRef.current == null) {
return;
@@ -993,10 +1002,63 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
clearAllRef.current?.focus();
}
}, [announce, isClearConfirmationOpen, t]);
+ useImperativeHandle(
+ requestDismissRef,
+ () => () => {
+ if (isDraftDirty) {
+ setIsDiscardConfirmationOpen(true);
+ } else {
+ onCloseSheet();
+ }
+ },
+ [isDraftDirty, onCloseSheet],
+ );
+
+ const handleSave = () => {
+ if (isDraftOverMax) {
+ return;
+ }
+ if (isDraftDirty) {
+ const added = draftValue.find(
+ item => !valueAtOpen.some(openItem => openItem.id === item.id),
+ );
+ const removed = valueAtOpen.find(
+ item => !draftValue.some(draftItem => draftItem.id === item.id),
+ );
+ const lastDraftChange = lastDraftChangeRef.current;
+ const lastChangeIsNet =
+ lastDraftChange != null &&
+ (lastDraftChange.type === 'remove'
+ ? valueAtOpen.some(item => item.id === lastDraftChange.item.id) &&
+ !draftValue.some(item => item.id === lastDraftChange.item.id)
+ : draftValue.some(item => item.id === lastDraftChange.item.id) &&
+ !valueAtOpen.some(item => item.id === lastDraftChange.item.id));
+ let change: SheetDraftChange<T> | null = null;
+ if (lastChangeIsNet) {
+ change = lastDraftChange;
+ } else if (lastDraftChange?.type === 'remove' && removed != null) {
+ change = {item: removed, type: 'remove'};
+ } else if (added != null) {
+ const type: SheetDraftChange<T>['type'] =
+ lastDraftChange?.item.id === added.id &&
+ lastDraftChange.type === 'create'
+ ? 'create'
+ : 'add';
+ change = {item: added, type};
+ } else if (removed != null) {
+ change = {item: removed, type: 'remove'};
+ }
+ if (change != null) {
+ onCommit([...draftValue], change);
+ }
+ }
+ onCloseSheet();
+ };
const searchLabel = t('@astryx.tokenizer.search', {label});
const noResultsTitle =
emptySearchResultsText ?? t('@astryx.typeahead.emptySearchResults');
+ const listDragProps = useDismissSearchOnTouchDrag(() => [searchRef.current]);
return (
<div {...stylex.props(styles.sheetBody)}>
@@ -1045,6 +1107,7 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
data-testid="mobile-tokenizer-list"
data-rendered-count={renderedItems.length}
data-total-count={visibleItems.length}
+ {...listDragProps}
onScroll={event => {
const list = event.currentTarget;
const distanceFromBottom =
@@ -1074,12 +1137,21 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
variant="secondary"
size="lg"
onClick={() => {
- if (onAdd(createItem)) {
- announce(
- t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),
- );
- }
+ const item: SearchableItem = {
+ id: trimmedQuery,
+ label: trimmedQuery,
+ };
+ const createdItem = item as T;
+ setDraftValue(current => [...current, createdItem]);
+ lastDraftChangeRef.current = {
+ item: createdItem,
+ type: 'create',
+ };
+ announce(
+ t('@astryx.tokenizer.tokenAdded', {label: trimmedQuery}),
+ );
handleQueryChange('');
+ searchRef.current?.focus();
}}
/>
</div>
@@ -1100,14 +1172,16 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
return;
}
if (isSelected) {
- if (onRemove(item)) {
- announce(
- t('@astryx.tokenizer.tokenRemoved', {
- label: item.label,
- }),
- );
- }
- } else if (onAdd(item)) {
+ setDraftValue(current =>
+ current.filter(selected => selected.id !== item.id),
+ );
+ lastDraftChangeRef.current = {item, type: 'remove'};
+ announce(
+ t('@astryx.tokenizer.tokenRemoved', {label: item.label}),
+ );
+ } else {
+ setDraftValue(current => [...current, item]);
+ lastDraftChangeRef.current = {item, type: 'add'};
announce(
t('@astryx.tokenizer.tokenAdded', {label: item.label}),
);
@@ -1139,37 +1213,39 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
})}
</div>
)}
- {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>
- )}
+ <div {...stylex.props(styles.footer)}>
+ <Button
+ ref={clearAllRef}
+ label={t('@astryx.tokenizer.clearAll')}
+ variant="secondary"
+ size="lg"
+ isDisabled={draftValue.length === 0}
+ tooltip={
+ draftValue.length === 0
+ ? t('@astryx.tokenizer.nothingToClear')
+ : undefined
+ }
+ onClick={() => setIsClearConfirmationOpen(true)}
+ xstyle={styles.footerAction}
+ />
+ <Button
+ label={t('@astryx.tokenizer.save')}
+ variant="primary"
+ size="lg"
+ isDisabled={isDraftOverMax}
+ tooltip={
+ isDraftOverMax
+ ? t('@astryx.tokenizer.selectionLimit', {
+ count: maxEntries ?? 0,
+ })
+ : undefined
+ }
+ onClick={handleSave}
+ xstyle={styles.footerAction}
+ />
+ </div>
{isClearConfirmationOpen && (
- <AlertDialog
+ <MobileSheetConfirmation
isOpen
onOpenChange={next => {
if (!next) {
@@ -1178,13 +1254,42 @@ function MobileTokenizerSheetContent<T extends SearchableItem>({
}}
title={t('@astryx.tokenizer.clearAllTitle')}
description={t('@astryx.tokenizer.clearAllDescription', {label})}
+ cancelLabel={t('@astryx.alertDialog.cancel')}
actionLabel={t('@astryx.tokenizer.clearSelection')}
onAction={() => {
- onClearAll();
+ const lastItem = draftValue[draftValue.length - 1];
+ if (lastItem != null) {
+ setDraftValue([]);
+ lastDraftChangeRef.current = {
+ item: lastItem,
+ type: 'remove',
+ };
+ }
closeClearConfirmation(true);
}}
/>
)}
+ {isDiscardConfirmationOpen && (
+ <MobileSheetConfirmation
+ isOpen
+ onOpenChange={next => {
+ if (!next) {
+ closeDiscardConfirmation();
+ }
+ }}
+ title={t('@astryx.tokenizer.discardChangesTitle')}
+ description={t('@astryx.tokenizer.discardChangesDescription', {
+ label,
+ })}
+ cancelLabel={t('@astryx.tokenizer.keepEditing')}
+ actionLabel={t('@astryx.tokenizer.discardChanges')}
+ onAction={() => {
+ shouldRestoreDraftFocusRef.current = false;
+ setIsDiscardConfirmationOpen(false);
+ onCloseSheet();
+ }}
+ />
+ )}
</div>
);
}
diff --git a/packages/lab/src/internal/MobileSheetConfirmation.test.tsx b/packages/lab/src/internal/MobileSheetConfirmation.test.tsx
new file mode 100644
index 0000000000..1e9534e26b
--- /dev/null
+++ b/packages/lab/src/internal/MobileSheetConfirmation.test.tsx
@@ -0,0 +1,68 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {fireEvent, render, screen, within} from '@testing-library/react';
+import {beforeEach, describe, expect, it, vi} from 'vitest';
+import {MobileSheetConfirmation} from './MobileSheetConfirmation';
+
+// jsdom has no native modal presentation; keep the public Dialog path active.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ window.scrollTo = vi.fn();
+});
+
+function setup() {
+ const onAction = vi.fn();
+ const onOpenChange = vi.fn();
+ render(
+ <MobileSheetConfirmation
+ isOpen
+ onOpenChange={onOpenChange}
+ title="Discard changes?"
+ description="The draft will be removed."
+ actionLabel="Discard"
+ cancelLabel="Keep editing"
+ onAction={onAction}
+ />,
+ );
+ const dialog = screen.getByRole('alertdialog', {name: 'Discard changes?'});
+ return {dialog, onAction, onOpenChange};
+}
+
+describe('MobileSheetConfirmation', () => {
+ it('keeps the alert-dialog theme target and accessible copy', () => {
+ const {dialog} = setup();
+ expect(dialog).toHaveClass('astryx-alert-dialog');
+ expect(dialog).toHaveAccessibleDescription('The draft will be removed.');
+ });
+
+ it('stacks full-width large actions with the secondary safe action focused', () => {
+ const {dialog} = setup();
+ const [destructive, safe] = within(dialog).getAllByRole('button');
+ expect(destructive).toHaveAccessibleName('Discard');
+ expect(destructive).toHaveAttribute('data-variant', 'destructive');
+ expect(safe).toHaveAccessibleName('Keep editing');
+ expect(safe).toHaveAttribute('data-variant', 'secondary');
+ for (const button of [destructive, safe]) {
+ expect(button).toHaveAttribute('data-size', 'lg');
+ expect(getComputedStyle(button).width).toBe('100%');
+ }
+ expect(getComputedStyle(safe.parentElement!).flexDirection).toBe('column');
+ expect(safe).toHaveFocus();
+ });
+
+ it('reports action and safe dismissal independently without committing on cancel', () => {
+ const {dialog, onAction, onOpenChange} = setup();
+ fireEvent.click(within(dialog).getByRole('button', {name: 'Keep editing'}));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(onAction).not.toHaveBeenCalled();
+ fireEvent.click(within(dialog).getByRole('button', {name: 'Discard'}));
+ expect(onAction).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/lab/src/internal/MobileSheetConfirmation.tsx b/packages/lab/src/internal/MobileSheetConfirmation.tsx
new file mode 100644
index 0000000000..d84b810906
--- /dev/null
+++ b/packages/lab/src/internal/MobileSheetConfirmation.tsx
@@ -0,0 +1,97 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file MobileSheetConfirmation.tsx
+ * @input Public Core Dialog, layout, text and action primitives; caller-owned copy
+ * @output Private confirmation shared by MobileTokenizer and MobilePowerSearch
+ * @position Lab-only mobile sheet confirmation owner; not a public export
+ *
+ * Core AlertDialog fixes its purpose to form and its safe action to ghost.
+ * These Lab flows instead allow scrim dismissal and use separated, full-width
+ * large actions with the secondary safe action focused first. Keep that
+ * difference here, while preserving the existing alert-dialog theme target.
+ */
+
+import {useId} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {Button} from '@astryxdesign/core/Button';
+import {Dialog} from '@astryxdesign/core/Dialog';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Layout, LayoutContent, LayoutFooter} from '@astryxdesign/core/Layout';
+import {Stack} from '@astryxdesign/core/Stack';
+import {Text} from '@astryxdesign/core/Text';
+import {themeProps} from '@astryxdesign/core/utils';
+
+interface MobileSheetConfirmationProps {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ title: string;
+ description: string;
+ cancelLabel: string;
+ actionLabel: string;
+ onAction: () => void;
+}
+
+const styles = stylex.create({
+ action: {width: '100%'},
+});
+
+export function MobileSheetConfirmation({
+ isOpen,
+ onOpenChange,
+ title,
+ description,
+ cancelLabel,
+ actionLabel,
+ onAction,
+}: MobileSheetConfirmationProps) {
+ const titleId = useId();
+ const descriptionId = useId();
+ return (
+ <Dialog
+ {...themeProps('alert-dialog')}
+ isOpen={isOpen}
+ onOpenChange={onOpenChange}
+ purpose="info"
+ role="alertdialog"
+ aria-labelledby={titleId}
+ aria-describedby={descriptionId}
+ width={400}>
+ <Layout
+ content={
+ <LayoutContent>
+ <Heading level={2} id={titleId}>
+ {title}
+ </Heading>
+ <Text type="body" color="secondary" id={descriptionId}>
+ {description}
+ </Text>
+ </LayoutContent>
+ }
+ footer={
+ <LayoutFooter>
+ <Stack direction="vertical" gap={4} hAlign="stretch">
+ <Button
+ label={actionLabel}
+ variant="destructive"
+ size="lg"
+ onClick={onAction}
+ xstyle={styles.action}
+ />
+ <Button
+ label={cancelLabel}
+ variant="secondary"
+ size="lg"
+ onClick={() => onOpenChange(false)}
+ data-autofocus
+ xstyle={styles.action}
+ />
+ </Stack>
+ </LayoutFooter>
+ }
+ />
+ </Dialog>
+ );
+}
diff --git a/packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsx b/packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsx
new file mode 100644
index 0000000000..33a834753b
--- /dev/null
+++ b/packages/lab/src/internal/useDismissSearchOnTouchDrag.test.tsx
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useRef} from 'react';
+import {fireEvent, render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {describe, expect, it, vi} from 'vitest';
+import {useDismissSearchOnTouchDrag} from './useDismissSearchOnTouchDrag';
+
+function Harness({hasSecondSearch = false}: {hasSecondSearch?: boolean}) {
+ const firstRef = useRef<HTMLInputElement>(null);
+ const secondRef = useRef<HTMLInputElement>(null);
+ const dragProps = useDismissSearchOnTouchDrag(() => [
+ firstRef.current,
+ secondRef.current,
+ ]);
+ return (
+ <>
+ <input ref={firstRef} aria-label="First search" />
+ {hasSecondSearch && <input ref={secondRef} aria-label="Second search" />}
+ <input aria-label="Unrelated field" />
+ <div role="group" aria-label="Results" {...dragProps} />
+ </>
+ );
+}
+
+const touches = (clientY: number) => [{clientY}];
+
+function setup() {
+ render(<Harness hasSecondSearch />);
+ const search = screen.getByRole('textbox', {name: 'First search'});
+ const results = screen.getByRole('group', {name: 'Results'});
+ search.focus();
+ return {search, results};
+}
+
+describe('useDismissSearchOnTouchDrag', () => {
+ it('preserves typing across programmatic result scrolling', async () => {
+ const {search, results} = setup();
+ fireEvent.scroll(results, {target: {scrollTop: 300}});
+ await userEvent.setup().type(search, 'Eng');
+ fireEvent.scroll(results, {target: {scrollTop: 0}});
+ expect(search).toHaveFocus();
+ expect(search).toHaveValue('Eng');
+ });
+
+ it('blurs a focused owned search once at the direct vertical drag threshold', () => {
+ const {search, results} = setup();
+ const blur = vi.spyOn(search, 'blur');
+ fireEvent.touchStart(results, {touches: touches(100)});
+ fireEvent.touchMove(results, {touches: touches(107)});
+ expect(search).toHaveFocus();
+ fireEvent.touchMove(results, {touches: touches(108)});
+ expect(search).not.toHaveFocus();
+ fireEvent.touchMove(results, {touches: touches(120)});
+ expect(blur).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not blur on an unowned touch move, tap, or horizontal motion', () => {
+ const {search, results} = setup();
+ fireEvent.touchMove(results, {touches: touches(120)});
+ expect(search).toHaveFocus();
+ fireEvent.touchStart(results, {touches: [{clientY: 100, clientX: 0}]});
+ fireEvent.touchMove(results, {touches: [{clientY: 100, clientX: 100}]});
+ fireEvent.touchEnd(results);
+ fireEvent.touchMove(results, {touches: touches(120)});
+ expect(search).toHaveFocus();
+ });
+
+ it('resets ownership on cancellation and multi-touch without dismissing', () => {
+ const {search, results} = setup();
+ fireEvent.touchStart(results, {touches: touches(100)});
+ fireEvent.touchCancel(results);
+ fireEvent.touchMove(results, {touches: touches(120)});
+ expect(search).toHaveFocus();
+ fireEvent.touchStart(results, {touches: touches(100)});
+ fireEvent.touchMove(results, {touches: [{clientY: 120}, {clientY: 140}]});
+ fireEvent.touchMove(results, {touches: touches(150)});
+ expect(search).toHaveFocus();
+ });
+
+ it('can dismiss either current owned input, but never an unrelated field', () => {
+ const {results} = setup();
+ const secondSearch = screen.getByRole('textbox', {name: 'Second search'});
+ secondSearch.focus();
+ fireEvent.touchStart(results, {touches: touches(100)});
+ fireEvent.touchMove(results, {touches: touches(90)});
+ expect(secondSearch).not.toHaveFocus();
+ const unrelated = screen.getByRole('textbox', {name: 'Unrelated field'});
+ unrelated.focus();
+ fireEvent.touchStart(results, {touches: touches(100)});
+ fireEvent.touchMove(results, {touches: touches(120)});
+ expect(unrelated).toHaveFocus();
+ });
+});
diff --git a/packages/lab/src/internal/useDismissSearchOnTouchDrag.ts b/packages/lab/src/internal/useDismissSearchOnTouchDrag.ts
new file mode 100644
index 0000000000..1683a5c58c
--- /dev/null
+++ b/packages/lab/src/internal/useDismissSearchOnTouchDrag.ts
@@ -0,0 +1,57 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useDismissSearchOnTouchDrag.ts
+ * @input Caller-owned search inputs and touch events from a separate results list
+ * @output Private touch handlers shared by the Lab mobile search sheets
+ * @position One owner for results-drag keyboard dismissal; not a public export
+ *
+ * A direct vertical touch drag dismisses only a focused caller-owned search.
+ * Scroll events are deliberately not observed: filtering can clamp scrollTop
+ * and fire scroll while someone is typing. Small moves, taps and multi-touch
+ * gestures leave focus alone. The hook acquires no external resource.
+ */
+
+import {useRef, type TouchEvent} from 'react';
+
+const DRAG_THRESHOLD_PX = 8;
+
+type SearchInput = HTMLInputElement | null | undefined;
+
+export function useDismissSearchOnTouchDrag(
+ getSearchInputs: () => readonly SearchInput[],
+) {
+ const startYRef = useRef<number | null>(null);
+ const reset = () => {
+ startYRef.current = null;
+ };
+
+ return {
+ onTouchStart: (event: TouchEvent<HTMLElement>) => {
+ startYRef.current =
+ event.touches.length === 1 ? event.touches[0].clientY : null;
+ },
+ onTouchMove: (event: TouchEvent<HTMLElement>) => {
+ if (event.touches.length !== 1) {
+ reset();
+ return;
+ }
+ const startY = startYRef.current;
+ if (
+ startY == null ||
+ Math.abs(event.touches[0].clientY - startY) < DRAG_THRESHOLD_PX
+ ) {
+ return;
+ }
+ reset();
+ const focusedSearch = getSearchInputs().find(
+ input => input != null && input === document.activeElement,
+ );
+ focusedSearch?.blur();
+ },
+ onTouchEnd: reset,
+ onTouchCancel: reset,
+ };
+}