Skip to content

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

TypeScript

feat(lab): MobilePowerSearch — touch PowerSearch prototype (#7402)

Xinzi Zhou77d435192462
diff --git a/apps/storybook/stories/MobilePowerSearch.stories.tsx b/apps/storybook/stories/MobilePowerSearch.stories.tsx
new file mode 100644
index 0000000000..79bcd1bcd4
--- /dev/null
+++ b/apps/storybook/stories/MobilePowerSearch.stories.tsx
@@ -0,0 +1,364 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file MobilePowerSearch.stories.tsx
+ * @input Uses MobilePowerSearch (Lab) with a representative PowerSearch config
+ * covering enum, enum_list, string, entity_list, integer, float, date and
+ * string_list operators, plus a content-search variant
+ * @output Storybook try-it stories at phone width (390px): the field-wide
+ * trigger with tokens, the Filters sheet, Add filter, the operator step,
+ * choice rows, and the inline content-search suggestions
+ * @position Lab story; touch PowerSearch prototype
+ */
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import type {
+ PowerSearchConfig,
+ PowerSearchFilter,
+} from '@astryxdesign/core/PowerSearch';
+import type {SearchSource, SearchableItem} from '@astryxdesign/core/Typeahead';
+import {MobilePowerSearch} from '@astryxdesign/lab';
+
+// =============================================================================
+// Sample data (mirrors the Core PowerSearch "full" configuration)
+// =============================================================================
+
+const statusValues = [
+ {value: 'open', label: 'Open'},
+ {value: 'in_progress', label: 'In Progress'},
+ {value: 'review', label: 'In Review'},
+ {value: 'closed', label: 'Closed'},
+ {value: 'blocked', label: 'Blocked'},
+];
+
+const priorityValues = [
+ {value: 'p0', label: 'P0 - Critical'},
+ {value: 'p1', label: 'P1 - High'},
+ {value: 'p2', label: 'P2 - Medium'},
+ {value: 'p3', label: 'P3 - Low'},
+];
+
+const tagValues = [
+ {value: 'bug', label: 'Bug'},
+ {value: 'feature', label: 'Feature'},
+ {value: 'docs', label: 'Documentation'},
+ {value: 'perf', label: 'Performance'},
+ {value: 'security', label: 'Security'},
+ {value: 'ux', label: 'UX'},
+ {value: 'infra', label: 'Infrastructure'},
+];
+
+const users: SearchableItem[] = [
+ {id: 'user-1', label: 'Alice Johnson'},
+ {id: 'user-2', label: 'Bob Smith'},
+ {id: 'user-3', label: 'Charlie Brown'},
+ {id: 'user-4', label: 'Diana Prince'},
+ {id: 'user-5', label: 'Eve Williams'},
+ {id: 'user-6', label: 'Frank Miller'},
+];
+
+const userSource: SearchSource = {
+ search: (query: string) =>
+ users.filter(u => u.label.toLowerCase().includes(query.toLowerCase())),
+ bootstrap: () => users,
+};
+
+const fullConfig: PowerSearchConfig = {
+ name: 'FullSearch',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ defaultOperator: 'any_of',
+ operators: [
+ {
+ key: 'any_of',
+ label: 'is any of',
+ value: {type: 'enum_list', values: statusValues},
+ },
+ {
+ key: 'none_of',
+ label: 'is none of',
+ value: {type: 'enum_list', values: statusValues},
+ },
+ ],
+ },
+ {
+ key: 'title',
+ label: 'Title',
+ defaultOperator: 'contains',
+ operators: [
+ {key: 'contains', label: 'contains', value: {type: 'string'}},
+ {
+ key: 'not_contains',
+ label: 'does not contain',
+ value: {type: 'string'},
+ },
+ ],
+ },
+ {
+ key: 'priority',
+ label: 'Priority',
+ defaultOperator: 'is',
+ operators: [
+ {
+ key: 'is',
+ label: 'is',
+ value: {type: 'enum', values: priorityValues},
+ },
+ ],
+ },
+ {
+ key: 'assignee',
+ label: 'Assignee',
+ defaultOperator: 'any_of',
+ typeaheadAliases: ['owner', 'assigned'],
+ operators: [
+ {
+ key: 'any_of',
+ label: 'is any of',
+ value: {type: 'entity_list', searchSource: userSource},
+ },
+ {
+ key: 'none_of',
+ label: 'is none of',
+ value: {type: 'entity_list', searchSource: userSource},
+ },
+ ],
+ },
+ {
+ key: 'tags',
+ label: 'Tags',
+ group: 'Metadata',
+ defaultOperator: 'include',
+ operators: [
+ {
+ key: 'include',
+ label: 'include',
+ value: {type: 'enum_list', values: tagValues},
+ },
+ {
+ key: 'exclude',
+ label: 'exclude',
+ value: {type: 'enum_list', values: tagValues},
+ },
+ ],
+ },
+ {
+ key: 'line_count',
+ label: 'Line count',
+ group: 'Metadata',
+ defaultOperator: 'gt',
+ operators: [
+ {
+ key: 'gt',
+ label: 'is greater than',
+ value: {
+ type: 'integer',
+ minValue: 0,
+ maxValue: 10000,
+ units: 'lines',
+ },
+ },
+ {
+ key: 'lt',
+ label: 'is less than',
+ value: {
+ type: 'integer',
+ minValue: 0,
+ maxValue: 10000,
+ units: 'lines',
+ },
+ },
+ ],
+ },
+ {
+ key: 'cost',
+ label: 'Cost',
+ group: 'Metadata',
+ defaultOperator: 'gt',
+ operators: [
+ {
+ key: 'gt',
+ label: '>',
+ value: {type: 'float', minValue: 0, maxValue: 100000, units: 'USD'},
+ },
+ {
+ key: 'lt',
+ label: '<',
+ value: {type: 'float', minValue: 0, maxValue: 100000, units: 'USD'},
+ },
+ ],
+ },
+ {
+ key: 'created',
+ label: 'Created',
+ group: 'Dates',
+ defaultOperator: 'after',
+ operators: [
+ {
+ key: 'after',
+ label: 'is after',
+ value: {type: 'date_absolute', isDateOnly: true},
+ },
+ {
+ key: 'newer_than',
+ label: 'is newer than',
+ value: {
+ type: 'date_relative',
+ isPastAllowed: true,
+ isFutureAllowed: false,
+ },
+ },
+ {key: 'between', label: 'is between', value: {type: 'date_range'}},
+ ],
+ },
+ {
+ key: 'ids',
+ label: 'ID',
+ defaultOperator: 'in',
+ operators: [
+ {key: 'in', label: 'is any of', value: {type: 'string_list'}},
+ ],
+ },
+ {
+ key: 'unread',
+ label: 'Unread only',
+ defaultOperator: 'yes',
+ operators: [{key: 'yes', label: '', value: {type: 'empty'}}],
+ },
+ ],
+};
+
+const contentSearchConfig: PowerSearchConfig = {
+ ...fullConfig,
+ name: 'ContentSearch',
+ contentSearchFieldKey: 'title',
+};
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta<typeof MobilePowerSearch> = {
+ title: 'Lab/MobilePowerSearch',
+ component: MobilePowerSearch,
+ parameters: {
+ layout: 'padded',
+ viewport: {defaultViewport: 'mobile2'},
+ },
+};
+export default meta;
+type Story = StoryObj<typeof MobilePowerSearch>;
+
+function PhoneFrame({children}: {children: React.ReactNode}) {
+ return <div style={{width: 390, maxWidth: '100%'}}>{children}</div>;
+}
+
+function FilterDump({filters}: {filters: ReadonlyArray<PowerSearchFilter>}) {
+ if (filters.length === 0) {
+ return null;
+ }
+ return (
+ <pre
+ style={{
+ marginTop: 16,
+ padding: 12,
+ borderRadius: 8,
+ fontSize: 12,
+ overflow: 'auto',
+ maxWidth: 390,
+ }}>
+ {JSON.stringify(filters, null, 2)}
+ </pre>
+ );
+}
+
+export const TouchFlow: Story = {
+ render: args => {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ {
+ field: 'status',
+ operator: 'any_of',
+ value: {type: 'enum_list', value: ['open', 'in_progress']},
+ },
+ {field: 'priority', operator: 'is', value: {type: 'enum', value: 'p1'}},
+ {
+ field: 'created',
+ operator: 'after',
+ value: {type: 'date_absolute', unixSeconds: 1710039600},
+ },
+ ]);
+ return (
+ <PhoneFrame>
+ <MobilePowerSearch
+ {...args}
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ timezoneID="America/Los_Angeles"
+ />
+ <FilterDump filters={filters} />
+ </PhoneFrame>
+ );
+ },
+ name: 'Touch flow (field-wide trigger, Filters sheet, drill-down)',
+};
+
+export const WithContentSearch: Story = {
+ render: args => {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>(
+ [],
+ );
+ return (
+ <PhoneFrame>
+ <MobilePowerSearch
+ {...args}
+ config={contentSearchConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ placeholder="Search issues…"
+ />
+ <FilterDump filters={filters} />
+ </PhoneFrame>
+ );
+ },
+ name: 'Content search (Add filter with inline suggestions)',
+};
+
+export const ReadOnlyAndDisabled: Story = {
+ render: () => {
+ const filters: ReadonlyArray<PowerSearchFilter> = [
+ {field: 'priority', operator: 'is', value: {type: 'enum', value: 'p0'}},
+ {
+ field: 'tags',
+ operator: 'include',
+ value: {type: 'enum_list', value: ['bug', 'security']},
+ isReadOnly: true,
+ },
+ ];
+ return (
+ <PhoneFrame>
+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>
+ <MobilePowerSearch
+ label="Read-only filters"
+ isLabelHidden={false}
+ config={fullConfig}
+ filters={filters}
+ onChange={() => {}}
+ isReadOnly
+ />
+ <MobilePowerSearch
+ label="Disabled filters"
+ isLabelHidden={false}
+ config={fullConfig}
+ filters={filters}
+ onChange={() => {}}
+ isDisabled
+ disabledMessage="Pick a project first"
+ />
+ </div>
+ </PhoneFrame>
+ );
+ },
+ name: 'Read-only and disabled',
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index cdb7420cee..97b4458b92 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -615,6 +615,11 @@
"path": "components/lab/log-stream",
"aliases": []
},
+ {
+ "name": "component-lab-mobile-power-search",
+ "path": "components/lab/mobile-power-search",
+ "aliases": []
+ },
{
"name": "component-lab-mobile-tokenizer",
"path": "components/lab/mobile-tokenizer",
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
new file mode 100644
index 0000000000..9fda6757a4
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
@@ -0,0 +1,160 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'MobilePowerSearch',
+ displayName: 'Mobile Power Search',
+ group: 'MobilePowerSearch',
+ category: 'Form Controls',
+ keywords: [
+ 'power search',
+ 'filters',
+ 'mobile',
+ 'touch',
+ 'bottom sheet',
+ 'filter builder',
+ ],
+ props: [
+ {
+ name: 'config',
+ type: 'PowerSearchConfig',
+ description:
+ 'Core PowerSearch configuration: fields, operators, and an optional contentSearchFieldKey.',
+ required: true,
+ },
+ {
+ name: 'filters',
+ type: 'ReadonlyArray<PowerSearchFilter>',
+ description: 'Currently active filters (Core PowerSearchFilter).',
+ required: true,
+ },
+ {
+ name: 'onChange',
+ type: '(filters, changeType, index) => void',
+ description:
+ "Mirrors Core PowerSearch: the next filters plus 'add' | 'edit' | 'remove' and the affected index.",
+ required: true,
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible label for the field and its trigger.',
+ default: "'Manage filters'",
+ },
+ {
+ name: 'placeholder',
+ type: 'string',
+ description:
+ 'Trigger text when no filter is selected; also the content-search placeholder.',
+ },
+ {
+ name: 'size',
+ type: "'sm' | 'md' | 'lg'",
+ description: 'Field size; tokens follow it.',
+ default: "'md'",
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description:
+ 'Disables the field; the sheet cannot open. Pair with disabledMessage to explain why.',
+ default: 'false',
+ },
+ {
+ name: 'isReadOnly',
+ type: 'boolean',
+ description:
+ 'Filters stay visible in the Filters sheet but cannot be added, edited, or removed.',
+ default: 'false',
+ },
+ {
+ name: 'hasClear',
+ type: 'boolean',
+ description:
+ 'Shows Clear all in the Filters sheet footer. Read-only filters are never cleared.',
+ default: 'true',
+ },
+ {
+ name: 'timezoneID',
+ type: 'string',
+ description:
+ 'IANA timezone for date values. Used by tokens, Filters rows, and the date editors alike, so a boundary date reads the same everywhere.',
+ },
+ {
+ name: 'maxSearchResults',
+ type: 'number',
+ description:
+ 'Max suggestions for a non-empty field or content-search query.',
+ default: '10',
+ },
+ {
+ name: 'popoverSaveButtonLabel',
+ type: 'string',
+ description: "Label for the edit sheet's confirm action.",
+ default: "'Apply' when editing, 'Add filter' when creating",
+ },
+ {
+ name: 'components',
+ type: 'PowerSearchComponents',
+ description:
+ 'Core per-type Token and Editor overrides. Tokens render display-only (no onClick/onRemove); an Editor replaces the value sheet body.',
+ },
+ {
+ name: 'resultCount',
+ type: 'number | string',
+ description:
+ 'Shown at the end of the field and announced when it changes.',
+ },
+ ],
+ 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 as a chevron row with its value in bold, Add filter at the top right, and sticky Clear all and Done actions. Opening a row edits that filter in a sheet with Cancel, Apply, and Remove. Add filter opens directly when no filter exists; 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. Single and multi-value choices are full-width rows with trailing checks; other value types use the matching Astryx input. Fields whose only operators are nested are left out with a development warning.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Try this in Lab/canary on touch layouts to validate the flow; the API mirrors Core PowerSearch so graduating is an import swap.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass timezoneID whenever filters carry dates, so tokens, rows, and editors agree on the calendar day.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Do not switch between MobilePowerSearch and PowerSearch while a sheet is open: the two keep separate draft state.',
+ },
+ {
+ 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:
+ 'Bordered field with display-only tokens; the entire field opens the sheet.',
+ },
+ {
+ name: 'Filters sheet',
+ required: true,
+ description:
+ 'Tall sheet with a heading, Add filter, a divided list of chevron rows, and sticky Clear all plus Done.',
+ },
+ {
+ name: 'Add filter sheet',
+ required: true,
+ description:
+ 'Back, a field list grouped by field group (searchable past eight fields), or the content search with inline suggestions.',
+ },
+ {
+ name: 'Value sheet',
+ required: true,
+ description:
+ 'Field or field-and-operator title, operator radios when needed, the value editor, and Cancel plus Add filter or Apply and Remove.',
+ },
+ ],
+ },
+};
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
new file mode 100644
index 0000000000..8ba2e55560
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
@@ -0,0 +1,1797 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file MobilePowerSearch.test.tsx
+ * @input Uses vitest, @testing-library/react, MobilePowerSearch (Lab) and its
+ * helpers
+ * @output Unit tests for the Lab touch PowerSearch flow: trigger, Filters
+ * sheet, Add filter, operator step, each value type, content search, focus
+ * restoration, timezone boundary dates, disabled/read-only, onChange
+ * metadata, nested exclusion
+ * @position Lab testing; validates MobilePowerSearch.tsx,
+ * MobilePowerSearchValueEditor.tsx and mobilePowerSearchUtils.ts
+ *
+ * SYNC: When MobilePowerSearch.tsx changes, update tests to match new behavior
+ */
+
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import React, {createRef, useState} from 'react';
+import type {
+ PowerSearchConfig,
+ PowerSearchEditorProps,
+ PowerSearchFilter,
+ PowerSearchHandle,
+ PowerSearchTokenProps,
+} from '@astryxdesign/core/PowerSearch';
+import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';
+import {MobilePowerSearch} from './MobilePowerSearch';
+import {
+ createContentSearchSource,
+ createMobilePowerSearchConfig,
+ isoDateTimeToUnixSeconds,
+ isoDateToUnixSeconds,
+ nearestEditableIndex,
+ resolveFilterIdentityIndex,
+ filterSignature,
+ unixSecondsToISODate,
+ unixSecondsToISODateTime,
+} from './mobilePowerSearchUtils';
+
+// jsdom implements neither <dialog> open/close nor pointer capture; the sheet
+// needs both. Same stubs BottomSheet's own tests install.
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.show = vi.fn(function (this: HTMLDialogElement) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+ if (!Element.prototype.setPointerCapture) {
+ Element.prototype.setPointerCapture = vi.fn();
+ Element.prototype.releasePointerCapture = vi.fn();
+ }
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockReturnValue({
+ matches: false,
+ media: '',
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ }),
+ );
+ // useAnnounce reads the frame id inside its callback, so the callback must
+ // not run before requestAnimationFrame returns.
+ vi.stubGlobal(
+ 'requestAnimationFrame',
+ vi.fn((callback: FrameRequestCallback) =>
+ window.setTimeout(() => callback(performance.now()), 0),
+ ),
+ );
+ vi.stubGlobal(
+ 'cancelAnimationFrame',
+ vi.fn((id: number) => window.clearTimeout(id)),
+ );
+ window.scrollTo = vi.fn();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+// =============================================================================
+// Fixtures
+// =============================================================================
+
+const STATUS_VALUES = [
+ {value: 'open', label: 'Open'},
+ {value: 'closed', label: 'Closed'},
+];
+
+const config: PowerSearchConfig = {
+ name: 'Issues',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ description: 'Workflow state',
+ operators: [
+ {key: 'is', label: 'is', value: {type: 'enum', values: STATUS_VALUES}},
+ {
+ key: 'isNot',
+ label: 'is not',
+ value: {type: 'enum', values: STATUS_VALUES},
+ },
+ {key: 'isEmpty', label: 'is empty', value: {type: 'empty'}},
+ ],
+ },
+ {
+ key: 'author',
+ label: 'Author',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'labels',
+ label: 'Labels',
+ group: 'Metadata',
+ operators: [
+ {
+ key: 'isAnyOf',
+ label: 'is any of',
+ value: {
+ type: 'enum_list',
+ values: [
+ {value: 'bug', label: 'Bug'},
+ {value: 'urgent', label: 'Urgent'},
+ ],
+ },
+ },
+ ],
+ },
+ {
+ key: 'unassigned',
+ label: 'Unassigned',
+ operators: [{key: 'isTrue', label: 'is true', value: {type: 'empty'}}],
+ },
+ ],
+};
+
+const contentSearchConfig: PowerSearchConfig = {
+ ...config,
+ name: 'ContentSearch',
+ contentSearchFieldKey: 'author',
+};
+
+const openFilter: PowerSearchFilter = {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'open'},
+};
+
+const authorFilter: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Ada'},
+};
+
+const people: SearchableItem[] = [
+ {id: 'p1', label: 'Ada Lovelace'},
+ {id: 'p2', label: 'Grace Hopper'},
+];
+const peopleSource: SearchSource = {
+ search: q =>
+ people.filter(p => p.label.toLowerCase().includes(q.toLowerCase())),
+ bootstrap: () => people,
+};
+
+/** One field per non-nested value type Core PowerSearch supports. */
+const valueTypesConfig: PowerSearchConfig = {
+ name: 'ValueTypes',
+ fields: [
+ {
+ key: 'title',
+ label: 'Title',
+ operators: [
+ {key: 'contains', label: 'contains', value: {type: 'string'}},
+ ],
+ },
+ {
+ key: 'owner',
+ label: 'Owner',
+ operators: [
+ {
+ key: 'is',
+ label: 'is',
+ value: {type: 'string', searchSource: peopleSource},
+ },
+ ],
+ },
+ {
+ key: 'ids',
+ label: 'ID',
+ operators: [
+ {key: 'in', label: 'is any of', value: {type: 'string_list'}},
+ ],
+ },
+ {
+ key: 'lines',
+ label: 'Lines',
+ operators: [
+ {
+ key: 'gt',
+ label: 'is greater than',
+ value: {type: 'integer', minValue: 0, units: 'lines'},
+ },
+ ],
+ },
+ {
+ key: 'cost',
+ label: 'Cost',
+ operators: [{key: 'gt', label: '>', value: {type: 'float'}}],
+ },
+ {
+ key: 'alarm',
+ label: 'Alarm',
+ operators: [{key: 'at', label: 'at', value: {type: 'time'}}],
+ },
+ {
+ key: 'created',
+ label: 'Created',
+ operators: [
+ {
+ key: 'after',
+ label: 'is after',
+ value: {type: 'date_absolute', isDateOnly: true},
+ },
+ ],
+ },
+ {
+ key: 'updated',
+ label: 'Updated',
+ operators: [
+ {
+ key: 'after',
+ label: 'is after',
+ value: {type: 'date_absolute', isDateOnly: false},
+ },
+ ],
+ },
+ {
+ key: 'age',
+ label: 'Age',
+ operators: [
+ {
+ key: 'newer',
+ label: 'is newer than',
+ value: {type: 'date_relative', isFutureAllowed: false},
+ },
+ ],
+ },
+ {
+ key: 'window',
+ label: 'Window',
+ operators: [
+ {key: 'between', label: 'is between', value: {type: 'date_range'}},
+ ],
+ },
+ {
+ key: 'assignee',
+ label: 'Assignee',
+ operators: [
+ {
+ key: 'anyOf',
+ label: 'is any of',
+ value: {type: 'entity_list', searchSource: peopleSource},
+ },
+ ],
+ },
+ {
+ key: 'color',
+ label: 'Color',
+ operators: [
+ {
+ key: 'is',
+ label: 'is',
+ value: {
+ type: 'custom',
+ Editor: ({value, onChange, placeholder}) => (
+ <input
+ aria-label="Color editor"
+ placeholder={placeholder}
+ value={value ?? ''}
+ onChange={e => onChange(e.target.value)}
+ />
+ ),
+ getString: v => v.toUpperCase(),
+ },
+ },
+ ],
+ },
+ ],
+};
+
+function setup(
+ props: Partial<React.ComponentProps<typeof MobilePowerSearch>> = {},
+) {
+ const onChange = vi.fn();
+ const result = render(
+ <MobilePowerSearch
+ config={config}
+ filters={[]}
+ onChange={onChange}
+ {...props}
+ />,
+ );
+ return {onChange, ...result};
+}
+
+function trigger(): HTMLElement {
+ return document.querySelector<HTMLElement>('[aria-haspopup="dialog"]')!;
+}
+
+/** The field wrapper holding the tokens and the trigger. */
+function field(): HTMLElement {
+ return trigger().parentElement!;
+}
+
+function openSheet(): void {
+ fireEvent.click(trigger());
+}
+
+/**
+ * Whether the flow is open. The dialog element outlives a close by an exit
+ * transition that jsdom never fires, so the flow's state is read from the
+ * trigger's aria-expanded.
+ */
+function isSheetOpen(): boolean {
+ return trigger().getAttribute('aria-expanded') === 'true';
+}
+
+function sheet(): HTMLElement {
+ const dialog = document.querySelector<HTMLElement>('dialog[open]');
+ if (!dialog) {
+ throw new Error('no open sheet');
+ }
+ return dialog;
+}
+
+/**
+ * Completes every pending sheet motion. jsdom resolves no transition timing,
+ * so the panels wait for a native transitionend; this fires it.
+ */
+function settleSheets(): void {
+ for (const panel of document.querySelectorAll<HTMLElement>(
+ '.astryx-bottom-sheet',
+ )) {
+ fireEvent.transitionEnd(panel, {propertyName: 'transform'});
+ fireEvent.transitionEnd(panel, {propertyName: 'opacity'});
+ }
+}
+
+function tapRow(name: RegExp | string): void {
+ const matches = within(sheet()).getAllByRole('button', {name});
+ // The switcher keeps the outgoing sheet mounted while the incoming one
+ // enters; the last match is always on the sheet that just arrived.
+ fireEvent.click(matches[matches.length - 1]);
+}
+
+function openAddFlow(): void {
+ openSheet();
+ if (within(sheet()).queryByRole('heading', {name: 'Filters'})) {
+ tapRow('Add filter');
+ }
+}
+
+function openEditFlow(name: RegExp | string): void {
+ openSheet();
+ tapRow(name);
+}
+
+function apply(): void {
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Apply'}));
+}
+
+function addFilter(): void {
+ const matches = within(sheet()).getAllByRole('button', {name: 'Add filter'});
+ fireEvent.click(matches[matches.length - 1]);
+}
+
+// =============================================================================
+// Trigger field
+// =============================================================================
+
+/**
+ * The sheet bodies pad their content and publish that padding as container
+ * padding; each list in them runs edge to edge with `edge="bleed"`, so row
+ * text keeps the body's inset (spacing-4) while dividers and backgrounds
+ * reach the sheet's sides. No private Item variable is set.
+ */
+function expectBleedRowsOnBodyInset(list: HTMLElement): void {
+ expect(list.className).toContain('reachesContainerPadding');
+ const rows = list.querySelectorAll('li');
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ expect(row.className).toMatch(/edgeBleed/);
+ expect(row.getAttribute('style') ?? '').not.toContain('--_item-inset');
+ }
+ // The published padding is the body's inline padding (spacing-4).
+ const body = list.closest('[class*="body"]') as HTMLElement | null;
+ expect(body).not.toBeNull();
+ const computed = getComputedStyle(body!);
+ expect(computed.getPropertyValue('--container-padding-inline-start')).toBe(
+ 'var(--spacing-4)',
+ );
+ expect(computed.getPropertyValue('--container-padding-inline-end')).toBe(
+ 'var(--spacing-4)',
+ );
+}
+
+describe('MobilePowerSearch trigger', () => {
+ it('uses the field label for its single sheet trigger', () => {
+ setup({label: 'Filter issues'});
+ const button = screen.getByRole('button', {name: 'Filter issues'});
+ expect(button).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(button).toHaveTextContent('Filters…');
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('renders display-only tokens with bold values and no remove controls', () => {
+ setup({filters: [openFilter, authorFilter]});
+ expect(within(field()).getByText('Status: is')).toBeTruthy();
+ expect(within(field()).getByText('Open')).toHaveStyle({
+ fontWeight: 'var(--font-weight-bold)',
+ });
+ expect(within(field()).getByText('Author: is')).toBeTruthy();
+ expect(within(field()).queryByRole('button', {name: /^Remove/})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Clear all'})).toBeNull();
+ });
+
+ it('opens the Filters sheet when a token is tapped and returns focus to the trigger', () => {
+ setup({filters: [openFilter]});
+ fireEvent.click(within(field()).getByText('Open'));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('wraps tokens without reserving a row for the trigger', () => {
+ setup({filters: [openFilter, authorFilter]});
+ const button = screen.getByRole('button', {name: 'Manage filters'});
+ expect(getComputedStyle(button.parentElement!).flexWrap).toBe('wrap');
+ expect(getComputedStyle(button).position).toBe('absolute');
+ });
+
+ it('does not open when disabled', () => {
+ setup({isDisabled: true});
+ openSheet();
+ expect(isSheetOpen()).toBe(false);
+ expect(trigger()).toBeDisabled();
+ });
+
+ it('keeps the trigger focusable when a disabled reason is given', () => {
+ setup({isDisabled: true, disabledMessage: 'Pick a project first'});
+ expect(trigger().hasAttribute('disabled')).toBe(false);
+ expect(trigger().getAttribute('aria-disabled')).toBe('true');
+ openSheet();
+ expect(isSheetOpen()).toBe(false);
+ });
+
+ it('auto-focuses the trigger when requested', () => {
+ setup({hasAutoFocus: true});
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('fires focus callbacks when focus crosses the field boundary', () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ setup({filters: [openFilter], onFocus, onBlur});
+ fireEvent.focus(trigger(), {relatedTarget: null});
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).not.toHaveBeenCalled();
+ fireEvent.blur(trigger(), {relatedTarget: document.body});
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ it('focuses the trigger through the Core imperative handle', () => {
+ const handle = createRef<PowerSearchHandle>();
+ setup({handleRef: handle});
+ handle.current?.focusTypeahead();
+ expect(trigger()).toHaveFocus();
+ handle.current?.blurTypeahead();
+ expect(trigger()).not.toHaveFocus();
+ });
+
+ it('renders the result count and announces a change to it', () => {
+ const {rerender} = setup({resultCount: 12});
+ expect(screen.getByText('12 results')).toBeTruthy();
+ rerender(
+ <MobilePowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ resultCount={1}
+ />,
+ );
+ expect(screen.getByText('1 result')).toBeTruthy();
+ });
+
+ it('forwards display-only props to token overrides', () => {
+ const seenProps = vi.fn();
+ function CustomToken(props: PowerSearchTokenProps) {
+ seenProps(props);
+ return <span>Custom token</span>;
+ }
+ setup({filters: [openFilter], components: {enum: {Token: CustomToken}}});
+ expect(screen.getByText('Custom token')).toBeTruthy();
+ expect(seenProps).toHaveBeenCalledWith(
+ expect.objectContaining({
+ filter: openFilter,
+ onClick: undefined,
+ onRemove: undefined,
+ }),
+ );
+ });
+});
+
+// =============================================================================
+// Filters sheet
+// =============================================================================
+
+describe('MobilePowerSearch Filters sheet', () => {
+ it('shows selected filters as chevron rows with bold values', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ const list = within(sheet()).getByRole('list');
+ const row = within(list).getByRole('button', {name: 'Status is Open'});
+ expect(within(row).getByText('Open')).toHaveStyle({
+ fontWeight: 'var(--font-weight-bold)',
+ });
+ expect(within(list).queryByRole('button', {name: /^Remove/})).toBeNull();
+ expect(list.querySelectorAll('svg')).toHaveLength(1);
+ });
+
+ it('places Add filter in the header and Clear all plus Done in the footer', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ const heading = within(sheet()).getByRole('heading', {name: 'Filters'});
+ const list = within(sheet()).getByRole('list');
+ const add = within(sheet()).getByRole('button', {name: 'Add filter'});
+ const clearAll = within(sheet()).getByRole('button', {name: 'Clear all'});
+ const done = within(sheet()).getByRole('button', {name: 'Done'});
+ expect(
+ heading.compareDocumentPosition(add) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ add.compareDocumentPosition(list) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(
+ list.compareDocumentPosition(clearAll) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+ expect(done).toHaveAttribute('data-variant', 'primary');
+ expect(getComputedStyle(clearAll.parentElement!).position).toBe('sticky');
+ });
+
+ it('runs filter rows edge to edge on the body inset (List edge="bleed")', () => {
+ setup({filters: [openFilter, authorFilter]});
+ openSheet();
+ expectBleedRowsOnBodyInset(within(sheet()).getByRole('list'));
+ });
+
+ it('closes on Done and restores focus to the trigger', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('clears removable filters, closes, and restores focus', () => {
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ return (
+ <MobilePowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ expect(within(field()).queryByText('Open')).toBeNull();
+ });
+
+ it('clears every removable filter but keeps read-only ones', () => {
+ const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};
+ const {onChange} = setup({filters: [authorFilter, pinned]});
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ expect(onChange).toHaveBeenCalledWith([pinned], 'remove', 0);
+ expect(isSheetOpen()).toBe(false);
+ });
+
+ it('respects hasClear', () => {
+ setup({filters: [openFilter], hasClear: false});
+ openSheet();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Clear all'}),
+ ).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Done'})).toBeTruthy();
+ });
+
+ it('opens a read-only Filters sheet without mutation actions', () => {
+ const {onChange} = setup({filters: [openFilter], isReadOnly: true});
+ openSheet();
+ expect(isSheetOpen()).toBe(true);
+ expect(within(sheet()).getByText('Status is')).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Status is Open'}),
+ ).toBe(null);
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Clear all'}),
+ ).toBeNull();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Add filter'}),
+ ).toBeNull();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('keeps read-only filters as plain rows next to editable ones', () => {
+ const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};
+ setup({filters: [pinned, authorFilter]});
+ openSheet();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Status is Open'}),
+ ).toBe(null);
+ expect(
+ within(sheet()).getByRole('button', {name: 'Author is Ada'}),
+ ).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Add filter
+// =============================================================================
+
+describe('MobilePowerSearch Add filter', () => {
+ it('opens directly to Add filter when no filters are selected', () => {
+ setup();
+ openSheet();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('heading', {name: 'Filters'}),
+ ).toBeNull();
+ });
+
+ it('closes to the trigger when Back is pressed from direct entry', () => {
+ setup();
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Back'}));
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('returns to Filters and focuses Add filter when Back is pressed from management', () => {
+ setup({filters: [openFilter]});
+ openAddFlow();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Back'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it('lists the fields, grouped, with chevrons', () => {
+ setup();
+ openAddFlow();
+ const status = within(sheet()).getByRole('button', {name: 'Status'});
+ expect(status.textContent).toBe('Status');
+ expect(within(sheet()).getByRole('button', {name: 'Author'})).toBeTruthy();
+ expect(within(sheet()).getByRole('list', {name: 'Metadata'})).toBeTruthy();
+ expect(status.closest('li')?.querySelectorAll('svg')).toHaveLength(1);
+ });
+
+ it('offers no field search for a short list', () => {
+ setup();
+ openAddFlow();
+ expect(within(sheet()).queryByRole('textbox')).toBeNull();
+ });
+
+ it('searches the field list once there are enough fields', () => {
+ const many: PowerSearchConfig = {
+ name: 'Many',
+ fields: Array.from({length: 10}, (_, i) => ({
+ key: `f${i}`,
+ label: `Field ${i}`,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'} as const}],
+ })),
+ };
+ setup({config: many, maxSearchResults: 2});
+ openAddFlow();
+ const search = within(sheet()).getByRole('textbox', {
+ name: 'Search filters',
+ });
+ fireEvent.change(search, {target: {value: 'Field'}});
+ expect(
+ within(sheet()).getAllByRole('button', {name: /^Field/}),
+ ).toHaveLength(2);
+ fireEvent.change(search, {target: {value: 'Field 7'}});
+ expect(within(sheet()).getByRole('button', {name: 'Field 7'})).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Field 3'})).toBeNull();
+ fireEvent.change(search, {target: {value: 'nope'}});
+ expect(
+ within(sheet()).getByText('No filters match your search'),
+ ).toBeTruthy();
+ });
+
+ it('leaves out nested-only fields and warns the developer', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const withNested: PowerSearchConfig = {
+ name: 'Nested',
+ fields: [
+ ...config.fields,
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ {
+ key: 'mixed',
+ label: 'Mixed',
+ operators: [
+ {key: 'all', label: 'all of', value: {type: 'nested'}},
+ {key: 'is', label: 'is', value: {type: 'string'}},
+ ],
+ },
+ ],
+ };
+ setup({config: withNested});
+ openAddFlow();
+ expect(within(sheet()).queryByRole('button', {name: 'Group'})).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Mixed'})).toBeTruthy();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('MobilePowerSearch: 1 field(s) were left out'),
+ );
+ // The mixed field offers only its non-nested operator.
+ tapRow('Mixed');
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Mixed is'}),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('radiogroup')).toBeNull();
+ warn.mockRestore();
+ });
+
+ it('disables an open field picker when the component becomes read-only', () => {
+ const {rerender} = setup();
+ openAddFlow();
+ rerender(
+ <MobilePowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ isReadOnly
+ />,
+ );
+ const status = within(sheet()).getByRole('button', {name: 'Status'});
+ expect(status).toBeDisabled();
+ fireEvent.click(status);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Value sheet: create, operator step, edit, remove
+// =============================================================================
+
+describe('MobilePowerSearch value sheet', () => {
+ it('runs field rows and choice rows edge to edge on the body inset', () => {
+ setup();
+ openAddFlow();
+ for (const list of within(sheet()).getAllByRole('list')) {
+ expectBleedRowsOnBodyInset(list);
+ }
+ tapRow('Status');
+ expectBleedRowsOnBodyInset(within(sheet()).getByRole('list'));
+ });
+
+ it('stages an enum selection and commits it with exact add metadata', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ tapRow('Closed');
+ expect(
+ within(sheet()).getByRole('button', {name: 'Closed, selected'}),
+ ).toBeTruthy();
+ expect(onChange).not.toHaveBeenCalled();
+ addFilter();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'closed'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('tapping the full row toggles a choice, not only its label', () => {
+ setup();
+ openAddFlow();
+ tapRow('Labels');
+ const bugRow = within(sheet())
+ .getByRole('button', {name: 'Bug'})
+ .closest('li')!;
+ // The invisible button fills the row: a tap on the row's padding lands.
+ fireEvent.click(bugRow.querySelector('button')!);
+ expect(
+ within(sheet()).getByRole('button', {name: 'Bug, selected'}),
+ ).toBeTruthy();
+ expect(within(bugRow).queryByRole('button', {name: 'Bug'})).toBeNull();
+ });
+
+ it('returns to Filters with focus on Add filter once a filter is committed', () => {
+ setup();
+ openAddFlow();
+ tapRow('Status');
+ tapRow('Closed');
+ addFilter();
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it('confirms an empty-value operator through Add filter', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Unassigned');
+ expect(onChange).not.toHaveBeenCalled();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Unassigned is true'}),
+ ).toBeTruthy();
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [{field: 'unassigned', operator: 'isTrue', value: {type: 'empty'}}],
+ 'add',
+ 0,
+ );
+ });
+
+ it('shows the operator step as radios only when a field has several', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('radiogroup', {name: 'Operator'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Status is'}),
+ ).toBeChecked();
+ fireEvent.click(
+ within(sheet()).getByRole('radio', {name: 'Status is not'}),
+ );
+ tapRow('Open');
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'status',
+ operator: 'isNot',
+ value: {type: 'enum', value: 'open'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('puts a single-operator field and its operator on one title line', () => {
+ setup();
+ openAddFlow();
+ tapRow('Author');
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Author is'}),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('radiogroup')).toBeNull();
+ });
+
+ it('keeps a staged value across operators of the same type and drops it otherwise', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ tapRow('Open');
+ fireEvent.click(
+ within(sheet()).getByRole('radio', {name: 'Status is not'}),
+ );
+ expect(
+ within(sheet()).getByRole('button', {name: 'Open, selected'}),
+ ).toBeTruthy();
+ fireEvent.click(
+ within(sheet()).getByRole('radio', {name: 'Status is empty'}),
+ );
+ expect(
+ within(sheet()).queryByRole('button', {name: /selected/}),
+ ).toBeNull();
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [{field: 'status', operator: 'isEmpty', value: {type: 'empty'}}],
+ 'add',
+ 0,
+ );
+ });
+
+ it('keeps Add filter disabled until a value is chosen', () => {
+ setup();
+ openAddFlow();
+ tapRow('Author');
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Remove'})).toBeNull();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeDisabled();
+ fireEvent.change(within(sheet()).getByRole('textbox', {name: 'Value'}), {
+ target: {value: 'Ada'},
+ });
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeEnabled();
+ });
+
+ it('restores focus to the chosen field when creation is canceled', () => {
+ setup();
+ openAddFlow();
+ tapRow('Author');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Author'})).toHaveFocus();
+ });
+
+ it('stages a multi-select and commits it from the footer', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Labels');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Bug'}));
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Urgent'}));
+ const bug = within(sheet()).getByRole('button', {name: 'Bug, selected'});
+ const urgent = within(sheet()).getByRole('button', {
+ name: 'Urgent, selected',
+ });
+ expect(bug.closest('li')?.querySelectorAll('svg')).toHaveLength(1);
+ expect(urgent.closest('li')?.querySelectorAll('svg')).toHaveLength(1);
+ expect(onChange).not.toHaveBeenCalled();
+ // Tapping a checked row unchecks it.
+ fireEvent.click(urgent);
+ expect(within(sheet()).getByRole('button', {name: 'Urgent'})).toBeTruthy();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Urgent'}));
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'labels',
+ operator: 'isAnyOf',
+ value: {type: 'enum_list', value: ['bug', 'urgent']},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('opens the edit sheet with Cancel, Apply and Remove from a selected row', () => {
+ setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Remove'})).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Open, selected'}),
+ ).toBeTruthy();
+ });
+
+ it('edits a filter only after Apply, with exact edit metadata', () => {
+ const {onChange} = setup({filters: [authorFilter, openFilter]});
+ openEditFlow('Status is Open');
+ tapRow('Closed');
+ expect(onChange).not.toHaveBeenCalled();
+ apply();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ authorFilter,
+ {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'closed'},
+ },
+ ],
+ 'edit',
+ 1,
+ );
+ });
+
+ it('uses popoverSaveButtonLabel for the confirm action', () => {
+ setup({filters: [openFilter], popoverSaveButtonLabel: 'Save'});
+ openEditFlow('Status is Open');
+ expect(within(sheet()).getByRole('button', {name: 'Save'})).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();
+ });
+
+ it('returns from editing to Filters without changes and restores row focus', () => {
+ const {onChange} = setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Open'}),
+ ).toHaveFocus();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('removes a filter from its edit sheet with exact remove metadata', () => {
+ const {onChange} = setup({filters: [authorFilter, openFilter]});
+ openEditFlow('Status is Open');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Remove'}));
+ expect(onChange).toHaveBeenCalledWith([authorFilter], 'remove', 1);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+
+ it('moves focus to the nearest editable row after a removal', () => {
+ const readOnlyLabel: PowerSearchFilter = {
+ field: 'labels',
+ operator: 'isAnyOf',
+ value: {type: 'enum_list', value: ['bug']},
+ isReadOnly: true,
+ };
+ const after: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace'},
+ };
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ authorFilter,
+ openFilter,
+ readOnlyLabel,
+ after,
+ ]);
+ return (
+ <MobilePowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ />
+ );
+ }
+ render(<Harness />);
+ openEditFlow('Status is Open');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Remove'}));
+ expect(
+ within(sheet()).getByRole('button', {name: 'Author is Grace'}),
+ ).toHaveFocus();
+ });
+
+ it('focuses Add filter after the last editable filter is removed', () => {
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ return (
+ <MobilePowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ />
+ );
+ }
+ render(<Harness />);
+ openEditFlow('Status is Open');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Remove'}));
+ expect(within(sheet()).getByText('No filters selected')).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it('follows the original filter when controlled props reorder it', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <MobilePowerSearch
+ config={config}
+ filters={[openFilter, authorFilter]}
+ onChange={onChange}
+ />,
+ );
+ openEditFlow('Status is Open');
+ rerender(
+ <MobilePowerSearch
+ config={config}
+ filters={[{...authorFilter}, {...openFilter}]}
+ onChange={onChange}
+ />,
+ );
+ tapRow('Closed');
+ apply();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ authorFilter,
+ {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'closed'},
+ },
+ ],
+ 'edit',
+ 1,
+ );
+ });
+
+ it('does not edit a different filter when the controlled target disappears', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <MobilePowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={onChange}
+ />,
+ );
+ openEditFlow('Status is Open');
+ rerender(
+ <MobilePowerSearch
+ config={config}
+ filters={[authorFilter]}
+ onChange={onChange}
+ />,
+ );
+ tapRow('Closed');
+ apply();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+
+ it('keeps a way out when a config update removes the edited field', () => {
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <MobilePowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={onChange}
+ />,
+ );
+ openEditFlow('Status is Open');
+ rerender(
+ <MobilePowerSearch
+ config={{
+ ...config,
+ fields: config.fields.filter(f => f.key !== 'status'),
+ }}
+ filters={[openFilter]}
+ onChange={onChange}
+ />,
+ );
+ expect(
+ within(sheet()).getByText('This filter is no longer available'),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('disables edit actions when an open editor becomes disabled', () => {
+ const {rerender} = setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ rerender(
+ <MobilePowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ isDisabled
+ />,
+ );
+ expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeDisabled();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Remove'}),
+ ).toBeDisabled();
+ expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toBeEnabled();
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Status is'}),
+ ).toBeDisabled();
+ });
+
+ it('commits the complete filter returned by a custom editor', () => {
+ const savedFilter: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace'},
+ isReadOnly: true,
+ };
+ function CustomEditor({onSave, timezoneID}: PowerSearchEditorProps) {
+ return (
+ <button type="button" onClick={() => onSave(savedFilter)}>
+ Custom save {timezoneID}
+ </button>
+ );
+ }
+ const {onChange} = setup({
+ components: {enum: {Editor: CustomEditor}},
+ timezoneID: 'Asia/Tokyo',
+ });
+ openAddFlow();
+ tapRow('Status');
+ fireEvent.click(
+ screen.getByRole('button', {name: 'Custom save Asia/Tokyo'}),
+ );
+ expect(onChange).toHaveBeenCalledWith([savedFilter], 'add', 0);
+ });
+
+ it('returns to Filters unchanged when a creating custom editor saves null', () => {
+ function CustomEditor({onSave}: PowerSearchEditorProps) {
+ return (
+ <button type="button" onClick={() => onSave(null)}>
+ Cancel custom
+ </button>
+ );
+ }
+ const {onChange} = setup({components: {enum: {Editor: CustomEditor}}});
+ openAddFlow();
+ tapRow('Status');
+ fireEvent.click(screen.getByRole('button', {name: 'Cancel custom'}));
+ expect(onChange).not.toHaveBeenCalled();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Content search
+// =============================================================================
+
+describe('MobilePowerSearch content search', () => {
+ it('opens empty content-search configurations directly to Add filter with focus in the search', () => {
+ setup({config: contentSearchConfig, placeholder: 'Search content…'});
+ openSheet();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ expect(input).toHaveAttribute('placeholder', 'Search content…');
+ expect(input).toHaveFocus();
+ });
+
+ it('lists suggestions inline below the search, reachable with ArrowDown', () => {
+ setup({config: contentSearchConfig});
+ openSheet();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ const results = within(sheet()).getByRole('list', {name: 'Search results'});
+ const options = within(results).getAllByRole('button');
+ expect(options.map(option => option.textContent)).toEqual([
+ 'Status',
+ 'Author',
+ 'Unassigned',
+ 'Labels',
+ ]);
+ expect(document.querySelectorAll('[role="option"]')).toHaveLength(0);
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ expect(options[0]).toHaveFocus();
+ fireEvent.keyDown(options[0], {key: 'ArrowDown'});
+ expect(options[1]).toHaveFocus();
+ fireEvent.keyDown(options[1], {key: 'ArrowUp'});
+ expect(options[0]).toHaveFocus();
+ fireEvent.keyDown(options[0], {key: 'ArrowUp'});
+ expect(input).toHaveFocus();
+ });
+
+ it('opens a structured editor from a field suggestion and returns to the search on Cancel', () => {
+ setup({config: contentSearchConfig});
+ openSheet();
+ const results = within(sheet()).getByRole('list', {name: 'Search results'});
+ fireEvent.click(within(results).getByRole('button', {name: 'Status'}));
+ expect(within(sheet()).getByRole('heading', {name: 'Status'})).toBeTruthy();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('searchbox', {name: 'Search'}),
+ ).toHaveFocus();
+ });
+
+ it('adds a free-text suggestion as a content filter and keeps the flow open', async () => {
+ const {onChange} = setup({
+ config: contentSearchConfig,
+ filters: [openFilter],
+ });
+ openSheet();
+ expect(within(sheet()).queryByRole('searchbox')).toBeNull();
+ tapRow('Add filter');
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ fireEvent.change(input, {target: {value: 'release notes'}});
+ fireEvent.click(
+ within(sheet()).getByRole('button', {name: '"release notes"'}),
+ );
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ openFilter,
+ {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'release notes'},
+ },
+ ],
+ 'add',
+ 1,
+ );
+ await waitFor(() => expect(isSheetOpen()).toBe(true));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+
+ it('adds a value suggestion from Enter and announces it', () => {
+ const {onChange} = setup({config: contentSearchConfig});
+ openSheet();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ fireEvent.change(input, {target: {value: 'status clo'}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}),
+ ).toBeTruthy();
+ fireEvent.keyDown(input, {key: 'Enter'});
+ // The first suggestion is the free-text content item.
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'status clo'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('does not submit a composing suggestion (IME guard)', () => {
+ const {onChange} = setup({config: contentSearchConfig});
+ openSheet();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ fireEvent.change(input, {target: {value: '검색'}});
+ expect(within(sheet()).getByRole('button', {name: '"검색"'})).toBeTruthy();
+ fireEvent.keyDown(input, {key: 'Enter', isComposing: true});
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input).toHaveValue('검색');
+ });
+
+ it('shows an empty state for a query with no suggestions', () => {
+ const noContent: PowerSearchConfig = {
+ ...contentSearchConfig,
+ fields: contentSearchConfig.fields.map(f =>
+ f.key === 'author' ? {...f, isValueMatchAllowed: false} : f,
+ ),
+ };
+ setup({config: {...noContent, contentSearchFieldKey: undefined}});
+ // Without a content field, Add filter shows the field list instead.
+ openSheet();
+ expect(within(sheet()).queryByRole('searchbox')).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Status'})).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Value types
+// =============================================================================
+
+describe('MobilePowerSearch value types', () => {
+ function setupValues(
+ props: Partial<React.ComponentProps<typeof MobilePowerSearch>> = {},
+ ) {
+ return setup({config: valueTypesConfig, ...props});
+ }
+
+ it('string: text input stages on change', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Title');
+ fireEvent.change(within(sheet()).getByRole('textbox', {name: 'Value'}), {
+ target: {value: 'hello'},
+ });
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'title',
+ operator: 'contains',
+ value: {type: 'string', value: 'hello'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('string with searchSource: typeahead stages the picked label', async () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Owner');
+ const input = within(sheet()).getByRole('combobox', {name: 'Value'});
+ fireEvent.change(input, {target: {value: 'Gra'}});
+ // The suggestion layer is a popover jsdom cannot show; query it hidden.
+ const option = await screen.findByRole('option', {
+ name: /Grace Hopper/,
+ hidden: true,
+ });
+ fireEvent.click(option);
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'owner',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace Hopper'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('string_list: tokenizer creates free-text values', async () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('ID');
+ const input = within(sheet()).getByRole('combobox', {name: 'Values'});
+ fireEvent.change(input, {target: {value: 'ABC-1'}});
+ fireEvent.click(
+ await screen.findByRole('option', {name: /ABC-1/, hidden: true}),
+ );
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'ids',
+ operator: 'in',
+ value: {type: 'string_list', value: ['ABC-1']},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('integer: number input stages as typed and commits on blur', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Lines');
+ const input = within(sheet()).getByRole('spinbutton', {name: 'Value'});
+ const add = within(sheet()).getByRole('button', {name: 'Add filter'});
+ expect(add).toBeDisabled();
+ fireEvent.input(input, {target: {value: '12'}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeEnabled();
+ fireEvent.blur(input);
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [{field: 'lines', operator: 'gt', value: {type: 'integer', value: 12}}],
+ 'add',
+ 0,
+ );
+ });
+
+ it('integer: a decimal does not stage', () => {
+ setupValues();
+ openAddFlow();
+ tapRow('Lines');
+ fireEvent.input(within(sheet()).getByRole('spinbutton', {name: 'Value'}), {
+ target: {value: '1.5'},
+ });
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeDisabled();
+ });
+
+ it('float: number input stages a decimal', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Cost');
+ const input = within(sheet()).getByRole('spinbutton', {name: 'Value'});
+ fireEvent.input(input, {target: {value: '2.5'}});
+ fireEvent.blur(input);
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [{field: 'cost', operator: 'gt', value: {type: 'float', value: 2.5}}],
+ 'add',
+ 0,
+ );
+ });
+
+ it('time: the time input is rendered and a staged value shows', () => {
+ const timeFilter: PowerSearchFilter = {
+ field: 'alarm',
+ operator: 'at',
+ value: {type: 'time', value: '09:30'},
+ };
+ setupValues({filters: [timeFilter]});
+ openEditFlow('Alarm at 09:30');
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Alarm at'}),
+ ).toBeTruthy();
+ expect(within(sheet()).getByLabelText('Time')).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeEnabled();
+ });
+
+ it('date_absolute (date only): the date input shows the stored day', () => {
+ const dateFilter: PowerSearchFilter = {
+ field: 'created',
+ operator: 'after',
+ // 2024-03-10T12:00:00Z
+ value: {type: 'date_absolute', unixSeconds: 1710072000},
+ };
+ setupValues({filters: [dateFilter], timezoneID: 'UTC'});
+ openEditFlow(/^Created is after/);
+ const input = within(sheet()).getByRole('combobox', {name: 'Date'});
+ expect(input).toHaveValue('March 10, 2024');
+ });
+
+ it('date_absolute (date and time): a date-time input is rendered', () => {
+ setupValues();
+ openAddFlow();
+ tapRow('Updated');
+ expect(within(sheet()).getByLabelText('Date and time')).toBeTruthy();
+ });
+
+ it('date_relative: rows stage a single relative value', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Age');
+ expect(
+ within(sheet()).queryByRole('button', {name: /from now/}),
+ ).toBeNull();
+ tapRow('7 days ago');
+ expect(
+ within(sheet()).getByRole('button', {name: '7 days ago, selected'}),
+ ).toBeTruthy();
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'age',
+ operator: 'newer',
+ value: {type: 'date_relative', value: '7d_ago'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('date_range: the range input is rendered with the stored range', () => {
+ const rangeFilter: PowerSearchFilter = {
+ field: 'window',
+ operator: 'between',
+ value: {
+ type: 'date_range',
+ value: {
+ start: {type: 'ABSOLUTE', unixSeconds: 1709251200}, // 2024-03-01Z
+ end: {type: 'ABSOLUTE', unixSeconds: 1709942400}, // 2024-03-09Z
+ },
+ },
+ };
+ setupValues({filters: [rangeFilter], timezoneID: 'UTC'});
+ openEditFlow(/^Window is between/);
+ const range = within(sheet()).getByLabelText('Date range');
+ expect(range.textContent ?? (range as HTMLInputElement).value).toMatch(
+ /Mar 1, 2024/,
+ );
+ });
+
+ it('entity_list: tokenizer picks entities from the search source', async () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Assignee');
+ const input = within(sheet()).getByRole('combobox', {name: 'Entities'});
+ fireEvent.change(input, {target: {value: 'Ada'}});
+ fireEvent.click(
+ await screen.findByRole('option', {name: /Ada Lovelace/, hidden: true}),
+ );
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'assignee',
+ operator: 'anyOf',
+ value: {
+ type: 'entity_list',
+ value: [{id: 'p1', label: 'Ada Lovelace'}],
+ },
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('custom: the configured editor stages a JSON string', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Color');
+ fireEvent.change(within(sheet()).getByLabelText('Color editor'), {
+ target: {value: 'teal'},
+ });
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'color',
+ operator: 'is',
+ value: {type: 'custom', value: 'teal'},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('custom: tokens and rows use getString', () => {
+ const colorFilter: PowerSearchFilter = {
+ field: 'color',
+ operator: 'is',
+ value: {type: 'custom', value: 'teal'},
+ };
+ setupValues({filters: [colorFilter]});
+ expect(within(field()).getByText('TEAL')).toBeTruthy();
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Color is TEAL'}),
+ ).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Timezone
+// =============================================================================
+
+describe('MobilePowerSearch timezone', () => {
+ // 2024-03-10T03:00:00Z: March 10 in Tokyo (UTC+9), still March 9 in
+ // Honolulu (UTC-10). A boundary instant exposes any surface that formats
+ // without the configured zone.
+ const BOUNDARY_SECONDS = 1710039600;
+ const dateFilter: PowerSearchFilter = {
+ field: 'created',
+ operator: 'after',
+ value: {type: 'date_absolute', unixSeconds: BOUNDARY_SECONDS},
+ };
+
+ it.each([
+ ['Asia/Tokyo', 'Mar 10, 2024', 'March 10, 2024'],
+ ['Pacific/Honolulu', 'Mar 9, 2024', 'March 9, 2024'],
+ ])(
+ 'formats the token, the row and the editor in %s',
+ (timezoneID, compact, long) => {
+ setup({config: valueTypesConfig, filters: [dateFilter], timezoneID});
+ const tokenValue = within(field()).getByText(new RegExp(compact));
+ expect(tokenValue).toHaveStyle({fontWeight: 'var(--font-weight-bold)'});
+ openSheet();
+ const row = within(sheet()).getByRole('button', {
+ name: new RegExp(`^Created is after ${compact}`),
+ });
+ expect(within(row).getByText(new RegExp(compact))).toHaveStyle({
+ fontWeight: 'var(--font-weight-bold)',
+ });
+ fireEvent.click(row);
+ expect(within(sheet()).getByRole('combobox', {name: 'Date'})).toHaveValue(
+ long,
+ );
+ },
+ );
+
+ it('converts a picked day to midnight in the configured zone', () => {
+ expect(isoDateToUnixSeconds('2024-03-09', 'Pacific/Honolulu')).toBe(
+ Date.UTC(2024, 2, 9, 10, 0) / 1000,
+ );
+ expect(isoDateToUnixSeconds('2024-03-10', 'Asia/Tokyo')).toBe(
+ Date.UTC(2024, 2, 9, 15, 0) / 1000,
+ );
+ expect(unixSecondsToISODate(BOUNDARY_SECONDS, 'Asia/Tokyo')).toBe(
+ '2024-03-10',
+ );
+ expect(unixSecondsToISODate(BOUNDARY_SECONDS, 'Pacific/Honolulu')).toBe(
+ '2024-03-09',
+ );
+ expect(unixSecondsToISODateTime(BOUNDARY_SECONDS, 'Asia/Tokyo')).toBe(
+ '2024-03-10T12:00',
+ );
+ expect(
+ isoDateTimeToUnixSeconds(
+ unixSecondsToISODateTime(BOUNDARY_SECONDS, 'Pacific/Honolulu'),
+ 'Pacific/Honolulu',
+ ),
+ ).toBe(BOUNDARY_SECONDS);
+ });
+});
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+describe('mobilePowerSearchUtils', () => {
+ it('resolves filter identity by reference, then slot, then unique signature', () => {
+ const a: PowerSearchFilter = {...openFilter};
+ const b: PowerSearchFilter = {...authorFilter};
+ const sig = filterSignature(a);
+ expect(resolveFilterIdentityIndex([b, a], a, sig, 0)).toBe(1);
+ expect(resolveFilterIdentityIndex([{...a}, b], a, sig, 0)).toBe(0);
+ expect(resolveFilterIdentityIndex([b, {...a}], a, sig, 0)).toBe(1);
+ expect(resolveFilterIdentityIndex([{...a}, {...a}], a, sig, 1)).toBe(1);
+ expect(resolveFilterIdentityIndex([{...a}, {...a}], a, sig, 5)).toBeNull();
+ expect(resolveFilterIdentityIndex([b], a, sig, 0)).toBeNull();
+ });
+
+ it('picks the nearest editable neighbor after a removal, preferring the next', () => {
+ const ro: PowerSearchFilter = {...openFilter, isReadOnly: true};
+ expect(nearestEditableIndex([authorFilter, authorFilter], 1)).toBe(1);
+ expect(nearestEditableIndex([authorFilter, ro], 1)).toBe(0);
+ expect(nearestEditableIndex([ro, ro], 0)).toBeUndefined();
+ expect(nearestEditableIndex([authorFilter, ro, authorFilter], 1)).toBe(2);
+ });
+
+ it('builds content-search suggestions like Core PowerSearch', () => {
+ const source = createContentSearchSource(
+ createMobilePowerSearchConfig(contentSearchConfig),
+ key => key,
+ 10,
+ );
+ expect(source.bootstrap().map(item => item.id)).toEqual([
+ 'status',
+ 'author',
+ 'unassigned',
+ 'labels',
+ ]);
+ const results = source.search('status is clo');
+ expect(results[0]).toMatchObject({
+ label: '"status is clo"',
+ auxiliaryData: {fieldKey: 'author', operatorKey: 'is'},
+ });
+ expect(results[1]).toMatchObject({
+ label: 'Status is Closed',
+ auxiliaryData: {
+ fieldKey: 'status',
+ operatorKey: 'is',
+ filterValue: {type: 'enum', value: 'closed'},
+ },
+ });
+ // An exact field match drops the free-text item.
+ expect(
+ source.search('Author').some(item => item.id.startsWith('__content')),
+ ).toBe(false);
+ });
+});
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx
new file mode 100644
index 0000000000..77890e81ad
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearch.tsx
@@ -0,0 +1,1709 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file MobilePowerSearch.tsx
+ * @input Core PowerSearch config, filters and onChange (the same props as
+ * @astryxdesign/core PowerSearch); public @astryxdesign/core components only
+ * (BottomSheet, BottomSheetSwitcher, Button, Field, Heading, Icon, List,
+ * RadioList, Text, TextInput, Token, Tooltip hooks, i18n, hooks, utils,
+ * Layout container-padding styles)
+ * @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 chevron rows, Add filter and sticky
+ * Clear all / Done, and a field → operator → value drill-down whose edit
+ * sheet holds Cancel / Apply / Remove
+ * @position Lab (canary) stack layer 1: validates the touch design before any
+ * Core promotion. The caller chooses it explicitly
+ * (`isTouch ? MobilePowerSearch : PowerSearch`); there is no pointer
+ * switching inside the component.
+ *
+ * API mirrors Core PowerSearchProps (config, filters, onChange with the same
+ * change metadata, label, placeholder, size, isDisabled, isReadOnly,
+ * timezoneID, status, startIcon, endContent, resultCount, handleRef,
+ * components, ...) so graduation is an import swap. Differences from Core are
+ * the Lab deltas:
+ * - no `menuWidth` or `tokenOverflowBehavior`: there is no typeahead popover
+ * and tokens wrap inside the trigger;
+ * - strings are literals (no new i18n keys; existing Core keys are reused
+ * only for the result count and the add announcement);
+ * - no theming contract: no `power-search` theme target or selectors;
+ * - `components[type].Token` overrides receive Core's PowerSearchTokenProps,
+ * which carry no `timezoneID`; the built-in token renders Core `Token`
+ * directly so the configured timezone reaches tokens and row summaries
+ * through the same formatter;
+ * - fields whose every operator is `nested` are left out with a development
+ * warning; `nested` has no sheet editor yet;
+ * - `date_absolute` honors `isDateOnly: false` with a DateTimeInput, and
+ * `date_relative` is a row list rather than a Selector;
+ * - the sheets pad their own content (`padding={0}` on BottomSheet); each
+ * sheet body publishes that padding as container padding so its
+ * `edge="bleed"` lists run edge to edge with row text on the body's inset.
+ *
+ * The sheets are pinned tall on purpose: the field list resizes as it is
+ * searched and the editor changes with the operator, and only a fully
+ * expanded tall sheet gives mobile-keyboard accommodation.
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/MobilePowerSearch/MobilePowerSearch.doc.mjs
+ * - /packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx
+ * - /apps/storybook/stories/MobilePowerSearch.stories.tsx
+ */
+
+import React, {
+ useCallback,
+ useEffect,
+ useId,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import type {BaseProps} from '@astryxdesign/core';
+import {BottomSheet, BottomSheetSwitcher} from '@astryxdesign/core/BottomSheet';
+import {Button} from '@astryxdesign/core/Button';
+import {
+ Field,
+ inputStatusBorderStyles,
+ inputStatusFocusWithinStyles,
+ inputStatusHoverShadowStyles,
+ inputWrapperStyles,
+ type FieldStatusVariant,
+ type InputStatus,
+} from '@astryxdesign/core/Field';
+import {Heading} from '@astryxdesign/core/Heading';
+import {Icon, renderIconSlot, type IconType} from '@astryxdesign/core/Icon';
+import {containerPaddingInlineVarStyles} from '@astryxdesign/core/Layout/padding.stylex';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {resolveOperatorLabel} from '@astryxdesign/core/PowerSearch';
+import type {
+ FilterValue,
+ PowerSearchChangeType,
+ PowerSearchComponents,
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchFilter,
+ PowerSearchHandle,
+ PowerSearchOperator,
+ PowerSearchSize,
+} from '@astryxdesign/core/PowerSearch';
+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 {Text} from '@astryxdesign/core/Text';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {Token} from '@astryxdesign/core/Token';
+import {useTooltip} from '@astryxdesign/core/Tooltip';
+import {
+ useAnnounce,
+ useDevWarning,
+ useMergedRefs,
+} from '@astryxdesign/core/hooks';
+import {useLocale, useTranslator} from '@astryxdesign/core/i18n';
+import {
+ colorVars,
+ fontWeightVars,
+ sizeVars,
+ spacingVars,
+ typeScaleVars,
+ typographyVars,
+} from '@astryxdesign/core/theme/tokens.stylex';
+import {isImeKeyEvent, isRenderable, rtlStyles} from '@astryxdesign/core/utils';
+import {MobilePowerSearchValueEditor} from './MobilePowerSearchValueEditor';
+import {
+ createContentSearchSource,
+ fieldMatchesQuery,
+ filterSignature,
+ isSupportedOperator,
+ nearestEditableIndex,
+ resolveFilterIdentityIndex,
+ useMobilePowerSearchConfig,
+ type MobilePowerSearchItem,
+} from './mobilePowerSearchUtils';
+
+// =============================================================================
+// Props
+// =============================================================================
+
+export interface MobilePowerSearchProps extends Omit<
+ BaseProps<HTMLElement>,
+ 'onChange'
+> {
+ /** PowerSearch configuration defining available fields and operators. */
+ config: PowerSearchConfig;
+ /** Currently active filters. */
+ filters: ReadonlyArray<PowerSearchFilter>;
+ /** Called when filters change, with the same metadata as Core PowerSearch. */
+ onChange: (
+ filters: ReadonlyArray<PowerSearchFilter>,
+ changeType: PowerSearchChangeType,
+ index: number,
+ ) => void;
+ /** Accessible label for the field and its trigger. @default 'Manage filters' */
+ label?: string;
+ /** Visually hide the label. @default true */
+ isLabelHidden?: boolean;
+ /** Trigger text when no filter is selected, and the content-search placeholder. */
+ placeholder?: string;
+ /** Auto-focus the trigger on mount. @default false */
+ hasAutoFocus?: boolean;
+ /** Show Clear all in the Filters sheet. @default true */
+ hasClear?: boolean;
+ /** Filters stay visible but cannot be added, edited, or removed. @default false */
+ isReadOnly?: boolean;
+ /** Disable the field; the sheet cannot open. @default false */
+ isDisabled?: boolean;
+ /**
+ * Explains why the field is disabled. With `isDisabled`, the trigger stays
+ * focusable (via `aria-disabled`) and shows this text in a tooltip.
+ */
+ disabledMessage?: string;
+ /** Icon at the start of the field. */
+ startIcon?: ReactNode | IconType;
+ /** Fires when focus enters the field from outside. */
+ onFocus?: (e: React.FocusEvent) => void;
+ /** Fires when focus leaves the field entirely. */
+ onBlur?: (e: React.FocusEvent) => void;
+ /** Validation status. */
+ status?: InputStatus;
+ /** How the status message is placed. @default 'attached' */
+ statusVariant?: FieldStatusVariant;
+ /** Max display length for token values. @default 40 */
+ maxTokenLength?: number;
+ /** Max suggestions in string and entity value typeaheads. @default 10 */
+ maxOperatorMenuItems?: number;
+ /** Max ranked results for a non-empty field or content query. @default 10 */
+ maxSearchResults?: number;
+ /** Label for the edit sheet's save action. @default 'Apply' when editing, 'Add filter' when creating */
+ popoverSaveButtonLabel?: string;
+ /** Timezone ID for date formatting in tokens, row summaries, and date editors. */
+ timezoneID?: string;
+ /** Content at the end of the field row. */
+ endContent?: ReactNode;
+ /** Result count: a number formats as "N results"; a string shows as-is. */
+ resultCount?: number | string;
+ /** Ref forwarded to the root element. */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Imperative handle; `focusTypeahead` focuses the sheet trigger. */
+ handleRef?: React.Ref<PowerSearchHandle>;
+ /** Size of the field. @default 'md' */
+ size?: PowerSearchSize;
+ /** Per-type overrides for token and editor rendering. */
+ components?: PowerSearchComponents;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const sizeStyles = stylex.create({
+ sm: {minHeight: sizeVars['--size-element-sm']},
+ md: {minHeight: sizeVars['--size-element-md']},
+ lg: {minHeight: sizeVars['--size-element-lg']},
+});
+
+const styles = stylex.create({
+ wrapper: {
+ position: 'relative',
+ flexWrap: 'nowrap',
+ gap: spacingVars['--spacing-1'],
+ height: 'auto',
+ cursor: {
+ default: 'pointer',
+ ':is([aria-disabled="true"])': 'default',
+ },
+ },
+ wrapperWithTokens: {
+ paddingBlock: `calc(${spacingVars['--spacing-1']} - 1px)`,
+ paddingInline: `calc(${spacingVars['--spacing-1']} - 1px)`,
+ },
+ contentSection: {
+ position: 'relative',
+ minWidth: 0,
+ flexGrow: 1,
+ display: 'flex',
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ columnGap: spacingVars['--spacing-1'],
+ rowGap: `calc(${spacingVars['--spacing-1']} - 1px)`,
+ },
+ startIconWithTokens: {
+ marginInlineStart: `calc(${spacingVars['--spacing-2']} - ${spacingVars['--spacing-1']} + 1px)`,
+ },
+ // The only tab stop in the field. It stays visually borderless while the
+ // wrapper delegates taps on tokens and empty space to it.
+ trigger: {
+ appearance: 'none',
+ flex: '1 1 40px',
+ minWidth: '40px',
+ alignSelf: 'stretch',
+ display: 'flex',
+ alignItems: 'center',
+ paddingBlock: 0,
+ paddingInline: spacingVars['--spacing-1'],
+ margin: 0,
+ borderWidth: 0,
+ borderStyle: 'none',
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-secondary'],
+ fontFamily: typographyVars['--font-family-body'],
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ textAlign: 'start',
+ whiteSpace: 'nowrap',
+ cursor: {
+ default: 'pointer',
+ ':is(:disabled,[aria-disabled="true"])': 'default',
+ },
+ outline: 'none',
+ },
+ // Once a token is present the empty trigger covers the token lane instead
+ // of reserving 40px or wrapping onto an otherwise blank row.
+ triggerWithTokens: {
+ position: 'absolute',
+ inset: 0,
+ minWidth: 0,
+ padding: 0,
+ },
+ tokenValue: {
+ fontWeight: fontWeightVars['--font-weight-bold'],
+ },
+ endSection: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ flexShrink: 0,
+ paddingInlineEnd: spacingVars['--spacing-1'],
+ },
+ resultCount: {
+ fontSize: typeScaleVars['--text-supporting-size'],
+ lineHeight: typeScaleVars['--text-supporting-leading'],
+ color: colorVars['--color-text-secondary'],
+ whiteSpace: 'nowrap',
+ },
+ // 44px touch targets for every sheet action, without resizing inputs.
+ touchAction: {
+ minHeight: 44,
+ },
+ touchIconAction: {
+ minWidth: 44,
+ minHeight: 44,
+ },
+ // --- sheet shell ---------------------------------------------------------
+ sheet: {
+ display: 'flex',
+ flexDirection: 'column',
+ minHeight: '100%',
+ },
+ header: {
+ position: 'sticky',
+ insetBlockStart: 0,
+ // 0, not higher: the sheet's grab handle is an absolutely positioned
+ // sibling at z-index 1; anything above it paints the pill out.
+ zIndex: 0,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-3'],
+ // Clears the sheet's floating grab handle.
+ paddingBlockStart: spacingVars['--spacing-6'],
+ paddingBlockEnd: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-4'],
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+ headerRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ },
+ headerText: {
+ minWidth: 0,
+ flexGrow: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ // The body pads the sheet's content and publishes that inline padding as
+ // the container padding its lists read: with `edge="bleed"` their rows run
+ // edge to edge (full-bleed dividers) while row text keeps this inset, so
+ // row text, group headings and the sheet title share one edge. The sheet
+ // itself has `padding={0}`, so it publishes none.
+ body: {
+ flexGrow: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlockEnd: spacingVars['--spacing-4'],
+ },
+ footer: {
+ position: 'sticky',
+ insetBlockEnd: 0,
+ zIndex: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-4'],
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+ footerActions: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ marginInlineStart: 'auto',
+ },
+ footerSoleAction: {
+ flexGrow: 1,
+ },
+ empty: {
+ paddingBlock: spacingVars['--spacing-6'],
+ textAlign: 'center',
+ },
+ rowValue: {
+ fontWeight: fontWeightVars['--font-weight-bold'],
+ },
+});
+
+// =============================================================================
+// Draft state
+// =============================================================================
+
+type SheetStep = 'manage' | 'fields' | 'value';
+
+type PendingSheetFocus =
+ | {readonly type: 'manager-add'}
+ | {readonly type: 'content-search'}
+ | {
+ readonly type: 'manager-filter';
+ readonly sourceFilter: PowerSearchFilter;
+ readonly sourceSignature: string;
+ readonly preferredIndex: number;
+ }
+ | {readonly type: 'field'; readonly fieldKey: string};
+
+interface FilterDraft {
+ readonly mode: 'create' | 'edit';
+ /** Where Cancel returns for a new filter. */
+ readonly returnStep?: 'fields' | 'manage';
+ /** Control within the return sheet that launched this draft. */
+ readonly returnFocus?: 'field' | 'content-search';
+ /** Index in `filters` when edit mode opened. */
+ readonly filterIndex?: number;
+ /** Original controlled filter identity, used to follow immutable reorders. */
+ readonly sourceFilter?: PowerSearchFilter;
+ /** Structural snapshot, used when controlled parents clone their values. */
+ readonly sourceSignature?: string;
+ readonly field: string;
+ readonly operator?: string;
+ readonly value?: FilterValue;
+}
+
+function resolveDraftFilterIndex(
+ filters: ReadonlyArray<PowerSearchFilter>,
+ draft: FilterDraft,
+): number | null {
+ if (
+ draft.mode !== 'edit' ||
+ draft.filterIndex == null ||
+ draft.sourceFilter == null ||
+ draft.sourceSignature == null
+ ) {
+ return null;
+ }
+ return resolveFilterIdentityIndex(
+ filters,
+ draft.sourceFilter,
+ draft.sourceSignature,
+ draft.filterIndex,
+ );
+}
+
+// Below this many fields a search box is noise: the whole list is on screen.
+const SEARCHABLE_FIELD_COUNT = 8;
+const DEFAULT_MAX_SEARCH_RESULTS = 10;
+const MAX_BROWSE_MENU_ITEMS = 1000;
+
+// =============================================================================
+// Token
+// =============================================================================
+
+/**
+ * Display-only token for the trigger. Core's PowerSearchToken has no
+ * `timezoneID` prop, so the value is formatted here with the same formatter
+ * and timezone the Filters rows use.
+ */
+function MobilePowerSearchToken({
+ config,
+ filter,
+ field,
+ operator,
+ maxLength,
+ size,
+ isDisabled,
+ timezoneID,
+}: {
+ config: InternalConfig;
+ filter: PowerSearchFilter;
+ field: PowerSearchField;
+ operator: PowerSearchOperator;
+ maxLength: number;
+ size: PowerSearchSize;
+ isDisabled: boolean;
+ timezoneID?: string;
+}) {
+ const t = useTranslator();
+ const locale = useLocale();
+ const operatorLabel = resolveOperatorLabel(operator, t);
+ const tokenLabel = operatorLabel
+ ? `${field.label}: ${operatorLabel}`
+ : field.label;
+ const adjustedMaxLength = Math.max(
+ maxLength - field.label.length - operatorLabel.length,
+ 10,
+ );
+ const value = formatFilterValue(
+ config,
+ operator.value,
+ filter.value,
+ adjustedMaxLength,
+ t,
+ locale,
+ timezoneID,
+ );
+ return (
+ <Token
+ label={tokenLabel}
+ size={size}
+ isDisabled={isDisabled}
+ endContent={
+ value ? (
+ <span {...stylex.props(styles.tokenValue)}>{value}</span>
+ ) : undefined
+ }
+ />
+ );
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * Lab prototype of the touch PowerSearch flow. The outer field keeps active
+ * filters as display-only tokens and acts as one sheet trigger. The Filters
+ * sheet lists selected filters as chevron rows with Add filter in its header
+ * and Clear all plus Done in its sticky footer; opening a row edits that
+ * filter in a sheet with Cancel, Apply and Remove. Add filter opens directly
+ * when no filter exists and, when the config names a content-search field,
+ * carries that search with inline suggestions.
+ */
+export function MobilePowerSearch({
+ config: configProp,
+ filters,
+ onChange,
+ label: labelFromProps,
+ isLabelHidden = true,
+ placeholder: placeholderFromProps,
+ hasAutoFocus = false,
+ hasClear = true,
+ isReadOnly = false,
+ isDisabled = false,
+ disabledMessage,
+ startIcon,
+ onFocus,
+ onBlur,
+ status,
+ statusVariant = 'attached',
+ maxTokenLength = 40,
+ maxOperatorMenuItems,
+ maxSearchResults = DEFAULT_MAX_SEARCH_RESULTS,
+ popoverSaveButtonLabel,
+ timezoneID,
+ endContent,
+ resultCount,
+ ref,
+ handleRef,
+ size: sizeProp,
+ 'data-testid': testId,
+ xstyle,
+ className,
+ style,
+ components: componentOverrides,
+}: MobilePowerSearchProps) {
+ const size = useSize(sizeProp, 'md');
+ const config = useMobilePowerSearchConfig(configProp);
+ const t = useTranslator();
+ const locale = useLocale();
+ const announce = useAnnounce();
+
+ const triggerLabel = labelFromProps ?? 'Manage filters';
+ const fieldPlaceholder = placeholderFromProps ?? 'Filters…';
+ const contentSearchPlaceholder = placeholderFromProps ?? 'Search…';
+
+ const contentSearchFieldKey = config.config.contentSearchFieldKey;
+ const contentSearchOperator =
+ contentSearchFieldKey == null
+ ? undefined
+ : config.getDefaultOperator(contentSearchFieldKey);
+ const hasContentSearch = contentSearchOperator?.value.type === 'string';
+ const contentSearchSource = useMemo(
+ () => createContentSearchSource(config, t, maxSearchResults),
+ [config, maxSearchResults, t],
+ );
+
+ const triggerId = useId();
+ const statusMessageId = useId();
+ const contentResultsId = useId();
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ const wrapperRef = useRef<HTMLDivElement>(null);
+ const managerAddButtonRef = useRef<HTMLButtonElement>(null);
+ const contentSearchRef = useRef<HTMLDivElement>(null);
+ const contentSuggestionListRef = useRef<HTMLUListElement>(null);
+ const managerRowsRef = useRef(new Map<number, HTMLLIElement>());
+ const fieldRowsRef = useRef(new Map<string, HTMLLIElement>());
+ const fieldPickerOriginRef = useRef<'manage' | 'trigger'>('manage');
+ const latestFiltersRef = useRef(filters);
+ const pendingSheetFocusRef = useRef<PendingSheetFocus | null>(null);
+ const pendingMutationFocusRef = useRef(false);
+
+ const [step, setStep] = useState<SheetStep | null>(null);
+ // The draft outlives a step change on purpose: the switcher keeps the
+ // outgoing sheet mounted while the incoming one enters, and clearing the
+ // draft with the step would blank that sheet mid-transition.
+ const [draft, setDraft] = useState<FilterDraft | null>(null);
+ const [fieldQuery, setFieldQuery] = useState('');
+ const [contentQuery, setContentQuery] = useState('');
+
+ const isInteractive = !isDisabled && !isReadOnly;
+ const contentResults = useMemo(() => {
+ if (step !== 'fields' || !hasContentSearch || !isInteractive) {
+ return [];
+ }
+ const results =
+ contentQuery.trim() === ''
+ ? contentSearchSource.bootstrap()
+ : contentSearchSource.search(contentQuery);
+ return results.slice(0, MAX_BROWSE_MENU_ITEMS);
+ }, [
+ contentQuery,
+ contentSearchSource,
+ hasContentSearch,
+ isInteractive,
+ step,
+ ]);
+
+ // ------------------------------------------------------------------ focus --
+
+ const focusPendingSheetTarget = useCallback(() => {
+ const target = pendingSheetFocusRef.current;
+ if (target == null) {
+ return;
+ }
+ pendingSheetFocusRef.current = null;
+ if (target.type === 'manager-add') {
+ managerAddButtonRef.current?.focus({preventScroll: true});
+ return;
+ }
+ if (target.type === 'content-search') {
+ contentSearchRef.current
+ ?.querySelector<HTMLInputElement>('input')
+ ?.focus({preventScroll: true});
+ return;
+ }
+ if (target.type === 'field') {
+ fieldRowsRef.current
+ .get(target.fieldKey)
+ ?.querySelector<HTMLButtonElement>('button')
+ ?.focus({preventScroll: true});
+ return;
+ }
+ const index = resolveFilterIdentityIndex(
+ latestFiltersRef.current,
+ target.sourceFilter,
+ target.sourceSignature,
+ target.preferredIndex,
+ );
+ const rowButton =
+ index == null
+ ? null
+ : managerRowsRef.current
+ .get(index)
+ ?.querySelector<HTMLButtonElement>('button');
+ (rowButton ?? managerAddButtonRef.current)?.focus({preventScroll: true});
+ }, []);
+
+ // Both effects run after the entering sheet's own panel focus (child
+ // effects commit first), so the intended control wins. The filters effect
+ // is declared first so a mutation that lands in the same commit as the step
+ // change resolves its row against the new filters.
+ useEffect(() => {
+ latestFiltersRef.current = filters;
+ if (step === 'manage' && pendingMutationFocusRef.current) {
+ pendingMutationFocusRef.current = false;
+ focusPendingSheetTarget();
+ }
+ }, [filters, focusPendingSheetTarget, step]);
+
+ useEffect(() => {
+ if (step != null) {
+ focusPendingSheetTarget();
+ }
+ }, [focusPendingSheetTarget, step]);
+
+ // ----------------------------------------------------------------- fields --
+
+ const fields = useMemo(
+ () =>
+ config
+ .getVisibleFields()
+ .filter(field => field.operators.some(isSupportedOperator)),
+ [config],
+ );
+
+ const droppedFieldCount = config.getVisibleFields().length - fields.length;
+ useDevWarning(
+ 'MobilePowerSearch',
+ `${droppedFieldCount} field(s) were left out of the filter list because every operator they define has a 'nested' value type, which the sheet editor cannot edit yet. Give those fields a non-nested operator to make them available.`,
+ droppedFieldCount > 0,
+ );
+
+ const normalizedFieldQuery = fieldQuery.trim().toLowerCase();
+ const matchingFields = useMemo(() => {
+ const matches = fields.filter(field =>
+ fieldMatchesQuery(field, normalizedFieldQuery),
+ );
+ return normalizedFieldQuery === ''
+ ? matches
+ : matches.slice(0, maxSearchResults);
+ }, [fields, maxSearchResults, normalizedFieldQuery]);
+
+ const groupedFields = useMemo(() => {
+ const groups = new Map<string, PowerSearchField[]>();
+ for (const field of matchingFields) {
+ const key = field.group ?? '';
+ const existing = groups.get(key);
+ if (existing) {
+ existing.push(field);
+ } else {
+ groups.set(key, [field]);
+ }
+ }
+ return [...groups.entries()];
+ }, [matchingFields]);
+
+ const isFieldSearchShown = fields.length >= SEARCHABLE_FIELD_COUNT;
+
+ // ------------------------------------------------------------------ draft --
+
+ const draftField = draft ? config.getField(draft.field) : undefined;
+ const draftOperator =
+ draft?.operator != null
+ ? config.getOperator(draft.field, draft.operator)
+ : undefined;
+ const draftOperators = useMemo(
+ () =>
+ draft
+ ? config.getVisibleOperators(draft.field).filter(isSupportedOperator)
+ : [],
+ [config, draft],
+ );
+
+ const closeSheet = useCallback(() => {
+ setStep(null);
+ }, []);
+
+ const openManager = useCallback(() => {
+ if (isDisabled) {
+ return;
+ }
+ // The switcher restores focus to the element that was active when its
+ // dialog opened; make sure that is the trigger even for a tap on a token.
+ triggerRef.current?.focus({preventScroll: true});
+ if (filters.length === 0 && isInteractive) {
+ fieldPickerOriginRef.current = 'trigger';
+ setFieldQuery('');
+ setContentQuery('');
+ pendingSheetFocusRef.current = hasContentSearch
+ ? {type: 'content-search'}
+ : null;
+ setStep('fields');
+ return;
+ }
+ fieldPickerOriginRef.current = 'manage';
+ setStep('manage');
+ }, [filters.length, hasContentSearch, isDisabled, isInteractive]);
+
+ const handleWrapperClick = useCallback(
+ (event: React.MouseEvent<HTMLDivElement>) => {
+ // Tokens are display-only; a tap anywhere on the field opens the sheet.
+ // The trigger button handles its own click.
+ if (
+ event.target instanceof Node &&
+ triggerRef.current?.contains(event.target)
+ ) {
+ return;
+ }
+ openManager();
+ },
+ [openManager],
+ );
+
+ const openFieldList = useCallback(() => {
+ if (!isInteractive) {
+ return;
+ }
+ fieldPickerOriginRef.current = 'manage';
+ setFieldQuery('');
+ setContentQuery('');
+ pendingSheetFocusRef.current = hasContentSearch
+ ? {type: 'content-search'}
+ : null;
+ setStep('fields');
+ }, [hasContentSearch, isInteractive]);
+
+ const queueManagerAddFocus = useCallback(() => {
+ pendingSheetFocusRef.current = {type: 'manager-add'};
+ }, []);
+
+ const commitSavedFilter = useCallback(
+ (next: FilterDraft, filter: PowerSearchFilter) => {
+ if (!isInteractive) {
+ queueManagerAddFocus();
+ setStep('manage');
+ return;
+ }
+ if (next.mode === 'edit') {
+ const filterIndex = resolveDraftFilterIndex(filters, next);
+ const currentFilter =
+ filterIndex == null ? undefined : filters[filterIndex];
+ if (
+ filterIndex == null ||
+ currentFilter == null ||
+ currentFilter.isReadOnly
+ ) {
+ queueManagerAddFocus();
+ setStep('manage');
+ return;
+ }
+ pendingSheetFocusRef.current = {
+ type: 'manager-filter',
+ sourceFilter: filter,
+ sourceSignature: filterSignature(filter),
+ preferredIndex: filterIndex,
+ };
+ const updated = [...filters];
+ updated[filterIndex] = filter;
+ onChange(updated, 'edit', filterIndex);
+ } else {
+ queueManagerAddFocus();
+ onChange([...filters, filter], 'add', filters.length);
+ }
+ setStep('manage');
+ },
+ [filters, isInteractive, onChange, queueManagerAddFocus],
+ );
+
+ // Opening a new filter can come from a field row or a content-search
+ // suggestion. The origin is kept so Cancel returns to the control the user
+ // came from.
+ const openCreateEditor = useCallback(
+ (
+ field: PowerSearchField,
+ operator: PowerSearchOperator,
+ returnFocus: 'field' | 'content-search' = 'field',
+ ) => {
+ setDraft({
+ mode: 'create',
+ returnStep: 'fields',
+ returnFocus,
+ field: field.key,
+ operator: operator.key,
+ value: operator.value.type === 'empty' ? {type: 'empty'} : undefined,
+ });
+ pendingSheetFocusRef.current = null;
+ setStep('value');
+ },
+ [],
+ );
+
+ const handleFieldSelect = useCallback(
+ (field: PowerSearchField) => {
+ if (!isInteractive) {
+ return;
+ }
+ const operators = field.operators.filter(isSupportedOperator);
+ const preferred = config.getDefaultOperator(field.key);
+ const operator =
+ preferred && isSupportedOperator(preferred) ? preferred : operators[0];
+ if (operator == null) {
+ return;
+ }
+ openCreateEditor(field, operator);
+ },
+ [config, isInteractive, openCreateEditor],
+ );
+
+ const handleContentSuggestionSelect = useCallback(
+ (item: MobilePowerSearchItem | null) => {
+ if (!isInteractive || item?.auxiliaryData == null) {
+ return;
+ }
+ const {fieldKey, filterValue, operatorKey} = item.auxiliaryData;
+ const field = config.getField(fieldKey);
+ const operator =
+ operatorKey == null
+ ? config.getDefaultOperator(fieldKey)
+ : config.getOperator(fieldKey, operatorKey);
+ if (field == null || operator == null || !isSupportedOperator(operator)) {
+ return;
+ }
+ setContentQuery('');
+ if (filterValue != null) {
+ const nextFilter: PowerSearchFilter = {
+ field: field.key,
+ operator: operator.key,
+ value: filterValue,
+ };
+ pendingSheetFocusRef.current = {
+ type: 'manager-filter',
+ sourceFilter: nextFilter,
+ sourceSignature: filterSignature(nextFilter),
+ preferredIndex: filters.length,
+ };
+ pendingMutationFocusRef.current = true;
+ onChange([...filters, nextFilter], 'add', filters.length);
+ announce(t('@astryx.tokenizer.tokenAdded', {label: item.label}));
+ setStep('manage');
+ return;
+ }
+ openCreateEditor(field, operator, 'content-search');
+ },
+ [announce, config, filters, isInteractive, onChange, openCreateEditor, t],
+ );
+
+ const handleFilterEdit = useCallback(
+ (index: number) => {
+ const filter = filters[index];
+ if (!isInteractive || filter == null || filter.isReadOnly) {
+ return;
+ }
+ setDraft({
+ mode: 'edit',
+ filterIndex: index,
+ sourceFilter: filter,
+ sourceSignature: filterSignature(filter),
+ field: filter.field,
+ operator: filter.operator,
+ value: filter.value,
+ });
+ pendingSheetFocusRef.current = null;
+ setStep('value');
+ },
+ [filters, isInteractive],
+ );
+
+ const handleRemoveFilter = useCallback(
+ (index: number) => {
+ const filter = filters[index];
+ if (!isInteractive || filter == null || filter.isReadOnly) {
+ return;
+ }
+ const nextFilters = filters.filter((_, i) => i !== index);
+ const nextIndex = nearestEditableIndex(nextFilters, index);
+ if (nextIndex == null) {
+ pendingSheetFocusRef.current = {type: 'manager-add'};
+ } else {
+ const nextFilter = nextFilters[nextIndex];
+ pendingSheetFocusRef.current = {
+ type: 'manager-filter',
+ sourceFilter: nextFilter,
+ sourceSignature: filterSignature(nextFilter),
+ preferredIndex: nextIndex,
+ };
+ }
+ pendingMutationFocusRef.current = true;
+ onChange(nextFilters, 'remove', index);
+ },
+ [filters, isInteractive, onChange],
+ );
+
+ const handleClearAll = useCallback(() => {
+ // Read-only filters are the consumer's, not the user's: Clear all leaves
+ // them in place.
+ const kept = filters.filter(filter => filter.isReadOnly);
+ const firstRemovedIndex = filters.findIndex(filter => !filter.isReadOnly);
+ if (firstRemovedIndex < 0) {
+ return;
+ }
+ onChange(kept, 'remove', firstRemovedIndex);
+ closeSheet();
+ }, [closeSheet, filters, onChange]);
+
+ const handleOperatorSelect = useCallback((operator: PowerSearchOperator) => {
+ setDraft(current => {
+ if (current == null) {
+ return current;
+ }
+ // A value survives an operator change only when the new operator
+ // reads the same value type.
+ const keepsValue =
+ current.value != null && current.value.type === operator.value.type;
+ return {
+ ...current,
+ operator: operator.key,
+ value:
+ operator.value.type === 'empty'
+ ? {type: 'empty'}
+ : keepsValue
+ ? current.value
+ : undefined,
+ };
+ });
+ }, []);
+
+ const handleDraftValueChange = useCallback((value: FilterValue) => {
+ setDraft(current => (current == null ? current : {...current, value}));
+ }, []);
+
+ const handleSave = useCallback(() => {
+ if (draft?.value == null || draft.operator == null) {
+ return;
+ }
+ commitSavedFilter(draft, {
+ field: draft.field,
+ operator: draft.operator,
+ value: draft.value,
+ });
+ }, [commitSavedFilter, draft]);
+
+ const returnFromValue = useCallback(() => {
+ if (draft == null) {
+ queueManagerAddFocus();
+ setStep('manage');
+ return;
+ }
+ if (
+ draft.mode === 'edit' &&
+ draft.sourceFilter != null &&
+ draft.sourceSignature != null &&
+ draft.filterIndex != null
+ ) {
+ pendingSheetFocusRef.current = {
+ type: 'manager-filter',
+ sourceFilter: draft.sourceFilter,
+ sourceSignature: draft.sourceSignature,
+ preferredIndex:
+ resolveDraftFilterIndex(filters, draft) ?? draft.filterIndex,
+ };
+ setStep('manage');
+ return;
+ }
+ if (draft.returnFocus === 'content-search') {
+ pendingSheetFocusRef.current = {type: 'content-search'};
+ setStep('fields');
+ return;
+ }
+ pendingSheetFocusRef.current = {type: 'field', fieldKey: draft.field};
+ setStep('fields');
+ }, [draft, filters, queueManagerAddFocus]);
+
+ const handleRemove = useCallback(() => {
+ if (draft?.mode !== 'edit') {
+ return;
+ }
+ const filterIndex = resolveDraftFilterIndex(filters, draft);
+ if (filterIndex == null || filters[filterIndex]?.isReadOnly) {
+ queueManagerAddFocus();
+ setStep('manage');
+ return;
+ }
+ handleRemoveFilter(filterIndex);
+ setStep('manage');
+ }, [draft, filters, handleRemoveFilter, queueManagerAddFocus]);
+
+ const handleActiveSheetChange = useCallback((active: string | null) => {
+ // The switcher only reports null, for a dismissal the active sheet
+ // allows. Every step change goes through the handlers above.
+ if (active == null) {
+ setStep(null);
+ }
+ }, []);
+
+ const handleFocusWithin = useCallback(
+ (event: React.FocusEvent<HTMLDivElement>) => {
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !event.currentTarget.contains(event.relatedTarget)
+ ) {
+ onFocus?.(event);
+ }
+ },
+ [onFocus],
+ );
+ const handleBlurWithin = useCallback(
+ (event: React.FocusEvent<HTMLDivElement>) => {
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !event.currentTarget.contains(event.relatedTarget)
+ ) {
+ onBlur?.(event);
+ }
+ },
+ [onBlur],
+ );
+
+ // ------------------------------------------------------------- imperative --
+
+ useImperativeHandle(handleRef, () => ({
+ focusTypeahead() {
+ triggerRef.current?.focus();
+ },
+ blurTypeahead() {
+ triggerRef.current?.blur();
+ },
+ }));
+
+ // ----------------------------------------------------------- result count --
+
+ const resultCountText = useMemo((): string | null => {
+ if (resultCount == null) {
+ return null;
+ }
+ if (typeof resultCount === 'number') {
+ return t('@astryx.powersearch.resultCount', {count: resultCount});
+ }
+ return resultCount;
+ }, [resultCount, t]);
+
+ const hasMountedRef = useRef(false);
+ useEffect(() => {
+ if (!hasMountedRef.current) {
+ hasMountedRef.current = true;
+ return;
+ }
+ if (resultCountText != null) {
+ announce(resultCountText);
+ }
+ }, [resultCountText, announce]);
+
+ // --------------------------------------------------------------- tooltip --
+
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: showsDisabledMessage,
+ });
+ const mergedWrapperRef = useMergedRefs(
+ wrapperRef,
+ disabledMessageTooltip.ref,
+ );
+
+ const triggerDescribedBy =
+ [
+ status?.message ? statusMessageId : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ // ---------------------------------------------------------------- render --
+
+ const filterRows = filters.flatMap((filter, index) => {
+ const field = config.getField(filter.field);
+ const operator = config.getOperator(filter.field, filter.operator);
+ if (!field || !operator) {
+ return [];
+ }
+ const operatorLabel = resolveOperatorLabel(operator, t);
+ const label = [field.label, operatorLabel].filter(Boolean).join(' ');
+ const value = formatFilterValue(
+ config,
+ operator.value,
+ filter.value,
+ Number.MAX_SAFE_INTEGER,
+ t,
+ locale,
+ timezoneID,
+ );
+ const displayLabel = value ? (
+ <>
+ {label} <span {...stylex.props(styles.rowValue)}>{value}</span>
+ </>
+ ) : (
+ label
+ );
+ return [
+ {
+ displayLabel,
+ filter,
+ index,
+ key: `${index}-${filter.field}-${filter.operator}`,
+ },
+ ];
+ });
+
+ const tokens = filters.map((filter, index) => {
+ const field = config.getField(filter.field);
+ const operator = config.getOperator(filter.field, filter.operator);
+ if (!field || !operator) {
+ return null;
+ }
+ const key = `${index}-${filter.field}-${filter.operator}`;
+ const TokenOverride = componentOverrides?.[operator.value.type]?.Token;
+ if (TokenOverride) {
+ return (
+ <TokenOverride
+ key={key}
+ config={configProp}
+ filter={filter}
+ field={field}
+ operator={operator}
+ maxLength={maxTokenLength}
+ onClick={undefined}
+ onRemove={undefined}
+ isDisabled={isDisabled}
+ />
+ );
+ }
+ return (
+ <MobilePowerSearchToken
+ key={key}
+ config={config}
+ filter={filter}
+ field={field}
+ operator={operator}
+ maxLength={maxTokenLength}
+ size={size}
+ isDisabled={isDisabled}
+ timezoneID={timezoneID}
+ />
+ );
+ });
+
+ const hasRemovableFilter = filters.some(filter => !filter.isReadOnly);
+ const isClearAllShown = hasClear && hasRemovableFilter && isInteractive;
+
+ const EditorOverride =
+ draftOperator != null
+ ? componentOverrides?.[draftOperator.value.type]?.Editor
+ : undefined;
+
+ const draftOperatorLabel =
+ draftOperator == null ? '' : resolveOperatorLabel(draftOperator, t);
+ const editorTitle =
+ draftField == null
+ ? draft?.mode === 'edit'
+ ? 'Edit filter'
+ : 'Add filter'
+ : draftOperators.length <= 1 && draftOperatorLabel !== ''
+ ? `${draftField.label} ${draftOperatorLabel}`
+ : draftField.label;
+ const saveButtonLabel =
+ popoverSaveButtonLabel ?? (draft?.mode === 'edit' ? 'Apply' : 'Add filter');
+
+ // Every sheet body: padded, and publishing that padding to its lists.
+ const bodyProps = stylex.props(
+ styles.body,
+ containerPaddingInlineVarStyles[4],
+ );
+
+ const isEditorDisabled = isDisabled || isReadOnly;
+ const isSaveDisabled =
+ isEditorDisabled || draft?.operator == null || draft.value == null;
+ const isDraftRenderable =
+ draft != null && draftField != null && draftOperator != null;
+
+ return (
+ <>
+ <Field
+ ref={ref}
+ label={triggerLabel}
+ isLabelHidden={isLabelHidden}
+ inputID={triggerId}
+ isDisabled={isDisabled}
+ status={
+ status
+ ? {
+ type: status.type,
+ message: status.message,
+ messageID: status.message ? statusMessageId : undefined,
+ }
+ : undefined
+ }
+ statusVariant={statusVariant}
+ xstyle={xstyle}
+ className={className}
+ style={style}>
+ <div
+ ref={mergedWrapperRef}
+ onClick={handleWrapperClick}
+ onFocus={handleFocusWithin}
+ onBlur={handleBlurWithin}
+ data-testid={testId}
+ aria-disabled={isDisabled ? true : undefined}
+ {...stylex.props(
+ inputWrapperStyles.base,
+ styles.wrapper,
+ filters.length > 0 && styles.wrapperWithTokens,
+ sizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status && !isDisabled && inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ )}>
+ <div {...stylex.props(styles.contentSection)}>
+ {startIcon && (
+ <span
+ {...stylex.props(
+ filters.length > 0 && styles.startIconWithTokens,
+ )}>
+ {renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
+ </span>
+ )}
+ {tokens}
+ <button
+ type="button"
+ id={triggerId}
+ ref={triggerRef}
+ autoFocus={hasAutoFocus}
+ onClick={openManager}
+ disabled={isDisabled && !showsDisabledMessage}
+ aria-disabled={isDisabled ? true : undefined}
+ aria-haspopup="dialog"
+ aria-expanded={step != null}
+ aria-describedby={triggerDescribedBy}
+ {...stylex.props(
+ styles.trigger,
+ filters.length > 0 && styles.triggerWithTokens,
+ )}>
+ {filters.length === 0 ? fieldPlaceholder : null}
+ </button>
+ </div>
+ {(endContent || isRenderable(resultCountText)) && (
+ <div {...stylex.props(styles.endSection)}>
+ {isRenderable(resultCountText) && (
+ <span {...stylex.props(styles.resultCount)}>
+ {resultCountText}
+ </span>
+ )}
+ {endContent}
+ </div>
+ )}
+ </div>
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </Field>
+
+ <BottomSheetSwitcher
+ activeSheet={step}
+ onActiveSheetChange={handleActiveSheetChange}>
+ <BottomSheet sheetId="manage" label="Filters" height="tall" padding={0}>
+ <div {...stylex.props(styles.sheet)}>
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.headerRow)}>
+ <div {...stylex.props(styles.headerText)}>
+ <Heading level={3}>Filters</Heading>
+ </div>
+ {isInteractive && (
+ <Button
+ ref={managerAddButtonRef}
+ label="Add filter"
+ variant="ghost"
+ xstyle={styles.touchAction}
+ onClick={openFieldList}
+ />
+ )}
+ </div>
+ </div>
+ <div {...bodyProps}>
+ {filterRows.length === 0 ? (
+ <div {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ No filters selected
+ </Text>
+ </div>
+ ) : (
+ <List hasDividers density="spacious" edge="bleed">
+ {filterRows.map(row => {
+ const canEdit = isInteractive && !row.filter.isReadOnly;
+ return (
+ <ListItem
+ key={row.key}
+ ref={node => {
+ if (node == null) {
+ managerRowsRef.current.delete(row.index);
+ } else {
+ managerRowsRef.current.set(row.index, node);
+ }
+ }}
+ label={row.displayLabel}
+ onClick={
+ canEdit
+ ? () => handleFilterEdit(row.index)
+ : undefined
+ }
+ endContent={
+ canEdit ? (
+ <Icon
+ icon="chevronRight"
+ size="sm"
+ color="secondary"
+ xstyle={rtlStyles.mirror}
+ />
+ ) : undefined
+ }
+ />
+ );
+ })}
+ </List>
+ )}
+ </div>
+ <div {...stylex.props(styles.footer)}>
+ {isClearAllShown && (
+ <Button
+ label="Clear all"
+ variant="ghost"
+ xstyle={styles.touchAction}
+ onClick={handleClearAll}
+ />
+ )}
+ <div
+ {...stylex.props(
+ styles.footerActions,
+ !isClearAllShown && styles.footerSoleAction,
+ )}>
+ <Button
+ label="Done"
+ variant="primary"
+ xstyle={styles.touchAction}
+ onClick={closeSheet}
+ width={isClearAllShown ? undefined : '100%'}
+ />
+ </div>
+ </div>
+ </div>
+ </BottomSheet>
+
+ <BottomSheet
+ sheetId="fields"
+ label="Add filter"
+ height="tall"
+ padding={0}>
+ <div {...stylex.props(styles.sheet)}>
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.headerRow)}>
+ <Button
+ label="Back"
+ icon={
+ <Icon
+ icon="chevronLeft"
+ size="sm"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ isIconOnly
+ variant="ghost"
+ size="sm"
+ xstyle={styles.touchIconAction}
+ onClick={() => {
+ if (fieldPickerOriginRef.current === 'trigger') {
+ closeSheet();
+ return;
+ }
+ queueManagerAddFocus();
+ setStep('manage');
+ }}
+ />
+ <div {...stylex.props(styles.headerText)}>
+ <Heading level={3}>Add filter</Heading>
+ </div>
+ </div>
+ {hasContentSearch ? (
+ <div ref={contentSearchRef}>
+ <TextInput
+ label="Search"
+ isLabelHidden
+ role="searchbox"
+ aria-controls={contentResultsId}
+ value={contentQuery}
+ onChange={setContentQuery}
+ onKeyDown={event => {
+ if (isImeKeyEvent(event.nativeEvent)) {
+ return;
+ }
+ if (event.key === 'Enter' && contentResults[0] != null) {
+ event.preventDefault();
+ handleContentSuggestionSelect(contentResults[0]);
+ return;
+ }
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ contentSuggestionListRef.current
+ ?.querySelector<HTMLButtonElement>('button')
+ ?.focus();
+ }
+ }}
+ placeholder={contentSearchPlaceholder}
+ hasClear
+ startIcon={
+ <Icon icon="search" size="sm" color="secondary" />
+ }
+ isDisabled={!isInteractive}
+ width="100%"
+ />
+ </div>
+ ) : isFieldSearchShown ? (
+ <TextInput
+ label="Search filters"
+ isLabelHidden
+ placeholder="Search filters…"
+ value={fieldQuery}
+ onChange={setFieldQuery}
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
+ isDisabled={!isInteractive}
+ width="100%"
+ />
+ ) : null}
+ </div>
+ <div {...bodyProps}>
+ {hasContentSearch ? (
+ contentResults.length > 0 ? (
+ <List
+ ref={contentSuggestionListRef}
+ id={contentResultsId}
+ aria-label="Search results"
+ hasDividers
+ density="spacious"
+ edge="bleed">
+ {contentResults.map((item, index) => (
+ <ListItem
+ key={item.id}
+ label={item.label}
+ isDisabled={!isInteractive}
+ onClick={() => handleContentSuggestionSelect(item)}
+ onKeyDown={event => {
+ if (
+ isImeKeyEvent(event.nativeEvent) ||
+ (event.key !== 'ArrowDown' &&
+ event.key !== 'ArrowUp')
+ ) {
+ return;
+ }
+ event.preventDefault();
+ const buttons = [
+ ...(contentSuggestionListRef.current?.querySelectorAll<HTMLButtonElement>(
+ 'button',
+ ) ?? []),
+ ];
+ const nextIndex =
+ event.key === 'ArrowDown'
+ ? Math.min(index + 1, buttons.length - 1)
+ : index - 1;
+ if (nextIndex < 0) {
+ contentSearchRef.current
+ ?.querySelector<HTMLInputElement>('input')
+ ?.focus();
+ } else {
+ buttons[nextIndex]?.focus();
+ }
+ }}
+ />
+ ))}
+ </List>
+ ) : (
+ contentQuery.trim() !== '' && (
+ <div {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ No results found
+ </Text>
+ </div>
+ )
+ )
+ ) : groupedFields.length === 0 ? (
+ <div {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ No filters match your search
+ </Text>
+ </div>
+ ) : (
+ groupedFields.map(([group, groupFields]) => (
+ <List
+ key={group}
+ hasDividers
+ density="spacious"
+ header={group === '' ? undefined : group}
+ edge="bleed">
+ {groupFields.map(field => (
+ <ListItem
+ key={field.key}
+ ref={node => {
+ if (node == null) {
+ fieldRowsRef.current.delete(field.key);
+ } else {
+ fieldRowsRef.current.set(field.key, node);
+ }
+ }}
+ label={field.label}
+ isDisabled={!isInteractive}
+ startContent={field.icon}
+ endContent={
+ <Icon
+ icon="chevronRight"
+ size="sm"
+ color="secondary"
+ xstyle={rtlStyles.mirror}
+ />
+ }
+ onClick={() => handleFieldSelect(field)}
+ />
+ ))}
+ </List>
+ ))
+ )}
+ </div>
+ </div>
+ </BottomSheet>
+
+ <BottomSheet
+ sheetId="value"
+ label={editorTitle}
+ height="tall"
+ padding={0}
+ purpose="form">
+ <div {...stylex.props(styles.sheet)}>
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.headerRow)}>
+ <div {...stylex.props(styles.headerText)}>
+ <Heading level={3} maxLines={1}>
+ {editorTitle}
+ </Heading>
+ </div>
+ </div>
+ </div>
+ {isDraftRenderable && EditorOverride != null ? (
+ <div {...bodyProps}>
+ <EditorOverride
+ key={`${draft.mode}-${draft.filterIndex ?? 'new'}-${draft.field}`}
+ config={configProp}
+ filter={{
+ field: draft.field,
+ operator: draft.operator,
+ value: draft.value,
+ }}
+ mode={draft.mode}
+ onSave={saved => {
+ if (saved == null) {
+ if (draft.mode === 'edit') {
+ handleRemove();
+ } else {
+ queueManagerAddFocus();
+ setStep('manage');
+ }
+ return;
+ }
+ commitSavedFilter(draft, saved);
+ }}
+ onCancel={returnFromValue}
+ saveButtonLabel={saveButtonLabel}
+ isReadOnly={isEditorDisabled}
+ timezoneID={timezoneID}
+ />
+ </div>
+ ) : (
+ <>
+ <div {...bodyProps}>
+ {isDraftRenderable ? (
+ <>
+ {draftOperators.length > 1 && (
+ <RadioList
+ label="Operator"
+ isLabelHidden
+ value={draft.operator ?? ''}
+ onChange={operatorKey => {
+ const operator = draftOperators.find(
+ candidate => candidate.key === operatorKey,
+ );
+ if (operator != null) {
+ handleOperatorSelect(operator);
+ }
+ }}
+ isDisabled={isEditorDisabled}>
+ {draftOperators.map(operator => (
+ <RadioListItem
+ key={operator.key}
+ label={`${draftField.label} ${resolveOperatorLabel(operator, t)}`}
+ value={operator.key}
+ />
+ ))}
+ </RadioList>
+ )}
+ <MobilePowerSearchValueEditor
+ key={`${draft.field}-${draft.operator}`}
+ operatorValue={draftOperator.value}
+ filterValue={draft.value}
+ onChange={handleDraftValueChange}
+ isDisabled={isEditorDisabled}
+ maxMenuItems={maxOperatorMenuItems}
+ timezoneID={timezoneID}
+ />
+ </>
+ ) : (
+ // A controlled config update removed the field or operator
+ // being edited: say so and keep a way out.
+ draft != null && (
+ <div {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ This filter is no longer available
+ </Text>
+ </div>
+ )
+ )}
+ </div>
+ <div {...stylex.props(styles.footer)}>
+ {draft?.mode === 'edit' && !isReadOnly && (
+ <Button
+ label="Remove"
+ variant="ghost"
+ isDisabled={isEditorDisabled}
+ xstyle={styles.touchAction}
+ onClick={handleRemove}
+ />
+ )}
+ <div
+ {...stylex.props(
+ styles.footerActions,
+ isReadOnly && styles.footerSoleAction,
+ )}>
+ <Button
+ label="Cancel"
+ variant="ghost"
+ xstyle={styles.touchAction}
+ onClick={returnFromValue}
+ width={isReadOnly ? '100%' : undefined}
+ />
+ {!isReadOnly && isDraftRenderable && (
+ <Button
+ label={saveButtonLabel}
+ variant="primary"
+ isDisabled={isSaveDisabled}
+ xstyle={styles.touchAction}
+ onClick={handleSave}
+ />
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ </BottomSheet>
+ </BottomSheetSwitcher>
+ </>
+ );
+}
+
+MobilePowerSearch.displayName = 'MobilePowerSearch';
diff --git a/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsx b/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsx
new file mode 100644
index 0000000000..5069f83a33
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/MobilePowerSearchValueEditor.tsx
@@ -0,0 +1,584 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file MobilePowerSearchValueEditor.tsx
+ * @input OperatorValue, staged FilterValue, onChange, timezoneID; public
+ * @astryxdesign/core inputs only (DateInput, DateRangeInput, DateTimeInput,
+ * Icon, List, NumberInput, TextInput, TimeInput, Tokenizer, Typeahead,
+ * VisuallyHidden)
+ * @output Sheet-native value editor for MobilePowerSearch: enum, enum_list and
+ * date_relative as full-row List choices with trailing checks; every other
+ * non-nested value type as the matching public input
+ * @position Lab sub-component consumed by MobilePowerSearch.tsx
+ *
+ * Core's PowerSearchValueEditor is private, so this file rebuilds each
+ * editor from public inputs. Closed vocabularies (enum, enum_list,
+ * date_relative) are rendered as rows instead of a Selector or Tokenizer,
+ * because a dropdown layer inside a sheet stacks a second overlay on a surface
+ * the user is already inside. Every editor stages its value; the sheet footer
+ * confirms it.
+ */
+
+import React, {useCallback, useMemo, type FormEvent} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {DateInput} from '@astryxdesign/core/DateInput';
+import {
+ DateRangeInput,
+ type DateRange,
+} from '@astryxdesign/core/DateRangeInput';
+import {DateTimeInput} from '@astryxdesign/core/DateTimeInput';
+import {Icon} from '@astryxdesign/core/Icon';
+import {List, ListItem} from '@astryxdesign/core/List';
+import {NumberInput} from '@astryxdesign/core/NumberInput';
+import type {
+ DateTimeRangePart,
+ FilterValue,
+ OperatorValue,
+ PowerSearchEntity,
+} from '@astryxdesign/core/PowerSearch';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {TimeInput} from '@astryxdesign/core/TimeInput';
+import {Tokenizer} from '@astryxdesign/core/Tokenizer';
+import {Typeahead} from '@astryxdesign/core/Typeahead';
+import type {SearchableItem, SearchSource} from '@astryxdesign/core/Typeahead';
+import type {ISODateString, ISOTimeString} from '@astryxdesign/core/utils';
+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';
+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
+import {
+ isoDateTimeToUnixSeconds,
+ isoDateToUnixSeconds,
+ unixSecondsToISODate,
+ unixSecondsToISODateTime,
+} from './mobilePowerSearchUtils';
+
+const styles = stylex.create({
+ input: {
+ paddingBlockStart: spacingVars['--spacing-1'],
+ },
+});
+
+export interface MobilePowerSearchValueEditorProps {
+ operatorValue: OperatorValue;
+ filterValue: FilterValue | undefined;
+ /** Stage a value without leaving the sheet. */
+ onChange: (value: FilterValue) => void;
+ isDisabled?: boolean;
+ /** Max suggestions in string and entity value typeaheads. */
+ maxMenuItems?: number;
+ timezoneID?: string;
+}
+
+const EMPTY_SOURCE: SearchSource<SearchableItem> = {
+ search: () => [],
+ bootstrap: () => [],
+};
+
+// =============================================================================
+// Choice rows (enum, enum_list, date_relative)
+// =============================================================================
+
+interface ChoiceItem {
+ readonly value: string;
+ readonly label: string;
+ readonly icon?: React.ReactNode;
+}
+
+function ChoiceRows({
+ items,
+ selected,
+ isDisabled,
+ onToggle,
+}: {
+ items: ReadonlyArray<ChoiceItem>;
+ selected: ReadonlySet<string>;
+ isDisabled?: boolean;
+ onToggle: (value: string, isSelected: boolean) => void;
+}) {
+ // The sheet body publishes its inline padding as container padding, so
+ // `bleed` runs the rows edge to edge (a tap anywhere across the sheet width
+ // lands on the row) while choice text keeps the body's inset and lines up
+ // with the sheet title and the operator radios.
+ return (
+ <List hasDividers density="spacious" edge="bleed">
+ {items.map(item => {
+ const isSelected = selected.has(item.value);
+ return (
+ <ListItem
+ key={item.value}
+ label={
+ isSelected ? (
+ <>
+ <span aria-hidden="true">{item.label}</span>
+ <VisuallyHidden>{`${item.label}, selected`}</VisuallyHidden>
+ </>
+ ) : (
+ item.label
+ )
+ }
+ startContent={item.icon}
+ isSelected={isSelected}
+ isDisabled={isDisabled}
+ endContent={
+ isSelected ? (
+ <Icon icon="check" size="sm" color="accent" />
+ ) : undefined
+ }
+ onClick={() => onToggle(item.value, isSelected)}
+ />
+ );
+ })}
+ </List>
+ );
+}
+
+function relativeDateChoices(
+ operatorValue: OperatorValue & {type: 'date_relative'},
+): ChoiceItem[] {
+ const result: ChoiceItem[] = [];
+ const units = [
+ {unit: 'day', plural: 'days', amounts: [1, 3, 7, 14, 30]},
+ {unit: 'week', plural: 'weeks', amounts: [1, 2, 4]},
+ {unit: 'month', plural: 'months', amounts: [1, 3, 6, 12]},
+ ];
+ for (const {unit, plural, amounts} of units) {
+ for (const amount of amounts) {
+ const noun = amount === 1 ? unit : plural;
+ if (operatorValue.isPastAllowed !== false) {
+ result.push({
+ value: `${amount}${unit[0]}_ago`,
+ label: `${amount} ${noun} ago`,
+ });
+ }
+ if (operatorValue.isFutureAllowed !== false) {
+ result.push({
+ value: `${amount}${unit[0]}_from_now`,
+ label: `${amount} ${noun} from now`,
+ });
+ }
+ }
+ }
+ return result;
+}
+
+// =============================================================================
+// Dates
+// =============================================================================
+
+const SECONDS_BY_UNIT = {
+ second: 1,
+ minute: 60,
+ hour: 3600,
+ day: 86400,
+ week: 604800,
+ month: 2592000,
+ year: 31536000,
+} as const;
+
+function resolveRangePart(part: DateTimeRangePart, nowSeconds: number): number {
+ switch (part.type) {
+ case 'NOW':
+ return Math.floor(nowSeconds);
+ case 'ABSOLUTE':
+ return part.unixSeconds;
+ case 'RELATIVE':
+ return Math.floor(
+ nowSeconds - part.backValue * SECONDS_BY_UNIT[part.unit],
+ );
+ }
+}
+
+// =============================================================================
+// Editor
+// =============================================================================
+
+/**
+ * Renders the value control for one filter inside the sheet editor.
+ */
+export function MobilePowerSearchValueEditor({
+ operatorValue,
+ filterValue,
+ onChange,
+ isDisabled = false,
+ maxMenuItems,
+ timezoneID,
+}: MobilePowerSearchValueEditorProps) {
+ const selectedValues = useMemo<ReadonlySet<string>>(() => {
+ if (filterValue?.type === 'enum' || filterValue?.type === 'date_relative') {
+ return new Set([filterValue.value]);
+ }
+ if (filterValue?.type === 'enum_list') {
+ return new Set(filterValue.value);
+ }
+ return new Set();
+ }, [filterValue]);
+
+ const handleNumberInput = useCallback(
+ (event: FormEvent<HTMLElement>) => {
+ // NumberInput commits on blur or Enter. Staging the raw text as it is
+ // typed lets the footer action enable while the user is still in the
+ // field; the committed value replaces it when the input blurs.
+ if (operatorValue.type !== 'integer' && operatorValue.type !== 'float') {
+ return;
+ }
+ const raw = (event.currentTarget as HTMLInputElement).value.trim();
+ if (raw === '') {
+ return;
+ }
+ const parsed = Number(raw.replace(/,/g, ''));
+ if (!Number.isFinite(parsed)) {
+ return;
+ }
+ if (operatorValue.type === 'integer') {
+ if (Number.isInteger(parsed)) {
+ onChange({type: 'integer', value: parsed});
+ }
+ return;
+ }
+ onChange({type: 'float', value: parsed});
+ },
+ [onChange, operatorValue.type],
+ );
+
+ switch (operatorValue.type) {
+ case 'empty':
+ case 'nested':
+ return null;
+
+ case 'string': {
+ const current = filterValue?.type === 'string' ? filterValue.value : '';
+ if (operatorValue.searchSource) {
+ return (
+ <div {...stylex.props(styles.input)}>
+ <Typeahead
+ label="Value"
+ isLabelHidden
+ searchSource={operatorValue.searchSource}
+ value={current ? {id: current, label: current} : null}
+ onChange={item =>
+ onChange({type: 'string', value: item?.label ?? ''})
+ }
+ placeholder="Search..."
+ debounceMs={150}
+ maxMenuItems={maxMenuItems}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+ return (
+ <div {...stylex.props(styles.input)}>
+ <TextInput
+ label="Value"
+ isLabelHidden
+ value={current}
+ placeholder="Enter a value"
+ onChange={value => onChange({type: 'string', value})}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'string_list': {
+ const current: SearchableItem[] =
+ filterValue?.type === 'string_list'
+ ? filterValue.value.map(v => ({id: v, label: v}))
+ : [];
+ const hasCreate =
+ operatorValue.isArbitraryStringAllowed || !operatorValue.searchSource;
+ return (
+ <div {...stylex.props(styles.input)}>
+ <Tokenizer
+ label="Values"
+ isLabelHidden
+ searchSource={operatorValue.searchSource ?? EMPTY_SOURCE}
+ value={current}
+ onChange={items =>
+ onChange({
+ type: 'string_list',
+ value: items.map(item => item.label),
+ })
+ }
+ placeholder="Add values..."
+ debounceMs={operatorValue.searchSource ? 150 : 0}
+ hasCreate={hasCreate}
+ maxMenuItems={maxMenuItems}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'integer':
+ case 'float': {
+ const current =
+ filterValue?.type === operatorValue.type ? filterValue.value : null;
+ return (
+ <div {...stylex.props(styles.input)}>
+ <NumberInput
+ label="Value"
+ isLabelHidden
+ value={current}
+ onChange={value =>
+ onChange(
+ operatorValue.type === 'integer'
+ ? {type: 'integer', value}
+ : {type: 'float', value},
+ )
+ }
+ onInput={handleNumberInput}
+ min={operatorValue.minValue}
+ max={operatorValue.maxValue}
+ units={operatorValue.units}
+ isIntegerOnly={operatorValue.type === 'integer'}
+ placeholder="Enter a number"
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'time': {
+ const current =
+ filterValue?.type === 'time'
+ ? (filterValue.value as ISOTimeString)
+ : undefined;
+ return (
+ <div {...stylex.props(styles.input)}>
+ <TimeInput
+ label="Time"
+ isLabelHidden
+ value={current}
+ onChange={value => {
+ if (value != null) {
+ onChange({type: 'time', value});
+ }
+ }}
+ min={operatorValue.minValue as ISOTimeString | undefined}
+ max={operatorValue.maxValue as ISOTimeString | undefined}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'date_absolute': {
+ const unixSeconds =
+ filterValue?.type === 'date_absolute'
+ ? filterValue.unixSeconds
+ : undefined;
+ if (operatorValue.isDateOnly === false) {
+ return (
+ <div {...stylex.props(styles.input)}>
+ <DateTimeInput
+ label="Date and time"
+ isLabelHidden
+ value={
+ unixSeconds == null
+ ? undefined
+ : unixSecondsToISODateTime(unixSeconds, timezoneID)
+ }
+ onChange={value => {
+ if (value != null) {
+ onChange({
+ type: 'date_absolute',
+ unixSeconds: isoDateTimeToUnixSeconds(value, timezoneID),
+ });
+ }
+ }}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+ return (
+ <div {...stylex.props(styles.input)}>
+ <DateInput
+ label="Date"
+ isLabelHidden
+ value={
+ unixSeconds == null
+ ? undefined
+ : unixSecondsToISODate(unixSeconds, timezoneID)
+ }
+ onChange={value => {
+ if (value != null) {
+ onChange({
+ type: 'date_absolute',
+ unixSeconds: isoDateToUnixSeconds(value, timezoneID),
+ });
+ }
+ }}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'date_relative':
+ return (
+ <ChoiceRows
+ items={relativeDateChoices(operatorValue)}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ onToggle={value => onChange({type: 'date_relative', value})}
+ />
+ );
+
+ case 'date_range': {
+ let current: DateRange | null = null;
+ if (filterValue?.type === 'date_range') {
+ const nowSeconds = Date.now() / 1000;
+ current = {
+ start: unixSecondsToISODate(
+ resolveRangePart(filterValue.value.start, nowSeconds),
+ timezoneID,
+ ),
+ end: unixSecondsToISODate(
+ resolveRangePart(filterValue.value.end, nowSeconds),
+ timezoneID,
+ ),
+ };
+ }
+ return (
+ <div {...stylex.props(styles.input)}>
+ <DateRangeInput
+ label="Date range"
+ isLabelHidden
+ value={current}
+ onChange={range => {
+ if (range == null) {
+ return;
+ }
+ onChange({
+ type: 'date_range',
+ value: {
+ start: {
+ type: 'ABSOLUTE',
+ unixSeconds: isoDateToUnixSeconds(
+ range.start as ISODateString,
+ timezoneID,
+ ),
+ },
+ end: {
+ type: 'ABSOLUTE',
+ unixSeconds: isoDateToUnixSeconds(
+ range.end as ISODateString,
+ timezoneID,
+ ),
+ },
+ },
+ });
+ }}
+ hasClear={false}
+ numberOfMonths={1}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'enum':
+ return (
+ <ChoiceRows
+ items={operatorValue.values}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ onToggle={value => onChange({type: 'enum', value})}
+ />
+ );
+
+ case 'enum_list':
+ return (
+ <ChoiceRows
+ items={operatorValue.values}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ onToggle={(value, isSelected) => {
+ const existing =
+ filterValue?.type === 'enum_list' ? filterValue.value : [];
+ onChange({
+ type: 'enum_list',
+ value: isSelected
+ ? existing.filter(v => v !== value)
+ : [...existing, value],
+ });
+ }}
+ />
+ );
+
+ case 'entity_list': {
+ const current: SearchableItem[] =
+ filterValue?.type === 'entity_list'
+ ? filterValue.value.map((entity: PowerSearchEntity) => ({
+ id: entity.id,
+ label: entity.label,
+ auxiliaryData: entity.photo ? {photo: entity.photo} : undefined,
+ }))
+ : [];
+ return (
+ <div {...stylex.props(styles.input)}>
+ <Tokenizer
+ label="Entities"
+ isLabelHidden
+ searchSource={operatorValue.searchSource ?? EMPTY_SOURCE}
+ value={current}
+ onChange={items =>
+ onChange({
+ type: 'entity_list',
+ value: items.map(item => {
+ const aux = item.auxiliaryData as
+ {photo?: string} | undefined;
+ return {
+ id: item.id,
+ label: item.label,
+ ...(aux?.photo ? {photo: aux.photo} : {}),
+ };
+ }),
+ })
+ }
+ renderItem={operatorValue.renderItem}
+ placeholder="Search..."
+ debounceMs={operatorValue.searchSource ? 150 : 0}
+ maxMenuItems={maxMenuItems}
+ isDisabled={isDisabled}
+ width="100%"
+ />
+ </div>
+ );
+ }
+
+ case 'custom': {
+ const EditorComponent = operatorValue.Editor;
+ return (
+ <div {...stylex.props(styles.input)}>
+ <EditorComponent
+ isDisabled={isDisabled}
+ onChange={value => {
+ if (value != null) {
+ onChange({type: 'custom', value});
+ }
+ }}
+ placeholder="Enter a value"
+ value={filterValue?.type === 'custom' ? filterValue.value : null}
+ />
+ </div>
+ );
+ }
+
+ default:
+ return null;
+ }
+}
+
+MobilePowerSearchValueEditor.displayName = 'MobilePowerSearchValueEditor';
diff --git a/packages/lab/src/MobilePowerSearch/index.ts b/packages/lab/src/MobilePowerSearch/index.ts
new file mode 100644
index 0000000000..3e95ffc1c9
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/index.ts
@@ -0,0 +1,13 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file index.ts
+ * @input MobilePowerSearch component
+ * @output Public MobilePowerSearch entry point for @astryxdesign/lab
+ * @position Component barrel; re-exported by /packages/lab/src/index.ts
+ */
+
+export {MobilePowerSearch} from './MobilePowerSearch';
+export type {MobilePowerSearchProps} from './MobilePowerSearch';
diff --git a/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts b/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts
new file mode 100644
index 0000000000..2bb07bacc4
--- /dev/null
+++ b/packages/lab/src/MobilePowerSearch/mobilePowerSearchUtils.ts
@@ -0,0 +1,524 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file mobilePowerSearchUtils.ts
+ * @input Public @astryxdesign/core PowerSearch config/filter types, i18n
+ * translator, Typeahead SearchableItem, plain-date utilities
+ * @output Pure helpers for MobilePowerSearch: a local InternalConfig adapter
+ * (Core's useInternalConfig is private), the content-search suggestion
+ * source, filter identity tracking across controlled re-renders, nested
+ * operator exclusion, field matching, and timezone-aware date conversion
+ * @position Lab helper module; consumed by MobilePowerSearch.tsx and
+ * MobilePowerSearchValueEditor.tsx
+ */
+
+import {useMemo} from 'react';
+import type {
+ FilterValue,
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchFilter,
+ PowerSearchOperator,
+} from '@astryxdesign/core/PowerSearch';
+import {resolveOperatorLabel} from '@astryxdesign/core/PowerSearch';
+import type {InternalConfig} from '@astryxdesign/core/PowerSearch/utils';
+import type {TranslatorFn} from '@astryxdesign/core/i18n';
+import type {SearchableItem} from '@astryxdesign/core/Typeahead';
+import type {ISODateTimeString} from '@astryxdesign/core/DateTimeInput';
+import type {ISODateString} from '@astryxdesign/core/utils';
+import {
+ groupItems,
+ plainDateFromDate,
+ plainDateFromInstant,
+ plainDateFromISO,
+ plainDateToDate,
+ plainDateToInstant,
+ plainDateToISO,
+} from '@astryxdesign/core/utils';
+
+// =============================================================================
+// Config adapter
+// =============================================================================
+
+/**
+ * Builds the `InternalConfig` shape that `formatFilterValue` and the rest of
+ * the public PowerSearch utilities take. Core's `useInternalConfig` is private
+ * to the package, so Lab carries this equivalent.
+ */
+export function createMobilePowerSearchConfig(
+ config: PowerSearchConfig,
+): InternalConfig {
+ const fieldMap = new Map<string, PowerSearchField>();
+ const operatorMap = new Map<string, Map<string, PowerSearchOperator>>();
+ for (const field of config.fields) {
+ fieldMap.set(field.key, field);
+ const opMap = new Map<string, PowerSearchOperator>();
+ for (const op of field.operators) {
+ opMap.set(op.key, op);
+ }
+ operatorMap.set(field.key, opMap);
+ }
+ return {
+ config,
+ getField(key) {
+ return fieldMap.get(key);
+ },
+ getOperator(fieldKey, operatorKey) {
+ return operatorMap.get(fieldKey)?.get(operatorKey);
+ },
+ getDefaultOperator(fieldKey) {
+ const field = fieldMap.get(fieldKey);
+ if (!field) {
+ return undefined;
+ }
+ if (field.defaultOperator) {
+ return operatorMap.get(fieldKey)?.get(field.defaultOperator);
+ }
+ return field.operators[0];
+ },
+ getVisibleFields() {
+ return config.fields;
+ },
+ getVisibleOperators(fieldKey) {
+ return fieldMap.get(fieldKey)?.operators ?? [];
+ },
+ };
+}
+
+export function useMobilePowerSearchConfig(
+ config: PowerSearchConfig,
+): InternalConfig {
+ return useMemo(() => createMobilePowerSearchConfig(config), [config]);
+}
+
+// =============================================================================
+// Operators and fields
+// =============================================================================
+
+/**
+ * Operators the sheet editor can render. Nested filter groups have no touch
+ * editor yet: offering the field and then showing a blank sheet is worse than
+ * leaving it out, so fields whose every operator is nested are dropped (with a
+ * development warning).
+ */
+export function isSupportedOperator(operator: PowerSearchOperator): boolean {
+ return operator.value.type !== 'nested';
+}
+
+export function fieldMatchesQuery(
+ field: PowerSearchField,
+ normalizedQuery: string,
+): boolean {
+ if (normalizedQuery === '') {
+ return true;
+ }
+ if (field.label.toLowerCase().includes(normalizedQuery)) {
+ return true;
+ }
+ return (
+ field.typeaheadAliases?.some(alias =>
+ alias.toLowerCase().includes(normalizedQuery),
+ ) ?? false
+ );
+}
+
+// =============================================================================
+// Filter identity across controlled updates
+// =============================================================================
+
+function stableSerialize(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(stableSerialize).join(',')}]`;
+ }
+ if (value != null && typeof value === 'object') {
+ return `{${Object.entries(value)
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableSerialize(entry)}`)
+ .join(',')}}`;
+ }
+ return JSON.stringify(value) ?? 'undefined';
+}
+
+/** Structural snapshot of a filter, for parents that clone their values. */
+export function filterSignature(filter: PowerSearchFilter): string {
+ return stableSerialize({
+ field: filter.field,
+ operator: filter.operator,
+ value: filter.value,
+ isReadOnly: filter.isReadOnly ?? false,
+ });
+}
+
+/**
+ * Finds the filter a draft was opened on after the controlled parent may have
+ * reordered, cloned, or removed it: object identity first, then the original
+ * slot when it still holds a structurally equal filter, then a unique
+ * structural match anywhere. Returns null when the target is gone or
+ * ambiguous, so an edit never lands on a different filter.
+ */
+export function resolveFilterIdentityIndex(
+ filters: ReadonlyArray<PowerSearchFilter>,
+ sourceFilter: PowerSearchFilter,
+ sourceSignature: string,
+ preferredIndex: number,
+): number | null {
+ const identityIndex = filters.indexOf(sourceFilter);
+ if (identityIndex >= 0) {
+ return identityIndex;
+ }
+ if (
+ filters[preferredIndex] != null &&
+ filterSignature(filters[preferredIndex]) === sourceSignature
+ ) {
+ return preferredIndex;
+ }
+ const matchingIndices = filters.flatMap((filter, index) =>
+ filterSignature(filter) === sourceSignature ? [index] : [],
+ );
+ return matchingIndices.length === 1 ? matchingIndices[0] : null;
+}
+
+/**
+ * After removing the filter at `removedIndex`, the editable row focus should
+ * land on: the nearest remaining editable filter, preferring the one after.
+ */
+export function nearestEditableIndex(
+ nextFilters: ReadonlyArray<PowerSearchFilter>,
+ removedIndex: number,
+): number | undefined {
+ const editableIndices = nextFilters.flatMap((candidate, candidateIndex) =>
+ candidate.isReadOnly ? [] : [candidateIndex],
+ );
+ return editableIndices.reduce<number | undefined>((nearest, candidate) => {
+ if (nearest == null) {
+ return candidate;
+ }
+ const candidateDistance = Math.abs(candidate - removedIndex);
+ const nearestDistance = Math.abs(nearest - removedIndex);
+ if (candidateDistance < nearestDistance) {
+ return candidate;
+ }
+ if (
+ candidateDistance === nearestDistance &&
+ candidate >= removedIndex &&
+ nearest < removedIndex
+ ) {
+ return candidate;
+ }
+ return nearest;
+ }, undefined);
+}
+
+// =============================================================================
+// Content-search suggestions
+// =============================================================================
+
+export interface MobilePowerSearchAuxData {
+ readonly fieldKey: string;
+ readonly operatorKey?: string;
+ readonly filterValue?: FilterValue;
+ readonly group?: string;
+}
+
+export type MobilePowerSearchItem = SearchableItem<MobilePowerSearchAuxData>;
+
+/** Synchronous suggestion source; the sheet renders results inline. */
+export interface ContentSearchSource {
+ search(query: string): MobilePowerSearchItem[];
+ bootstrap(): MobilePowerSearchItem[];
+}
+
+interface ValueMatch {
+ displayValue: string;
+ filterValue: FilterValue;
+ quoted: boolean;
+}
+
+function resolveValueMatches(
+ op: PowerSearchOperator,
+ rawValue: string,
+): ValueMatch[] {
+ const opType = op.value.type;
+ if (opType === 'string') {
+ return [
+ {
+ displayValue: rawValue,
+ filterValue: {type: 'string', value: rawValue},
+ quoted: true,
+ },
+ ];
+ }
+ if (opType === 'string_list') {
+ return [
+ {
+ displayValue: rawValue,
+ filterValue: {type: 'string_list', value: [rawValue]},
+ quoted: true,
+ },
+ ];
+ }
+ if (opType === 'enum') {
+ const lower = rawValue.toLowerCase();
+ return op.value.values
+ .filter(item => item.label.toLowerCase().includes(lower))
+ .map(item => ({
+ displayValue: item.label,
+ filterValue: {type: 'enum' as const, value: item.value},
+ quoted: false,
+ }));
+ }
+ if (opType === 'enum_list') {
+ const lower = rawValue.toLowerCase();
+ return op.value.values
+ .filter(item => item.label.toLowerCase().includes(lower))
+ .map(item => ({
+ displayValue: item.label,
+ filterValue: {type: 'enum_list' as const, value: [item.value]},
+ quoted: false,
+ }));
+ }
+ return [];
+}
+
+/**
+ * The suggestion source behind Add filter's content search: field names,
+ * field + operator combinations, field + operator + value matches for string
+ * and enum operators, and a leading free-text `"query"` item for the
+ * configured content-search field. Mirrors Core PowerSearch's typeahead
+ * suggestions, which are private to Core; nested-only fields are excluded.
+ */
+export function createContentSearchSource(
+ config: InternalConfig,
+ t: TranslatorFn,
+ maxTypedResults: number,
+): ContentSearchSource {
+ const fields = config
+ .getVisibleFields()
+ .filter(field => field.operators.some(isSupportedOperator));
+ const opLabel = (op: PowerSearchOperator): string =>
+ resolveOperatorLabel(op, t);
+ const allItems: MobilePowerSearchItem[] = groupItems(
+ fields.map(field => ({
+ id: field.key,
+ label: field.label,
+ auxiliaryData: {
+ fieldKey: field.key,
+ operatorKey: config.getDefaultOperator(field.key)?.key,
+ group: field.group,
+ },
+ })),
+ {ungroupedFirst: true},
+ ).flatMap(group => group.items);
+
+ return {
+ search(query: string): MobilePowerSearchItem[] {
+ const lower = query.toLowerCase().trim();
+ if (lower === '') {
+ return allItems;
+ }
+ const results: MobilePowerSearchItem[] = [];
+ const seen = new Set<string>();
+
+ for (const field of fields) {
+ if (
+ field.typeaheadMinQueryLength != null &&
+ lower.length < field.typeaheadMinQueryLength
+ ) {
+ continue;
+ }
+ if (fieldMatchesQuery(field, lower) && !seen.has(field.key)) {
+ seen.add(field.key);
+ results.push({
+ id: field.key,
+ label: field.label,
+ auxiliaryData: {
+ fieldKey: field.key,
+ operatorKey: config.getDefaultOperator(field.key)?.key,
+ },
+ });
+ }
+ for (const op of field.operators.filter(isSupportedOperator)) {
+ const combinedLabel = `${field.label} ${opLabel(op)}`;
+ if (combinedLabel.toLowerCase().includes(lower)) {
+ const id = `${field.key}:${op.key}`;
+ if (!seen.has(id)) {
+ seen.add(id);
+ results.push({
+ id,
+ label: combinedLabel,
+ auxiliaryData: {fieldKey: field.key, operatorKey: op.key},
+ });
+ }
+ }
+ }
+ }
+
+ for (const field of fields) {
+ if (field.isValueMatchAllowed === false) {
+ continue;
+ }
+ const operators = field.operators.filter(isSupportedOperator);
+ const fieldLabel = field.label.toLowerCase();
+ const pushMatches = (op: PowerSearchOperator, rawValue: string) => {
+ const matches = resolveValueMatches(op, rawValue);
+ for (const match of matches) {
+ const id = `${field.key}:${op.key}:value:${match.displayValue}`;
+ if (!seen.has(id)) {
+ seen.add(id);
+ results.push({
+ id,
+ label: `${field.label} ${opLabel(op)} ${
+ match.quoted ? `"${match.displayValue}"` : match.displayValue
+ }`,
+ auxiliaryData: {
+ fieldKey: field.key,
+ operatorKey: op.key,
+ filterValue: match.filterValue,
+ },
+ });
+ }
+ }
+ return matches.length > 0;
+ };
+
+ let hasExactOperatorMatch = false;
+ for (const op of operators) {
+ const prefix = `${fieldLabel} ${opLabel(op).toLowerCase()} `;
+ if (lower.startsWith(prefix) && lower.length > prefix.length) {
+ if (pushMatches(op, query.slice(prefix.length))) {
+ hasExactOperatorMatch = true;
+ }
+ }
+ }
+
+ const fieldPrefix = `${fieldLabel} `;
+ if (
+ !hasExactOperatorMatch &&
+ lower.startsWith(fieldPrefix) &&
+ lower.length > fieldPrefix.length
+ ) {
+ const remainder = lower.slice(fieldPrefix.length);
+ const isOperatorPrefix = operators.some(op =>
+ opLabel(op).toLowerCase().startsWith(remainder),
+ );
+ if (!isOperatorPrefix) {
+ const rawValue = query.slice(fieldPrefix.length);
+ for (const op of operators) {
+ pushMatches(op, rawValue);
+ }
+ }
+ }
+ }
+
+ const contentFieldKey = config.config.contentSearchFieldKey;
+ const hasExactMatch = fields.some(
+ field =>
+ field.label.toLowerCase() === lower ||
+ field.operators.some(
+ op => `${field.label} ${opLabel(op)}`.toLowerCase() === lower,
+ ),
+ );
+ if (contentFieldKey != null && !hasExactMatch) {
+ const contentOp = config.getDefaultOperator(contentFieldKey);
+ if (
+ config.getField(contentFieldKey) != null &&
+ contentOp?.value.type === 'string'
+ ) {
+ results.unshift({
+ id: `__content_search__:${query}`,
+ label: `"${query}"`,
+ auxiliaryData: {
+ fieldKey: contentFieldKey,
+ operatorKey: contentOp.key,
+ filterValue: {type: 'string', value: query},
+ },
+ });
+ }
+ }
+
+ return results.slice(0, maxTypedResults);
+ },
+ bootstrap(): MobilePowerSearchItem[] {
+ return allItems;
+ },
+ };
+}
+
+// =============================================================================
+// Dates
+// =============================================================================
+
+/**
+ * The calendar date an instant falls on in `timezoneID`, or in the viewer's
+ * zone when none is configured. The same zone drives `formatFilterValue`, so
+ * the editor and the token agree on a boundary date.
+ */
+export function unixSecondsToISODate(
+ unixSeconds: number,
+ timezoneID: string | undefined,
+): ISODateString {
+ const instant = unixSeconds * 1000;
+ const plain =
+ timezoneID != null
+ ? plainDateFromInstant(instant, timezoneID)
+ : plainDateFromDate(new Date(instant));
+ return plainDateToISO(plain);
+}
+
+/** Wall-clock `YYYY-MM-DDTHH:mm` of an instant in `timezoneID` or the viewer's zone. */
+export function unixSecondsToISODateTime(
+ unixSeconds: number,
+ timezoneID: string | undefined,
+): ISODateTimeString {
+ const date = new Date(unixSeconds * 1000);
+ const parts = new Intl.DateTimeFormat('en-US', {
+ ...(timezoneID != null ? {timeZone: timezoneID} : {}),
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ hourCycle: 'h23',
+ calendar: 'gregory',
+ }).formatToParts(date);
+ const lookup = Object.fromEntries(
+ parts.filter(part => part.type !== 'literal').map(p => [p.type, p.value]),
+ );
+ return `${lookup.year}-${lookup.month}-${lookup.day}T${lookup.hour}:${lookup.minute}` as ISODateTimeString;
+}
+
+/** The instant a wall-clock `YYYY-MM-DDTHH:mm` names in `timezoneID` or the viewer's zone. */
+export function isoDateTimeToUnixSeconds(
+ value: ISODateTimeString,
+ timezoneID: string | undefined,
+): number {
+ const [datePart, timePart = '00:00'] = value.split('T');
+ const [hour, minute] = timePart.split(':').map(Number);
+ const plain = plainDateFromISO(datePart as ISODateString);
+ const instant =
+ timezoneID != null
+ ? plainDateToInstant(plain, timezoneID, hour, minute)
+ : new Date(
+ plain.year,
+ plain.month - 1,
+ plain.day,
+ hour,
+ minute,
+ ).getTime();
+ return Math.floor(instant / 1000);
+}
+
+/** Midnight at the start of `date` in `timezoneID` (or the viewer's zone). */
+export function isoDateToUnixSeconds(
+ date: ISODateString,
+ timezoneID: string | undefined,
+): number {
+ const plain = plainDateFromISO(date);
+ const instant =
+ timezoneID != null
+ ? plainDateToInstant(plain, timezoneID)
+ : plainDateToDate(plain).getTime();
+ return Math.floor(instant / 1000);
+}
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index fa9cd74ac3..4e6d9f0f7f 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -324,6 +324,15 @@ export {
type MobileTokenizerChange,
} from './MobileTokenizer';
+// MobilePowerSearch — Lab prototype (stack layer 1) of the touch PowerSearch
+// flow: field-wide "Manage filters" trigger with display-only tokens, a
+// Filters sheet, and a field → operator → value drill-down. The caller picks
+// it explicitly on touch layouts; the API mirrors Core PowerSearch.
+export {
+ MobilePowerSearch,
+ type MobilePowerSearchProps,
+} from './MobilePowerSearch';
+
// RichTextEditor (RFC facebook/astryx#3899) moved out of @astryxdesign/lab into
// its own package, @astryxdesign/richtext. Import it from there:
// import {RichTextEditor, RichTextView} from '@astryxdesign/richtext';