Skip to content

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

TypeScript

feat(core): PowerSearch touch sheet flow behind experimental.presentation (#8001)

Xinzi Zhou30160f5ceb9f
diff --git a/.changeset/powersearch-experimental-bottom-sheet.md b/.changeset/powersearch-experimental-bottom-sheet.md
new file mode 100644
index 0000000000..a1061040a0
--- /dev/null
+++ b/.changeset/powersearch-experimental-bottom-sheet.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[experimental] PowerSearch gains a touch surface behind `experimental={{presentation: 'bottom-sheet' | 'adaptive'}}`. `bottom-sheet` makes the whole field one trigger showing display-only filter tokens, and moves filter editing into a flow of tall modal sheets that stack: each step opens above the one that led to it, and dismissing a step reveals the one beneath, so no sheet has a Back action. A Filters sheet lists the active filters as rows that edit a filter, each with a trailing remove button, under a fixed header with Add filter and over a fixed footer with Clear all and Done; with no filter it shows one centered Add filter. Clear all asks for confirmation, removes the editable filters, keeps read-only ones, and leaves Filters open. An Add filter sheet lists the fields grouped (searchable from eight fields), or the content search with the field typeahead's suggestions listed inline, and leaves its search unfocused until tapped; a field whose only operator takes no value adds at once. A value step stages operator → value and confirms from its footer, the editor on the sheet's surface, or in muted sections beside the operator choice. Closed vocabularies are full-width rows, numbers stage as typed, and `string_list` / `entity_list` values edit through the Tokenizer's own sheet presentation titled with the field label. `adaptive` uses the sheet on compact coarse-pointer screens and the popover otherwise, resolved the same way Selector resolves it. The sheet flow loads on demand, so a PowerSearch that does not opt in does not carry it. New `@astryx.powersearch.sheet.*` catalog keys for the sheets' strings; no new theming target. Anything inside PowerSearch's `experimental` prop may change or be removed in a patch release; omitting it keeps the stable behavior.
+
+@imdreamrunner
diff --git a/apps/storybook/stories/PowerSearch.stories.tsx b/apps/storybook/stories/PowerSearch.stories.tsx
index 60c8ee7934..532afcfc12 100644
--- a/apps/storybook/stories/PowerSearch.stories.tsx
+++ b/apps/storybook/stories/PowerSearch.stories.tsx
@@ -452,8 +452,10 @@ const meta: Meta<typeof PowerSearch> = {
component: PowerSearch,
tags: ['autodocs'],
decorators: [
+ // A 600px column where there is room that shrinks with the viewport, so
+ // the stories, the touch presentations above all, fit a phone-sized canvas.
Story => (
- <div style={{width: 600}}>
+ <div style={{display: 'grid', gridTemplateColumns: 'minmax(0, 600px)'}}>
<Story />
</div>
),
@@ -2054,3 +2056,184 @@ export const StatusVariantComparison: Story = {
);
},
};
+
+// =============================================================================
+// Experimental bottom-sheet presentation
+// =============================================================================
+
+// The sheet flow is designed for a phone: view these stories at a compact
+// touch viewport (Storybook's mobile2 preset) to see the sheets as a person
+// would.
+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>
+ );
+}
+
+const sheetPresetFilters: 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},
+ },
+];
+
+/**
+ * `experimental={{presentation: 'bottom-sheet'}}`: the field is one trigger
+ * with display-only tokens; a tap opens the Filters sheet, whose rows edit or
+ * remove a filter, Add filter opens above it with the fields, and the value
+ * step opens above that and stages operator → value. Dismissing a step
+ * reveals the one beneath. Clear all asks first. List values (Assignee, Tags)
+ * open the Tokenizer's own sheet above the step.
+ */
+export const ExperimentalBottomSheet: Story = {
+ render: args => {
+ const [filters, setFilters] =
+ useState<ReadonlyArray<PowerSearchFilter>>(sheetPresetFilters);
+ return (
+ <PhoneFrame>
+ <PowerSearch
+ {...args}
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ // A count that follows the filters, so a commit from the flow (and
+ // Clear all) changes it and the flow announces the change.
+ resultCount={Math.max(1, Math.round(240 / (filters.length + 1)))}
+ timezoneID="America/Los_Angeles"
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <FilterDump filters={filters} />
+ </PhoneFrame>
+ );
+ },
+ name: 'Experimental: bottom sheet (forced)',
+ parameters: {viewport: {defaultViewport: 'mobile2'}},
+};
+
+/**
+ * `experimental={{presentation: 'adaptive'}}`: the sheet flow on a compact
+ * coarse-pointer screen, the tokenizer field and editor popover otherwise.
+ * Resize the viewport or switch the pointer emulation to see it switch.
+ */
+export const ExperimentalAdaptive: Story = {
+ render: args => {
+ const [filters, setFilters] =
+ useState<ReadonlyArray<PowerSearchFilter>>(sheetPresetFilters);
+ return (
+ <PhoneFrame>
+ <PowerSearch
+ {...args}
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ timezoneID="America/Los_Angeles"
+ experimental={{presentation: 'adaptive'}}
+ />
+ <FilterDump filters={filters} />
+ </PhoneFrame>
+ );
+ },
+ name: 'Experimental: adaptive',
+};
+
+/**
+ * With `contentSearchFieldKey`, Add filter carries the content search: the
+ * field typeahead's suggestions list inline under the search box, and a value
+ * suggestion commits a filter straight away.
+ */
+export const ExperimentalBottomSheetContentSearch: Story = {
+ render: args => {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>(
+ [],
+ );
+ return (
+ <PhoneFrame>
+ <PowerSearch
+ {...args}
+ config={contentSearchConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ placeholder="Search issues…"
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <FilterDump filters={filters} />
+ </PhoneFrame>
+ );
+ },
+ name: 'Experimental: bottom sheet with content search',
+ parameters: {viewport: {defaultViewport: 'mobile2'}},
+};
+
+/**
+ * Read-only keeps the Filters sheet as plain rows with Done only; disabled
+ * keeps the trigger focusable (aria-disabled) and shows its reason; the result
+ * count renders at the end of the field in both presentations.
+ */
+export const ExperimentalBottomSheetStates: Story = {
+ render: () => {
+ const [filters, setFilters] =
+ useState<ReadonlyArray<PowerSearchFilter>>(sheetPresetFilters);
+ return (
+ <PhoneFrame>
+ <div style={{display: 'flex', flexDirection: 'column', gap: 24}}>
+ <PowerSearch
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ label="Read-only filters"
+ isLabelHidden={false}
+ isReadOnly
+ resultCount={42}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <PowerSearch
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ label="Disabled filters"
+ isLabelHidden={false}
+ isDisabled
+ disabledMessage="Pick a project first"
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ <PowerSearch
+ config={fullConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ label="With a status"
+ isLabelHidden={false}
+ status={{type: 'error', message: 'Add at least one filter'}}
+ startIcon={MagnifyingGlassIcon}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </div>
+ </PhoneFrame>
+ );
+ },
+ name: 'Experimental: bottom sheet states',
+ parameters: {viewport: {defaultViewport: 'mobile2'}},
+};
diff --git a/docs/specs/components/PowerSearch/PowerSearch.spec.md b/docs/specs/components/PowerSearch/PowerSearch.spec.md
index ce5025b8cf..c10317e586 100644
--- a/docs/specs/components/PowerSearch/PowerSearch.spec.md
+++ b/docs/specs/components/PowerSearch/PowerSearch.spec.md
@@ -14,10 +14,11 @@ verified_by:
[
packages/core/src/PowerSearch/PowerSearch.test.tsx,
packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx,
+ packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx,
+ packages/core/src/PowerSearch/PowerSearch.ssr.test.tsx,
packages/core/src/Tokenizer/Tokenizer.test.tsx,
packages/core/src/Typeahead/Typeahead.test.tsx,
packages/core/src/Layer/useLayer.test.tsx,
- packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx,
scripts/check-knowledge.mjs,
]
modules: []
@@ -25,9 +26,12 @@ families: [family:overlay-dismissal]
design_specs: []
architecture:
[
+ architecture:component-style-authoring,
architecture:interaction-modality,
+ architecture:internationalization,
architecture:layer-runtime,
architecture:public-component-api,
+ architecture:react-component-runtime,
]
contributing: []
system_specs:
@@ -35,6 +39,8 @@ system_specs:
spec:AST-017/FR21,
spec:AST-017/FR27,
spec:AST-020/FR15,
+ spec:AST-055/FR3,
+ spec:AST-056/FR3,
spec:AST-085/FR1,
spec:AST-085/FR2,
spec:AST-085/FR4,
@@ -204,33 +210,33 @@ popover, rendered when `experimental` is omitted or resolves to `popover`. The
editor popover does not render in the `bottom-sheet` presentation, whose surface
FR10–FR21 govern.
-| ID | Invariant | Basis | Status |
-| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| FR1 | In the `popover` presentation, the filter-editor popover MUST have a rendered border-box width no greater than 720 CSS px. | Owner direction; legibility issue demonstrated by wide PowerSearch adopters | Accepted contract; implementation pending |
-| FR2 | In the `popover` presentation, before viewport collision handling, the editor's preferred width MUST be the outer PowerSearch width clamped to the inclusive 400–720 CSS px range. The 400 px floor MUST yield when the available viewport width cannot fit it. | Existing 400 px editing floor plus `component:PowerSearch/DEC-1` | Accepted contract; implementation pending |
-| FR3 | In the `popover` presentation, when the 720 CSS px cap does not make the editor narrower than the outer PowerSearch, including when the 400 px floor is active, the editor MUST preserve current logical-start alignment to the outer PowerSearch. | Compatibility requirement | Accepted contract; implementation pending |
-| FR4 | In the `popover` presentation, when the 720 CSS px cap makes the editor narrower, PowerSearch MUST resolve one stable opening control for that open: the inner typeahead input for the add path, or the actual activated token/control for the edit path. | Owner direction plus current composition analysis | Accepted contract; implementation pending |
-| FR5 | In the `popover` presentation, for a capped editor, PowerSearch MUST compare the opening control's border-box distance from the outer PowerSearch's physical left and right edges, select the nearer outer edge, and align the editor to that edge. Equal distances MUST fall back to the outer PowerSearch's logical-start edge. The result MUST depend on control geometry, not pointer coordinates or pointer/keyboard modality. | `component:PowerSearch/DEC-2` | Accepted contract; implementation pending |
-| FR6 | In the `popover` presentation, opening-control identity and the selected edge MUST be latched for the open lifetime. Reopening from a control on the opposite side MUST recalculate both; movement after open MUST NOT move the editor. | Stable interaction and performance requirement | Accepted contract; implementation pending |
-| FR7 | In the `popover` presentation, width and preferred-edge selection MUST still yield to the layer runtime's viewport collision handling so the editor remains horizontally visible within the runtime's existing safe area. | `architecture:layer-runtime` | Accepted contract; implementation pending |
-| FR8 | In the `popover` presentation, the width and alignment change MUST NOT alter editor content, field/operator/value state, vertical placement, focus movement, selection, dismissal, or screen-reader semantics. | Compatibility and accessibility requirement | Accepted contract; implementation pending |
-| FR9 | In the `popover` presentation, the opening-control descriptor owned by `component:Tokenizer/DEC-1` and consumed by PowerSearch MUST remain package-internal. PowerSearch MUST NOT add a public width, maximum-width, input-ref, or positioning prop for this behavior. | `component:Tokenizer/DEC-1`, `architecture:public-component-api`, and `component:PowerSearch/DEC-1` | Accepted contract; implementation pending |
-| FR10 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the tokenizer field with its typeahead and editor popover, unchanged except as FR19 (no mount announcement) states. `bottom-sheet` is the trigger and sheet flow of FR11–FR21 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the same shared resolution the selection controls use (`component:Selector/FR4`). That resolution answers `popover` on the server and during the hydrating render, so an `adaptive` field server-renders as, and hydrates without a mismatch as, the popover presentation's tokenizer field; on a compact coarse-pointer screen the first client render after hydration swaps it to the trigger. Focus follows the resolution rule below: before any interaction nothing in the field has focus and nothing moves, except that with `hasAutoFocus` the server markup's `autofocus` has focused the combobox input, and the swap then moves focus to the trigger within the same visit — the caller is told of neither a blur nor a new focus. The two closed fields share the field's wrapper, border, and minimum height for the size, and show the same tokens, but their row counts may differ: the popover field's editable tokens each carry a 16 px remove control the trigger's display-only tokens do not (FR11), so the trigger's tokens can wrap into fewer rows (seven filters in a 326 px field take seven rows editable and six as display-only tokens), and the popover field also carries its inline combobox input after the tokens, which may take a row of its own — the swap then changes the field's height by those rows (none on the measured story at 390 px, one token row at 414 px). A resolution change while the flow is open takes effect after it closes and focus has returned to the trigger (the focus the close reports, FR11) — the presentation hold `architecture:layer-runtime/INV14` assigns to the layer runtime; INV14 gap: the runtime does not yet provide one (its record names INV14 as ownership not yet met), so until it does the field keeps its own hold, to be replaced by the runtime's when it exists; when the new presentation is `popover`, focus then moves to the tokenizer's combobox input as the same visit — no `onBlur` and no second `onFocus` reaches the caller. A resolution change while the flow is closed takes effect at once; when focus is anywhere inside the closed field — the trigger, the combobox input, a token or its remove control, the clear control, or an interactive `endContent` — and the focused element does not survive the switch, focus moves to the other presentation's primary control (the combobox input, or the trigger) as a continuation of the same visit — no `onBlur` and no `onFocus` reaches the caller for the hand-off; when the focused element survives, or focus is outside the field, focus stays where it is. When the switch to the sheet presentation happens while the popover presentation's editor popover is open, the popover and its focused control unmount with the tokenizer field, and focus moves to the trigger. Focus never lands on the page body. | DEC-3; touch-flow evidence from the Lab prototype | Current contract. Implementation gap: the shipped PowerSearch has no `experimental` prop and renders the tokenizer field on every device. |
-| FR11 | In the sheet presentation the field's control is one trigger: a button with `aria-haspopup="dialog"` and `aria-expanded`, whose accessible name is the field label followed by the trigger's visible text — the placeholder while no filter exists, otherwise the text of the filter tokens — so the name contains what is visible and exposes the selected filters. The tokens are display-only — each is the token's static structure (`component:Token/FR2`): no remove control, no click of its own, no inner control inside the trigger button — and the tokens, the placeholder, and the empty space around them belong to the trigger: a tap on any of them opens the flow. Tokens wrap onto further lines; the trigger does not reserve a row of its own once a token exists. The trigger's tokens are the popover presentation's tokens, the same component and the same words for a value, and a `date_absolute` value reads as the sheet's date editor shows it (FR17): a date-only value as its day in `timezoneID`, else the UTC day, and a value whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone. The popover's token does not read dates this way yet (see the known gap on dates). A `components[type].Token` override renders on the trigger in place of PowerSearch's token, receiving the props the popover presentation hands it — `config`, `filter`, `field`, `operator`, `maxLength`, `isDisabled` — with `onClick` and `onRemove` undefined, as the popover hands them for a read-only filter: the trigger's tokens are display-only, and the override formats its own value. `startIcon` renders in the trigger's lane. The result count and `endContent` render in the field's end lane, outside the trigger button and after it: an interactive `endContent` keeps its own tab stop, its own taps, and its own accessible name, and a tap on it does not open the flow, so a caller's control is never nested inside the component's button and the end lane's text is not part of the trigger's name. `size` sizes the trigger field and its tokens as it sizes the tokenizer field; `statusVariant` places `status.message` as the popover presentation places it; `hasAutoFocus` focuses the trigger on mount. `onFocus` fires when focus enters the field from outside and `onBlur` when it leaves the field: opening the flow moves focus into a sheet, outside the field, so `onBlur` fires, and the close that returns focus to the trigger fires `onFocus` — as the popover presentation fires them around its editor. While disabled the trigger stays focusable with `aria-disabled="true"`, never carries the native `disabled` attribute, does not open, and shows `disabledMessage` as the field does (`spec:AST-085/FR1`, `FR2`). When the component becomes disabled with the flow open, every open sheet of the flow closes and focus moves to the trigger, the destination this record names (`spec:AST-085/FR4`). | DEC-3; Lab touch-flow evidence; `spec:AST-085`; WCAG 2.5.3 | Current contract. Implementation gap: no trigger exists. |
-| FR12 | Opening the flow from a field with at least one filter, or from a read-only field, shows the Filters sheet, a tall modal sheet named "Filters". Its header — a heading and, while the field is interactive and at least one filter exists, an Add filter button at the medium size whose hit area is at least 44 px tall — and its footer — Done and, while `hasClear` is set, the field is interactive, and at least one editable filter exists, Clear all — stay fixed while only the rows between them scroll, the scroll viewport reaching the sheet's edge so its scrollbar does too, with the rows' text on the header's inset. One row per filter shows "{field label} {operator label}" (one catalog message, so a locale can reorder it) and, in bold, the value as the trigger's token shows it — the same formatter, so the same words, with the token's width budget lifted: the row never truncates a single value and never collapses a list to its "{n} items" count — with the token's summaries resolved from the catalog (`@astryx.powersearch.valueEditor.dateRange`, `itemsCount`, `filtersCount`, ICU plurals): an `integer` or `float` value reads as the token's own text (`String(value)`: `2.3456`, `1e+21`, `1e-7`, and `0` for negative zero) wherever the locale writes numbers with the token's numerals — Latin digits and a `.` decimal mark — and elsewhere with the locale's digits and decimal mark, no grouping and no rounding; a `string_list`, `enum_list`, or `entity_list` value reads as all of its items joined by the locale's narrow conjunction list (`Intl.ListFormat`, `{type: 'conjunction', style: 'narrow'}` — "Open, Closed" in English, "高、中" in Simplified Chinese and Japanese, "A, B und C" in German); a date-only `date_absolute` value reads as its day in `timezoneID`, else the UTC day, with no time, and one whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone, a `date_range` as "date range", a `nested` value as "{n} filters", and a `date_relative` value as the value step's choice row reads it ("3 days ago", FR20) when a choice matches the stored value, otherwise as stored. A row's label and value are one catalog message, "{label} {value}", the same message the removal announcement of AR6 uses, with the value segment bold. A filter the field can edit is a row button that opens the value step on it, with a trailing remove action — an icon button at the medium size named "Remove {field label} filter", its hit area at least 44 px square, that commits `onChange(rest, 'remove', index)` without opening the step — except that a filter whose operator takes an `empty` value (a one-tap boolean filter) is a row whose tap removes it, with the same trailing remove action, since it has no value to edit; a read-only filter, or every filter while the field is read-only, is a plain row with no remove action, as the popover gives such a token no remove control. A `nested` filter's row is a row button like any other; its step edits the group with the popover presentation's built-in nested editor (FR14). An editable filter whose field or operator the config no longer has — which the trigger still shows as a token — lists as a row button reading the field's label when the config still has the field and the raw key for whatever is gone — "{field key} {operator key}" when both are, "{field label} {operator key}" when only the operator is — that opens the step's "This filter is no longer available" state (FR14), its trailing remove action still the removal path; it is a plain row while the filter, or the field, is read-only. With no filter the body is one empty state: a heading "No filters applied", a line of guidance, and, while the field is interactive, a centered primary Add filter action that is then the sheet's only Add filter (the header shows none), so the single thing to do is the only visible action. Done closes the flow. Clear all opens a confirmation above the sheet — a dialog titled "Clear all filters?" with "Clear filters" and "Keep filters" — and only confirming commits `onChange(kept, 'remove', <index of the first removed filter>)`, where `kept` is the read-only filters in their order: read-only filters are the consumer's, not the person's, so Clear all leaves them in place, as the popover presentation's Clear all does (FR23); the Filters sheet stays open for further editing and focus returns to it (FR16). After the flow closes focus returns to the trigger. | DEC-3; Lab touch-flow evidence; the read-only filter contract (`isReadOnly`, FR22); DEC-4 | Current contract. Implementation gap: no Filters sheet exists. |
-| FR13 | Add filter — from the Filters sheet's Add filter action, or directly when an interactive field with no filter opens — is a tall modal sheet named "Add filter" opened above the Filters sheet, which stays open beneath it (FR15a), so the sheet has no Back action: dismissing it — Escape, a scrim tap, a swipe — reveals Filters again, or closes the flow when Add filter was the entry point, in which case its fixed footer holds Done. Its header — the heading and, when one shows, the search field — stays fixed while the rows scroll. Without a content-search field it lists the visible fields grouped by `group`, each group a named list: the ungrouped fields first, under the heading "General", then each group under its name in order of first appearance, each a row button with the field's icon, a trailing chevron — or, for a field whose only operator takes an `empty` value, a trailing plus, since choosing it adds the filter at once (FR15) — and, once the field count reaches eight, a "Search filters" field above the list that matches labels and `typeaheadAliases` case-insensitively, caps a non-empty query's matches at `maxSearchResults`, and shows the empty state "No filters match your search" when nothing matches. With a `contentSearchFieldKey` whose default operator takes a `string` value it shows instead a "Search" searchbox using `placeholder`, with the same suggestions the popover presentation's typeahead offers listed inline as row buttons ("Search results"): fields, field-and-operator pairs, value matches, and a leading free-text item for the content field; Enter commits the first suggestion, ArrowDown and ArrowUp move between the search and the rows — arrow movement across independently focusable controls, recorded here as this record's exception to `spec:AST-020/FR15`, which adopts arrow keys for a single composite only: the searchbox-to-list continuity is what the popover presentation's combobox gives the same suggestions, and the rows stay in the Tab order as well — an IME-composing Enter does nothing, and a query with no suggestion shows the empty state "No results found" — the searchbox's `aria-controls` names the results list, or that message while nothing lists, so it always names an element; the field list's "No filters match your search" likewise shows only for a non-empty query that matches nothing, never for a config with no field. Each of the two is a compact empty state with a search icon, that title, and the description "Try a different search.", mounted only while the Add filter sheet is the open one. Neither search field takes focus when the sheet opens: the sheet opens with focus on its panel and the software keyboard stays down until the person taps the search; a direct vertical touch drag on the rows while a search field has focus blurs it, so the keyboard leaves and the rows can be read. A suggestion that carries a value commits `onChange([...filters, filter], 'add', filters.length)`, announces `Added {label}` inside the Filters sheet (AR6), and shows Filters as FR15a states; any other suggestion or field row opens the value step with that field and operator, above Add filter. Every visible field lists, a field whose every operator is `nested` included: the value step edits every operator's value (FR14). | DEC-3; Lab touch-flow evidence; current typeahead source | Current contract. Implementation gap: no Add filter sheet exists. |
-| FR14 | The value step is a tall modal sheet that edits every operator's value, opened above the sheet that led to it — Filters for an edit, Add filter for a creation — which stays open beneath it (FR15a); its title is the dialog's name (AR5), and for a filter whose field or operator the config no longer has it reads as the Filters row does (FR12): the field's label when the config still has the field, the raw key for whatever is gone. Its header and footer stay fixed while the body scrolls. When the field offers more than one operator the body starts with an "Operator" radio group whose options read "{field label} {operator label}" and list the field's operators, with the operator the step opened with checked — the filter's operator while editing, and while creating the operator the suggestion named (FR13) or else the field's default operator, else its first; otherwise there is no group and the title is "{field label} {operator label}" naming that operator. When no operator label applies the title is the field label. The body below the group is the editor for the checked operator's value type: the sheet-native controls of FR17, or for a `nested` value the popover presentation's built-in nested editor — the sub-filter tree with its Add action, each sub-filter's field, operator, and value controls, and removal — rendered as the popover renders it, with one difference: the step's Operator group takes the place of the editor's root group-operator picker, which is not shown, and the tree root reads the checked operator's label; a sub-filter's controls are the popover editor's own, in their default presentation (a Selector's menu, the Tokenizer's inline field), not the sheet's choice rows (FR17) or Tokenizer sheet (FR21), which govern the step's top-level value only, because the sheet passes no `experimental` option down to them; the tree is its own width container, so below 400 CSS px its rows wrap instead of overflowing the sheet, as they wrap in a narrow popover. A group is created and edited the same way in both presentations; switching the operator swaps the body. A value chosen in the body is staged, not committed: no `onChange` fires until the footer confirms it. Changing the operator keeps a staged value only when the new operator reads the same value type; an `empty` operator stages `{type: 'empty'}`. The body's sections sit on the sheet's surface when the editor is the body's only section; when the body has more than one section — the Operator group above the editor — each section is a muted container, so the grouping reads without a frame around a lone editor. The footer holds Cancel and the confirm action — `popoverSaveButtonLabel` when given, otherwise "Add filter" while creating and "Apply" while editing — disabled until the staged value is complete; the step has no Remove action: a filter is removed from its Filters row (FR12). When `components[type].Editor` is set for the checked operator's value type it replaces the body below the Operator group and the footer — the group stays outside it, so switching operators still swaps the body — receiving the props the popover presentation hands it, with the same meaning: the caller's `config`, the partial `filter`, `mode`, `saveButtonLabel`, `isReadOnly`, `onSave`, and `onCancel`, and nothing the popover does not pass; `onSave(filter)` commits it, `onSave(null)` removes the filter while editing and returns to Filters unchanged while creating. A controlled update that removes the field or operator being edited replaces the body with "This filter is no longer available", announced from its rendered element inside the sheet while the step is the open one (AR6), and keeps Cancel as the way out, the filter's trailing remove action on its Filters row being the removal path (FR12); when focus was on a control of the replaced body it moves to Cancel, so it never falls to the page body inside the open sheet (FR16). | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no value step exists. |
-| FR15 | Confirming a created filter commits `onChange([...filters, filter], 'add', filters.length)`; choosing a field whose only operator takes an `empty` value commits that filter the same way from the Add filter row, with no value step. Tapping an editable Filters row opens the value step on that filter in edit mode; Apply commits `onChange(updated, 'edit', index)`; the row's trailing remove action, or a tap on an `empty`-valued filter's row, commits `onChange(rest, 'remove', index)`, where `index` is the filter's position at commit time: a controlled parent that reorders or clones its filters while the step is open is followed by object identity, then by a structurally equal filter in the original slot, then by a unique structural match; when the target is gone or ambiguous nothing is committed and the step closes back to Filters, focus landing as FR16 states for a row that no longer exists. Every commit shows the Filters sheet as FR15a states. While the field is read-only, or disabled, no commit happens. | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no edit path exists. |
-| FR15a | The steps stack: each step opens above the sheet that led to it, which stays open — receded and blocked as a covered sheet of the stack (`component:BottomSheet` FR5, FR6) — so the stack is Filters alone; Filters under Add filter; Filters under the value step for an edit; Filters under Add filter under the value step for a creation; or, when Add filter was the entry point, Add filter alone and then Add filter under the value step. No sheet of the flow carries a Back action: a dismissal — Escape, a scrim tap, a swipe, a platform close request — reaches only the top sheet (`component:BottomSheet` FR7), closes it, and reveals the sheet beneath, which takes focus back as FR16 states; dismissing the bottom sheet of the stack closes the flow. Cancel on the value step is that dismissal. A commit closes the step that made it: an edit's commit reveals Filters beneath the value step; a creation's commit, from the value step or from an Add filter row or suggestion that commits directly, closes Add filter, and the value step above it, together and shows Filters, so the person sees the filter just added: Filters is revealed when it is open beneath them; after a direct entry it opens in the same update that closes them — BottomSheet's same-update replace (`component:BottomSheet` FR10) when Add filter alone closes, and the stack's ordinary closes and open (`component:BottomSheet` FR5–FR9) when the value step closes with it. A creating `Editor` override's `onSave(null)` (FR14) shows Filters the same way. The flow therefore has one direction forward (open a step above) and one back (close the top step): no dismissal replaces a step, and Filters opens as other sheets close only when a creation ends after a direct entry. | DEC-3; `component:BottomSheet` FR5–FR9 | Current contract. Implementation gap: no flow exists. |
-| FR16 | Focus follows the step: after a commit from the value step while creating, the value step and Add filter close and focus lands on the Filters header's Add filter, ready for the next filter; after a content-search suggestion or an `empty`-valued field row commits a filter directly, that filter's row; after Apply or Cancel from editing, the edited filter's row — followed across a controlled reorder or clone, and, when a controlled update removed it or left two filters it could be, the nearest remaining row that is a button around its former position (the following one on a tie), else Add filter; after a row's trailing remove action, or a caller's `Editor` override's `onSave(null)` while editing, which closes the value step, the trailing remove action of the nearest remaining row that has one (the following one on a tie) — a plain row, a read-only filter's, has none and is passed over — so a run of removals needs no re-aiming, else Add filter when no such row remains; after Cancel from creation, Add filter is revealed with focus on the field row that opened the step, or on the content search when a suggestion opened it — and when a controlled update has removed that field, or the content-search field itself, the Add filter sheet's first control: its search field when one shows, else its first field row; after Add filter is dismissed, the Filters header's Add filter, or the empty state's; after a caller's `Editor` override calls `onSave(null)` while creating, the same (the flow returns to Filters unchanged, FR14); after a confirmed Clear all, the Filters sheet's first remaining control — a kept read-only filter's row has none, so Add filter — with the sheet still open; after Keep filters, Escape, or a scrim tap dismisses the confirmation, Clear all (`component:Dialog` AR2); and, as one rule for the Filters and Add filter sheets, when a controlled update unmounts the control that holds focus — a filter's row or its remove action, a dropped field's row, Clear all gone with the last editable filter — the nearest remaining row that is a button, counted among the button rows by the removed one's index (the following one, else the last) — a plain row (a read-only filter, or every filter while the field is read-only) is passed over — else the sheet's first control (the Add filter sheet's search field, Add filter in the Filters header or empty state), else the sheet's panel, so focus never lands on the page body inside the open sheet; when a controlled update replaces the value step's body with the unavailable state while focus was on one of its controls, Cancel (FR14); after the flow closes, the trigger. A sheet that opens takes focus on its panel, not on a control, except where this row names one; the Add filter sheet's search fields never take it on open (FR13). | DEC-3; Lab touch-flow evidence | Current contract. Implementation gap: no flow exists. |
-| FR17 | The value step edits every value type with the same editor the popover presentation uses (`nested` through its built-in nested editor, FR14), with four sheet-native differences: `enum`, `enum_list`, and `date_relative` render as full-width choice rows with a trailing indicator instead of a dropdown that would stack a second layer on the sheet — `radio` rows in a `radiogroup` named by the field label for `enum` and `date_relative` (a tap selects the row; the group is one tab stop — the checked row, else the first — and the arrow keys move focus and check the row they land on, wrapping, Home and End move to and check the first and last row, and Space or Enter checks the focused row — `spec:AST-020/FR15`), `checkbox` rows in a `group` named by the field label for `enum_list` (a tap toggles the row; each row is its own tab stop, toggled with Space or Enter), each carrying its state as `aria-checked`, as the Tokenizer's sheet rows do; `integer` and `float` stage every parseable keystroke, so the confirm action enables while the person is still typing, and unstage when the field is cleared or stops parsing, so it disables again over an empty field; a `string_list` or `entity_list` value edits through the Tokenizer's own sheet presentation (`component:Tokenizer/FR16–FR24`), its trigger showing the staged tokens in the step and its sheet titled with the field label; and a `date_absolute` value with `isDateOnly` unset or `true`, and a `date_range` value, edit through an inline Calendar on the sheet's surface — no popover opens from a sheet — reading a stored instant as its day in `timezoneID`, else the UTC day, and writing a picked day as that day's midnight in the same zone, the day the trigger's token and the Filters row show (FR11, FR12); a `date_absolute` value with `isDateOnly: false` edits through a date-and-time input, sized for touch, that reads and writes the wall-clock time in `timezoneID`, else the viewer's zone. The popover presentation's date editors do not follow these zones yet (see the known gap on dates). `maxOperatorMenuItems` caps the string and entity suggestions as in the popover presentation. | DEC-3; Lab touch-flow evidence; current value editors | Current contract. Implementation gap: no sheet editors exist. |
-| FR18 | Every list in the sheets derives synchronously from the config — the field list, its search, the content-search suggestions, and the choice rows — so no sheet shows an empty state before results arrive: "No filters match your search" and "No results found" render only for a non-empty query whose synchronous result set is empty, and only while their sheet is the open one; a sheet that is open beneath another, or closed with its body retained, renders and announces no empty-result or unavailable message (AR6). The value typeaheads and tokenizers inside the value step own their own pending states. | DEC-3; `architecture:react-component-runtime/INV1` | Current contract. Implementation gap: no sheets exist. |
-| FR19 | The result count renders at the end of the field in both presentations and is announced only when it changes after mount; the first render announces nothing, including under StrictMode's effect replay. The announcement takes the route `spec:AST-086/FR14` names for where the field is at that moment: inside the open sheet's dialog while a sheet of the flow is open (AR6), otherwise inside the nearest open native modal that holds the field (a Dialog, a modal Drawer), and the shared polite channel only when no modal does — never a channel the record names itself. | Current popover behavior; `architecture:react-component-runtime/INV3` | Current contract. Implementation gap: the closed field meets this row, with no announcement on mount under StrictMode and the route into the modal that holds it; no sheet exists to carry the in-sheet route. |
-| FR20 | Every string the sheets introduce comes from the `@astryx.powersearch.*` catalog, reusing the existing editor keys where their meaning fits (Cancel, Apply, Operator, Value, Values, Entities, the placeholders, the result count). Content the popover presentation already renders keeps its source — field, operator, and value text from the config and its formatters — except that every label the sheets render for a generated choice comes from the catalog as one ICU message with a plural: the relative-date choice rows (`@astryx.powersearch.sheet.relative{Days,Weeks,Months}{Ago,FromNow}`, the same choices and, in English, the same words as the popover's editor lists) and the value summaries of FR12. | DEC-3; catalog contract | Current contract. Implementation gap: no sheet strings exist. |
-| FR21 | A `string_list` or `entity_list` value inside the value step opens the Tokenizer's sheet above the value step, one more sheet of the same stack (FR15a). Escape, a scrim tap, and a swipe dismiss only that topmost sheet; closing it returns focus to its trigger inside the value step; the value step keeps its staged state. | DEC-3; `family:overlay-dismissal`; `component:Tokenizer/FR18` | Current contract. Implementation gap: no nested sheet exists. |
-| FR22 | In the `popover` presentation, a read-only field (`isReadOnly`) MUST NOT remove a filter: it shows no Clear all, no token has a remove control, and Backspace on an empty input removes nothing. | The `isReadOnly` prop docs: "Prevent adding, editing, or removing filters." | Current contract |
-| FR23 | In the `popover` presentation, Clear all MUST remove every editable filter and keep every read-only filter: it commits `onChange(<the read-only filters>, 'remove', <index of the first removed filter>)` and announces "Editable filters removed" while a read-only filter remains, otherwise "All filters removed". The clear control MUST render only while `hasClear` is set, the field is neither read-only nor disabled, and at least one editable filter exists. Backspace on an empty input MUST NOT remove a read-only filter; its token has no remove control. | DEC-4; a read-only filter's token has no remove control (current source) | Current contract |
-| FR24 | In the popover presentation, a built-in filter token (no `components` Token override) that opens its editor is named by its visible text (field, operator and value); `aria-haspopup="dialog"`, `aria-expanded` is true while its editor is open, and the editor is a dialog named by the token's visible text. Its remove button is named by the remove word and the same visible text. | `spec:AST-020` FR1; WCAG 2.5.3 and 4.1.2; `component:Token/FR10` | Current contract. |
+| ID | Invariant | Basis | Status |
+| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| FR1 | In the `popover` presentation, the filter-editor popover MUST have a rendered border-box width no greater than 720 CSS px. | Owner direction; legibility issue demonstrated by wide PowerSearch adopters | Accepted contract; implementation pending |
+| FR2 | In the `popover` presentation, before viewport collision handling, the editor's preferred width MUST be the outer PowerSearch width clamped to the inclusive 400–720 CSS px range. The 400 px floor MUST yield when the available viewport width cannot fit it. | Existing 400 px editing floor plus `component:PowerSearch/DEC-1` | Accepted contract; implementation pending |
+| FR3 | In the `popover` presentation, when the 720 CSS px cap does not make the editor narrower than the outer PowerSearch, including when the 400 px floor is active, the editor MUST preserve current logical-start alignment to the outer PowerSearch. | Compatibility requirement | Accepted contract; implementation pending |
+| FR4 | In the `popover` presentation, when the 720 CSS px cap makes the editor narrower, PowerSearch MUST resolve one stable opening control for that open: the inner typeahead input for the add path, or the actual activated token/control for the edit path. | Owner direction plus current composition analysis | Accepted contract; implementation pending |
+| FR5 | In the `popover` presentation, for a capped editor, PowerSearch MUST compare the opening control's border-box distance from the outer PowerSearch's physical left and right edges, select the nearer outer edge, and align the editor to that edge. Equal distances MUST fall back to the outer PowerSearch's logical-start edge. The result MUST depend on control geometry, not pointer coordinates or pointer/keyboard modality. | `component:PowerSearch/DEC-2` | Accepted contract; implementation pending |
+| FR6 | In the `popover` presentation, opening-control identity and the selected edge MUST be latched for the open lifetime. Reopening from a control on the opposite side MUST recalculate both; movement after open MUST NOT move the editor. | Stable interaction and performance requirement | Accepted contract; implementation pending |
+| FR7 | In the `popover` presentation, width and preferred-edge selection MUST still yield to the layer runtime's viewport collision handling so the editor remains horizontally visible within the runtime's existing safe area. | `architecture:layer-runtime` | Accepted contract; implementation pending |
+| FR8 | In the `popover` presentation, the width and alignment change MUST NOT alter editor content, field/operator/value state, vertical placement, focus movement, selection, dismissal, or screen-reader semantics. | Compatibility and accessibility requirement | Accepted contract; implementation pending |
+| FR9 | In the `popover` presentation, the opening-control descriptor owned by `component:Tokenizer/DEC-1` and consumed by PowerSearch MUST remain package-internal. PowerSearch MUST NOT add a public width, maximum-width, input-ref, or positioning prop for this behavior. | `component:Tokenizer/DEC-1`, `architecture:public-component-api`, and `component:PowerSearch/DEC-1` | Accepted contract; implementation pending |
+| FR10 | `experimental.presentation` selects the surface. `popover`, the value when `experimental` or the option is omitted, is the tokenizer field with its typeahead and editor popover, unchanged except as FR19 (no mount announcement) states. `bottom-sheet` is the trigger and sheet flow of FR11–FR21 on every device. `adaptive` resolves to `bottom-sheet` on compact coarse-pointer screens and to `popover` otherwise, through the same shared resolution the selection controls use (`component:Selector/FR4`). That resolution answers `popover` on the server and during the hydrating render, so an `adaptive` field server-renders as, and hydrates without a mismatch as, the popover presentation's tokenizer field; on a compact coarse-pointer screen the first client render after hydration swaps it to the trigger. Focus follows the resolution rule below: before any interaction nothing in the field has focus and nothing moves, except that with `hasAutoFocus` the server markup's `autofocus` has focused the combobox input, and the swap then moves focus to the trigger within the same visit — the caller is told of neither a blur nor a new focus. The two closed fields share the field's wrapper, border, and minimum height for the size, and show the same tokens, but their row counts may differ: the popover field's editable tokens each carry a 16 px remove control the trigger's display-only tokens do not (FR11), so the trigger's tokens can wrap into fewer rows (seven filters in a 326 px field take seven rows editable and six as display-only tokens), and the popover field also carries its inline combobox input after the tokens, which may take a row of its own — the swap then changes the field's height by those rows (none on the measured story at 390 px, one token row at 414 px). A resolution change while the flow is open takes effect after it closes and focus has returned to the trigger (the focus the close reports, FR11) — the presentation hold `architecture:layer-runtime/INV14` assigns to the layer runtime; INV14 gap: the runtime does not yet provide one (its record names INV14 as ownership not yet met), so until it does the field keeps its own hold, to be replaced by the runtime's when it exists; when the new presentation is `popover`, focus then moves to the tokenizer's combobox input as the same visit — no `onBlur` and no second `onFocus` reaches the caller. A resolution change while the flow is closed takes effect at once; when focus is anywhere inside the closed field — the trigger, the combobox input, a token or its remove control, the clear control, or an interactive `endContent` — and the focused element does not survive the switch, focus moves to the other presentation's primary control (the combobox input, or the trigger) as a continuation of the same visit — no `onBlur` and no `onFocus` reaches the caller for the hand-off; when the focused element survives, or focus is outside the field, focus stays where it is. When the switch to the sheet presentation happens while the popover presentation's editor popover is open, the popover and its focused control unmount with the tokenizer field, and focus moves to the trigger. Focus never lands on the page body. | DEC-3; touch-flow evidence from the Lab prototype | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR11 | In the sheet presentation the field's control is one trigger: a button with `aria-haspopup="dialog"` and `aria-expanded`, whose accessible name is the field label followed by the trigger's visible text — the placeholder while no filter exists, otherwise the text of the filter tokens — so the name contains what is visible and exposes the selected filters. The tokens are display-only — each is the token's static structure (`component:Token/FR2`): no remove control, no click of its own, no inner control inside the trigger button — and the tokens, the placeholder, and the empty space around them belong to the trigger: a tap on any of them opens the flow. Tokens wrap onto further lines; the trigger does not reserve a row of its own once a token exists. The trigger's tokens are the popover presentation's tokens, the same component and the same words for a value, and a `date_absolute` value reads as the sheet's date editor shows it (FR17): a date-only value as its day in `timezoneID`, else the UTC day, and a value whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone. The popover's token does not read dates this way yet (see the known gap on dates). A `components[type].Token` override renders on the trigger in place of PowerSearch's token, receiving the props the popover presentation hands it — `config`, `filter`, `field`, `operator`, `maxLength`, `isDisabled` — with `onClick` and `onRemove` undefined, as the popover hands them for a read-only filter: the trigger's tokens are display-only, and the override formats its own value. `startIcon` renders in the trigger's lane. The result count and `endContent` render in the field's end lane, outside the trigger button and after it: an interactive `endContent` keeps its own tab stop, its own taps, and its own accessible name, and a tap on it does not open the flow, so a caller's control is never nested inside the component's button and the end lane's text is not part of the trigger's name. `size` sizes the trigger field and its tokens as it sizes the tokenizer field; `statusVariant` places `status.message` as the popover presentation places it; `hasAutoFocus` focuses the trigger on mount. `onFocus` fires when focus enters the field from outside and `onBlur` when it leaves the field: opening the flow moves focus into a sheet, outside the field, so `onBlur` fires, and the close that returns focus to the trigger fires `onFocus` — as the popover presentation fires them around its editor. While disabled the trigger stays focusable with `aria-disabled="true"`, never carries the native `disabled` attribute, does not open, and shows `disabledMessage` as the field does (`spec:AST-085/FR1`, `FR2`). When the component becomes disabled with the flow open, every open sheet of the flow closes and focus moves to the trigger, the destination this record names (`spec:AST-085/FR4`). | DEC-3; Lab touch-flow evidence; `spec:AST-085`; WCAG 2.5.3 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: the trigger's token reads a `date_absolute` value as the popover presentation's token does, as its day in the device's zone with no time, not in `timezoneID`. |
+| FR12 | Opening the flow from a field with at least one filter, or from a read-only field, shows the Filters sheet, a tall modal sheet named "Filters". Its header — a heading and, while the field is interactive and at least one filter exists, an Add filter button at the medium size whose hit area is at least 44 px tall — and its footer — Done and, while `hasClear` is set, the field is interactive, and at least one editable filter exists, Clear all — stay fixed while only the rows between them scroll, the scroll viewport reaching the sheet's edge so its scrollbar does too, with the rows' text on the header's inset. One row per filter shows "{field label} {operator label}" (one catalog message, so a locale can reorder it) and, in bold, the value as the trigger's token shows it — the same formatter, so the same words, with the token's width budget lifted: the row never truncates a single value and never collapses a list to its "{n} items" count — with the token's summaries resolved from the catalog (`@astryx.powersearch.valueEditor.dateRange`, `itemsCount`, `filtersCount`, ICU plurals): an `integer` or `float` value reads as the token's own text (`String(value)`: `2.3456`, `1e+21`, `1e-7`, and `0` for negative zero) wherever the locale writes numbers with the token's numerals — Latin digits and a `.` decimal mark — and elsewhere with the locale's digits and decimal mark, no grouping and no rounding; a `string_list`, `enum_list`, or `entity_list` value reads as all of its items joined by the locale's narrow conjunction list (`Intl.ListFormat`, `{type: 'conjunction', style: 'narrow'}` — "Open, Closed" in English, "高、中" in Simplified Chinese and Japanese, "A, B und C" in German); a date-only `date_absolute` value reads as its day in `timezoneID`, else the UTC day, with no time, and one whose operator sets `isDateOnly: false` as its date and time in `timezoneID`, else the viewer's zone, a `date_range` as "date range", a `nested` value as "{n} filters", and a `date_relative` value as the value step's choice row reads it ("3 days ago", FR20) when a choice matches the stored value, otherwise as stored. A row's label and value are one catalog message, "{label} {value}", the same message the removal announcement of AR6 uses, with the value segment bold. A filter the field can edit is a row button that opens the value step on it, with a trailing remove action — an icon button at the medium size named "Remove {field label} filter", its hit area at least 44 px square, that commits `onChange(rest, 'remove', index)` without opening the step — except that a filter whose operator takes an `empty` value (a one-tap boolean filter) is a row whose tap removes it, with the same trailing remove action, since it has no value to edit; a read-only filter, or every filter while the field is read-only, is a plain row with no remove action, as the popover gives such a token no remove control. A `nested` filter's row is a row button like any other; its step edits the group with the popover presentation's built-in nested editor (FR14). An editable filter whose field or operator the config no longer has — which the trigger still shows as a token — lists as a row button reading the field's label when the config still has the field and the raw key for whatever is gone — "{field key} {operator key}" when both are, "{field label} {operator key}" when only the operator is — that opens the step's "This filter is no longer available" state (FR14), its trailing remove action still the removal path; it is a plain row while the filter, or the field, is read-only. With no filter the body is one empty state: a heading "No filters applied", a line of guidance, and, while the field is interactive, a centered primary Add filter action that is then the sheet's only Add filter (the header shows none), so the single thing to do is the only visible action. Done closes the flow. Clear all opens a confirmation above the sheet — a dialog titled "Clear all filters?" with "Clear filters" and "Keep filters" — and only confirming commits `onChange(kept, 'remove', <index of the first removed filter>)`, where `kept` is the read-only filters in their order: read-only filters are the consumer's, not the person's, so Clear all leaves them in place, as the popover presentation's Clear all does (FR23); the Filters sheet stays open for further editing and focus returns to it (FR16). After the flow closes focus returns to the trigger. | DEC-3; Lab touch-flow evidence; the read-only filter contract (`isReadOnly`, FR22); DEC-4 | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a row reads a `date_absolute` value as the trigger's token does, as its day in the device's zone with no time, not in `timezoneID`. |
+| FR13 | Add filter — from the Filters sheet's Add filter action, or directly when an interactive field with no filter opens — is a tall modal sheet named "Add filter" opened above the Filters sheet, which stays open beneath it (FR15a), so the sheet has no Back action: dismissing it — Escape, a scrim tap, a swipe — reveals Filters again, or closes the flow when Add filter was the entry point, in which case its fixed footer holds Done. Its header — the heading and, when one shows, the search field — stays fixed while the rows scroll. Without a content-search field it lists the visible fields grouped by `group`, each group a named list: the ungrouped fields first, under the heading "General", then each group under its name in order of first appearance, each a row button with the field's icon, a trailing chevron — or, for a field whose only operator takes an `empty` value, a trailing plus, since choosing it adds the filter at once (FR15) — and, once the field count reaches eight, a "Search filters" field above the list that matches labels and `typeaheadAliases` case-insensitively, caps a non-empty query's matches at `maxSearchResults`, and shows the empty state "No filters match your search" when nothing matches. With a `contentSearchFieldKey` whose default operator takes a `string` value it shows instead a "Search" searchbox using `placeholder`, with the same suggestions the popover presentation's typeahead offers listed inline as row buttons ("Search results"): fields, field-and-operator pairs, value matches, and a leading free-text item for the content field; Enter commits the first suggestion, ArrowDown and ArrowUp move between the search and the rows — arrow movement across independently focusable controls, recorded here as this record's exception to `spec:AST-020/FR15`, which adopts arrow keys for a single composite only: the searchbox-to-list continuity is what the popover presentation's combobox gives the same suggestions, and the rows stay in the Tab order as well — an IME-composing Enter does nothing, and a query with no suggestion shows the empty state "No results found" — the searchbox's `aria-controls` names the results list, or that message while nothing lists, so it always names an element; the field list's "No filters match your search" likewise shows only for a non-empty query that matches nothing, never for a config with no field. Each of the two is a compact empty state with a search icon, that title, and the description "Try a different search.", mounted only while the Add filter sheet is the open one. Neither search field takes focus when the sheet opens: the sheet opens with focus on its panel and the software keyboard stays down until the person taps the search; a direct vertical touch drag on the rows while a search field has focus blurs it, so the keyboard leaves and the rows can be read. A suggestion that carries a value commits `onChange([...filters, filter], 'add', filters.length)`, announces `Added {label}` inside the Filters sheet (AR6), and shows Filters as FR15a states; any other suggestion or field row opens the value step with that field and operator, above Add filter. Every visible field lists, a field whose every operator is `nested` included: the value step edits every operator's value (FR14). | DEC-3; Lab touch-flow evidence; current typeahead source | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR14 | The value step is a tall modal sheet that edits every operator's value, opened above the sheet that led to it — Filters for an edit, Add filter for a creation — which stays open beneath it (FR15a); its title is the dialog's name (AR5), and for a filter whose field or operator the config no longer has it reads as the Filters row does (FR12): the field's label when the config still has the field, the raw key for whatever is gone. Its header and footer stay fixed while the body scrolls. When the field offers more than one operator the body starts with an "Operator" radio group whose options read "{field label} {operator label}" and list the field's operators, with the operator the step opened with checked — the filter's operator while editing, and while creating the operator the suggestion named (FR13) or else the field's default operator, else its first; otherwise there is no group and the title is "{field label} {operator label}" naming that operator. When no operator label applies the title is the field label. The body below the group is the editor for the checked operator's value type: the sheet-native controls of FR17, or for a `nested` value the popover presentation's built-in nested editor — the sub-filter tree with its Add action, each sub-filter's field, operator, and value controls, and removal — rendered as the popover renders it, with one difference: the step's Operator group takes the place of the editor's root group-operator picker, which is not shown, and the tree root reads the checked operator's label; a sub-filter's controls are the popover editor's own, in their default presentation (a Selector's menu, the Tokenizer's inline field), not the sheet's choice rows (FR17) or Tokenizer sheet (FR21), which govern the step's top-level value only, because the sheet passes no `experimental` option down to them; the tree is its own width container, so below 400 CSS px its rows wrap instead of overflowing the sheet, as they wrap in a narrow popover. A group is created and edited the same way in both presentations; switching the operator swaps the body. A value chosen in the body is staged, not committed: no `onChange` fires until the footer confirms it. Changing the operator keeps a staged value only when the new operator reads the same value type; an `empty` operator stages `{type: 'empty'}`. The body's sections sit on the sheet's surface when the editor is the body's only section; when the body has more than one section — the Operator group above the editor — each section is a muted container, so the grouping reads without a frame around a lone editor. The footer holds Cancel and the confirm action — `popoverSaveButtonLabel` when given, otherwise "Add filter" while creating and "Apply" while editing — disabled until the staged value is complete; the step has no Remove action: a filter is removed from its Filters row (FR12). When `components[type].Editor` is set for the checked operator's value type it replaces the body below the Operator group and the footer — the group stays outside it, so switching operators still swaps the body — receiving the props the popover presentation hands it, with the same meaning: the caller's `config`, the partial `filter`, `mode`, `saveButtonLabel`, `isReadOnly`, `onSave`, and `onCancel`, and nothing the popover does not pass; `onSave(filter)` commits it, `onSave(null)` removes the filter while editing and returns to Filters unchanged while creating. A controlled update that removes the field or operator being edited replaces the body with "This filter is no longer available", announced from its rendered element inside the sheet while the step is the open one (AR6), and keeps Cancel as the way out, the filter's trailing remove action on its Filters row being the removal path (FR12); when focus was on a control of the replaced body it moves to Cancel, so it never falls to the page body inside the open sheet (FR16). | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR15 | Confirming a created filter commits `onChange([...filters, filter], 'add', filters.length)`; choosing a field whose only operator takes an `empty` value commits that filter the same way from the Add filter row, with no value step. Tapping an editable Filters row opens the value step on that filter in edit mode; Apply commits `onChange(updated, 'edit', index)`; the row's trailing remove action, or a tap on an `empty`-valued filter's row, commits `onChange(rest, 'remove', index)`, where `index` is the filter's position at commit time: a controlled parent that reorders or clones its filters while the step is open is followed by object identity, then by a structurally equal filter in the original slot, then by a unique structural match; when the target is gone or ambiguous nothing is committed and the step closes back to Filters, focus landing as FR16 states for a row that no longer exists. Every commit shows the Filters sheet as FR15a states. While the field is read-only, or disabled, no commit happens. | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR15a | The steps stack: each step opens above the sheet that led to it, which stays open — receded and blocked as a covered sheet of the stack (`component:BottomSheet` FR5, FR6) — so the stack is Filters alone; Filters under Add filter; Filters under the value step for an edit; Filters under Add filter under the value step for a creation; or, when Add filter was the entry point, Add filter alone and then Add filter under the value step. No sheet of the flow carries a Back action: a dismissal — Escape, a scrim tap, a swipe, a platform close request — reaches only the top sheet (`component:BottomSheet` FR7), closes it, and reveals the sheet beneath, which takes focus back as FR16 states; dismissing the bottom sheet of the stack closes the flow. Cancel on the value step is that dismissal. A commit closes the step that made it: an edit's commit reveals Filters beneath the value step; a creation's commit, from the value step or from an Add filter row or suggestion that commits directly, closes Add filter, and the value step above it, together and shows Filters, so the person sees the filter just added: Filters is revealed when it is open beneath them; after a direct entry it opens in the same update that closes them — BottomSheet's same-update replace (`component:BottomSheet` FR10) when Add filter alone closes, and the stack's ordinary closes and open (`component:BottomSheet` FR5–FR9) when the value step closes with it. A creating `Editor` override's `onSave(null)` (FR14) shows Filters the same way. The flow therefore has one direction forward (open a step above) and one back (close the top step): no dismissal replaces a step, and Filters opens as other sheets close only when a creation ends after a direct entry. | DEC-3; `component:BottomSheet` FR5–FR9 | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR16 | Focus follows the step: after a commit from the value step while creating, the value step and Add filter close and focus lands on the Filters header's Add filter, ready for the next filter; after a content-search suggestion or an `empty`-valued field row commits a filter directly, that filter's row; after Apply or Cancel from editing, the edited filter's row — followed across a controlled reorder or clone, and, when a controlled update removed it or left two filters it could be, the nearest remaining row that is a button around its former position (the following one on a tie), else Add filter; after a row's trailing remove action, or a caller's `Editor` override's `onSave(null)` while editing, which closes the value step, the trailing remove action of the nearest remaining row that has one (the following one on a tie) — a plain row, a read-only filter's, has none and is passed over — so a run of removals needs no re-aiming, else Add filter when no such row remains; after Cancel from creation, Add filter is revealed with focus on the field row that opened the step, or on the content search when a suggestion opened it — and when a controlled update has removed that field, or the content-search field itself, the Add filter sheet's first control: its search field when one shows, else its first field row; after Add filter is dismissed, the Filters header's Add filter, or the empty state's; after a caller's `Editor` override calls `onSave(null)` while creating, the same (the flow returns to Filters unchanged, FR14); after a confirmed Clear all, the Filters sheet's first remaining control — a kept read-only filter's row has none, so Add filter — with the sheet still open; after Keep filters, Escape, or a scrim tap dismisses the confirmation, Clear all (`component:Dialog` AR2); and, as one rule for the Filters and Add filter sheets, when a controlled update unmounts the control that holds focus — a filter's row or its remove action, a dropped field's row, Clear all gone with the last editable filter — the nearest remaining row that is a button, counted among the button rows by the removed one's index (the following one, else the last) — a plain row (a read-only filter, or every filter while the field is read-only) is passed over — else the sheet's first control (the Add filter sheet's search field, Add filter in the Filters header or empty state), else the sheet's panel, so focus never lands on the page body inside the open sheet; when a controlled update replaces the value step's body with the unavailable state while focus was on one of its controls, Cancel (FR14); after the flow closes, the trigger. A sheet that opens takes focus on its panel, not on a control, except where this row names one; the Add filter sheet's search fields never take it on open (FR13). | DEC-3; Lab touch-flow evidence | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR17 | The value step edits every value type with the same editor the popover presentation uses (`nested` through its built-in nested editor, FR14), with four sheet-native differences: `enum`, `enum_list`, and `date_relative` render as full-width choice rows with a trailing indicator instead of a dropdown that would stack a second layer on the sheet — `radio` rows in a `radiogroup` named by the field label for `enum` and `date_relative` (a tap selects the row; the group is one tab stop — the checked row, else the first — and the arrow keys move focus and check the row they land on, wrapping, Home and End move to and check the first and last row, and Space or Enter checks the focused row — `spec:AST-020/FR15`), `checkbox` rows in a `group` named by the field label for `enum_list` (a tap toggles the row; each row is its own tab stop, toggled with Space or Enter), each carrying its state as `aria-checked`, as the Tokenizer's sheet rows do; `integer` and `float` stage every parseable keystroke, so the confirm action enables while the person is still typing, and unstage when the field is cleared or stops parsing, so it disables again over an empty field; a `string_list` or `entity_list` value edits through the Tokenizer's own sheet presentation (`component:Tokenizer/FR16–FR24`), its trigger showing the staged tokens in the step and its sheet titled with the field label; and a `date_absolute` value with `isDateOnly` unset or `true`, and a `date_range` value, edit through an inline Calendar on the sheet's surface — no popover opens from a sheet — reading a stored instant as its day in `timezoneID`, else the UTC day, and writing a picked day as that day's midnight in the same zone, the day the trigger's token and the Filters row show (FR11, FR12); a `date_absolute` value with `isDateOnly: false` edits through a date-and-time input, sized for touch, that reads and writes the wall-clock time in `timezoneID`, else the viewer's zone. The popover presentation's date editors do not follow these zones yet (see the known gap on dates). `maxOperatorMenuItems` caps the string and entity suggestions as in the popover presentation. | DEC-3; Lab touch-flow evidence; current value editors | Current contract; verified by focused sheet tests and real-engine touch evidence. Implementation gap: a date-only `date_absolute` value and a `date_range` value edit through the popover presentation's date fields in their sheet presentation, which read and write the UTC day whatever `timezoneID` is, not through an inline Calendar; a value whose operator sets `isDateOnly: false` edits a date only and stores its midnight. |
+| FR18 | Every list in the sheets derives synchronously from the config — the field list, its search, the content-search suggestions, and the choice rows — so no sheet shows an empty state before results arrive: "No filters match your search" and "No results found" render only for a non-empty query whose synchronous result set is empty, and only while their sheet is the open one; a sheet that is open beneath another, or closed with its body retained, renders and announces no empty-result or unavailable message (AR6). The value typeaheads and tokenizers inside the value step own their own pending states. | DEC-3; `architecture:react-component-runtime/INV1` | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR19 | The result count renders at the end of the field in both presentations and is announced only when it changes after mount; the first render announces nothing, including under StrictMode's effect replay. The announcement takes the route `spec:AST-086/FR14` names for where the field is at that moment: inside the open sheet's dialog while a sheet of the flow is open (AR6), otherwise inside the nearest open native modal that holds the field (a Dialog, a modal Drawer), and the shared polite channel only when no modal does — never a channel the record names itself. | Current popover behavior; `architecture:react-component-runtime/INV3` | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR20 | Every string the sheets introduce comes from the `@astryx.powersearch.*` catalog, reusing the existing editor keys where their meaning fits (Cancel, Apply, Operator, Value, Values, Entities, the placeholders, the result count). Content the popover presentation already renders keeps its source — field, operator, and value text from the config and its formatters — except that every label the sheets render for a generated choice comes from the catalog as one ICU message with a plural: the relative-date choice rows (`@astryx.powersearch.sheet.relative{Days,Weeks,Months}{Ago,FromNow}`, the same choices and, in English, the same words as the popover's editor lists) and the value summaries of FR12. | DEC-3; catalog contract | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR21 | A `string_list` or `entity_list` value inside the value step opens the Tokenizer's sheet above the value step, one more sheet of the same stack (FR15a). Escape, a scrim tap, and a swipe dismiss only that topmost sheet; closing it returns focus to its trigger inside the value step; the value step keeps its staged state. | DEC-3; `family:overlay-dismissal`; `component:Tokenizer/FR18` | Current contract; verified by focused sheet tests and real-engine touch evidence. |
+| FR22 | In the `popover` presentation, a read-only field (`isReadOnly`) MUST NOT remove a filter: it shows no Clear all, no token has a remove control, and Backspace on an empty input removes nothing. | The `isReadOnly` prop docs: "Prevent adding, editing, or removing filters." | Current contract |
+| FR23 | In the `popover` presentation, Clear all MUST remove every editable filter and keep every read-only filter: it commits `onChange(<the read-only filters>, 'remove', <index of the first removed filter>)` and announces "Editable filters removed" while a read-only filter remains, otherwise "All filters removed". The clear control MUST render only while `hasClear` is set, the field is neither read-only nor disabled, and at least one editable filter exists. Backspace on an empty input MUST NOT remove a read-only filter; its token has no remove control. | DEC-4; a read-only filter's token has no remove control (current source) | Current contract |
+| FR24 | In the popover presentation, a built-in filter token (no `components` Token override) that opens its editor is named by its visible text (field, operator and value); `aria-haspopup="dialog"`, `aria-expanded` is true while its editor is open, and the editor is a dialog named by the token's visible text. Its remove button is named by the remove word and the same visible text. | `spec:AST-020` FR1; WCAG 2.5.3 and 4.1.2; `component:Token/FR10` | Current contract. |
### Allowed variation
@@ -324,7 +330,7 @@ FR10–FR21 govern.
on the trigger
(`architecture:component-style-authoring/INV7`); the trigger, its end lane
(the result count, `endContent`) and the field chrome of FR11 render as the
- field does. Implementation gap: no sheet surface exists.
+ field does.
## Accessibility contract
@@ -341,7 +347,7 @@ FR10–FR21 govern.
and `aria-expanded`; `status.message` and `disabledMessage` describe it; a
disabled trigger uses `aria-disabled` and keeps its focus order; an
interactive `endContent` is a sibling of the trigger with its own name and
- tab stop, never a descendant of it. Implementation gap: no trigger exists.
+ tab stop, never a descendant of it.
- **AR5 — Sheet semantics.** Each step is a modal dialog named by its title
("Filters", "Add filter", the value step's title), the open one on top of the
sheets it was opened from, which are `inert` beneath it
@@ -362,7 +368,6 @@ FR10–FR21 govern.
search is a textbox named "Search filters"; every sheet action has a hit area
at least 44 px tall, and the trailing remove action and the header's Add
filter keep their medium visible size, their hit area meeting that minimum.
- Implementation gap: no sheets exist.
- **AR6 — Announcements and focus.** While a sheet is open, every announcement
the flow makes — `Added {label}` for a committed suggestion or an
`empty`-valued field row, `Removed {label}` for a filter removed by its row's
@@ -400,7 +405,7 @@ FR10–FR21 govern.
filters removed. {result count}", so a locale orders and punctuates the pair;
while the flow is closed the result count takes the route `spec:AST-086/FR14`
names for the field's position (FR19). Focus moves as FR16 states and returns
- to the trigger after the flow closes. Implementation gap: no flow exists.
+ to the trigger after the flow closes.
## Design relationships
@@ -494,17 +499,17 @@ mark implementation and focused real-Chromium verification as pending.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------- |
-| FR1–FR3, FR7 | PowerSearch unit tests plus real-Chromium geometry assertions | 399/400, 720/721, wide outer surface, narrow viewport, LTR/RTL, collision | Removing either clamp, capping the main menu, or allowing viewport overflow fails. | `audit:PowerSearch/layout` |
-| FR4–FR6, FR9 | Opening-path tests plus real-Chromium geometry assertions | Add from inner input; edit actual left/right/equidistant token/control; pointer/keyboard; reopen opposite side | Using pointer coordinates, modality, wrapper-only identity, stale identity, or public props fails. | `audit:PowerSearch/interaction` |
-| PR1–PR4 | Instrumented unit tests plus first-frame real-Chromium capture | Open, close, reopen opposite side; hidden placement commit; first painted frame | Render-time reads, repeated reads, observers, pointer tracking, or a default-position flash fails. | `audit:PowerSearch/performance` |
-| FR8, AR1–AR3 | Existing PowerSearch/editor suites plus focused browser checks | Pointer and keyboard edit, apply, cancel, Escape, light dismiss, focus return, selection, semantics | Focus, semantics, selection, dismissal, or reachability changes fail. | `audit:PowerSearch/accessibility` |
-| FR22 | PowerSearch and Tokenizer unit tests | A read-only field with a filter: no Clear all, no token remove control, Backspace on the empty input | A read-only field removes a filter through Backspace, Clear all, or a token control. | `audit:PowerSearch/interaction` |
-| FR23 | PowerSearch and Tokenizer unit tests | Clear all with a read-only filter before two editable ones; every filter read-only; Backspace with a read-only last filter; the words with and without a read-only filter left | A read-only filter is removed, Clear all reports an index other than the first removed one, Clear all shows with no editable filter, or its words say every filter went while one remains. | `audit:PowerSearch/interaction` |
-| FR24 | `PowerSearchTokenNaming.test.tsx`; real-Chromium accessibility tree of a popover token | Popover token with a value, read-only token, editor open and closed, a verb-last remove word | A token named without its value, a missing or stale `aria-expanded`, an unnamed or non-dialog editor, or a remove name that loses its locale's word order fails. | `audit:PowerSearch/accessibility` |
-| FR10–FR21, AR4–AR6, PR5 | Focused PowerSearch sheet tests with the compact-touch query stubbed both ways, plus real-engine touch evidence (implementation gap: not yet in the tree; the Lab prototype's suite, `packages/lab/src/MobilePowerSearch/MobilePowerSearch.test.tsx`, is the current evidence for the flow the rows describe) | default popover, forced sheet, adaptive both ways (server markup and hydration as the popover field on a coarse-pointer client, then the trigger, no recoverable error, focus on the body; with `hasAutoFocus`, the autofocused input's focus ending on the trigger with no `onBlur` or `onFocus` to the caller), trigger name, Filters/Add filter/value steps, each value type, list value through the Tokenizer sheet, Clear all, read-only, disabled while open, focus after each step, focus after an `adaptive` switch from the trigger, the input, a removed control, an open editor popover, and from outside the field, a field inside an open Dialog announcing the count, Clear all, and in-sheet messages inside that Dialog and never on the page body, StrictMode result count, in-sheet live region while a sheet is open (added, removed, count, empty results), Clear all announced only after the dialog's exit, row, token and Removed text sharing one formatter, a date-only value as its day in `timezoneID`, else the UTC day, and a date-and-time value in `timezoneID`, else the viewer's zone, on all three (UTC, Tokyo, Honolulu, unset), summaries and relative-date labels and values from the catalog, the row and Removed through one reorderable message, an unmatched relative-date value as stored, a filter the config no longer knows listed and removable, a cleared number unstaged, choice rows as radios and checkboxes with `aria-checked`, a stale read-only filter as a plain row, a removal next to a nested row focusing that row's remove action, a list value joined by the locale's narrow conjunction list in English, Simplified Chinese, Japanese, and German, an empty-result message spoken once per query from its rendered element, a controlled update that removes the edited field moving focus from the replaced body to Cancel and announcing the unavailable state in the sheet while the step is open and never from a step beneath another or retained closed, Apply and Cancel after a controlled update removed the edited filter focusing the nearest row, else Add filter, a row's trailing remove action focusing the next row's remove action, a one-tap `empty`-valued filter added from its field row and removed from its row, Clear all behind its confirmation keeping read-only filters and leaving Filters open, a dismissed step revealing the step beneath with focus restored to it, Add filter opening with its search unfocused and a touch drag on the rows blurring a focused search, a stale filter's step titled as its row reads (raw keys for what is gone, the field's label when the field remains), Cancel from creation after the opening field was removed focusing the Add filter sheet's first control, a removed focused Filters row, a removed Clear all, and a dropped focused field row each handing focus to the nearest remaining row or the sheet's first control, element counts at rest and with each of the Filters, Add filter and value sheets open, and with the Tokenizer's list-value sheet stacked above the value step, under fine and coarse pointers, nothing of the flow in the DOM at rest before a press and after the exit, a nested filter edited and created through the built-in nested editor (its sub-filter rows wrapping inside a 390 and a 414 px sheet; its root operator picker absent on a mixed field, the Operator group in its place), a nested-only field and its suggestion offered, a suggestion's operator checked over the field's default, the Operator group outside a caller's Editor override on a mixed field, a count changed during the exit spoken with Clear all's message as one catalog message after the close, a radio group's arrow keys, Home, and End moving and checking, Space and Enter checking a focused radio row and toggling a checkbox row, right-to-left layout with the row chevrons mirrored in RTL (`design:bidirectionality/DR4`) | A field without `experimental` changes beyond what FR19 states, a value commits before the step confirms, Clear all removes a read-only filter, the trigger carries native `disabled`, focus lands elsewhere, an announcement reaches a channel outside the modal that holds the field at that moment, or the popover bundle carries the sheets. | `audit:PowerSearch/sheet` |
-| Record structure | `scripts/check-knowledge.mjs` | Component-contract schema and current-authority dependency | Missing or invalid metadata and sections fail repository validation. | `audit:PowerSearch/knowledge` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ----------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------- |
+| FR1–FR3, FR7 | PowerSearch unit tests plus real-Chromium geometry assertions | 399/400, 720/721, wide outer surface, narrow viewport, LTR/RTL, collision | Removing either clamp, capping the main menu, or allowing viewport overflow fails. | `audit:PowerSearch/layout` |
+| FR4–FR6, FR9 | Opening-path tests plus real-Chromium geometry assertions | Add from inner input; edit actual left/right/equidistant token/control; pointer/keyboard; reopen opposite side | Using pointer coordinates, modality, wrapper-only identity, stale identity, or public props fails. | `audit:PowerSearch/interaction` |
+| PR1–PR4 | Instrumented unit tests plus first-frame real-Chromium capture | Open, close, reopen opposite side; hidden placement commit; first painted frame | Render-time reads, repeated reads, observers, pointer tracking, or a default-position flash fails. | `audit:PowerSearch/performance` |
+| FR8, AR1–AR3 | Existing PowerSearch/editor suites plus focused browser checks | Pointer and keyboard edit, apply, cancel, Escape, light dismiss, focus return, selection, semantics | Focus, semantics, selection, dismissal, or reachability changes fail. | `audit:PowerSearch/accessibility` |
+| FR22 | PowerSearch and Tokenizer unit tests | A read-only field with a filter: no Clear all, no token remove control, Backspace on the empty input | A read-only field removes a filter through Backspace, Clear all, or a token control. | `audit:PowerSearch/interaction` |
+| FR23 | PowerSearch and Tokenizer unit tests | Clear all with a read-only filter before two editable ones; every filter read-only; Backspace with a read-only last filter; the words with and without a read-only filter left | A read-only filter is removed, Clear all reports an index other than the first removed one, Clear all shows with no editable filter, or its words say every filter went while one remains. | `audit:PowerSearch/interaction` |
+| FR24 | `PowerSearchTokenNaming.test.tsx`; real-Chromium accessibility tree of a popover token | Popover token with a value, read-only token, editor open and closed, a verb-last remove word | A token named without its value, a missing or stale `aria-expanded`, an unnamed or non-dialog editor, or a remove name that loses its locale's word order fails. | `audit:PowerSearch/accessibility` |
+| FR10–FR21, AR4–AR6, PR5 | Focused PowerSearch sheet tests with the compact-touch query stubbed both ways, plus real-engine touch evidence | default popover, forced sheet, adaptive both ways (server markup and hydration as the popover field on a coarse-pointer client, then the trigger, no recoverable error, focus on the body; with `hasAutoFocus`, the autofocused input's focus ending on the trigger with no `onBlur` or `onFocus` to the caller), trigger name, Filters/Add filter/value steps, each value type, list value through the Tokenizer sheet, Clear all, read-only, disabled while open, focus after each step, focus after an `adaptive` switch from the trigger, the input, a removed control, an open editor popover, and from outside the field, a field inside an open Dialog announcing the count, Clear all, and in-sheet messages inside that Dialog and never on the page body, StrictMode result count, in-sheet live region while a sheet is open (added, removed, count, empty results), Clear all announced only after the dialog's exit, row, token and Removed text sharing one formatter, a date-only value as its day in `timezoneID`, else the UTC day, and a date-and-time value in `timezoneID`, else the viewer's zone, on all three (UTC, Tokyo, Honolulu, unset), summaries and relative-date labels and values from the catalog, the row and Removed through one reorderable message, an unmatched relative-date value as stored, a filter the config no longer knows listed and removable, a cleared number unstaged, choice rows as radios and checkboxes with `aria-checked`, a stale read-only filter as a plain row, a removal next to a nested row focusing that row's remove action, a list value joined by the locale's narrow conjunction list in English, Simplified Chinese, Japanese, and German, an empty-result message spoken once per query from its rendered element, a controlled update that removes the edited field moving focus from the replaced body to Cancel and announcing the unavailable state in the sheet while the step is open and never from a step beneath another or retained closed, Apply and Cancel after a controlled update removed the edited filter focusing the nearest row, else Add filter, a row's trailing remove action focusing the next row's remove action, a one-tap `empty`-valued filter added from its field row and removed from its row, Clear all behind its confirmation keeping read-only filters and leaving Filters open, a dismissed step revealing the step beneath with focus restored to it, Add filter opening with its search unfocused and a touch drag on the rows blurring a focused search, a stale filter's step titled as its row reads (raw keys for what is gone, the field's label when the field remains), Cancel from creation after the opening field was removed focusing the Add filter sheet's first control, a removed focused Filters row, a removed Clear all, and a dropped focused field row each handing focus to the nearest remaining row or the sheet's first control, element counts at rest and with each of the Filters, Add filter and value sheets open, and with the Tokenizer's list-value sheet stacked above the value step, under fine and coarse pointers, nothing of the flow in the DOM at rest before a press and after the exit, a nested filter edited and created through the built-in nested editor (its sub-filter rows wrapping inside a 390 and a 414 px sheet; its root operator picker absent on a mixed field, the Operator group in its place), a nested-only field and its suggestion offered, a suggestion's operator checked over the field's default, the Operator group outside a caller's Editor override on a mixed field, a count changed during the exit spoken with Clear all's message as one catalog message after the close, a radio group's arrow keys, Home, and End moving and checking, Space and Enter checking a focused radio row and toggling a checkbox row, right-to-left layout with the row chevrons mirrored in RTL (`design:bidirectionality/DR4`) | A field without `experimental` changes beyond what FR19 states, a value commits before the step confirms, Clear all removes a read-only filter, the trigger carries native `disabled`, focus lands elsewhere, an announcement reaches a channel outside the modal that holds the field at that moment, or the popover bundle carries the sheets. | `audit:PowerSearch/sheet` |
+| Record structure | `scripts/check-knowledge.mjs` | Component-contract schema and current-authority dependency | Missing or invalid metadata and sections fail repository validation. | `audit:PowerSearch/knowledge` |
Current-source Chromium evidence establishes the geometry gap, not implementation
completion:
@@ -629,9 +634,7 @@ open editor on the Experimental Adaptive story under a fine pointer: 334, and
at rest, 339 with Filters open, 340 with Add filter above Filters, 366 with a
choice-row value step above both, 429 with a list-value step above both, and 413
with an edit step above Filters; it keeps all three sheets mounted from the
-first render, so its rest count already carries them. Core's own counts for each
-state of the stack are recorded here with its implementation; implementation
-gap: Core has no sheet flow to measure.
+first render, so its rest count already carries them. Core's sheet flow, on the same story under a coarse pointer, each state read once it has settled (every open dialog is that state's own and two readings one second apart agree), reads 123 at rest, 313 with Filters open, 314 with Add filter above Filters, 332 with a choice-row value step above both, 349 with a list-value step above both and 420 with the Tokenizer's list-value sheet above that step, 373 with an edit step above Filters, and 333 with the Clear all confirmation above Filters. From the first press until the exit completes, it keeps the closed Add filter sheet and value step mounted, which is most of the step from 123 to 313; the confirmation mounts only while it is open.
Owner exception to INV7's surface budget, which asks that a pointer-specific
presentation be a change of attributes and styles on the same elements: under
diff --git a/packages/core/api-report.md b/packages/core/api-report.md
index 2f4f9034a9..d407090e5c 100644
--- a/packages/core/api-report.md
+++ b/packages/core/api-report.md
@@ -1809,6 +1809,7 @@ component PowerSearch(props: PowerSearchProps)
prop config: PowerSearchConfig
prop disabledMessage?: string
prop endContent?: React.ReactNode
+ prop experimental?: { presentation?: 'popover' | 'bottom-sheet' | 'adaptive' } @experimental
prop filters: ReadonlyArray<PowerSearchFilter>
prop handleRef?: React.Ref<PowerSearchHandle>
prop hasAutoFocus?: boolean = false
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 72d6f10697..7cde835ef0 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -255,6 +255,126 @@
"defaultMessage": "{count, number} {count, plural, one {result} other {results}}",
"description": "Live result-count text next to the PowerSearch input, announced to screen readers on change. Example: `12 results`, `1 result`; keep compact."
},
+ "@astryx.powersearch.sheet.filtersTitle": {
+ "defaultMessage": "Filters",
+ "description": "Heading and accessible name of the PowerSearch touch sheet that lists the active filters (experimental bottom-sheet presentation). Plural noun."
+ },
+ "@astryx.powersearch.sheet.addFilter": {
+ "defaultMessage": "Add filter",
+ "description": "Button label in the PowerSearch touch flow: in the Filters sheet header it opens the field list; in the value step it confirms a new filter. Imperative verb; no leading plus sign."
+ },
+ "@astryx.powersearch.sheet.noFilters": {
+ "defaultMessage": "No filters applied",
+ "description": "Heading of the PowerSearch Filters sheet empty state when no filter is active (experimental bottom-sheet presentation). Neutral tone."
+ },
+ "@astryx.powersearch.sheet.noFiltersDescription": {
+ "defaultMessage": "Add a filter to narrow your results and find what you need faster.",
+ "description": "Guidance line under the PowerSearch Filters sheet empty state, above its Add filter action. One short sentence."
+ },
+ "@astryx.powersearch.sheet.clearAll": {
+ "defaultMessage": "Clear all",
+ "description": "Button label in the PowerSearch Filters sheet footer that asks to remove every editable filter. Imperative verb + determiner."
+ },
+ "@astryx.powersearch.sheet.clearAllTitle": {
+ "defaultMessage": "Clear all filters?",
+ "description": "Title and accessible name of the confirmation dialog that Clear all opens in the PowerSearch touch flow. A short question."
+ },
+ "@astryx.powersearch.sheet.clearAllDescription": {
+ "defaultMessage": "This removes all editable filters from this search.",
+ "description": "Body text of the PowerSearch Clear all confirmation dialog. Read-only filters stay, so it names editable filters."
+ },
+ "@astryx.powersearch.sheet.clearAllConfirm": {
+ "defaultMessage": "Clear filters",
+ "description": "Destructive action of the PowerSearch Clear all confirmation dialog: removes the editable filters. Imperative verb + plural noun."
+ },
+ "@astryx.powersearch.sheet.clearAllCancel": {
+ "defaultMessage": "Keep filters",
+ "description": "Safe action of the PowerSearch Clear all confirmation dialog: closes it and changes nothing. Imperative verb + plural noun."
+ },
+ "@astryx.powersearch.sheet.done": {
+ "defaultMessage": "Done",
+ "description": "Primary button label in the PowerSearch Filters sheet footer that closes the sheet. Short; marks the end of the filtering task."
+ },
+ "@astryx.powersearch.sheet.search": {
+ "defaultMessage": "Search",
+ "description": "Screen-reader-only label of the content-search box at the top of the PowerSearch Add filter sheet; its suggestions list inline below it. Noun or verb as reads best."
+ },
+ "@astryx.powersearch.sheet.searchResults": {
+ "defaultMessage": "Search results",
+ "description": "Screen-reader-only name of the inline suggestion list under the PowerSearch Add filter sheet's content search. Plural noun."
+ },
+ "@astryx.powersearch.sheet.searchFields": {
+ "defaultMessage": "Search filters",
+ "description": "Screen-reader-only label of the field-list filter box in the PowerSearch Add filter sheet, shown once the config has eight or more fields. Imperative verb + plural noun."
+ },
+ "@astryx.powersearch.sheet.searchFieldsPlaceholder": {
+ "defaultMessage": "Search filters…",
+ "description": "Placeholder inside the field-list filter box in the PowerSearch Add filter sheet. Imperative verb; trailing `…` is one character."
+ },
+ "@astryx.powersearch.sheet.ungroupedFields": {
+ "defaultMessage": "General",
+ "description": "Heading of the PowerSearch Add filter sheet's list of fields that belong to no group, shown before the named groups. A short noun."
+ },
+ "@astryx.powersearch.sheet.noMatchingFields": {
+ "defaultMessage": "No filters match your search",
+ "description": "Empty-state text in the PowerSearch Add filter sheet when the field-list filter matches no field. Neutral tone."
+ },
+ "@astryx.powersearch.sheet.tryDifferentSearch": {
+ "defaultMessage": "Try a different search.",
+ "description": "Guidance line under the PowerSearch Add filter sheet's empty search result (\"No results found\", \"No filters match your search\"). One short sentence."
+ },
+ "@astryx.powersearch.sheet.noResults": {
+ "defaultMessage": "No results found",
+ "description": "Empty-state text in the PowerSearch Add filter sheet when the content search has no suggestion for the typed query. Neutral tone (not error-y)."
+ },
+ "@astryx.powersearch.sheet.filterUnavailable": {
+ "defaultMessage": "This filter is no longer available",
+ "description": "Message in the PowerSearch value step when a config update removed the field or operator being edited; Cancel remains as the way out, and the Filters row keeps its remove action."
+ },
+ "@astryx.powersearch.sheet.removeFilter": {
+ "defaultMessage": "Remove {field} filter",
+ "description": "Accessible name and tooltip of the trailing remove button on a PowerSearch Filters sheet row; field is the filter's field label (for example \"Remove Status filter\")."
+ },
+ "@astryx.powersearch.sheet.relativeDaysAgo": {
+ "defaultMessage": "{count, number} {count, plural, one {day} other {days}} ago",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the past (for example \"3 days ago\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.relativeDaysFromNow": {
+ "defaultMessage": "{count, number} {count, plural, one {day} other {days}} from now",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the future (for example \"3 days from now\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.relativeWeeksAgo": {
+ "defaultMessage": "{count, number} {count, plural, one {week} other {weeks}} ago",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the past (for example \"3 weeks ago\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.relativeWeeksFromNow": {
+ "defaultMessage": "{count, number} {count, plural, one {week} other {weeks}} from now",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the future (for example \"3 weeks from now\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.relativeMonthsAgo": {
+ "defaultMessage": "{count, number} {count, plural, one {month} other {months}} ago",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the past (for example \"3 months ago\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.relativeMonthsFromNow": {
+ "defaultMessage": "{count, number} {count, plural, one {month} other {months}} from now",
+ "description": "A relative-date choice row in the PowerSearch touch sheet, in the future (for example \"3 months from now\"). The popover editor lists the same choices."
+ },
+ "@astryx.powersearch.sheet.fieldOperator": {
+ "defaultMessage": "{field} {operator}",
+ "description": "A field label joined with an operator label in the PowerSearch touch sheet: the value step's title, an operator radio's name, and the first part of a Filters row (for example \"Status is\"). Translators may reorder the two parts."
+ },
+ "@astryx.powersearch.sheet.labelValue": {
+ "defaultMessage": "{label} {value}",
+ "description": "A Filters row's \"field operator\" text joined with its value, as the removal announcement reads it (for example \"Status is Open\"). Translators may reorder the two parts."
+ },
+ "@astryx.powersearch.sheet.filtersClearedWithCount": {
+ "defaultMessage": "All filters removed. {resultCount}",
+ "description": "Polite screen-reader announcement after Clear all in the PowerSearch touch sheet when the result count changed with it; resultCount is the field's already formatted result count (for example \"240 results\"). Live-region text, never shown on screen."
+ },
+ "@astryx.powersearch.sheet.editableFiltersClearedWithCount": {
+ "defaultMessage": "Editable filters removed. {resultCount}",
+ "description": "Polite screen-reader announcement after Clear all in the PowerSearch touch sheet removes the editable filters, keeps read-only ones, and the result count changed with it; resultCount is the field's already formatted result count (for example \"240 results\"). Live-region text, never shown on screen."
+ },
"@astryx.alertDialog.cancel": {
"defaultMessage": "Cancel",
"description": "Button label on the secondary/dismiss button of an AlertDialog (modal confirmation). Imperative verb; consumers usually override with task-specific text."
diff --git a/packages/core/src/Field/Field.tsx b/packages/core/src/Field/Field.tsx
index 924a5a55dc..842222cada 100644
--- a/packages/core/src/Field/Field.tsx
+++ b/packages/core/src/Field/Field.tsx
@@ -25,11 +25,11 @@ import {FieldStatus} from '../FieldStatus/FieldStatus';
import {useFieldStatusAnnouncement} from '../FieldStatus/useFieldStatusAnnouncement';
import {spacingVars, borderVars, sizeVars} from '../theme/tokens.stylex';
import type {IconType} from '../Icon';
-import {mergeProps} from '../utils';
+import {mergeProps} from '../utils/mergeProps';
import {useDevWarning} from '../hooks/useDevWarning';
import {FormLayoutContext} from '../FormLayout/FormLayoutContext';
import {Text} from '../Text/Text';
-import {VisuallyHidden} from '../VisuallyHidden';
+import {VisuallyHidden} from '../VisuallyHidden/VisuallyHidden';
import {themeProps} from '../utils/themeProps';
import type {FieldStatusPlacement} from './fieldStatusPlacement';
diff --git a/packages/core/src/Field/fieldInputFamily.test.tsx b/packages/core/src/Field/fieldInputFamily.test.tsx
index 174a3e6e9e..e6e527b515 100644
--- a/packages/core/src/Field/fieldInputFamily.test.tsx
+++ b/packages/core/src/Field/fieldInputFamily.test.tsx
@@ -15,9 +15,18 @@ const SRC = join(__dirname, '..');
// Directories that render <Field> without being a Field-composed input.
const NOT_FIELD_INPUTS = new Set(['Field', 'InputGroup', 'FormLayout']);
-// Field-composed inputs not yet converted to FR10. Every member is converted;
-// typed explicitly so the empty set still accepts string lookups.
-const PENDING_FR10: ReadonlySet<string> = new Set<string>();
+// Field-composed inputs not yet converted to FR10. Every member is converted.
+// PowerSearch is outside the family (a composition that consumes member
+// behavior) and composes Field only in its experimental sheet presentation,
+// whose trigger renders the Field box the tokenizer field has. Its stable
+// contract keeps `ref` on the root (FR10 item 1 sends it to the primary
+// control) and carries root `xstyle`, `className`, and `style` (documented,
+// in use), which both presentations apply to that field box — the
+// `container*` target under FR10 items 2–4. Moving `ref` or omitting the
+// root styling props is a stable API change for existing callers, so it waits
+// for its own decision rather than riding the experimental option
+// (`component:PowerSearch` Open questions).
+const PENDING_FR10: ReadonlySet<string> = new Set<string>(['PowerSearch']);
function fieldComposedComponents(): string[] {
return readdirSync(SRC)
diff --git a/packages/core/src/PowerSearch/PowerSearch.doc.mjs b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
index 381a3499f1..2f31796810 100644
--- a/packages/core/src/PowerSearch/PowerSearch.doc.mjs
+++ b/packages/core/src/PowerSearch/PowerSearch.doc.mjs
@@ -65,7 +65,8 @@ export const docs = {
{
name: 'hasClear',
type: 'boolean',
- description: 'Show a clear-all button that removes every editable filter. Read-only filters stay.',
+ description:
+ 'Show a clear-all button that removes every editable filter. Read-only filters stay.',
default: 'true',
},
{
@@ -173,17 +174,20 @@ export const docs = {
{
name: 'menuWidth',
type: 'number',
- description: 'Maximum width for the operator/value dropdown menu in pixels.',
+ description:
+ 'Maximum width for the operator/value dropdown menu in pixels.',
},
{
name: 'maxOperatorMenuItems',
type: 'number',
- description: 'Maximum number of items displayed in the operator dropdown.',
+ description:
+ 'Maximum number of items displayed in the operator dropdown.',
},
{
name: 'tokenOverflowBehavior',
type: "'none' | 'unfocusedInline' | 'unfocusedLayer'",
- description: 'Controls how tokens overflow when the container is too narrow. Forwarded to Tokenizer.',
+ description:
+ 'Controls how tokens overflow when the container is too narrow. Forwarded to Tokenizer.',
default: "'none'",
},
{
@@ -202,6 +206,25 @@ export const docs = {
description:
'StyleX styles for layout customization. Must be a stylex.create() value.',
},
+ {
+ name: 'experimental',
+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",
+ stability: 'experimental',
+ description:
+ "Experimental options: anything in this object may change or be removed in a patch release, and omitting it keeps the stable behavior. presentation (default 'popover') chooses how the field presents filter editing. popover is the tokenizer field with its typeahead and the editor popover. bottom-sheet makes the whole field one trigger showing display-only filter tokens: it opens a Filters sheet listing the filters as rows that edit or remove a filter, with Add filter, Done, and Clear all (which asks first and keeps read-only filters); an Add filter sheet with the fields (or the content search with inline suggestions) opens above it, and a value step that stages operator → value and confirms from its footer opens above that. Dismissing a step reveals the one beneath. List values edit through the Tokenizer's own sheet. adaptive uses the bottom sheet on compact touch screens and the popover otherwise, resolved the same way Selector resolves it. In the sheet presentation menuWidth and tokenOverflowBehavior have no surface to act on and warn in development.",
+ },
+ ],
+ examples: [
+ {
+ label: 'Touch sheet on compact screens (experimental)',
+ code: `const [filters, setFilters] = useState([]);
+<PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'adaptive'}}
+/>`,
+ },
],
// `config` and `filters` are custom values the docsite preview cannot
// generate automatically. Keep this small, but include an initial token so
@@ -276,6 +299,22 @@ export const docs = {
},
theming: {
targets: [{className: 'astryx-power-search'}],
+ vars: [
+ {
+ name: '--_power-search-sheet-hit-inset',
+ description:
+ "Outset of the invisible hit area of the touch sheet's icon-sized actions (the Filters header's Add filter and each row's remove button), applied to a ::after overlay. 0 on a fine pointer; negative on a coarse one, which grows the action to a 44px touch target without changing what is drawn.",
+ default: '0px',
+ private: true,
+ },
+ {
+ name: '--_power-search-sheet-hit-content',
+ description:
+ 'Whether the touch sheet\'s invisible hit overlay exists. `none` on a fine pointer, so no ::after is generated and hover still reaches the action; `""` on a coarse one, where the overlay provides the 44px touch target.',
+ default: 'none',
+ private: true,
+ },
+ ],
},
};
@@ -439,6 +478,13 @@ export const docsZh = {
type: 'StyleXStyles',
description: '用于布局自定义的 StyleX 样式。必须是 stylex.create() 值。',
},
+ {
+ name: 'experimental',
+ type: "{presentation?: 'popover' | 'bottom-sheet' | 'adaptive'}",
+ stability: 'experimental',
+ description:
+ "实验性选项:此对象中的任何内容都可能在补丁版本中更改或移除;省略它即保持稳定行为。presentation(默认 'popover')决定字段如何呈现筛选编辑:popover 为带有预输入和编辑弹出层的标记字段;bottom-sheet 将整个字段变为一个显示只读筛选标记的触发按钮——点按后打开列出筛选项的「筛选」面板,每行可编辑或移除筛选(含添加筛选、完成、全部清除;全部清除会先确认,并保留只读筛选);列出字段(或带内联建议的内容搜索)的「添加筛选」面板在其上方打开,按运算符 → 值暂存并在底部确认的取值步骤再在其上方打开。关闭某一步会露出下方的那一步。列表值通过 Tokenizer 自身的面板编辑。adaptive 在紧凑触摸屏上使用底部面板,其他情况使用 popover,解析方式与 Selector 相同。在底部面板呈现中,menuWidth 和 tokenOverflowBehavior 没有作用对象,并会在开发环境中发出警告。",
+ },
],
usage: {
description:
@@ -507,7 +553,8 @@ export const docsDense = {
isLabelHidden: 'Visually hides label while keeping accessible.',
placeholder: 'Text shown when no filters selected.',
hasAutoFocus: 'Auto-focus input on mount.',
- hasClear: 'Show clear-all button; removes editable filters, keeps read-only ones.',
+ hasClear:
+ 'Show clear-all button; removes editable filters, keeps read-only ones.',
isReadOnly: 'Prevent adding, editing, or removing filters.',
isDisabled: 'Disables entire component.',
status: 'Validation status object w/ type + optional message.',
@@ -532,5 +579,7 @@ export const docsDense = {
size: 'Search input+token size.',
xstyle:
'StyleX styles for layout customization. Must be stylex.create() value.',
+ experimental:
+ "Experimental; may change in a patch. presentation: 'popover' (default, tokenizer field + editor popover) | 'bottom-sheet' (one trigger with display-only tokens + stacked Filters / Add filter / value sheets; rows remove inline; Clear all confirms, keeps read-only; list values via Tokenizer's sheet) | 'adaptive' (sheet on compact touch, else popover).",
},
};
diff --git a/packages/core/src/PowerSearch/PowerSearch.ssr.test.tsx b/packages/core/src/PowerSearch/PowerSearch.ssr.test.tsx
new file mode 100644
index 0000000000..9ab246c86f
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearch.ssr.test.tsx
@@ -0,0 +1,172 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PowerSearch.ssr.test.tsx
+ * @input PowerSearch server markup and React hydration under a compact
+ * coarse-pointer `matchMedia`
+ * @output Proves an `adaptive` PowerSearch server-renders and hydrates as the
+ * popover presentation's field without a recoverable error, then swaps to
+ * the sheet presentation's trigger on a touch screen with focus undisturbed
+ * (component:PowerSearch FR10)
+ * @position SSR acceptance test for PowerSearch's experimental presentation
+ */
+
+import {act} from 'react';
+import {afterEach, describe, expect, it, vi} from 'vitest';
+import {hydrateRoot} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import type {PowerSearchConfig, PowerSearchFilter} from './types';
+
+const config: PowerSearchConfig = {
+ name: 'Issues',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ operators: [
+ {
+ key: 'is',
+ label: 'is',
+ value: {
+ type: 'enum',
+ values: [
+ {value: 'open', label: 'Open'},
+ {value: 'closed', label: 'Closed'},
+ ],
+ },
+ },
+ ],
+ },
+ ],
+};
+
+const filters: PowerSearchFilter[] = [
+ {field: 'status', operator: 'is', value: {type: 'enum', value: 'open'}},
+];
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+function stubCoarsePointerScreen() {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: query.includes('pointer: coarse'),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+async function hydrateAdaptiveOnTouchScreen({
+ hasAutoFocus = false,
+ onFocus,
+ onBlur,
+}: {
+ hasAutoFocus?: boolean;
+ onFocus?: () => void;
+ onBlur?: () => void;
+} = {}) {
+ // A fresh module graph is a fresh server process.
+ vi.resetModules();
+ const {PowerSearch} = await import('./PowerSearch');
+ const tree = (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={() => {}}
+ hasAutoFocus={hasAutoFocus}
+ onFocus={onFocus}
+ onBlur={onBlur}
+ experimental={{presentation: 'adaptive'}}
+ />
+ );
+
+ // The server has no media query: `adaptive` answers `popover`, so the
+ // markup is the tokenizer field, not the trigger.
+ const html = renderToString(tree);
+ expect(html).toContain('role="combobox"');
+ // The sheet trigger is named by the label and its content; a popover token
+ // that opens its editor also says it opens a dialog, but is named itself.
+ expect(html).not.toMatch(
+ /<button(?=[^>]*aria-haspopup="dialog")(?=[^>]*aria-labelledby=)[^>]*>/,
+ );
+ if (hasAutoFocus) {
+ expect(html).toMatch(/<input[^>]*\sautofocus(=""|\s|>)/);
+ }
+
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ document.body.appendChild(container);
+ if (hasAutoFocus) {
+ // What a browser does with the markup's `autofocus` on load, before
+ // hydration attaches any listener; jsdom does not, so the test does.
+ (container.querySelector('[role="combobox"]') as HTMLElement).focus();
+ expect(document.activeElement).toBe(
+ container.querySelector('[role="combobox"]'),
+ );
+ }
+
+ // The client is a compact touch screen. The hydrating render still
+ // answers `popover` (the shared resolver's server snapshot), so the
+ // markup matches and no recoverable error is reported; the subscribed
+ // value then swaps the field to the trigger.
+ stubCoarsePointerScreen();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const recoverableErrors: unknown[] = [];
+ let root!: ReturnType<typeof hydrateRoot>;
+ await act(async () => {
+ root = hydrateRoot(container, tree, {
+ onRecoverableError: error => recoverableErrors.push(error),
+ });
+ });
+ expect(recoverableErrors).toEqual([]);
+ expect(consoleError).not.toHaveBeenCalled();
+ expect(
+ container.querySelector('button[aria-haspopup="dialog"][aria-labelledby]'),
+ ).not.toBe(null);
+ expect(container.querySelector('[role="combobox"]')).toBe(null);
+ return {
+ container,
+ trigger: container.querySelector(
+ 'button[aria-haspopup="dialog"][aria-labelledby]',
+ ) as HTMLElement,
+ unmount: async () => {
+ await act(async () => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+}
+
+describe('PowerSearch — SSR', () => {
+ it('server-renders and hydrates an adaptive field as the popover field, then swaps to the trigger on a touch screen without a mismatch or moving focus (FR10)', async () => {
+ const {unmount} = await hydrateAdaptiveOnTouchScreen();
+ // Nothing had focus before the swap, and nothing takes it.
+ expect(document.activeElement).toBe(document.body);
+ await unmount();
+ });
+
+ it("moves the autofocused input's focus to the trigger at the swap, within the same visit — no onBlur, no onFocus (FR10)", async () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ const {trigger, unmount} = await hydrateAdaptiveOnTouchScreen({
+ hasAutoFocus: true,
+ onFocus,
+ onBlur,
+ });
+ expect(document.activeElement).toBe(trigger);
+ expect(onBlur).not.toHaveBeenCalled();
+ expect(onFocus).not.toHaveBeenCalled();
+ await unmount();
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsx
index b5f7dcc60e..31376bc6bf 100644
--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx
@@ -546,6 +546,23 @@ describe('PowerSearch', () => {
});
});
+ it('keeps hasAutoFocus on the combobox across re-renders in the popover presentation, so a Dialog that opens later still finds data-autofocus', () => {
+ const field = (count: number) => (
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={() => {}}
+ hasAutoFocus
+ resultCount={count}
+ />
+ );
+ const {rerender} = render(field(1));
+ expect(screen.getByRole('combobox')).toHaveAttribute('data-autofocus');
+ rerender(field(2));
+ rerender(field(3));
+ expect(screen.getByRole('combobox')).toHaveAttribute('data-autofocus');
+ });
+
describe('result count announcements', () => {
const politeRegion = () =>
document.querySelector('[data-astryx-live-region="polite"]');
diff --git a/packages/core/src/PowerSearch/PowerSearch.tsx b/packages/core/src/PowerSearch/PowerSearch.tsx
index 697b9f9faa..b8e281cf75 100644
--- a/packages/core/src/PowerSearch/PowerSearch.tsx
+++ b/packages/core/src/PowerSearch/PowerSearch.tsx
@@ -4,19 +4,25 @@
/**
* @file PowerSearch.tsx
- * @input PowerSearchConfig, filters, onChange
+ * @input PowerSearchConfig, filters, onChange; Tokenizer, Field parts, Token,
+ * useAdaptivePresentation, and PowerSearchBottomSheet (lazy)
* @output Structured filter bar with token-based filter management
* @position Main component; forwards DOM ref and exposes tokenizer control via
- * handleRef
+ * handleRef. The experimental `presentation` option swaps the tokenizer
+ * field and editor popover for one trigger that opens PowerSearchBottomSheet.
*
* SYNC: When modified, update:
* - /packages/core/src/PowerSearch/index.ts
+ * - /packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx (sheet presentation)
* - /packages/cli/assets/templates/blocks/components/PowerSearch/ (showcase blocks)
*/
import React, {
+ lazy,
+ Suspense,
useCallback,
useEffect,
+ useId,
useImperativeHandle,
useMemo,
useRef,
@@ -37,30 +43,45 @@ import {Token} from '../Token';
import {TokenNamingContext} from '../Token/TokenNamingContext';
import {Avatar} from '../Avatar';
import {layerAnimations} from '../Layer/layerAnimations.stylex';
-import {Icon} from '../Icon';
+import {Icon, renderIconSlot} from '../Icon';
import type {IconType} from '../Icon';
import type {IconName} from '../Icon/globalIconRegistry';
import type {InputStatus} from '../Field';
+import {Field} from '../Field/Field';
+import {
+ inputStatusBorderStyles,
+ inputStatusFocusWithinStyles,
+ inputStatusHoverShadowStyles,
+ inputWrapperStyles,
+} from '../Field/inputStyles.stylex';
import {usePopover} from '../Popover/usePopover';
+import {useTooltip} from '../Tooltip/useTooltip';
import {layerViewportInset} from '../Layer/layerViewportInset.stylex';
import {useAnnounce} from '../hooks/useAnnounce';
+import {useAdaptivePresentation} from '../hooks/useAdaptivePresentation';
+import {useDevWarning} from '../hooks/useDevWarning';
+import {useIsHydrating} from '../hooks/useIsHydrating';
import {
spacingVars,
colorVars,
+ sizeVars,
typeScaleVars,
+ typographyVars,
fontWeightVars,
} from '../theme/tokens.stylex';
import {useSize} from '../SizeContext/SizeContext';
+import {isFocusDetached} from '../utils/focusReturn';
+import {isRenderable} from '../utils/isRenderable';
import {useInternalConfig} from './useInternalConfig';
import {usePowerSearchSource} from './usePowerSearchSource';
+import {formatFilterValue} from './formatFilterValue';
+import {NestedEditor, PowerSearchEditPopover} from './PowerSearchEditPopover';
import {
- formatFilterValue,
- formatDateAbsoluteCompact,
-} from './formatFilterValue';
-import {PowerSearchEditPopover} from './PowerSearchEditPopover';
+ buildRelativeDateOptions,
+ PowerSearchValueEditor,
+} from './PowerSearchValueEditor';
import {resolveOperatorLabel} from './resolveOperatorLabel';
import {themeProps} from '../utils/themeProps';
-import {truncateCharacters} from '../utils/characters';
import {useLocale} from '../i18n/useLocale';
import type {Locale} from '../i18n/types';
import type {SearchableItem} from '../Typeahead/types';
@@ -74,10 +95,14 @@ import type {
PowerSearchHandle,
FilterValue,
OperatorValue,
- EnumItem,
PowerSearchComponents,
PowerSearchOperator,
} from './types';
+import type {
+ PowerSearchBottomSheetProps,
+ PowerSearchSheetEditors,
+} from './PowerSearchBottomSheet';
+import {formatTokenValueText} from './formatTokenValue';
import {useMergedRefs} from '../hooks/useMergedRefs';
import type {FieldStatusPlacement} from '../Field/fieldStatusPlacement';
@@ -150,130 +175,127 @@ const resultCountStyles = stylex.create({
},
});
-function truncateString(value: string, limit: number): string {
- // Same semantics as before — strings within limit + 3 pass through, longer
- // ones cut to limit + '...' — but counted in characters, not code units.
- return truncateCharacters(value, limit + 3, '...');
-}
+// The sheet presentation's trigger field: the same control box as the
+// tokenizer field, with display-only tokens and one button as its only tab
+// stop.
+const sheetTriggerSizeStyles = stylex.create({
+ sm: {minHeight: sizeVars['--size-element-sm']},
+ md: {minHeight: sizeVars['--size-element-md']},
+ lg: {minHeight: sizeVars['--size-element-lg']},
+});
-function getEnumLabel(values: ReadonlyArray<EnumItem>, value: string): string {
- return values.find(v => v.value === value)?.label ?? value;
-}
+const sheetTriggerStyles = 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([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,
+ },
+ endSection: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-2'],
+ flexShrink: 0,
+ paddingInlineEnd: spacingVars['--spacing-1'],
+ },
+});
+
+// The sheet flow (three standalone sheets, the sheet editors) only
+// renders for the bottom-sheet presentation. Loading it on demand keeps it out
+// of pages whose PowerSearch stays a tokenizer field.
+// One import promise, shared by the preload and the lazy element: the sheet
+// presentation loads the flow's chunk as soon as it is active, so the first
+// press does not wait for the network, while nothing of the flow is rendered
+// until a press.
+const loadPowerSearchBottomSheet = async () =>
+ import('./PowerSearchBottomSheet');
+const LazyPowerSearchBottomSheet = lazy(async () =>
+ loadPowerSearchBottomSheet().then(module => ({
+ default: module.PowerSearchBottomSheet,
+ })),
+);
+// The value step reuses the popover presentation's editors, which this
+// module already loads; see PowerSearchSheetEditors.
+const SHEET_EDITORS: PowerSearchSheetEditors = {
+ NestedEditor,
+ PowerSearchValueEditor,
+ buildRelativeDateOptions,
+};
/**
- * The visible text of a filter token's value. The token renders it, and the
- * token's remove button and editor dialog are named by the same text.
+ * Hosts the lazily loaded sheet flow. Renders nothing on the server or in the
+ * render that hydrates server HTML: a lazy component that has not loaded yet
+ * would leave server markup incomplete and abort hydration. The closed flow
+ * has no visible markup, so it first renders right after hydration.
*/
-function tokenValueText(
- operatorValue: OperatorValue,
- filterValue: FilterValue,
- maxLength: number,
- locale: Locale,
-): string | null {
- switch (filterValue.type) {
- case 'empty':
- return null;
-
- case 'string':
- return truncateString(filterValue.value, maxLength);
-
- case 'integer':
- case 'float':
- return String(filterValue.value);
-
- case 'enum':
- if (operatorValue.type === 'enum') {
- return truncateString(
- getEnumLabel(operatorValue.values, filterValue.value),
- maxLength,
- );
- }
- return truncateString(filterValue.value, maxLength);
-
- case 'string_list': {
- const items = filterValue.value;
- if (items.length === 0) {
- return null;
- }
- if (items.length === 1) {
- return truncateString(items[0], maxLength);
- }
- const totalLength = items.reduce((sum, s) => sum + s.length, 0);
- if (totalLength > maxLength) {
- return `${items.length} items`;
- }
- return items.join(', ');
- }
-
- case 'enum_list': {
- const items = filterValue.value;
- if (items.length === 0) {
- return null;
- }
- if (operatorValue.type === 'enum_list') {
- const labels = items.map(v => getEnumLabel(operatorValue.values, v));
- if (labels.length === 1) {
- return truncateString(labels[0], maxLength);
- }
- const totalLength = labels.reduce((sum, s) => sum + s.length, 0);
- if (totalLength > maxLength) {
- return `${labels.length} items`;
- }
- return labels.join(', ');
- }
- if (items.length === 1) {
- return truncateString(items[0], maxLength);
- }
- return `${items.length} items`;
- }
-
- case 'entity_list': {
- const entities = filterValue.value;
- if (entities.length === 0) {
- return null;
- }
- if (entities.length === 1) {
- return truncateString(entities[0].label, maxLength);
- }
- const totalLength = entities.reduce((sum, e) => sum + e.label.length, 0);
- if (totalLength > maxLength) {
- return `${entities.length} items`;
- }
- return entities.map(e => e.label).join(', ');
- }
-
- case 'time':
- return filterValue.value;
-
- case 'date_absolute':
- return truncateString(
- formatDateAbsoluteCompact(filterValue.unixSeconds, locale),
- maxLength,
- );
-
- case 'date_relative':
- return truncateString(filterValue.value, maxLength);
-
- case 'date_range':
- return 'date range';
-
- case 'custom':
- if (operatorValue.type === 'custom') {
- return truncateString(
- operatorValue.getString(filterValue.value),
- maxLength,
- );
- }
- return filterValue.value;
-
- case 'nested': {
- const count = filterValue.value.length;
- return count === 1 ? '1 filter' : `${count} filters`;
- }
-
- default:
- return null;
+function PowerSearchSheetHost(
+ props: Omit<PowerSearchBottomSheetProps, 'editors'>,
+) {
+ const isHydrating = useIsHydrating();
+ if (isHydrating) {
+ return null;
}
+ return (
+ <Suspense fallback={null}>
+ <LazyPowerSearchBottomSheet {...props} editors={SHEET_EDITORS} />
+ </Suspense>
+ );
}
function PowerSearchTokenValue({text}: {text: string}) {
@@ -388,6 +410,37 @@ export interface PowerSearchProps extends Omit<
* Keys are operator value types (e.g. 'string', 'enum', 'date_absolute').
*/
components?: PowerSearchComponents;
+
+ /**
+ * Experimental options, outside the stable compatibility promise: anything
+ * in this object may change or be removed in a patch release. Omit it for
+ * the stable behavior.
+ * @experimental
+ */
+ experimental?: {
+ /**
+ * How the field presents filter editing.
+ * - `'popover'`: the tokenizer field with its typeahead and the editor
+ * popover — the stable behavior.
+ * - `'bottom-sheet'`: the whole field is one trigger showing display-only
+ * filter tokens; it opens a stack of sheets. Filters lists the filters
+ * as rows that edit or remove one, with Add filter, Done, and Clear
+ * all, which asks first and keeps read-only filters. Add filter opens
+ * above it with the fields (or the content search with inline
+ * suggestions), and a value step opens above that, stages operator →
+ * value, and confirms from its footer. Dismissing a step reveals the
+ * one beneath. Suited to compact touch screens, where the editor
+ * popover competes with the software keyboard.
+ * - `'adaptive'`: the bottom sheet on compact coarse-pointer screens,
+ * otherwise the popover — the same resolution Selector uses.
+ *
+ * In the sheet presentation `menuWidth` and `tokenOverflowBehavior` have
+ * no surface to act on and warn in development.
+ * @experimental
+ * @default 'popover'
+ */
+ presentation?: 'popover' | 'bottom-sheet' | 'adaptive';
+ };
}
// =============================================================================
@@ -524,6 +577,7 @@ export function PowerSearch({
className,
style,
components: componentOverrides,
+ experimental,
}: PowerSearchProps) {
const size = useSize(sizeProp, 'md');
const config = useInternalConfig(configProp);
@@ -537,6 +591,105 @@ export function PowerSearch({
popoverSaveButtonLabelFromProps ?? t('@astryx.powersearch.editor.apply');
const tokenizerRef = useRef<TokenizerHandle>(null);
+ // Experimental presentation. `adaptive`
+ // resolves through the policy the selection controls share; an open flow
+ // keeps its presentation until it closes, so a resolution change mid-task
+ // cannot pull the surface out from under the person.
+ const presentation = experimental?.presentation ?? 'popover';
+ const resolvedPresentation = useAdaptivePresentation(presentation);
+ const [isSheetOpen, setIsSheetOpen] = useState(false);
+ // Latched for the flow's lifetime: the flow stays presented after it closes
+ // until the sheets have run their exit and handed focus back to the trigger.
+ // Without the latch, `adaptive` resolving to `popover` mid-session (a phone
+ // turned to landscape) would unmount the sheets and the trigger they return
+ // focus to in the same render, dropping focus to the page body.
+ const [isSheetPresented, setIsSheetPresented] = useState(false);
+ const isSheetPresentation =
+ isSheetOpen || isSheetPresented || resolvedPresentation === 'bottom-sheet';
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ // `hasAutoFocus` applies only to the control the field first mounts. A
+ // presentation swap remounts the control (combobox input or trigger), and
+ // React's `autoFocus` on the new one would pull focus from wherever on the
+ // page it was; the roots' callback refs hand over the focus the field held
+ // instead. A field that never swaps keeps `autoFocus` on every render, so a
+ // Dialog that keeps it mounted still finds its `data-autofocus` on open.
+ const [autoFocusState, setAutoFocusState] = useState({
+ presentation: isSheetPresentation,
+ isFirstControl: true,
+ });
+ if (autoFocusState.presentation !== isSheetPresentation) {
+ setAutoFocusState({
+ presentation: isSheetPresentation,
+ isFirstControl: false,
+ });
+ }
+ const autoFocusOnMount =
+ hasAutoFocus &&
+ autoFocusState.isFirstControl &&
+ autoFocusState.presentation === isSheetPresentation;
+ // A focus the swap moves continues the same visit to the field: the
+ // control that held focus is gone (no blur fires for a removed element), so
+ // the caller is told of neither a blur nor a new focus.
+ const isSwapFocusRef = useRef(false);
+ const focusAfterSwap = useCallback((control: {focus(): void} | null) => {
+ if (control == null) {
+ return;
+ }
+ isSwapFocusRef.current = true;
+ try {
+ control.focus();
+ } finally {
+ isSwapFocusRef.current = false;
+ }
+ }, []);
+ const handleFieldFocus = useCallback(
+ (event: React.FocusEvent) => {
+ if (!isSwapFocusRef.current) {
+ onFocus?.(event);
+ }
+ },
+ [onFocus],
+ );
+ const handleFieldBlur = useCallback(
+ (event: React.FocusEvent) => {
+ onBlur?.(event);
+ },
+ [onBlur],
+ );
+ // While the flow is open, the sheet announces its own content from inside
+ // its dialog; this component announces only with the flow closed, and
+ // `useAnnounce` routes those messages by where the field is — into a Dialog
+ // or modal Drawer that holds it, or the shared channel when no modal does.
+ // A result count that changed during the flow's exit is spoken once the
+ // flow has fully closed and focus is back on the trigger: the closing
+ // dialog stays modal through its exit, so neither its region nor the
+ // page-body channel is heard before.
+ const afterCloseResultCountRef = useRef<string | null>(null);
+ const triggerId = useId();
+ const triggerLabelId = useId();
+ const triggerContentId = useId();
+ const statusMessageId = useId();
+ // A field that becomes disabled cannot keep its flow open, and must not
+ // reopen it when re-enabled. Adjusted in the
+ // render that sees the change, not an effect, so no frame shows both.
+ const [wasDisabled, setWasDisabled] = useState(isDisabled);
+ if (isDisabled !== wasDisabled) {
+ setWasDisabled(isDisabled);
+ if (isDisabled && isSheetOpen) {
+ setIsSheetOpen(false);
+ }
+ }
+ useDevWarning(
+ 'PowerSearch',
+ '`menuWidth` has no surface in the bottom-sheet presentation: the sheet flow has no typeahead popover to size. Scope it to the popover presentation or leave it out.',
+ isSheetPresentation && menuWidth != null,
+ );
+ useDevWarning(
+ 'PowerSearch',
+ '`tokenOverflowBehavior` has no surface in the bottom-sheet presentation: the trigger wraps its display-only tokens. Scope it to the popover presentation or leave it out.',
+ isSheetPresentation && tokenOverflowBehavior != null,
+ );
+
const [popoverState, setPopoverStateRaw] = useState<PopoverState>({
type: 'idle',
});
@@ -552,7 +705,7 @@ export function PowerSearch({
const operatorLabel = operator ? resolveOperatorLabel(operator, t) : '';
const label = `${fieldLabel}: ${operatorLabel}`.trim();
const value = operator
- ? tokenValueText(
+ ? formatTokenValueText(
operator.value,
filter.value,
Math.max(
@@ -581,9 +734,21 @@ export function PowerSearch({
componentOverrides?.[editedOperator.value.type]?.Token == null
? editedFilter
: undefined;
+ // Whether the editor popover is open, for the hand-off below, which runs
+ // in the commit that swaps presentations.
+ const isPopoverOpenRef = useRef(false);
+ // When `adaptive` flips to the sheet while the editor popover is open (a
+ // phone rotated), the editing ends with the popover: its state returns to
+ // idle (through the raw setter, since the tokenizer input is gone), in the
+ // render that sees the swap, so a later switch back does not reopen a stale
+ // editor.
+ if (isSheetPresentation && popoverState.type !== 'idle') {
+ setPopoverStateRaw({type: 'idle'});
+ }
// Layer for positioning the edit popover anchored to the tokenizer
const handleLayerHide = useCallback(() => {
+ isPopoverOpenRef.current = false;
setPopoverStateRaw({type: 'idle'});
}, []);
@@ -604,9 +769,54 @@ export function PowerSearch({
: undefined,
});
+ // A presentation swap removes the focused control, so the other
+ // presentation's primary control (the combobox input or the trigger) takes
+ // focus and focus never falls to the page body. Each presentation keys its
+ // root, so a swap mounts a new root. The detaching root notes that it held
+ // focus, which also covers an input focused by server-rendered `autofocus`
+ // before hydration. The editor popover is portaled outside the root, so an
+ // open editor counts as held focus. The attaching root gives focus to its
+ // primary control when focus has fallen to the page body; the sheet root
+ // also hides a popover layer left open.
+ const isFocusPendingHandOffRef = useRef(false);
+ const hidePopover = popover.hide;
+ const handOffFocusRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (node == null) {
+ return;
+ }
+ const trigger = triggerRef.current;
+ const isSheetRoot = trigger != null && node.contains(trigger);
+ // The sheet presentation preloads the flow's chunk, so the first press
+ // opens without waiting for the network; nothing renders.
+ if (isSheetRoot) {
+ void loadPowerSearchBottomSheet();
+ }
+ if (isSheetRoot && isPopoverOpenRef.current) {
+ isPopoverOpenRef.current = false;
+ hidePopover();
+ }
+ const takesFocus = isFocusPendingHandOffRef.current;
+ isFocusPendingHandOffRef.current = false;
+ if (takesFocus && isFocusDetached(node.ownerDocument)) {
+ focusAfterSwap(isSheetRoot ? trigger : tokenizerRef.current);
+ }
+ return () => {
+ if (
+ node.contains(node.ownerDocument.activeElement) ||
+ isPopoverOpenRef.current
+ ) {
+ isFocusPendingHandOffRef.current = true;
+ }
+ };
+ },
+ [focusAfterSwap, hidePopover],
+ );
+
// Wrapper that manages layer visibility and tokenizer focus alongside state
const setPopoverState = useCallback(
(state: PopoverState) => {
+ isPopoverOpenRef.current = state.type !== 'idle';
setPopoverStateRaw(state);
if (state.type !== 'idle') {
// Schedule after the current frame so React can render the popover
@@ -623,13 +833,22 @@ export function PowerSearch({
[popover],
);
- // Expose imperative handle
+ // Expose imperative handle; in the sheet presentation the trigger is the
+ // field's focusable control.
useImperativeHandle(handleRef, () => ({
focusTypeahead() {
- tokenizerRef.current?.focus();
+ if (isSheetPresentation) {
+ triggerRef.current?.focus();
+ } else {
+ tokenizerRef.current?.focus();
+ }
},
blurTypeahead() {
- tokenizerRef.current?.blur();
+ if (isSheetPresentation) {
+ triggerRef.current?.blur();
+ } else {
+ tokenizerRef.current?.blur();
+ }
},
}));
@@ -833,10 +1052,12 @@ export function PowerSearch({
setPopoverState({type: 'idle'});
}, [setPopoverState]);
- // Custom token renderer
- // Custom token renderer
- const renderToken = useCallback(
- (item: PowerSearchItem, onRemove: () => void) => {
+ // Token renderer for both presentations. Given `onRemove`, the token is
+ // the tokenizer field's: click edits, × removes. Without it (the sheet
+ // presentation's trigger) the token is display-only; the field as a whole
+ // opens the flow.
+ const renderFilterToken = useCallback(
+ (item: PowerSearchItem, onRemove: (() => void) | undefined) => {
const auxData = item.auxiliaryData;
const filterIndex = auxData?.filterIndex ?? -1;
const filter = filterIndex >= 0 ? filters[filterIndex] : undefined;
@@ -846,7 +1067,8 @@ export function PowerSearch({
? config.getOperator(auxData.fieldKey, auxData.operatorKey)
: undefined;
- const canInteract = !isReadOnly && !isDisabled && !filter?.isReadOnly;
+ const canInteract =
+ onRemove != null && !isReadOnly && !isDisabled && !filter?.isReadOnly;
const handleClick = canInteract
? () => handleTokenClick(filterIndex)
: undefined;
@@ -959,6 +1181,12 @@ export function PowerSearch({
],
);
+ const renderToken = useCallback(
+ (item: PowerSearchItem, onRemove: () => void) =>
+ renderFilterToken(item, onRemove),
+ [renderFilterToken],
+ );
+
// Custom typeahead item renderer — adds field icon and description
const renderItem = useCallback(
(item: PowerSearchItem) => {
@@ -1076,13 +1304,18 @@ export function PowerSearch({
return resultCount;
}, [resultCount, t]);
- // Announce result-count changes to screen readers through a polite live
- // region, mirroring the way Typeahead announces its dropdown result count.
- // The count is otherwise only shown visually and stays silent to assistive
- // tech. Only a change after mount is spoken: the guard compares against the
- // last announced text rather than a mounted flag, so StrictMode's effect
- // replay (which resets a flag and would speak the count present on mount
- // unprompted) announces nothing until the count changes.
+ // This Effect synchronizes a polite live region with the result count,
+ // mirroring the way Typeahead announces its dropdown result count: the count
+ // is otherwise only shown visually and stays silent to assistive tech. The
+ // region follows where the field is: the modal that holds the field (a
+ // Dialog, a modal Drawer), else the shared channel. While a sheet of the flow is open the sheet itself announces the
+ // count from inside its dialog, and this Effect stays quiet. Only a
+ // change after mount is spoken — the count present on mount is not
+ // announced unprompted — and the guard compares against the last announced
+ // text rather than a mounted flag, so StrictMode's effect replay announces
+ // nothing either. A change that lands while the flow is closing waits for
+ // the trigger focus, since the dialog is still modal through its exit. The
+ // announcement acquires no resource, so there is no cleanup.
const announce = useAnnounce();
// PowerSearch words its Clear all as its record does; the field announces
// these words instead of Tokenizer's (component:Tokenizer AR7).
@@ -1095,15 +1328,20 @@ export function PowerSearch({
[hasReadOnlyFilter, t],
);
const announcedResultCountRef = useRef(resultCountText);
+ const isSheetExiting = isSheetPresented && !isSheetOpen;
useEffect(() => {
if (resultCountText === announcedResultCountRef.current) {
return;
}
announcedResultCountRef.current = resultCountText;
if (resultCountText != null) {
- announce(resultCountText);
+ if (isSheetExiting) {
+ afterCloseResultCountRef.current = resultCountText;
+ } else if (!isSheetOpen) {
+ announce(resultCountText);
+ }
}
- }, [resultCountText, announce]);
+ }, [resultCountText, announce, isSheetExiting, isSheetOpen]);
// Build combined endContent from resultCount + endContent props
const combinedEndContent = useMemo((): React.ReactNode => {
@@ -1124,14 +1362,230 @@ export function PowerSearch({
return resultCountNode || endContent || undefined;
}, [resultCountText, endContent]);
+ // ------------------------------------------------------- sheet trigger --
+
+ // Disabled-reason tooltip for the sheet trigger. Disabled controls swallow
+ // pointer events, so the listeners attach to the field's control box; the
+ // trigger stays perceivable through aria-disabled.
+ const showsDisabledMessage = isDisabled && !!disabledMessage;
+ const disabledMessageTooltip = useTooltip({
+ placement: 'above',
+ focusTrigger: 'always',
+ isEnabled: isSheetPresentation && showsDisabledMessage,
+ });
+ const rootRef = useMergedRefs(
+ ref,
+ popover.triggerRef as React.Ref<HTMLDivElement>,
+ handOffFocusRef,
+ );
+
+ const openSheet = useCallback(() => {
+ if (isDisabled) {
+ return;
+ }
+ // The flow restores focus to the element that was active when it opened;
+ // make sure that is the trigger even for a tap on a token.
+ triggerRef.current?.focus({preventScroll: true});
+ setIsSheetPresented(true);
+ setIsSheetOpen(true);
+ }, [isDisabled]);
+
+ // The field's end lane — the result count and `endContent` — sits outside
+ // the trigger button: a caller's action button there keeps its own tab stop
+ // and taps, and an interactive control must not nest in a component
+ // button, so a tap on it must not open the flow.
+ const endLaneRef = useRef<HTMLDivElement>(null);
+ const handleTriggerWrapperClick = useCallback(
+ (event: React.MouseEvent<HTMLDivElement>) => {
+ // Tokens are display-only; a tap on them or the empty space around them
+ // opens the flow. The trigger button handles its own click, and the end
+ // lane handles its own.
+ if (
+ event.target instanceof Node &&
+ (triggerRef.current?.contains(event.target) ||
+ endLaneRef.current?.contains(event.target))
+ ) {
+ return;
+ }
+ openSheet();
+ },
+ [openSheet],
+ );
+
+ const handleTriggerFocusWithin = useCallback(
+ (event: React.FocusEvent<HTMLDivElement>) => {
+ // The flow focuses the trigger only after its exit completes; that focus
+ // is the signal that the retained sheets can leave. If the resolution
+ // moved to the popover meanwhile, the tokenizer input takes over the
+ // focus once it mounts (the hand-off above).
+ if (!isSheetOpen && isSheetPresented) {
+ setIsSheetPresented(false);
+ // The dialogs have closed: the page-body channel is exposed again.
+ const resultCount = afterCloseResultCountRef.current;
+ afterCloseResultCountRef.current = null;
+ if (resultCount != null) {
+ announce(resultCount);
+ }
+ }
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !event.currentTarget.contains(event.relatedTarget)
+ ) {
+ handleFieldFocus(event);
+ }
+ },
+ [announce, handleFieldFocus, isSheetOpen, isSheetPresented],
+ );
+ const handleTriggerBlurWithin = useCallback(
+ (event: React.FocusEvent<HTMLDivElement>) => {
+ if (
+ !(event.relatedTarget instanceof Node) ||
+ !event.currentTarget.contains(event.relatedTarget)
+ ) {
+ handleFieldBlur(event);
+ }
+ },
+ [handleFieldBlur],
+ );
+
+ if (isSheetPresentation) {
+ const triggerDescribedBy =
+ [
+ status?.message ? statusMessageId : null,
+ showsDisabledMessage ? disabledMessageTooltip.describedBy : null,
+ ]
+ .filter(Boolean)
+ .join(' ') || undefined;
+
+ return (
+ <div key="sheet" ref={rootRef} {...themeProps('power-search')}>
+ <Field
+ label={label}
+ isLabelHidden={isLabelHidden}
+ inputID={triggerId}
+ labelID={triggerLabelId}
+ 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={disabledMessageTooltip.ref}
+ onClick={handleTriggerWrapperClick}
+ onFocus={handleTriggerFocusWithin}
+ onBlur={handleTriggerBlurWithin}
+ aria-disabled={isDisabled ? true : undefined}
+ {...stylex.props(
+ inputWrapperStyles.base,
+ sheetTriggerStyles.wrapper,
+ filters.length > 0 && sheetTriggerStyles.wrapperWithTokens,
+ sheetTriggerSizeStyles[size],
+ isDisabled && inputWrapperStyles.disabled,
+ status && inputStatusBorderStyles[status.type],
+ status &&
+ !isDisabled &&
+ inputStatusHoverShadowStyles[status.type],
+ status && inputStatusFocusWithinStyles[status.type],
+ )}>
+ {/* The trigger's name is the label plus everything visible here:
+ the placeholder, or the tokens, so speech input can say what
+ it sees and assistive technology hears the selected filters
+ (WCAG 2.5.3). */}
+ <div
+ id={triggerContentId}
+ {...stylex.props(sheetTriggerStyles.contentSection)}>
+ {isRenderable(startIcon as React.ReactNode) && (
+ <span
+ {...stylex.props(
+ filters.length > 0 &&
+ sheetTriggerStyles.startIconWithTokens,
+ )}>
+ {renderIconSlot(startIcon, {size: 'sm', color: 'secondary'})}
+ </span>
+ )}
+ {tokenizerValue.map(item => (
+ <React.Fragment key={item.id}>
+ {renderFilterToken(item, undefined)}
+ </React.Fragment>
+ ))}
+ <button
+ type="button"
+ id={triggerId}
+ ref={triggerRef}
+ // The field's primary control: `data-testid` lands here, as it
+ // lands on the combobox input in the popover presentation.
+ data-testid={testId}
+ autoFocus={autoFocusOnMount}
+ onClick={openSheet}
+ aria-disabled={isDisabled ? true : undefined}
+ aria-haspopup="dialog"
+ aria-expanded={isSheetOpen}
+ aria-labelledby={`${triggerLabelId} ${triggerContentId}`}
+ aria-describedby={triggerDescribedBy}
+ {...stylex.props(
+ sheetTriggerStyles.trigger,
+ filters.length > 0 && sheetTriggerStyles.triggerWithTokens,
+ )}>
+ {filters.length === 0 ? placeholder : null}
+ </button>
+ </div>
+ {(endContent || isRenderable(resultCountText)) && (
+ <div
+ ref={endLaneRef}
+ {...stylex.props(sheetTriggerStyles.endSection)}>
+ {isRenderable(resultCountText) && (
+ <span {...stylex.props(resultCountStyles.text)}>
+ {resultCountText}
+ </span>
+ )}
+ {endContent}
+ </div>
+ )}
+ </div>
+ {showsDisabledMessage &&
+ disabledMessageTooltip.renderTooltip(disabledMessage)}
+ </Field>
+ {/* Mounted from the press until the flow's exit has completed and
+ focus is back on the trigger (`isSheetPresented`): at rest the
+ field renders its trigger alone — no closed dialogs, rows, search
+ field or editors in the DOM. */}
+ {(isSheetOpen || isSheetPresented) && (
+ <PowerSearchSheetHost
+ isOpen={isSheetOpen}
+ onOpenChange={setIsSheetOpen}
+ finalFocusRef={triggerRef}
+ resultCountText={resultCountText}
+ config={config}
+ configProp={configProp}
+ filters={filters}
+ onChange={onChange}
+ searchSource={searchSource}
+ placeholder={placeholder}
+ isReadOnly={isReadOnly}
+ isDisabled={isDisabled}
+ hasClear={hasClear}
+ maxOperatorMenuItems={maxOperatorMenuItems}
+ maxSearchResults={maxSearchResults}
+ saveButtonLabel={popoverSaveButtonLabelFromProps}
+ components={componentOverrides}
+ />
+ )}
+ </div>
+ );
+ }
+
return (
<>
- <div
- ref={useMergedRefs(
- ref,
- popover.triggerRef as React.Ref<HTMLDivElement>,
- )}
- {...themeProps('power-search')}>
+ <div key="popover" ref={rootRef} {...themeProps('power-search')}>
{/* The field's Clear all announces PowerSearch's own words
(component:PowerSearch; component:Tokenizer AR7). */}
<TokenizerClearAllMessageContext value={clearAllMessage}>
@@ -1148,7 +1602,7 @@ export function PowerSearch({
maxMenuItems={MAX_BROWSE_MENU_ITEMS}
menuWidth={menuWidth}
placeholder={filters.length === 0 ? placeholder : ''}
- hasAutoFocus={hasAutoFocus}
+ hasAutoFocus={autoFocusOnMount}
hasClear={hasClear && !isReadOnly}
startIcon={startIcon}
endContent={combinedEndContent}
@@ -1160,8 +1614,8 @@ export function PowerSearch({
debounceMs={0}
status={status}
statusVariant={statusVariant}
- onFocus={onFocus}
- onBlur={onBlur}
+ onFocus={handleFieldFocus}
+ onBlur={handleFieldBlur}
containerXstyle={xstyle}
containerClassName={className}
containerStyle={style}
diff --git a/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx b/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
new file mode 100644
index 0000000000..cf7779b69d
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchBottomSheet.test.tsx
@@ -0,0 +1,5001 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file PowerSearchBottomSheet.test.tsx
+ * @input Uses vitest, @testing-library/react, PowerSearch with
+ * `experimental.presentation`, and the sheet helpers
+ * @output Unit tests for the touch presentation (`component:PowerSearch`
+ * FR10–FR21, AR4–AR6): presentation resolution, the trigger, the Filters
+ * sheet, Add filter, the operator step, each value type (list values
+ * through the Tokenizer's sheet), content search, focus after each step,
+ * disabled while open, the StrictMode-safe result count, onChange metadata,
+ * nested filters through the built-in nested editor
+ * @position Core testing; validates PowerSearch.tsx (sheet trigger),
+ * PowerSearchBottomSheet.tsx and powerSearchSheetUtils.ts
+ *
+ * SYNC: When PowerSearchBottomSheet.tsx changes, update tests to match new
+ * behavior
+ */
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterEach,
+} from 'vitest';
+import {
+ cleanup,
+ render,
+ screen,
+ fireEvent,
+ waitFor,
+ within,
+} from '@testing-library/react';
+import React, {createRef, StrictMode, useState} from 'react';
+import {act} from '@testing-library/react';
+import {PowerSearch, type PowerSearchProps} from './PowerSearch';
+import type {
+ PowerSearchConfig,
+ PowerSearchEditorProps,
+ PowerSearchFilter,
+ PowerSearchHandle,
+ PowerSearchTokenProps,
+} from './types';
+import type {SearchableItem, SearchSource} from '../Typeahead/types';
+import {COMPACT_TOUCH_PRESENTATION_QUERY} from '../hooks/useAdaptivePresentation';
+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';
+import * as stylex from '@stylexjs/stylex';
+import {Dialog} from '../Dialog/Dialog';
+import userEvent from '@testing-library/user-event';
+import {rtlStyles} from '../utils';
+import {InternationalizationProvider} from '../i18n/InternationalizationProvider';
+import type {Overrides} from '../i18n/types';
+import {useInternalConfig} from './useInternalConfig';
+import {usePowerSearchSource} from './usePowerSearchSource';
+import {
+ createSheetSuggestionSource,
+ filterSignature,
+ nearestEditableIndex,
+ resolveFilterIdentityIndex,
+} from './powerSearchSheetUtils';
+import {renderHook} from '@testing-library/react';
+
+// =============================================================================
+// Environment
+// =============================================================================
+
+function stubMatchMedia(matcher: (query: string) => boolean) {
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ matches: matcher(query),
+ media: query,
+ onchange: null,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+}
+
+// jsdom implements neither <dialog> open/close nor pointer capture; the sheets
+// need both. Same stubs BottomSheet's own tests install.
+function stubEnvironment() {
+ 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();
+ }
+ stubMatchMedia(() => false);
+ // 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();
+}
+
+/**
+ * jsdom has no showModal(), so an open dialog never matches `:modal`; stand in
+ * for the sheets the browser presents modally. Returns the spy to restore.
+ */
+function mockModalDialogs() {
+ const matches = Element.prototype.matches;
+ return vi.spyOn(Element.prototype, 'matches').mockImplementation(function (
+ this: Element,
+ selector: string,
+ ) {
+ return selector === ':modal'
+ ? this instanceof HTMLDialogElement && this.open
+ : matches.call(this, selector);
+ });
+}
+
+const sharedLiveRegion = () =>
+ document.querySelector('[data-astryx-live-region="polite"]');
+const modalLiveRegion = (dialog: Element) =>
+ dialog.querySelector(':scope > [data-astryx-modal-live-region="polite"]');
+
+// =============================================================================
+// 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,
+};
+
+// A locale that puts the value first: module scope, since the provider
+// memoizes on prop identity.
+const REORDERED: Overrides = {
+ en: {
+ '@astryx.powersearch.sheet.labelValue': '{value} ({label})',
+ '@astryx.powersearch.sheet.filtersClearedWithCount':
+ '{resultCount} — all filters removed',
+ },
+};
+
+/** One field per non-nested value type 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: '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(),
+ },
+ },
+ ],
+ },
+ ],
+};
+
+type Presentation = NonNullable<
+ NonNullable<PowerSearchProps['experimental']>['presentation']
+>;
+
+function setup(
+ props: Partial<PowerSearchProps> & {presentation?: Presentation} = {},
+) {
+ const {presentation = 'bottom-sheet', ...rest} = props;
+ const onChange = vi.fn();
+ const result = render(
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={onChange}
+ experimental={{presentation}}
+ {...rest}
+ />,
+ );
+ return {onChange, ...result};
+}
+
+// The sheet presentation's trigger: it opens a dialog and is named by the
+// label and its content. A popover token that opens its editor also opens a
+// dialog, but is named itself.
+const SHEET_TRIGGER = 'button[aria-haspopup="dialog"][aria-labelledby]';
+
+function trigger(): HTMLElement {
+ return document.querySelector<HTMLElement>(SHEET_TRIGGER)!;
+}
+
+/** The field's control box holding the tokens and the trigger. */
+function field(): HTMLElement {
+ return trigger().parentElement!.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';
+}
+
+/**
+ * Every step is its own standalone sheet with its own dialog, and a list
+ * value's Tokenizer opens one more above the step. A replaced or covered
+ * dialog stays presented but inert, and a closing one that still holds focus
+ * drops `aria-modal` until its exit ends, so return the topmost open modal.
+ */
+function sheet(): HTMLElement {
+ const dialogs = document.querySelectorAll<HTMLElement>(
+ 'dialog[open][aria-modal="true"]:not([inert])',
+ );
+ const dialog = dialogs[dialogs.length - 1];
+ if (!dialog) {
+ throw new Error('no active 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 {
+ // A field or filter row is a button; a choice row is a radio or a checkbox
+ // (FR17). The replace handoff keeps the outgoing sheet presented while the
+ // incoming one enters; the last match is always on the sheet that just
+ // arrived.
+ const matches = [
+ ...within(sheet()).queryAllByRole('button', {name}),
+ ...within(sheet()).queryAllByRole('radio', {name}),
+ ...within(sheet()).queryAllByRole('checkbox', {name}),
+ ];
+ expect(matches.length).toBeGreaterThan(0);
+ fireEvent.click(matches[matches.length - 1]);
+}
+
+/** A choice row of the value step: a radio, or a checkbox for `enum_list`. */
+function choice(name: string): HTMLElement {
+ return (
+ within(sheet()).queryByRole('radio', {name}) ??
+ within(sheet()).getByRole('checkbox', {name})
+ );
+}
+
+function expectBleedChoiceRows(group: HTMLElement): void {
+ expect(group.className).toMatch(/choiceList/);
+ const rows = group.querySelectorAll('[role="radio"], [role="checkbox"]');
+ expect(rows.length).toBeGreaterThan(0);
+ for (const row of rows) {
+ expect(row.className).toMatch(/choiceRow/);
+ }
+ const body = group.closest('[class*="body"]');
+ expect(body).not.toBeNull();
+ const computed = getComputedStyle(body!);
+ expect(computed.getPropertyValue('--container-padding-inline-start')).toBe(
+ 'var(--spacing-4)',
+ );
+}
+
+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]);
+}
+
+/** The Clear all confirmation, open above the Filters sheet. */
+function clearConfirmation(): HTMLElement {
+ return screen.getByRole('alertdialog', {name: 'Clear all filters?'});
+}
+
+function confirmClearAll(): void {
+ fireEvent.click(
+ within(clearConfirmation()).getByRole('button', {name: 'Clear filters'}),
+ );
+}
+
+/** A Filters row's trailing remove action. */
+function removeButton(fieldLabel: string): HTMLElement {
+ return within(sheet()).getByRole('button', {
+ name: `Remove ${fieldLabel} filter`,
+ });
+}
+
+/**
+ * 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');
+ }
+ const body = list.closest('[class*="scrollContent"], [class*="body"]');
+ 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)',
+ );
+}
+
+// The sheet flow is loaded with React.lazy, so the first flow renders a tick
+// after it opens. Open one up front so the module is cached and every later
+// flow renders synchronously.
+beforeAll(async () => {
+ stubEnvironment();
+ try {
+ setup({filters: [openFilter]});
+ openSheet();
+ await screen.findByRole('heading', {name: 'Filters'}, {timeout: 15000});
+ } finally {
+ cleanup();
+ vi.unstubAllGlobals();
+ }
+}, 20000);
+
+beforeEach(() => {
+ __resetLiveRegionsForTest();
+ stubEnvironment();
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+// =============================================================================
+// Presentation resolution (FR10)
+// =============================================================================
+
+describe('PowerSearch presentation resolution (FR10)', () => {
+ it('keeps the tokenizer field when experimental is omitted', () => {
+ render(<PowerSearch config={config} filters={[]} onChange={vi.fn()} />);
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(document.querySelector(SHEET_TRIGGER)).toBeNull();
+ });
+
+ it('keeps the tokenizer field for an empty experimental object and for popover', () => {
+ const {unmount} = render(
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ experimental={{}}
+ />,
+ );
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ unmount();
+ setup({presentation: 'popover'});
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(document.querySelector(SHEET_TRIGGER)).toBeNull();
+ });
+
+ it('forces the trigger and the sheet flow for bottom-sheet', () => {
+ setup({filters: [openFilter]});
+ expect(screen.queryByRole('combobox')).toBeNull();
+ openSheet();
+ const dialog = sheet();
+ expect(dialog).toHaveAttribute('aria-label', 'Filters');
+ expect(dialog).toHaveAttribute('aria-modal', 'true');
+ });
+
+ it('uses the sheet for adaptive on a compact coarse-pointer screen', () => {
+ stubMatchMedia(query => query === COMPACT_TOUCH_PRESENTATION_QUERY);
+ setup({presentation: 'adaptive', filters: [openFilter]});
+ expect(screen.queryByRole('combobox')).toBeNull();
+ openSheet();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+
+ it('keeps adaptive on the tokenizer field without compact touch', () => {
+ setup({presentation: 'adaptive', filters: [openFilter]});
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(document.querySelector(SHEET_TRIGGER)).toBeNull();
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ });
+
+ it('warns once in development about props with no sheet surface', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ setup({menuWidth: 320, tokenOverflowBehavior: 'unfocusedInline'});
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('`menuWidth` has no surface'),
+ );
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('`tokenOverflowBehavior` has no surface'),
+ );
+ warn.mockClear();
+ cleanup();
+ setup({presentation: 'popover', menuWidth: 320});
+ expect(warn).not.toHaveBeenCalledWith(
+ expect.stringContaining('has no surface'),
+ );
+ warn.mockRestore();
+ });
+});
+
+// =============================================================================
+// Trigger field (FR11, AR4)
+// =============================================================================
+
+describe('PowerSearch sheet trigger (FR11)', () => {
+ it('names the trigger with the label and its visible placeholder', () => {
+ setup({label: 'Filter issues', placeholder: 'Search issues…'});
+ const button = trigger();
+ expect(button).toHaveAccessibleName('Filter issues Search issues…');
+ expect(button).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(button).toHaveTextContent('Search issues…');
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('exposes the selected filters in the trigger name', () => {
+ setup({filters: [openFilter, authorFilter]});
+ // Token text with no inline whitespace between label and value reads
+ // "is Open" or "isOpen" depending on the name computation.
+ expect(trigger()).toHaveAccessibleName(
+ /^Search Status: is ?Open Author: is ?Ada$/,
+ );
+ });
+
+ 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 = trigger();
+ expect(getComputedStyle(button.parentElement!).flexWrap).toBe('wrap');
+ expect(getComputedStyle(button).position).toBe('absolute');
+ });
+
+ it('stays focusable while disabled, with aria-disabled and no native disabled, and does not open', () => {
+ setup({isDisabled: true});
+ expect(trigger().hasAttribute('disabled')).toBe(false);
+ expect(trigger()).toHaveAttribute('aria-disabled', 'true');
+ expect(trigger()).not.toHaveAttribute('tabindex');
+ openSheet();
+ expect(isSheetOpen()).toBe(false);
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ });
+
+ it('describes a disabled trigger with its disabled reason', () => {
+ setup({isDisabled: true, disabledMessage: 'Pick a project first'});
+ expect(trigger()).toHaveAttribute('aria-disabled', 'true');
+ fireEvent.focus(trigger());
+ expect(trigger().getAttribute('aria-describedby')).toBeTruthy();
+ openSheet();
+ expect(isSheetOpen()).toBe(false);
+ });
+
+ it('closes the flow and returns focus to the trigger when the field becomes disabled (AST-085 FR2)', () => {
+ const {rerender} = setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ expect(isSheetOpen()).toBe(true);
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ isDisabled
+ />,
+ );
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ expect(trigger()).toHaveAttribute('aria-disabled', 'true');
+ // Re-enabling does not reopen it.
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ 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('fires onBlur when the flow opens and onFocus when it closes, as the popover does around its editor (FR11)', () => {
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ setup({filters: [openFilter], onFocus, onBlur});
+ openSheet();
+ // Focus moved into the sheet's dialog, outside the field.
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(2);
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ it('focuses the trigger through the imperative handle', () => {
+ const handle = createRef<PowerSearchHandle>();
+ setup({handleRef: handle});
+ handle.current?.focusTypeahead();
+ expect(trigger()).toHaveFocus();
+ handle.current?.blurTypeahead();
+ expect(trigger()).not.toHaveFocus();
+ });
+
+ it('forwards ref to the root, data-testid to the trigger, and the styling props to the field', () => {
+ const ref = createRef<HTMLDivElement>();
+ setup({
+ ref,
+ 'data-testid': 'ps',
+ className: 'custom-field',
+ filters: [openFilter],
+ });
+ expect(ref.current).toBeInstanceOf(HTMLDivElement);
+ expect(ref.current?.contains(trigger())).toBe(true);
+ expect(screen.getByTestId('ps')).toBe(trigger());
+ expect(document.querySelector('.custom-field')).not.toBeNull();
+ });
+
+ it('renders an interactive endContent beside the trigger, with its own tab stop and taps (FR11)', () => {
+ const onAction = vi.fn();
+ setup({
+ filters: [openFilter],
+ resultCount: 4,
+ endContent: (
+ <button type="button" onClick={onAction}>
+ Save view
+ </button>
+ ),
+ });
+ const action = screen.getByRole('button', {name: 'Save view'});
+ // A sibling of the trigger, never a descendant of it; the end lane's
+ // text is not part of the trigger's name.
+ expect(trigger().contains(action)).toBe(false);
+ expect(field().contains(action)).toBe(true);
+ expect(trigger()).toHaveAccessibleName(/^Search Status: is ?Open$/);
+ expect(screen.getByText('4 results')).toBeTruthy();
+ // Its own tab stop: two tab stops in the field, the trigger and the action.
+ expect(
+ Array.from(field().querySelectorAll('button')).filter(
+ element => element.tabIndex >= 0,
+ ),
+ ).toHaveLength(2);
+ // Its own taps: the action fires and the flow stays closed.
+ fireEvent.click(action);
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(isSheetOpen()).toBe(false);
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ // The empty space around the tokens still opens the flow.
+ fireEvent.click(trigger().parentElement!);
+ expect(isSheetOpen()).toBe(true);
+ });
+
+ it('keeps data-testid on the combobox input in the popover presentation', () => {
+ render(
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ data-testid="ps"
+ />,
+ );
+ expect(screen.getByTestId('ps')).toBe(screen.getByRole('combobox'));
+ });
+
+ it('renders the result count and announces only a change to it, not the mount (FR19)', async () => {
+ const {rerender} = render(
+ <StrictMode>
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ resultCount={12}
+ />
+ </StrictMode>,
+ );
+ expect(screen.getByText('12 results')).toBeTruthy();
+ const liveRegion = () =>
+ document.querySelector('[data-astryx-live-region="polite"]');
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(liveRegion()?.textContent ?? '').toBe('');
+ rerender(
+ <StrictMode>
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ resultCount={1}
+ />
+ </StrictMode>,
+ );
+ expect(screen.getByText('1 result')).toBeTruthy();
+ await waitFor(() =>
+ expect(liveRegion()?.textContent ?? '').toContain('1 result'),
+ );
+ });
+
+ it('announces a result-count change inside the open sheet, and on the shared channel once closed (FR19; AST-086 FR14)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const {rerender} = setup({filters: [openFilter], resultCount: 12});
+ openSheet();
+ const dialog = sheet();
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ resultCount={3}
+ />,
+ );
+ await waitFor(() =>
+ expect(modalLiveRegion(dialog)).toHaveTextContent('3 results'),
+ );
+ expect(modalLiveRegion(dialog)).toHaveAttribute('role', 'status');
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ fireEvent.click(within(dialog).getByRole('button', {name: 'Done'}));
+ settleSheets();
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ resultCount={1}
+ />,
+ );
+ await waitFor(() =>
+ expect(sharedLiveRegion()?.textContent ?? '').toContain('1 result'),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ function stubFlippableMatchMedia(initialCompact: boolean) {
+ let compact = initialCompact;
+ const listeners = new Set<() => void>();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ get matches() {
+ return query === COMPACT_TOUCH_PRESENTATION_QUERY ? compact : false;
+ },
+ media: query,
+ onchange: null,
+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),
+ removeEventListener: (_: string, cb: () => void) =>
+ listeners.delete(cb),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ return (next: boolean) => {
+ compact = next;
+ act(() => {
+ for (const cb of listeners) {
+ cb();
+ }
+ });
+ };
+ }
+
+ it('announces inside the modal that holds the field, in both presentations and after the flow closes (FR19, AR6; AST-086 FR14)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ // The field lives inside an open Astryx Dialog. Under FR14 its
+ // announcements belong to that dialog's region: `useAnnounce` follows
+ // the modal that encloses its caller.
+ function Host({
+ presentation,
+ resultCount,
+ filters,
+ onChange,
+ }: {
+ presentation: 'popover' | 'bottom-sheet';
+ resultCount: number;
+ filters: ReadonlyArray<PowerSearchFilter>;
+ onChange: (next: ReadonlyArray<PowerSearchFilter>) => void;
+ }) {
+ return (
+ <Dialog isOpen onOpenChange={() => {}} aria-label="Settings">
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={onChange}
+ resultCount={resultCount}
+ experimental={{presentation}}
+ />
+ </Dialog>
+ );
+ }
+ const noop = () => {};
+ const {rerender} = render(
+ <Host
+ presentation="popover"
+ resultCount={12}
+ filters={[openFilter]}
+ onChange={noop}
+ />,
+ );
+ const host = screen.getByRole('dialog', {name: 'Settings'});
+ // Popover presentation: a count change lands in the host dialog.
+ rerender(
+ <Host
+ presentation="popover"
+ resultCount={3}
+ filters={[openFilter]}
+ onChange={noop}
+ />,
+ );
+ await waitFor(() =>
+ expect(modalLiveRegion(host)).toHaveTextContent('3 results'),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ // Sheet presentation, flow closed: the same.
+ rerender(
+ <Host
+ presentation="bottom-sheet"
+ resultCount={3}
+ filters={[openFilter]}
+ onChange={noop}
+ />,
+ );
+ rerender(
+ <Host
+ presentation="bottom-sheet"
+ resultCount={5}
+ filters={[openFilter]}
+ onChange={noop}
+ />,
+ );
+ await waitFor(() =>
+ expect(modalLiveRegion(host)).toHaveTextContent('5 results'),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ // Clear all from the flow: its message, held until the sheet has gone,
+ // then lands in the host dialog, not on the page body.
+ const onChange = (next: ReadonlyArray<PowerSearchFilter>) => {
+ rerender(
+ <Host
+ presentation="bottom-sheet"
+ resultCount={next.length === 0 ? 240 : 5}
+ filters={next}
+ onChange={onChange}
+ />,
+ );
+ };
+ rerender(
+ <Host
+ presentation="bottom-sheet"
+ resultCount={5}
+ filters={[openFilter]}
+ onChange={onChange}
+ />,
+ );
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ confirmClearAll();
+ // Clear all leaves Filters open: its message lands in the Filters
+ // sheet's own region once the confirmation has closed, never in the
+ // host dialog's region or on the page body.
+ expect(isSheetOpen()).toBe(true);
+ const filtersSheet = screen.getByRole('dialog', {name: 'Filters'});
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersSheet)).toHaveTextContent(
+ 'All filters removed. 240 results',
+ ),
+ );
+ expect(modalLiveRegion(host)?.textContent ?? '').not.toContain(
+ 'All filters removed',
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it("hands focus to the other presentation's control when adaptive flips while the closed field holds it, as one visit (FR10)", async () => {
+ const flip = stubFlippableMatchMedia(true);
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ setup({presentation: 'adaptive', filters: [openFilter], onFocus, onBlur});
+ // Trigger → combobox: the phone turned to landscape with the trigger
+ // focused.
+ trigger().focus();
+ expect(trigger()).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ flip(false);
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ expect(document.querySelector(SHEET_TRIGGER)).toBeNull();
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ // Combobox → trigger: back to a compact touch screen with the input
+ // focused.
+ flip(true);
+ await waitFor(() =>
+ expect(document.querySelector(SHEET_TRIGGER)).toBeTruthy(),
+ );
+ expect(screen.queryByRole('combobox')).toBeNull();
+ expect(trigger()).toHaveFocus();
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ // Both hand-offs continued the one visit: the caller saw the first focus
+ // only, and no blur.
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).not.toHaveBeenCalled();
+ });
+
+ it('moves focus from any control the switch removes to the primary control (FR10)', async () => {
+ const flip = stubFlippableMatchMedia(false);
+ setup({
+ presentation: 'adaptive',
+ filters: [openFilter],
+ endContent: <button type="button">Save view</button>,
+ });
+ // A token's remove button holds focus in the popover presentation; the
+ // sheet presentation renders no remove button, so focus moves to the
+ // trigger.
+ screen.getByRole('button', {name: /^Remove/}).focus();
+ flip(true);
+ await waitFor(() =>
+ expect(document.querySelector(SHEET_TRIGGER)).toBeTruthy(),
+ );
+ expect(trigger()).toHaveFocus();
+ // `endContent` renders in both presentations, but each presentation
+ // mounts its own element for it, so the focused one does not survive the
+ // switch either: focus moves to the primary control.
+ screen.getByRole('button', {name: 'Save view'}).focus();
+ flip(false);
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ screen.getByRole('button', {name: 'Save view'}).focus();
+ flip(true);
+ await waitFor(() =>
+ expect(document.querySelector(SHEET_TRIGGER)).toBeTruthy(),
+ );
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('moves focus to the trigger when adaptive flips to the sheet while the editor popover is open (FR10)', async () => {
+ const user = userEvent.setup();
+ const flip = stubFlippableMatchMedia(false);
+ // jsdom has no Popover API; track which layer elements were shown so the
+ // test can tell an open layer from a mounted-but-closed one.
+ const shown = new Set<HTMLElement>();
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ shown.add(this);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ shown.delete(this);
+ });
+ const openLayers = () =>
+ Array.from(document.querySelectorAll<HTMLElement>('[popover]')).filter(
+ el => shown.has(el) || el.matches(':popover-open'),
+ );
+ setup({presentation: 'adaptive', filters: [openFilter]});
+ // Open the popover presentation's editor on the token and focus a
+ // control inside it (the popover is portaled, outside the field's root).
+ await user.click(screen.getByText('Status: is'));
+ const apply = await screen.findByRole('button', {
+ name: 'Apply',
+ hidden: true,
+ });
+ apply.focus();
+ expect(apply).toHaveFocus();
+ // The layer shows one frame after the editor state opens.
+ await waitFor(() => expect(openLayers()).toHaveLength(1));
+ // Rotate: the popover and its control unmount with the tokenizer field.
+ flip(true);
+ await waitFor(() =>
+ expect(document.querySelector(SHEET_TRIGGER)).toBeTruthy(),
+ );
+ expect(
+ screen.queryByRole('button', {name: 'Apply', hidden: true}),
+ ).toBeNull();
+ // Focus never fell to the body: the trigger has it.
+ expect(trigger()).toHaveFocus();
+ expect(HTMLDialogElement.prototype.showModal).not.toHaveBeenCalled();
+ // The sheet presentation renders no editor layer at all.
+ expect(document.querySelectorAll('[popover]')).toHaveLength(0);
+ // The edit ended with its surface: moving focus elsewhere and switching
+ // back does not reopen a stale editor or pull focus into it.
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ outside.focus();
+ flip(false);
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(
+ screen.queryByRole('button', {name: 'Apply', hidden: true}),
+ ).toBeNull();
+ expect(outside).toHaveFocus();
+ // And the editor's layer did not come back open and empty for the next
+ // Escape to close: the layer was hidden with its state at the swap (its
+ // closed element is the field's normal idle mount).
+ expect(openLayers()).toHaveLength(0);
+ outside.remove();
+ });
+
+ it('applies hasAutoFocus on the first mount only: a resolution change with focus elsewhere leaves it there and reports no onFocus (FR10)', async () => {
+ const flip = stubFlippableMatchMedia(false);
+ const onFocus = vi.fn();
+ render(
+ <>
+ <button type="button">Elsewhere</button>
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={() => {}}
+ hasAutoFocus
+ onFocus={onFocus}
+ experimental={{presentation: 'adaptive'}}
+ />
+ </>,
+ );
+ // The first mount autofocused the combobox input.
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ const elsewhere = screen.getByRole('button', {name: 'Elsewhere'});
+ elsewhere.focus();
+ expect(elsewhere).toHaveFocus();
+ // The swap remounts the field's control as a trigger; `autoFocus` must
+ // not fire again.
+ flip(true);
+ await waitFor(() =>
+ expect(document.querySelector(SHEET_TRIGGER)).toBeTruthy(),
+ );
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(elsewhere).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ // And back.
+ flip(false);
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(elsewhere).toHaveFocus();
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves focus alone when adaptive flips while the closed field does not hold it (FR10)', async () => {
+ const flip = stubFlippableMatchMedia(true);
+ setup({presentation: 'adaptive', filters: [openFilter]});
+ const outside = document.createElement('button');
+ document.body.appendChild(outside);
+ outside.focus();
+ flip(false);
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ expect(outside).toHaveFocus();
+ outside.remove();
+ });
+
+ it('keeps focus when adaptive stops resolving to the sheet while the flow is open, and the input takes over as one visit (FR10)', async () => {
+ // A matchMedia stub whose match can flip, with a change listener the
+ // test fires, as a phone turned to landscape would.
+ let compact = true;
+ const listeners = new Set<() => void>();
+ vi.stubGlobal(
+ 'matchMedia',
+ vi.fn().mockImplementation((query: string) => ({
+ get matches() {
+ return query === COMPACT_TOUCH_PRESENTATION_QUERY ? compact : false;
+ },
+ media: query,
+ onchange: null,
+ addEventListener: (_: string, cb: () => void) => listeners.add(cb),
+ removeEventListener: (_: string, cb: () => void) =>
+ listeners.delete(cb),
+ addListener: vi.fn(),
+ removeListener: vi.fn(),
+ dispatchEvent: vi.fn(),
+ })),
+ );
+ const onFocus = vi.fn();
+ const onBlur = vi.fn();
+ setup({presentation: 'adaptive', filters: [openFilter], onFocus, onBlur});
+ const button = trigger();
+ openSheet();
+ const dialog = sheet();
+ within(dialog).getByRole('button', {name: 'Add filter'}).focus();
+ // Opening the flow reported one blur (FR11).
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ onFocus.mockClear();
+
+ // The viewport stops being compact while the flow is open: nothing
+ // changes until the flow closes.
+ compact = false;
+ act(() => {
+ for (const cb of listeners) {
+ cb();
+ }
+ });
+ expect(sheet()).toBe(dialog);
+ expect(button).toBeInTheDocument();
+ expect(screen.queryByRole('combobox')).toBeNull();
+
+ fireEvent.click(within(dialog).getByRole('button', {name: 'Done'}));
+ // The flow is closing; the trigger stays mounted to take focus back, and
+ // the tokenizer field does not appear yet.
+ expect(button).toBeInTheDocument();
+ expect(screen.queryByRole('combobox')).toBeNull();
+ settleSheets();
+ // Focus came back to the trigger, the latch released into the popover
+ // presentation, and the tokenizer input took the focus over.
+ await waitFor(() => expect(screen.getByRole('combobox')).toBeTruthy());
+ expect(screen.getByRole('combobox')).toHaveFocus();
+ expect(document.querySelector(SHEET_TRIGGER)).toBeNull();
+ // The close reported one focus (FR11, the trigger); the input taking
+ // over is the same visit, so no second focus and no blur between.
+ expect(onFocus).toHaveBeenCalledTimes(1);
+ expect(onBlur).toHaveBeenCalledTimes(1);
+ });
+
+ it("renders a Token override on the trigger with the popover's props and its callbacks withheld (FR11)", () => {
+ 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(
+ trigger().parentElement!.contains(screen.getByText('Custom token')),
+ ).toBe(true);
+ // The same props the popover hands it — config, filter, field, operator,
+ // maxLength, isDisabled — and `onClick`/`onRemove` undefined, as for a
+ // read-only filter in the popover: the trigger's tokens are display-only.
+ expect(seenProps).toHaveBeenLastCalledWith({
+ config,
+ filter: openFilter,
+ field: config.fields[0],
+ operator: config.fields[0].operators[0],
+ maxLength: 40,
+ onClick: undefined,
+ onRemove: undefined,
+ isDisabled: false,
+ });
+ });
+
+ it('announces a row removal and Clear all inside the open Filters sheet (AR6)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([authorFilter, openFilter]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ // The count follows the filters, so Clear all changes it in the
+ // same commit as the removal.
+ resultCount={filters.length === 0 ? 240 : 12}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ const filtersDialog = sheet();
+ expect(filtersDialog).toHaveAttribute('aria-label', 'Filters');
+ // A row's trailing remove action stays in Filters and speaks there at
+ // once, naming the row's text, as the popover's token × names its token.
+ fireEvent.click(removeButton('Status'));
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed Status is Open',
+ ),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ // Clear all asks first: nothing is removed or spoken while the
+ // confirmation is the top modal.
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ expect(clearConfirmation()).toBeTruthy();
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(modalLiveRegion(filtersDialog)?.textContent ?? '').not.toMatch(
+ /All filters removed|240 results/,
+ );
+ // Confirmed, the outcome and the count that changed with it are one
+ // announcement in the still-open Filters sheet.
+ confirmClearAll();
+ expect(isSheetOpen()).toBe(true);
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'All filters removed. 240 results',
+ ),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('words Clear all as "Editable filters removed" while a read-only filter remains (AR6)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};
+ function Harness({resultCount}: {resultCount?: number}) {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([authorFilter, pinned]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ resultCount={resultCount}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ const filtersDialog = sheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ confirmClearAll();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Editable filters removed',
+ ),
+ );
+ expect(modalLiveRegion(filtersDialog)?.textContent ?? '').not.toContain(
+ 'All filters removed',
+ );
+ // The kept read-only row is plain, so the first remaining control is
+ // Add filter.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
+// =============================================================================
+// Filters sheet (FR12)
+// =============================================================================
+
+describe('PowerSearch Filters sheet (FR12)', () => {
+ it('shows selected filters as editable rows with trailing remove actions and 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)',
+ });
+ const remove = within(list).getByRole('button', {
+ name: 'Remove Status filter',
+ });
+ // An icon button: no chevron, and the remove glyph is the row's only
+ // icon.
+ expect(remove.querySelector('svg')).toBeTruthy();
+ expect(list.querySelectorAll('svg')).toHaveLength(1);
+ });
+
+ it('removes a filter from its row without opening the step, with exact remove metadata (FR12, FR15)', () => {
+ const {onChange} = setup({filters: [authorFilter, openFilter]});
+ openSheet();
+ fireEvent.click(removeButton('Status'));
+ expect(onChange).toHaveBeenCalledWith([authorFilter], 'remove', 1);
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ });
+
+ it('removes a one-tap filter with a tap on its row or its remove action, not a checked indicator (FR12)', () => {
+ const unassigned: PowerSearchFilter = {
+ field: 'unassigned',
+ operator: 'isTrue',
+ value: {type: 'empty'},
+ };
+ const {onChange} = setup({filters: [unassigned]});
+ openSheet();
+ const remove = removeButton('Unassigned');
+ expect(remove.querySelector('svg')).toBeTruthy();
+ expect(within(sheet()).queryByRole('checkbox')).toBeNull();
+ tapRow('Unassigned is true');
+ expect(onChange).toHaveBeenLastCalledWith([], 'remove', 0);
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ fireEvent.click(remove);
+ expect(onChange).toHaveBeenCalledTimes(2);
+ });
+
+ it('shows one centered Add filter and no header action, Done or Clear all when no filter is applied (FR12)', () => {
+ function EmptyStateHarness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<EmptyStateHarness />);
+ openSheet();
+ fireEvent.click(removeButton('Status'));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'No filters applied'}),
+ ).toBeTruthy();
+ const addActions = within(sheet()).getAllByRole('button', {
+ name: 'Add filter',
+ });
+ expect(addActions).toHaveLength(1);
+ expect(addActions[0]).toHaveAttribute('data-variant', 'primary');
+ // After the last removal, focus lands on that one action.
+ expect(addActions[0]).toHaveFocus();
+ expect(within(sheet()).queryByRole('button', {name: 'Done'})).toBeNull();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Clear all'}),
+ ).toBeNull();
+ fireEvent.click(addActions[0]);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ });
+
+ it('keeps the header with the Add filter icon and the footer with Clear all and Done fixed around a scroll viewport (FR12)', () => {
+ 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(add).toHaveAttribute('data-variant', 'secondary');
+ expect(add.textContent).toBe('');
+ expect(done).toHaveAttribute('data-variant', 'primary');
+ expect(clearAll).toHaveAttribute('data-variant', 'secondary');
+ expect(getComputedStyle(clearAll).flexGrow).toBe('1');
+ expect(getComputedStyle(done).flexGrow).toBe('1');
+ // Only the rows scroll: the footer is outside the viewport.
+ const footer = clearAll.parentElement!;
+ expect(getComputedStyle(footer).position).toBe('relative');
+ const viewport = list.closest<HTMLElement>('[class*="scrollViewport"]')!;
+ expect(viewport).not.toBeNull();
+ expect(getComputedStyle(viewport).overflowY).toBe('auto');
+ expect(viewport.contains(footer)).toBe(false);
+ expect(viewport.contains(heading)).toBe(false);
+ });
+
+ it('grows each icon-sized action to a 44px hit area under a coarse pointer, without resizing it (AR5)', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ const rules: string[] = [];
+ for (const styleSheet of Array.from(document.styleSheets)) {
+ for (const rule of Array.from(styleSheet.cssRules)) {
+ rules.push(rule.cssText);
+ }
+ }
+ const hasRule = (element: HTMLElement, pattern: RegExp) =>
+ Array.from(element.classList).some(className =>
+ rules.some(
+ text => text.includes(`.${className}`) && pattern.test(text),
+ ),
+ );
+ for (const action of [
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ removeButton('Status'),
+ ]) {
+ expect(
+ hasRule(action, /--_power-search-sheet-hit-inset:\s*min\(0px/),
+ ).toBe(true);
+ expect(hasRule(action, /--_power-search-sheet-hit-content:\s*none/)).toBe(
+ true,
+ );
+ }
+ });
+
+ 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 editable filters behind a confirmation, keeps Filters open, and focuses Add filter (FR12, FR16)', () => {
+ const onChange = vi.fn();
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ authorFilter,
+ openFilter,
+ ]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={(next, type, index) => {
+ onChange(next, type, index);
+ setFilters(next);
+ }}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ expect(onChange).not.toHaveBeenCalled();
+ const confirmation = clearConfirmation();
+ expect(
+ within(confirmation).getByText(
+ 'This removes all editable filters from this search.',
+ ),
+ ).toBeTruthy();
+ // The safe action takes focus first.
+ expect(
+ within(confirmation).getByRole('button', {name: 'Keep filters'}),
+ ).toHaveFocus();
+ confirmClearAll();
+ expect(onChange).toHaveBeenCalledWith([], 'remove', 0);
+ expect(
+ screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),
+ ).toBeNull();
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'No filters applied'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ expect(within(field()).queryByText('Open')).toBeNull();
+ });
+
+ it('keeps read-only filters on Clear all, reporting the first removed index (FR12)', () => {
+ const pinned: PowerSearchFilter = {...openFilter, isReadOnly: true};
+ const {onChange} = setup({filters: [pinned, authorFilter]});
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ confirmClearAll();
+ expect(onChange).toHaveBeenCalledWith([pinned], 'remove', 1);
+ expect(isSheetOpen()).toBe(true);
+ });
+
+ it('returns to Filters unchanged when the confirmation is dismissed or kept (FR12)', () => {
+ const {onChange} = setup({filters: [openFilter]});
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ // A scrim press, which starts and ends on the dialog itself, dismisses
+ // the confirmation and returns focus to Clear all.
+ const confirmation = clearConfirmation();
+ fireEvent.pointerDown(confirmation);
+ fireEvent.pointerUp(confirmation);
+ fireEvent.click(confirmation);
+ expect(
+ screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),
+ ).toBeNull();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Clear all'}),
+ ).toHaveFocus();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ fireEvent.click(
+ within(clearConfirmation()).getByRole('button', {name: 'Keep filters'}),
+ );
+ expect(
+ screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),
+ ).toBeNull();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Clear all'}),
+ ).toHaveFocus();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(isSheetOpen()).toBe(true);
+ expect(within(sheet()).getByText('Status is')).toBeTruthy();
+ });
+
+ it('hides Clear all when every filter is read-only', () => {
+ setup({filters: [{...openFilter, isReadOnly: true}]});
+ openSheet();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Clear all'}),
+ ).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Done'})).toBeTruthy();
+ });
+
+ it('closes the Clear all confirmation with the flow when the field becomes disabled', () => {
+ const {rerender} = setup({filters: [openFilter]});
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ expect(clearConfirmation()).toBeTruthy();
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ isDisabled
+ />,
+ );
+ expect(
+ screen.queryByRole('alertdialog', {name: 'Clear all filters?'}),
+ ).toBeNull();
+ expect(isSheetOpen()).toBe(false);
+ });
+
+ it('drops a focus target left pending when the flow closes, so a reopen does not move focus to it', () => {
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ const [isDisabled, setIsDisabled] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setIsDisabled(false)}>
+ Enable
+ </button>
+ <PowerSearch
+ config={config}
+ filters={filters}
+ isDisabled={isDisabled}
+ // The commit that queues focus on Add filter also disables the
+ // field, which closes the flow before that focus lands.
+ onChange={next => {
+ setFilters(next);
+ setIsDisabled(true);
+ }}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </>
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Add filter'}));
+ tapRow('Status');
+ tapRow('Closed');
+ addFilter();
+ expect(isSheetOpen()).toBe(false);
+ // Reopened before the closing sheets finish their exit, so the flow is
+ // still mounted.
+ fireEvent.click(screen.getByRole('button', {name: 'Enable'}));
+ openSheet();
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).not.toHaveFocus();
+ });
+
+ 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("lists a nested filter as a row whose step edits it with the popover's built-in nested editor, plain while read-only (FR12, FR14)", async () => {
+ const spy = mockModalDialogs();
+ try {
+ const withNested: PowerSearchConfig = {
+ name: 'Nested',
+ fields: [
+ ...config.fields,
+ {
+ key: 'mixed',
+ label: 'Mixed',
+ operators: [
+ {key: 'all', label: 'all of', value: {type: 'nested'}},
+ {key: 'is', label: 'is', value: {type: 'string'}},
+ ],
+ },
+ ],
+ };
+ const nestedFilter: PowerSearchFilter = {
+ field: 'mixed',
+ operator: 'all',
+ value: {type: 'nested', value: [openFilter]},
+ };
+ const onChange = vi.fn();
+ function Harness({readOnly}: {readOnly?: boolean}) {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([openFilter, nestedFilter]);
+ return (
+ <PowerSearch
+ config={withNested}
+ filters={filters}
+ onChange={(next, type, index) => {
+ onChange(next, type, index);
+ setFilters(next);
+ }}
+ isReadOnly={readOnly}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ const {unmount} = render(<Harness />);
+ openSheet();
+ // The row is a button; its step holds the popover's built-in nested
+ // editor (the sub-filter tree with its Add action) and the Operator
+ // group for the field's two operators, each in its own section, and no
+ // Remove: the row's trailing action removes it.
+ fireEvent.click(
+ within(sheet()).getByRole('button', {name: 'Mixed all of 1 filter'}),
+ );
+ expect(within(sheet()).getByRole('tree')).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: '+ Add filter'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Mixed all of'}),
+ ).toBeChecked();
+ expect(within(sheet()).getByRole('button', {name: 'Apply'})).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Remove'}),
+ ).toBeNull();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ // The value step finishes its exit before the removal.
+ settleSheets();
+ fireEvent.click(removeButton('Mixed'));
+ expect(onChange).toHaveBeenCalledWith([openFilter], 'remove', 1);
+ const filtersDialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed Mixed all of 1 filter',
+ ),
+ );
+ unmount();
+ // Read-only field: a plain row.
+ render(<Harness readOnly />);
+ openSheet();
+ expect(within(sheet()).getByText(/^Mixed all of/)).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('button', {name: /^Mixed all of/}),
+ ).toBeNull();
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('lists a stale filter as a plain row when it, or the field, is read-only (FR12)', () => {
+ const orphan: PowerSearchFilter = {
+ field: 'legacy',
+ operator: 'was',
+ value: {type: 'string', value: 'x'},
+ };
+ const {unmount} = setup({filters: [{...orphan, isReadOnly: true}]});
+ openSheet();
+ expect(within(sheet()).getByText(/^legacy was/)).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('button', {name: /^legacy was/}),
+ ).toBeNull();
+ unmount();
+ setup({filters: [orphan], isReadOnly: true});
+ openSheet();
+ expect(within(sheet()).getByText(/^legacy was/)).toBeTruthy();
+ expect(
+ within(sheet()).queryByRole('button', {name: /^legacy was/}),
+ ).toBeNull();
+ });
+
+ it("mirrors the field rows' chevrons in right-to-left layouts, and no sheet has a Back action (DR4, FR15a)", () => {
+ const {className: mirrorClassName} = stylex.props(rtlStyles.mirror);
+ const mirrorClasses = mirrorClassName?.split(' ') ?? [];
+ expect(mirrorClasses.length).toBeGreaterThan(0);
+ // The Icon applies `xstyle` to its wrapper, the element that holds the
+ // glyph.
+ const hasMirror = (container: HTMLElement) =>
+ Array.from(container.querySelectorAll('*')).some(el =>
+ mirrorClasses.every(c => el.classList.contains(c)),
+ );
+ render(
+ <div dir="rtl" style={{direction: 'rtl'}}>
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </div>,
+ );
+ openSheet();
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ tapRow('Add filter');
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ // Every field row's chevron points into the row's reading direction once
+ // flipped; a one-tap field's plus is not mirrored.
+ const statusRow = within(sheet())
+ .getByRole('button', {name: 'Status'})
+ .closest('li')!;
+ expect(hasMirror(statusRow)).toBe(true);
+ const unassignedRow = within(sheet())
+ .getByRole('button', {name: 'Unassigned'})
+ .closest('li')!;
+ expect(hasMirror(unassignedRow)).toBe(false);
+ });
+
+ it("offers a nested-only field and its suggestion, and creates the filter through the popover's built-in nested editor (FR13, FR14)", async () => {
+ const nestedOnly: PowerSearchConfig = {
+ name: 'NestedOnly',
+ contentSearchFieldKey: 'author',
+ fields: [
+ ...config.fields,
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const {onChange} = setup({config: nestedOnly});
+ openAddFlow();
+ expect(within(sheet()).getByRole('button', {name: 'Group'})).toBeTruthy();
+ fireEvent.change(within(sheet()).getByRole('searchbox', {name: 'Search'}), {
+ target: {value: 'Gro'},
+ });
+ const suggestion = await within(sheet()).findByRole('button', {
+ name: /^Group all of/,
+ });
+ fireEvent.click(suggestion);
+ // One operator: no group, the title names the operator the step opened
+ // with, and the body is the built-in nested editor. The primary action
+ // ("Add filter" when creating) waits for a complete sub-filter.
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Group all of'}),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('radiogroup')).toBeNull();
+ expect(within(sheet()).getByRole('tree')).toBeTruthy();
+ const primary = () =>
+ within(sheet())
+ .getAllByRole('button', {name: 'Add filter'})
+ .find(button => button.closest('[role="tree"]') == null) as HTMLElement;
+ expect(primary()).toBeDisabled();
+ fireEvent.click(
+ within(sheet()).getByRole('button', {name: '+ Add filter'}),
+ );
+ // The new sub-filter takes the first field (Status) and its default
+ // operator; pick a value from the row's own Value selector to complete it.
+ const valuePicker = within(sheet()).getByRole('combobox', {name: 'Value'});
+ fireEvent.click(valuePicker);
+ const listbox = document.getElementById(
+ valuePicker.getAttribute('aria-controls') as string,
+ ) as HTMLElement;
+ fireEvent.click(
+ within(listbox).getByRole('option', {name: 'Open', hidden: true}),
+ );
+ expect(primary()).toBeEnabled();
+ fireEvent.click(primary());
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'group',
+ operator: 'all',
+ value: {type: 'nested', value: [openFilter]},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it("checks the operator a suggestion opened the step with, not the field's default (FR13, FR14)", async () => {
+ setup({config: contentSearchConfig});
+ openAddFlow();
+ fireEvent.change(within(sheet()).getByRole('searchbox', {name: 'Search'}), {
+ target: {value: 'status is not'},
+ });
+ fireEvent.click(
+ await within(sheet()).findByRole('button', {name: /^Status is not$/}),
+ );
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Status is not'}),
+ ).toBeChecked();
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Status is'}),
+ ).not.toBeChecked();
+ });
+
+ it("keeps the Operator group outside a caller's Editor override, so a mixed field's other operator is still reachable (FR14)", () => {
+ const mixed: PowerSearchConfig = {
+ name: 'Mixed',
+ fields: [
+ ...config.fields,
+ {
+ key: 'mixed',
+ label: 'Mixed',
+ operators: [
+ {key: 'all', label: 'all of', value: {type: 'nested'}},
+ {key: 'is', label: 'is', value: {type: 'string'}},
+ ],
+ defaultOperator: 'all',
+ },
+ ],
+ };
+ const seen = vi.fn();
+ function NestedEditor(props: PowerSearchEditorProps) {
+ seen(props.filter.operator);
+ return <div>Custom nested editor</div>;
+ }
+ setup({config: mixed, components: {nested: {Editor: NestedEditor}}});
+ openAddFlow();
+ tapRow('Mixed');
+ // Opened on the default (nested) operator: the override is the body, the
+ // group sits above it, and the title is the field alone.
+ expect(within(sheet()).getByRole('heading', {name: 'Mixed'})).toBeTruthy();
+ expect(within(sheet()).getByText('Custom nested editor')).toBeTruthy();
+ expect(seen).toHaveBeenLastCalledWith('all');
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Mixed all of'}),
+ ).toBeChecked();
+ // Switching the operator swaps the body for the sheet's own editor.
+ fireEvent.click(within(sheet()).getByRole('radio', {name: 'Mixed is'}));
+ expect(within(sheet()).queryByText('Custom nested editor')).toBeNull();
+ expect(within(sheet()).getByRole('textbox')).toBeTruthy();
+ // And back.
+ fireEvent.click(within(sheet()).getByRole('radio', {name: 'Mixed all of'}));
+ expect(within(sheet()).getByText('Custom nested editor')).toBeTruthy();
+ });
+
+ it('shows each group its own sub-filters when two groups on one field are edited in a row (FR14)', async () => {
+ const withGroup: PowerSearchConfig = {
+ name: 'Groups',
+ fields: [
+ ...config.fields,
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const statusGroup: PowerSearchFilter = {
+ field: 'group',
+ operator: 'all',
+ value: {type: 'nested', value: [openFilter]},
+ };
+ const authorGroup: PowerSearchFilter = {
+ field: 'group',
+ operator: 'all',
+ value: {type: 'nested', value: [authorFilter]},
+ };
+ const onChange = vi.fn();
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ statusGroup,
+ authorGroup,
+ ]);
+ return (
+ <PowerSearch
+ config={withGroup}
+ filters={filters}
+ onChange={(next, type, index) => {
+ onChange(next, type, index);
+ setFilters(next);
+ }}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ const rows = () =>
+ within(sheet()).getAllByRole('button', {name: 'Group all of 1 filter'});
+ // First group: its sub-filter is on Status.
+ fireEvent.click(rows()[0]);
+ const subField = () =>
+ within(sheet())
+ .getAllByRole('combobox', {name: 'Field'})
+ .map(el => el.textContent);
+ expect(subField()).toEqual(['Status']);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ // Second group, same field and operator: the step remounts its editor
+ // for the newly opened filter, so it shows this group's sub-filter, not
+ // the first group's.
+ fireEvent.click(rows()[1]);
+ expect(subField()).toEqual(['Author']);
+ // Saving writes this group, unchanged, at its own index.
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Apply'}));
+ expect(onChange).toHaveBeenCalledWith(
+ [statusGroup, authorGroup],
+ 'edit',
+ 1,
+ );
+ // And reopening the first group again shows the first group's content.
+ fireEvent.click(rows()[0]);
+ expect(subField()).toEqual(['Status']);
+ });
+
+ it('mounts nothing of the flow at rest: the trigger alone before a press and again after the exit (INV7)', async () => {
+ setup({filters: [openFilter]});
+ // Before any press: no dialog, no sheet content.
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(document.querySelector('dialog')).toBeNull();
+ expect(screen.queryByText('Add filter')).toBeNull();
+ expect(screen.queryByRole('heading', {name: 'Filters'})).toBeNull();
+ openSheet();
+ expect(document.querySelectorAll('dialog').length).toBeGreaterThan(0);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ // Closing: the sheets stay mounted through their exit, then leave once
+ // focus is back on the trigger.
+ expect(document.querySelector('dialog')).not.toBeNull();
+ settleSheets();
+ await waitFor(() => expect(trigger()).toHaveFocus());
+ await waitFor(() => expect(document.querySelector('dialog')).toBeNull());
+ expect(screen.queryByRole('heading', {name: 'Filters'})).toBeNull();
+ });
+
+ it('returns focus to the nearest row when Apply or Cancel finds the edited filter gone after a controlled update (FR15, FR16)', () => {
+ const third: PowerSearchFilter = {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'closed'},
+ };
+ function Harness({filters}: {filters: ReadonlyArray<PowerSearchFilter>}) {
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ // Apply: the edited (middle) filter is removed while its step is open.
+ const {rerender, unmount} = render(
+ <Harness filters={[openFilter, authorFilter, third]} />,
+ );
+ openEditFlow('Author is Ada');
+ rerender(<Harness filters={[openFilter, third]} />);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Apply'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ // Nothing was written, and focus is on the row that followed it.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}),
+ ).toHaveFocus();
+ unmount();
+ // Cancel, with no row left: Add filter.
+ const second = render(<Harness filters={[authorFilter]} />);
+ openEditFlow('Author is Ada');
+ second.rerender(<Harness filters={[]} />);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it("falls back to the Add filter sheet's first control when Cancel from creation finds the opening field row gone (FR14, FR16)", () => {
+ function Harness({cfg}: {cfg: PowerSearchConfig}) {
+ return (
+ <PowerSearch
+ config={cfg}
+ filters={[]}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ // Few fields: no search field, so the fallback is the first field row.
+ const {rerender, unmount} = render(<Harness cfg={config} />);
+ openAddFlow();
+ tapRow('Author');
+ const without = {
+ ...config,
+ fields: config.fields.filter(f => f.key !== 'author'),
+ };
+ rerender(<Harness cfg={without} />);
+ expect(
+ within(sheet()).getByText('This filter is no longer available'),
+ ).toBeTruthy();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Author'})).toBeNull();
+ const firstRow = within(sheet())
+ .getAllByRole('button')
+ .find(b => b.closest('li') != null) as HTMLElement;
+ expect(firstRow).toHaveFocus();
+ unmount();
+ // Many fields: the search field shows, and takes the focus instead.
+ const many: PowerSearchConfig = {
+ name: 'Many',
+ fields: Array.from({length: 9}, (_, i) => ({
+ key: `f${i}`,
+ label: `Field ${i}`,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'} as const}],
+ })),
+ };
+ const second = render(<Harness cfg={many} />);
+ openAddFlow();
+ tapRow('Field 3');
+ second.rerender(
+ <Harness
+ cfg={{...many, fields: many.fields.filter(f => f.key !== 'f3')}}
+ />,
+ );
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('textbox', {name: 'Search filters'}),
+ ).toHaveFocus();
+ });
+
+ describe('a controlled update that removes the focused control (FR16)', () => {
+ const third: PowerSearchFilter = {
+ field: 'status',
+ operator: 'is',
+ value: {type: 'enum', value: 'closed'},
+ };
+ function Harness({
+ filters,
+ cfg = config,
+ hasClear,
+ }: {
+ filters: ReadonlyArray<PowerSearchFilter>;
+ cfg?: PowerSearchConfig;
+ hasClear?: boolean;
+ }) {
+ return (
+ <PowerSearch
+ config={cfg}
+ filters={filters}
+ onChange={() => {}}
+ hasClear={hasClear}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+
+ it('moves focus from a removed Filters row to the nearest remaining row by index', () => {
+ const {rerender} = render(
+ <Harness filters={[openFilter, authorFilter, third]} />,
+ );
+ openSheet();
+ within(sheet()).getByRole('button', {name: 'Author is Ada'}).focus();
+ // The focused (middle) row is removed by the parent.
+ rerender(<Harness filters={[openFilter, third]} />);
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}),
+ ).toHaveFocus();
+ // The focused (now last) row is removed: the new last row takes focus.
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}).focus();
+ rerender(<Harness filters={[openFilter]} />);
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Open'}),
+ ).toHaveFocus();
+ });
+
+ it('keeps focus on the same filter when the parent reorders the filters (FR12, FR16)', () => {
+ const {rerender} = render(
+ <Harness filters={[openFilter, authorFilter, third]} />,
+ );
+ openSheet();
+ const authorRow = within(sheet()).getByRole('button', {
+ name: 'Author is Ada',
+ });
+ authorRow.focus();
+ // Same objects, new order: the row moves, its element stays.
+ rerender(<Harness filters={[third, openFilter, authorFilter]} />);
+ expect(within(sheet()).getByRole('button', {name: 'Author is Ada'})).toBe(
+ authorRow,
+ );
+ expect(authorRow).toHaveFocus();
+ // Cloned objects, new order: the row is matched by its signature.
+ rerender(
+ <Harness filters={[{...authorFilter}, {...third}, {...openFilter}]} />,
+ );
+ expect(within(sheet()).getByRole('button', {name: 'Author is Ada'})).toBe(
+ authorRow,
+ );
+ expect(authorRow).toHaveFocus();
+ });
+
+ it('keeps focus on the same filter when the parent removes a filter above it (FR12, FR16)', () => {
+ const {rerender} = render(
+ <Harness filters={[openFilter, authorFilter, third]} />,
+ );
+ openSheet();
+ const authorRow = within(sheet()).getByRole('button', {
+ name: 'Author is Ada',
+ });
+ authorRow.focus();
+ rerender(<Harness filters={[authorFilter, third]} />);
+ expect(authorRow).toHaveFocus();
+ expect(within(sheet()).getByRole('button', {name: 'Author is Ada'})).toBe(
+ authorRow,
+ );
+ // Not the row at the old index.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}),
+ ).not.toHaveFocus();
+ });
+
+ it('counts rows in one index space — plain read-only rows above the removed row are not counted (FR16)', () => {
+ const readOnlyFirst: PowerSearchFilter = {
+ ...openFilter,
+ isReadOnly: true,
+ };
+ const fourth: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace'},
+ };
+ const {rerender} = render(
+ <Harness filters={[readOnlyFirst, authorFilter, third, fourth]} />,
+ );
+ openSheet();
+ // Row 0 is plain (read-only); the focused Author row is button row 0.
+ within(sheet()).getByRole('button', {name: 'Author is Ada'}).focus();
+ rerender(<Harness filters={[readOnlyFirst, third, fourth]} />);
+ // The row that followed it — not one row too far (counting the plain
+ // row would land on "Author is Grace").
+ expect(
+ within(sheet()).getByRole('button', {name: 'Status is Closed'}),
+ ).toHaveFocus();
+ });
+
+ it('moves focus from Clear all, gone with the last filter, to Add filter', () => {
+ const {rerender} = render(<Harness filters={[openFilter]} hasClear />);
+ openSheet();
+ within(sheet()).getByRole('button', {name: 'Clear all'}).focus();
+ rerender(<Harness filters={[]} hasClear />);
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Clear all'}),
+ ).toBeNull();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it("moves focus from a dropped field's row in Add filter to the nearest remaining row", () => {
+ const {rerender} = render(<Harness filters={[]} />);
+ openAddFlow();
+ within(sheet()).getByRole('button', {name: 'Author'}).focus();
+ rerender(
+ <Harness
+ filters={[]}
+ cfg={{
+ ...config,
+ fields: config.fields.filter(f => f.key !== 'author'),
+ }}
+ />,
+ );
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Author'}),
+ ).toBeNull();
+ const focused = document.activeElement as HTMLElement;
+ expect(focused.closest('li')).not.toBeNull();
+ expect(sheet().contains(focused)).toBe(true);
+ });
+ });
+
+ it('shows "No filters match your search" only for a non-empty query: a config with no field lists nothing (FR13)', () => {
+ setup({config: {name: 'Empty', fields: []}});
+ openSheet();
+ // No filter and no field: Add filter opens directly, and shows no
+ // "no match" message for a query nobody typed.
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Add filter'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).queryByText('No filters match your search'),
+ ).toBeNull();
+ });
+
+ it("keeps the content searchbox's aria-controls pointing at an element while nothing lists (FR13)", async () => {
+ const noContent: PowerSearchConfig = {
+ name: 'NoContent',
+ contentSearchFieldKey: 'author',
+ fields: [
+ {
+ key: 'author',
+ label: 'Author',
+ isValueMatchAllowed: false,
+ typeaheadMinQueryLength: 99,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ setup({config: noContent});
+ openSheet();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ const controlled = () =>
+ document.getElementById(input.getAttribute('aria-controls') as string);
+ // With results listed, the list.
+ expect(controlled()).toBe(within(sheet()).getByRole('list'));
+ // With a dead-end query, the empty-result message.
+ fireEvent.change(input, {target: {value: 'Author'}});
+ expect(controlled()).toHaveTextContent('No results found');
+ // With an empty query and no bootstrap suggestion — here the free-text
+ // item lists, so clear to a query that lists nothing: the message again.
+ fireEvent.change(input, {target: {value: ''}});
+ expect(controlled()).not.toBeNull();
+ expect(sheet().contains(controlled())).toBe(true);
+ });
+
+ it("lists ungrouped fields first even when the config's first field is grouped, as the popover's suggestions do (FR13)", () => {
+ const groupedFirst: PowerSearchConfig = {
+ name: 'GroupedFirst',
+ fields: [
+ {
+ key: 'owner',
+ label: 'Owner',
+ group: 'People',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'title',
+ label: 'Title',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'reviewer',
+ label: 'Reviewer',
+ group: 'People',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'due',
+ label: 'Due',
+ group: 'Dates',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ setup({config: groupedFirst});
+ openAddFlow();
+ const names = within(sheet())
+ .getAllByRole('button')
+ .filter(button => button.closest('li') != null)
+ .map(button => button.textContent?.trim());
+ // Ungrouped first, then the groups in first-appearance order.
+ expect(names).toEqual(['Title', 'Owner', 'Reviewer', 'Due']);
+ const lists = within(sheet()).getAllByRole('list');
+ expect(lists).toHaveLength(3);
+ expect(within(sheet()).getByText('People')).toBeTruthy();
+ expect(within(sheet()).getByText('Dates')).toBeTruthy();
+ });
+
+ it("renders a caller's nested Editor override in a nested filter's step, with the popover's props (FR12, FR14)", () => {
+ const withNested: PowerSearchConfig = {
+ name: 'Nested',
+ fields: [
+ ...config.fields,
+ {
+ key: 'mixed',
+ label: 'Mixed',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const nestedFilter: PowerSearchFilter = {
+ field: 'mixed',
+ operator: 'all',
+ value: {type: 'nested', value: [openFilter]},
+ };
+ const seenProps = vi.fn();
+ const saved: PowerSearchFilter = {
+ ...nestedFilter,
+ value: {type: 'nested', value: [openFilter, authorFilter]},
+ };
+ function NestedEditor(props: PowerSearchEditorProps) {
+ seenProps(props);
+ return (
+ <button type="button" onClick={() => props.onSave(saved)}>
+ Save group
+ </button>
+ );
+ }
+ const {onChange} = setup({
+ config: withNested,
+ filters: [nestedFilter],
+ components: {nested: {Editor: NestedEditor}},
+ });
+ openSheet();
+ fireEvent.click(
+ within(sheet()).getByRole('button', {name: 'Mixed all of 1 filter'}),
+ );
+ // The override replaces the body and footer, as it does in the popover,
+ // and receives the popover's props; no remove-only message shows.
+ expect(
+ within(sheet()).queryByText("This filter can't be edited here"),
+ ).toBeNull();
+ expect(seenProps).toHaveBeenLastCalledWith({
+ config: withNested,
+ filter: nestedFilter,
+ mode: 'edit',
+ saveButtonLabel: 'Apply',
+ isReadOnly: false,
+ onSave: expect.any(Function),
+ onCancel: expect.any(Function),
+ });
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Save group'}));
+ expect(onChange).toHaveBeenCalledWith([saved], 'edit', 0);
+ });
+
+ 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 (FR13)
+// =============================================================================
+
+describe('PowerSearch Add filter (FR13)', () => {
+ it("keeps the value step's sticky header and footer above the body that scrolls under them, without covering the grab handle", () => {
+ setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ const title = within(sheet()).getByRole('heading', {name: 'Status'});
+ // The title sits in the sticky header; the header's parent is the sheet
+ // content wrapper.
+ let header: HTMLElement | null = title;
+ while (header && getComputedStyle(header).position !== 'sticky') {
+ header = header.parentElement;
+ }
+ expect(header).not.toBeNull();
+ const content = header!.parentElement!;
+ let footer: HTMLElement | null = within(sheet()).getByRole('button', {
+ name: 'Apply',
+ });
+ while (footer && getComputedStyle(footer).position !== 'sticky') {
+ footer = footer.parentElement;
+ }
+ // jsdom resolves the injected StyleX rules: the header and footer have a
+ // layer above the List rows (position: relative, z-index auto) between
+ // them...
+ expect(getComputedStyle(header!).zIndex).toBe('1');
+ expect(footer).not.toBeNull();
+ expect(getComputedStyle(footer!).zIndex).toBe('1');
+ // ...scoped to the sheet content, so the panel's grab handle (z-index 1,
+ // outside this wrapper) still paints above the header.
+ const rules: string[] = [];
+ for (const styleSheet of Array.from(document.styleSheets)) {
+ for (const rule of Array.from(styleSheet.cssRules)) {
+ rules.push(rule.cssText);
+ }
+ }
+ const isolated = Array.from(content.classList).some(className =>
+ rules.some(
+ text =>
+ text.includes(`.${className}`) && /isolation:\s*isolate/.test(text),
+ ),
+ );
+ expect(isolated).toBe(true);
+ });
+
+ 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 from the footer Done when Add filter was the entry point, with no Back, Close or Cancel (FR13)', () => {
+ setup();
+ openSheet();
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ expect(within(sheet()).queryByRole('button', {name: 'Close'})).toBeNull();
+ expect(within(sheet()).queryByRole('button', {name: 'Cancel'})).toBeNull();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('closes the flow when Add filter, the entry point, is dismissed (FR15a)', () => {
+ setup();
+ openSheet();
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('reveals Filters and focuses Add filter when Add filter is dismissed from management (FR15a, FR16)', () => {
+ setup({filters: [openFilter]});
+ openAddFlow();
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ expect(within(sheet()).queryByRole('button', {name: 'Done'})).toBeNull();
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it('lists the fields, ungrouped first under "General", then each group, with chevrons (FR13)', () => {
+ setup();
+ openAddFlow();
+ const status = within(sheet()).getByRole('button', {name: 'Status'});
+ expect(status.textContent).toBe('Status');
+ expect(
+ within(sheet()).getByRole('heading', {name: 'General', level: 4}),
+ ).toBeTruthy();
+ expect(within(sheet()).getByRole('list', {name: 'General'})).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Author'})).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Metadata', level: 4}),
+ ).toBeTruthy();
+ expect(within(sheet()).getByRole('list', {name: 'Metadata'})).toBeTruthy();
+ expect(status.closest('li')?.querySelectorAll('svg')).toHaveLength(1);
+ });
+
+ it("focuses a directly added filter's row, not its remove action, after the last editable filter was removed (FR16)", () => {
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ // Removing the last editable filter sends focus to Add filter, not to a
+ // remove action.
+ fireEvent.click(removeButton('Status'));
+ const addFilterButton = within(sheet()).getByRole('button', {
+ name: 'Add filter',
+ });
+ expect(addFilterButton).toHaveFocus();
+ fireEvent.click(addFilterButton);
+ tapRow('Unassigned');
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ expect(
+ within(sheet()).getByRole('button', {name: 'Unassigned is true'}),
+ ).toHaveFocus();
+ });
+
+ it('adds a one-tap field at once from its row, which shows a plus, and announces it in Filters (FR13, FR15, AR6)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const onChange = vi.fn();
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([openFilter]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={(next, type, index) => {
+ onChange(next, type, index);
+ setFilters(next);
+ }}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openAddFlow();
+ const unassignedRow = within(sheet())
+ .getByRole('button', {name: 'Unassigned'})
+ .closest('li')!;
+ expect(unassignedRow.querySelectorAll('svg')).toHaveLength(1);
+ expect(unassignedRow.querySelector('path[d="M5 12h14"]')).not.toBeNull();
+ tapRow('Unassigned');
+ const unassigned = {
+ field: 'unassigned',
+ operator: 'isTrue',
+ value: {type: 'empty'},
+ };
+ expect(onChange).toHaveBeenCalledWith([openFilter, unassigned], 'add', 1);
+ const filtersDialog = sheet();
+ expect(filtersDialog).toHaveAttribute('aria-label', 'Filters');
+ expect(
+ within(filtersDialog).getByRole('button', {name: 'Unassigned is true'}),
+ ).toHaveFocus();
+ // Add filter closed holding focus, so the words wait for its exit.
+ settleSheets();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Added Unassigned is true',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ 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('lists nested-only and mixed fields like any other, with the Operator group for a mixed one (FR13, FR14)', () => {
+ 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()).getByRole('button', {name: 'Group'})).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: 'Mixed'})).toBeTruthy();
+ expect(warn).not.toHaveBeenCalled();
+ // The mixed field opens on its first operator (nested) with the group
+ // listing both; the built-in nested editor is the body.
+ tapRow('Mixed');
+ expect(within(sheet()).getByRole('heading', {name: 'Mixed'})).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('radio', {name: 'Mixed all of'}),
+ ).toBeChecked();
+ expect(within(sheet()).getByRole('radio', {name: 'Mixed is'})).toBeTruthy();
+ const tree = within(sheet()).getByRole('tree');
+ // The Operator group takes the place of the built-in editor's root
+ // operator picker: the tree root shows the checked operator's label and
+ // offers no second operator control.
+ expect(
+ within(sheet()).queryByRole('combobox', {name: 'Group operator'}),
+ ).toBeNull();
+ expect(within(tree).getAllByRole('treeitem')[0]).toHaveTextContent(
+ /^all of/,
+ );
+ warn.mockRestore();
+ });
+
+ it('disables an open field picker when the component becomes read-only', () => {
+ const {rerender} = setup();
+ openAddFlow();
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ 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 step: create, operator step, edit, remove (FR14–FR16)
+// =============================================================================
+
+describe('PowerSearch value step (FR14–FR16)', () => {
+ it("runs field rows edge to edge, and a lone editor's choice rows on the sheet surface (FR14)", () => {
+ setup();
+ openAddFlow();
+ for (const list of within(sheet()).getAllByRole('list')) {
+ expectBleedRowsOnBodyInset(list);
+ }
+ // One operator: the editor is the body's only section and sits on the
+ // sheet's surface, its rows on the body's inset.
+ tapRow('Labels');
+ const group = within(sheet()).getByRole('group', {name: 'Labels'});
+ expectBleedChoiceRows(group);
+ expect(group.closest('[class*="controlSection"]')).toBeNull();
+ });
+
+ it('puts the Operator group and the editor each in a muted section when the field has several operators (FR14)', () => {
+ setup();
+ openAddFlow();
+ tapRow('Status');
+ const operators = within(sheet()).getByRole('radiogroup', {
+ name: 'Operator',
+ });
+ const values = within(sheet()).getByRole('radiogroup', {name: 'Status'});
+ const operatorSection = operators.closest<HTMLElement>(
+ '[class*="controlSection"]',
+ );
+ const valueSection = values.closest<HTMLElement>(
+ '[class*="controlSection"]',
+ );
+ expect(operatorSection).not.toBeNull();
+ expect(valueSection).not.toBeNull();
+ expect(operatorSection).not.toBe(valueSection);
+ expect(getComputedStyle(valueSection!).backgroundColor).toBe(
+ 'var(--color-background-muted)',
+ );
+ // The section publishes its own padding, so the choice rows run edge to
+ // edge inside it.
+ expect(values.className).toMatch(/choiceList/);
+ expect(
+ getComputedStyle(valueSection!).getPropertyValue(
+ '--container-padding-inline-start',
+ ),
+ ).toBe('var(--spacing-3)');
+ });
+
+ it('stages an enum selection and commits it with exact add metadata', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ tapRow('Closed');
+ expect(choice('Closed')).toBeChecked();
+ 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');
+ // The whole row is the control: tapping its label toggles it.
+ const bug = choice('Bug');
+ expect(bug).not.toBeChecked();
+ fireEvent.click(within(bug).getByText('Bug'));
+ expect(choice('Bug')).toBeChecked();
+ expect(choice('Bug')).toHaveAttribute('role', 'checkbox');
+ expect(within(sheet()).getByRole('group', {name: 'Labels'})).toBeTruthy();
+ });
+
+ it('returns focus to Add filter when the closing steps finish their exit, even when the first move did not land (FR16)', () => {
+ setup({filters: [openFilter]});
+ openAddFlow();
+ tapRow('Labels');
+ tapRow('Bug');
+ addFilter();
+ // A browser can keep focus in a closing sheet until its exit ends, so
+ // the first move may not land; the closing steps then return focus to
+ // the control the commit named.
+ act(() => (document.activeElement as HTMLElement | null)?.blur());
+ settleSheets();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ 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('opens Filters as the value step and Add filter close when Add filter was the entry point, with focus on Add filter once the sheets settle (FR15a, FR16)', () => {
+ setup();
+ openSheet();
+ tapRow('Status');
+ tapRow('Closed');
+ const valueStep = sheet();
+ expect(valueStep).toHaveAttribute('aria-label', 'Status');
+ addFilter();
+ // Two sheets close as one opens: the stack's ordinary closes and open,
+ // not BottomSheet's replace, which pairs exactly one close with one open.
+ expect(valueStep).not.toHaveAttribute('data-sheet-stack', 'replaced');
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ settleSheets();
+ expect(
+ Array.from(document.querySelectorAll('dialog[open]')).map(d =>
+ d.getAttribute('aria-label'),
+ ),
+ ).toEqual(['Filters']);
+ // Focus is still on Add filter once every motion has settled.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toHaveFocus();
+ });
+
+ it('confirms an empty-value operator of a field with several operators through Add filter', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ fireEvent.click(
+ within(sheet()).getByRole('radio', {name: 'Status is empty'}),
+ );
+ expect(onChange).not.toHaveBeenCalled();
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [{field: 'status', operator: 'isEmpty', 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(choice('Open')).toBeChecked();
+ fireEvent.click(
+ within(sheet()).getByRole('radio', {name: 'Status is empty'}),
+ );
+ expect(
+ within(sheet()).queryByRole('radio', {
+ checked: true,
+ name: /^(Open|Closed)/,
+ }),
+ ).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('makes a radio group one tab stop whose arrow keys move and check, and leaves checkbox rows one stop each (FR17)', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Status');
+ const group = within(sheet()).getByRole('radiogroup', {name: 'Status'});
+ const radios = within(group).getAllByRole('radio');
+ // Nothing checked yet: the first row is the group's single tab stop.
+ expect(radios.map(r => r.tabIndex)).toEqual([0, -1]);
+ radios[0].focus();
+ fireEvent.keyDown(radios[0], {key: 'ArrowDown'});
+ // The arrow moved focus and checked the row it landed on.
+ expect(radios[1]).toHaveFocus();
+ expect(radios[1]).toBeChecked();
+ expect(radios.map(r => r.tabIndex)).toEqual([-1, 0]);
+ fireEvent.keyDown(radios[1], {key: 'ArrowUp'});
+ expect(radios[0]).toHaveFocus();
+ expect(radios[0]).toBeChecked();
+ fireEvent.keyDown(radios[0], {key: 'ArrowUp'});
+ // Wraps.
+ expect(radios[1]).toHaveFocus();
+ expect(radios[1]).toBeChecked();
+ fireEvent.keyDown(radios[1], {key: 'Home'});
+ expect(radios[0]).toBeChecked();
+ fireEvent.keyDown(radios[0], {key: 'End'});
+ expect(radios[1]).toBeChecked();
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+
+ tapRow('Labels');
+ const boxes = within(
+ within(sheet()).getByRole('group', {name: 'Labels'}),
+ ).getAllByRole('checkbox');
+ // Every checkbox row is a tab stop; arrows do nothing to them.
+ expect(boxes.every(b => b.tabIndex === 0)).toBe(true);
+ boxes[0].focus();
+ fireEvent.keyDown(boxes[0], {key: 'ArrowDown'});
+ expect(boxes[0]).toHaveFocus();
+ expect(boxes[0]).not.toBeChecked();
+ // Activation (Space/Enter on a button fires click) toggles.
+ fireEvent.click(boxes[0]);
+ expect(boxes[0]).toBeChecked();
+ });
+
+ it('checks a focused radio row with Space or Enter and toggles a checkbox row with Space (FR17; AST-020 FR15)', async () => {
+ const user = userEvent.setup();
+ setup();
+ openAddFlow();
+ tapRow('Status');
+ const radios = within(
+ within(sheet()).getByRole('radiogroup', {name: 'Status'}),
+ ).getAllByRole('radio');
+ radios[0].focus();
+ await user.keyboard(' ');
+ expect(radios[0]).toBeChecked();
+ // Arrow to the next row without a pointer, then Enter checks it too (it
+ // is already checked by the arrow; Enter keeps it so).
+ await user.keyboard('{ArrowDown}');
+ expect(radios[1]).toBeChecked();
+ await user.keyboard('{Enter}');
+ expect(radios[1]).toBeChecked();
+ expect(radios[0]).not.toBeChecked();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+
+ tapRow('Labels');
+ const boxes = within(
+ within(sheet()).getByRole('group', {name: 'Labels'}),
+ ).getAllByRole('checkbox');
+ boxes[1].focus();
+ await user.keyboard(' ');
+ expect(boxes[1]).toBeChecked();
+ await user.keyboard(' ');
+ expect(boxes[1]).not.toBeChecked();
+ await user.keyboard('{Enter}');
+ expect(boxes[1]).toBeChecked();
+ });
+
+ it('stages a multi-select and commits it from the footer', () => {
+ const {onChange} = setup();
+ openAddFlow();
+ tapRow('Labels');
+ fireEvent.click(choice('Bug'));
+ fireEvent.click(choice('Urgent'));
+ const bug = choice('Bug');
+ const urgent = choice('Urgent');
+ expect(bug).toBeChecked();
+ expect(urgent).toBeChecked();
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(urgent);
+ expect(choice('Urgent')).not.toBeChecked();
+ fireEvent.click(choice('Urgent'));
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'labels',
+ operator: 'isAnyOf',
+ value: {type: 'enum_list', value: ['bug', 'urgent']},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('opens the edit step above Filters with only Cancel and Apply from a selected row (FR14, FR15a)', () => {
+ 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()).queryByRole('button', {name: 'Remove'})).toBeNull();
+ expect(choice('Open')).toBeChecked();
+ // Filters stays open beneath the step, covered and blocked.
+ const filters = document.querySelector('dialog[aria-label="Filters"]');
+ expect(filters).toHaveAttribute('open');
+ expect(filters).toHaveAttribute('inert');
+ });
+
+ 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("moves focus to the next editable row's remove action after a removal (FR16)", () => {
+ 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 (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(removeButton('Status'));
+ // The read-only row in between is plain and is passed over.
+ const graceRow = within(sheet())
+ .getByRole('button', {name: 'Author is Grace'})
+ .closest('li')!;
+ expect(
+ within(graceRow).getByRole('button', {name: 'Remove Author filter'}),
+ ).toHaveFocus();
+ });
+
+ it("focuses a nested filter's remove action after a removal, since its row is editable too (FR16)", () => {
+ const withNested: PowerSearchConfig = {
+ name: 'Nested',
+ fields: [
+ ...config.fields,
+ {
+ key: 'mixed',
+ label: 'Mixed',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const nested: PowerSearchFilter = {
+ field: 'mixed',
+ operator: 'all',
+ value: {type: 'nested', value: [openFilter]},
+ };
+ const after: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace'},
+ };
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ nested,
+ after,
+ ]);
+ return (
+ <PowerSearch
+ config={withNested}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(removeButton('Status'));
+ // The nested row is the nearest following row and is editable, so its
+ // remove action takes focus.
+ expect(removeButton('Mixed')).toHaveFocus();
+ });
+
+ it('focuses Add filter after the last editable filter is removed', () => {
+ function Harness() {
+ const [filters, setFilters] = useState<ReadonlyArray<PowerSearchFilter>>([
+ openFilter,
+ ]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ fireEvent.click(removeButton('Status'));
+ expect(within(sheet()).getByText('No filters applied')).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(
+ <PowerSearch
+ config={config}
+ filters={[openFilter, authorFilter]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ openEditFlow('Status is Open');
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[{...authorFilter}, {...openFilter}]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ 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(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ openEditFlow('Status is Open');
+ rerender(
+ <PowerSearch
+ config={config}
+ filters={[authorFilter]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ tapRow('Closed');
+ apply();
+ expect(onChange).not.toHaveBeenCalled();
+ expect(isSheetOpen()).toBe(true);
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ });
+
+ it('lists a saved filter the config no longer knows as a row that opens the unavailable step and stays removable from its row (FR12)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const orphan: PowerSearchFilter = {
+ field: 'legacy',
+ operator: 'was',
+ value: {type: 'string', value: 'x'},
+ };
+ const onChange = vi.fn();
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([openFilter, orphan]);
+ return (
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={(next, type, index) => {
+ onChange(next, type, index);
+ setFilters(next);
+ }}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ // Listed by its raw keys, as the token is; a button, not a plain row.
+ const row = within(sheet()).getByRole('button', {name: 'legacy was'});
+ fireEvent.click(row);
+ // The step's title — the dialog's name — reads the raw keys, as the
+ // row does (FR12, FR14, AR5).
+ expect(
+ within(sheet()).getByRole('heading', {name: 'legacy was'}),
+ ).toBeTruthy();
+ expect(sheet().getAttribute('aria-label')).toBe('legacy was');
+ expect(
+ within(sheet()).getByText('This filter is no longer available'),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();
+ expect(
+ within(sheet()).queryByRole('button', {name: 'Remove'}),
+ ).toBeNull();
+ // Cancel is the way back; the row's trailing action removes it.
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('button', {name: 'legacy was'}),
+ ).toHaveFocus();
+ // The value step finishes its exit before the removal.
+ settleSheets();
+ fireEvent.click(removeButton('legacy'));
+ expect(onChange).toHaveBeenCalledWith([openFilter], 'remove', 1);
+ const filtersDialog = sheet();
+ expect(
+ within(filtersDialog).queryByRole('button', {name: 'legacy was'}),
+ ).toBeNull();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed legacy was',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('keeps a way out when a config update removes the edited field, moves focus to Cancel, and announces it (FR14, FR16, AR6)', async () => {
+ const spy = mockModalDialogs();
+ const onChange = vi.fn();
+ const {rerender} = render(
+ <PowerSearch
+ config={config}
+ filters={[openFilter]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ openEditFlow('Status is Open');
+ const dialog = sheet();
+ // Focus is on one of the body's controls — a choice row.
+ const row = within(dialog).getByRole('radio', {name: 'Open'});
+ row.focus();
+ expect(row).toHaveFocus();
+ rerender(
+ <PowerSearch
+ config={{
+ ...config,
+ fields: config.fields.filter(f => f.key !== 'status'),
+ }}
+ filters={[openFilter]}
+ onChange={onChange}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ expect(
+ within(sheet()).getByText('This filter is no longer available'),
+ ).toBeTruthy();
+ expect(within(sheet()).queryByRole('button', {name: 'Apply'})).toBeNull();
+ // The row unmounted without a blur; focus did not fall to the page body
+ // but moved to the way out, and the message was announced inside the
+ // sheet's dialog.
+ expect(within(sheet()).getByRole('button', {name: 'Cancel'})).toHaveFocus();
+ await waitFor(() =>
+ expect(modalLiveRegion(dialog)).toHaveTextContent(
+ 'This filter is no longer available',
+ ),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ spy.mockRestore();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('hands a custom editor the props the popover presentation hands it, and commits what it saves (FR14)', () => {
+ const savedFilter: PowerSearchFilter = {
+ field: 'author',
+ operator: 'is',
+ value: {type: 'string', value: 'Grace'},
+ isReadOnly: true,
+ };
+ const seenProps = vi.fn();
+ function CustomEditor(props: PowerSearchEditorProps) {
+ seenProps(props);
+ return (
+ <button type="button" onClick={() => props.onSave(savedFilter)}>
+ Custom save
+ </button>
+ );
+ }
+ const {onChange} = setup({
+ components: {enum: {Editor: CustomEditor}},
+ timezoneID: 'Asia/Tokyo',
+ popoverSaveButtonLabel: 'Keep',
+ });
+ openAddFlow();
+ tapRow('Status');
+ // The same props, with the same meaning, as the popover passes: the
+ // caller's config, the partial filter, the mode, the save label, the
+ // read-only flag, and the two callbacks; no sheet-only `timezoneID`.
+ expect(seenProps).toHaveBeenLastCalledWith({
+ config,
+ filter: {field: 'status', operator: 'is', value: undefined},
+ mode: 'create',
+ saveButtonLabel: 'Keep',
+ isReadOnly: false,
+ onSave: expect.any(Function),
+ onCancel: expect.any(Function),
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Custom save'}));
+ 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 (FR13)
+// =============================================================================
+
+// =============================================================================
+// Stacked steps (FR15a)
+// =============================================================================
+
+describe('PowerSearch step sheets (retained stack, FR15a)', () => {
+ // Dismissing the top step closes only that sheet, so the prior step returns
+ // through the stack's reveal motion instead of reopening above the current
+ // one. These assertions read only what a person or assistive technology can
+ // observe.
+ function stepDialogs(): HTMLElement[] {
+ return Array.from(document.querySelectorAll<HTMLElement>('dialog[open]'));
+ }
+ const stepNames = () => stepDialogs().map(d => d.getAttribute('aria-label'));
+
+ it('Filters opens as one modal dialog, named by the step', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ expect(stepNames()).toEqual(['Filters']);
+ expect(sheet()).toHaveAttribute('aria-modal', 'true');
+ expect(sheet()).not.toHaveAttribute('inert');
+ expect(sheet()).not.toHaveAttribute('aria-hidden');
+ });
+
+ it('opens Add filter above Filters without a Back button, and a dismissal reveals Filters', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ const filters = sheet();
+ tapRow('Add filter');
+ expect(stepNames()).toEqual(['Filters', 'Add filter']);
+ expect(filters).toHaveAttribute('inert');
+ expect(filters).toHaveAttribute('aria-hidden', 'true');
+ expect(sheet()).toHaveAttribute('aria-label', 'Add filter');
+ expect(sheet()).not.toHaveAttribute('inert');
+ settleSheets();
+ // Settling the motion keeps Filters beneath: it is covered, not replaced.
+ expect(stepNames()).toEqual(['Filters', 'Add filter']);
+ expect(within(sheet()).queryByRole('button', {name: 'Back'})).toBeNull();
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ expect(stepNames()).toEqual(['Filters']);
+ expect(sheet()).not.toHaveAttribute('inert');
+ expect(sheet()).not.toHaveAttribute('aria-hidden');
+ });
+
+ it('stacks Filters, Add filter and the value step for a creation, and Filters and the value step for an edit', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ tapRow('Add filter');
+ tapRow('Author');
+ expect(stepNames()).toEqual(['Filters', 'Add filter', 'Author is']);
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ settleSheets();
+ expect(stepNames()).toEqual(['Filters', 'Add filter']);
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ tapRow('Status is Open');
+ expect(stepNames()).toEqual(['Filters', 'Status']);
+ });
+
+ it('stacks the value step above Add filter alone when Add filter was the entry point', () => {
+ setup();
+ openSheet();
+ expect(stepNames()).toEqual(['Add filter']);
+ tapRow('Author');
+ expect(stepNames()).toEqual(['Add filter', 'Author is']);
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ expect(stepNames()).toEqual(['Add filter']);
+ expect(isSheetOpen()).toBe(true);
+ });
+
+ it('returns focus to the trigger after a flow that crossed every step', () => {
+ setup({filters: [openFilter]});
+ trigger().focus();
+ openSheet();
+ tapRow('Add filter');
+ settleSheets();
+ tapRow(/^Status/);
+ settleSheets();
+ expect(sheet()).toHaveAttribute(
+ 'aria-label',
+ expect.stringContaining('Status'),
+ );
+ // Cancel from the value step, dismiss Add filter, Done from Filters.
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ settleSheets();
+ expect(sheet()).toHaveAttribute('aria-label', 'Add filter');
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Done'}));
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('closes the flow on Escape from Filters, the bottom sheet, and returns focus to the trigger', () => {
+ setup({filters: [openFilter]});
+ trigger().focus();
+ openSheet();
+ settleSheets();
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+ expect(trigger()).toHaveFocus();
+ });
+
+ it('reveals Add filter on Escape from a value step above it, with focus on the field row', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ tapRow('Add filter');
+ tapRow(/^Status/);
+ settleSheets();
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ expect(isSheetOpen()).toBe(true);
+ expect(sheet()).toHaveAttribute('aria-label', 'Add filter');
+ expect(within(sheet()).getByRole('button', {name: 'Status'})).toHaveFocus();
+ });
+
+ it('closes the flow on a scrim press on Filters; a value step scrim reveals the step beneath', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ settleSheets();
+ // A click on the dialog element itself is the scrim.
+ fireEvent.click(sheet());
+ expect(isSheetOpen()).toBe(false);
+ settleSheets();
+
+ openSheet();
+ tapRow('Add filter');
+ tapRow(/^Status/);
+ settleSheets();
+ expect(sheet()).toHaveAttribute(
+ 'aria-label',
+ expect.stringContaining('Status'),
+ );
+ // The value step is an info sheet: its scrim dismisses it.
+ fireEvent.click(sheet());
+ settleSheets();
+ expect(isSheetOpen()).toBe(true);
+ expect(sheet()).toHaveAttribute('aria-label', 'Add filter');
+ });
+
+ it('reveals Filters on a downward swipe on Add filter instead of closing the flow', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ tapRow('Add filter');
+ settleSheets();
+ const handle = sheet().querySelector<HTMLElement>(
+ '.astryx-bottom-sheet > div[aria-hidden="true"]',
+ )!;
+ fireEvent.pointerDown(handle, {
+ pointerId: 1,
+ clientY: 0,
+ button: 0,
+ isPrimary: true,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerMove(handle, {
+ pointerId: 1,
+ clientY: 40,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerMove(handle, {
+ pointerId: 1,
+ clientY: 120,
+ pointerType: 'touch',
+ });
+ fireEvent.pointerUp(handle, {
+ pointerId: 1,
+ clientY: 120,
+ pointerType: 'touch',
+ });
+ settleSheets();
+ expect(isSheetOpen()).toBe(true);
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ });
+
+ it('ignores a scrim press on the covered Filters sheet while Add filter is on top', () => {
+ setup({filters: [openFilter]});
+ openSheet();
+ const filters = sheet();
+ tapRow('Add filter');
+ fireEvent.click(filters);
+ expect(isSheetOpen()).toBe(true);
+ expect(sheet()).toHaveAttribute('aria-label', 'Add filter');
+ });
+
+ it('keeps the value step a dismissible info sheet (FR14)', () => {
+ setup({filters: [openFilter]});
+ openEditFlow('Status is Open');
+ tapRow('Closed');
+ // The staged value is not protected by a form purpose: a scrim press
+ // reveals Filters, and nothing is committed.
+ fireEvent.click(sheet());
+ expect(sheet()).toHaveAttribute('aria-label', 'Filters');
+ });
+
+ it('speaks announcements only in the open step: a covered or retained step stays silent (AR6, FR18)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ setup({config: contentSearchConfig, filters: [openFilter]});
+ openSheet();
+ tapRow('Add filter');
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ fireEvent.change(input, {target: {value: 'status'}});
+ expect(
+ within(sheet()).getAllByRole('button', {name: /Status/}).length,
+ ).toBeGreaterThan(0);
+ // Back to Filters: the Add filter sheet's body stays mounted; no
+ // empty-result message is spoken, on the page or in Filters.
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ await new Promise(resolve => setTimeout(resolve, 40));
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ expect(modalLiveRegion(sheet())?.textContent ?? '').not.toContain(
+ 'No results found',
+ );
+ // Escape out of the flow after another query: nothing on the page.
+ tapRow('Add filter');
+ fireEvent.change(
+ within(sheet()).getByRole('searchbox', {name: 'Search'}),
+ {target: {value: 'status'}},
+ );
+ fireEvent.keyDown(sheet(), {key: 'Escape'});
+ settleSheets();
+ await new Promise(resolve => setTimeout(resolve, 40));
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('announces the unavailable state only while its step is open, and again when the same stale filter reopens (AR6)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const stale: PowerSearchConfig = {
+ ...config,
+ fields: config.fields.map(f =>
+ f.key === 'status'
+ ? {...f, operators: f.operators.filter(o => o.key !== 'is')}
+ : f,
+ ),
+ };
+ const {rerender} = setup({filters: [openFilter, authorFilter]});
+ openEditFlow('Status is Open');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ expect(
+ within(sheet()).getByRole('heading', {name: 'Filters'}),
+ ).toBeTruthy();
+ // The value step is closed but its body stays mounted with the draft; a
+ // config update that drops the edited operator is not spoken — not now,
+ // and not held for the next dialog that opens.
+ rerender(
+ <PowerSearch
+ config={stale}
+ filters={[openFilter, authorFilter]}
+ onChange={vi.fn()}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ await new Promise(resolve => setTimeout(resolve, 40));
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ tapRow('Author is Ada');
+ await new Promise(resolve => setTimeout(resolve, 40));
+ for (const region of document.querySelectorAll('[aria-live]')) {
+ expect(region.textContent ?? '').not.toContain(
+ 'This filter is no longer available',
+ );
+ }
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ // Reopening the stale filter — its row reads the field's label and the
+ // raw operator key — speaks it in its own dialog, as a new occasion.
+ tapRow('Status is');
+ const dialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(dialog)?.textContent).toBe(
+ 'This filter is no longer available',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+});
+
+describe('PowerSearch content search (FR13)', () => {
+ it('opens empty content-search configurations directly to Add filter without focusing the search (FR13)', () => {
+ 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…');
+ // The software keyboard stays down until the person taps the search.
+ expect(input).not.toHaveFocus();
+ expect(sheet().contains(document.activeElement)).toBe(true);
+ });
+
+ it('leaves the search unfocused when Add filter opens from Filters, and a vertical touch drag on the rows moves focus off it (FR13)', () => {
+ setup({config: contentSearchConfig, filters: [openFilter]});
+ openAddFlow();
+ const dialog = sheet();
+ const input = within(dialog).getByRole('searchbox', {name: 'Search'});
+ expect(input).not.toHaveFocus();
+ input.focus();
+ const results = within(dialog).getByRole('list', {name: 'Search results'});
+ const viewport = results.closest<HTMLElement>('[class*="scrollViewport"]')!;
+ // A scroll alone (filtering can clamp it) and a small move leave focus.
+ fireEvent.scroll(viewport);
+ expect(input).toHaveFocus();
+ fireEvent.touchStart(viewport, {touches: [{clientY: 100}]});
+ fireEvent.touchMove(viewport, {touches: [{clientY: 107}]});
+ expect(input).toHaveFocus();
+ // A drag past the threshold moves focus to the sheet.
+ fireEvent.touchMove(viewport, {touches: [{clientY: 109}]});
+ expect(input).not.toHaveFocus();
+ expect(dialog.contains(document.activeElement)).toBe(true);
+ // A multi-touch gesture leaves a focused search alone.
+ input.focus();
+ fireEvent.touchStart(viewport, {
+ touches: [{clientY: 100}, {clientY: 140}],
+ });
+ fireEvent.touchMove(viewport, {
+ touches: [{clientY: 140}, {clientY: 180}],
+ });
+ 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);
+ // The search takes no focus on open; the person moves into it first.
+ input.focus();
+ 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();
+ // The ends do not wrap.
+ fireEvent.keyDown(input, {key: 'ArrowUp'});
+ expect(input).toHaveFocus();
+ options[3].focus();
+ fireEvent.keyDown(options[3], {key: 'ArrowDown'});
+ expect(options[3]).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 inside the Filters sheet (AR6; AST-086 FR14)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ 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,
+ );
+ // The announcement lands in the Filters sheet the flow moved to, the
+ // dialog that stays open, not on the page body behind the modal.
+ const filtersDialog = sheet();
+ expect(filtersDialog).toHaveAttribute('aria-label', 'Filters');
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Added "status clo"',
+ ),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ 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 the no-results empty state only for a non-empty query with no suggestion (FR18)', () => {
+ const noMatches: PowerSearchConfig = {
+ name: 'NoMatches',
+ contentSearchFieldKey: 'author',
+ fields: [
+ {
+ key: 'author',
+ label: 'Author',
+ isValueMatchAllowed: false,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ setup({config: noMatches});
+ openSheet();
+ expect(within(sheet()).queryByText('No results found')).toBeNull();
+ const input = within(sheet()).getByRole('searchbox', {name: 'Search'});
+ // "Author" matches the field exactly, which drops the free-text item.
+ fireEvent.change(input, {target: {value: 'Author'}});
+ expect(within(sheet()).getByRole('button', {name: 'Author'})).toBeTruthy();
+ expect(within(sheet()).queryByText('No results found')).toBeNull();
+ });
+
+ it('announces the empty-result message once per query that matches nothing, read from the rendered element, inside the open sheet (AR6, INV10)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ // No content-search field: a non-matching query is a dead end with no
+ // free-text fallback item.
+ const noContent: PowerSearchConfig = {
+ name: 'NoContent',
+ contentSearchFieldKey: 'author',
+ fields: [
+ {
+ key: 'author',
+ label: 'Author',
+ isValueMatchAllowed: false,
+ typeaheadMinQueryLength: 99,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ };
+ setup({config: noContent});
+ openSheet();
+ const dialog = sheet();
+ const input = within(dialog).getByRole('searchbox', {name: 'Search'});
+ const region = () => modalLiveRegion(dialog);
+ // The free-text item hides for a query equal to the field's label, and
+ // the field itself is below its min query length: nothing lists.
+ fireEvent.change(input, {target: {value: 'Author'}});
+ expect(within(dialog).getByText('No results found')).toBeTruthy();
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('No results found'),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ // The same words for the same query are not spoken twice.
+ await new Promise(resolve => setTimeout(resolve, 20));
+ region()!.textContent = '';
+ fireEvent.change(input, {target: {value: 'Author'}});
+ await new Promise(resolve => setTimeout(resolve, 20));
+ expect(region()?.textContent ?? '').toBe('');
+ // Back to results, then a dead end for a new query: a new occasion,
+ // announced again, once.
+ fireEvent.change(input, {target: {value: 'zzz'}});
+ expect(within(dialog).getByRole('button', {name: '"zzz"'})).toBeTruthy();
+ await new Promise(resolve => setTimeout(resolve, 20));
+ region()!.textContent = '';
+ fireEvent.change(input, {target: {value: 'Author'}});
+ await waitFor(() =>
+ expect(region()).toHaveTextContent('No results found'),
+ );
+ // One announcement of the empty state's rendered text, not one from
+ // the element and one from the sheet.
+ expect(region()?.textContent).toBe(
+ 'No results found Try a different search.',
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('announces "No filters match your search" inside the Add filter sheet (AR6)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ 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});
+ openAddFlow();
+ const dialog = sheet();
+ fireEvent.change(
+ within(dialog).getByRole('textbox', {name: 'Search filters'}),
+ {target: {value: 'nope'}},
+ );
+ await waitFor(() =>
+ expect(modalLiveRegion(dialog)).toHaveTextContent(
+ 'No filters match your search',
+ ),
+ );
+ expect(sharedLiveRegion()?.textContent ?? '').toBe('');
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('falls back to the field list without a content-search field', () => {
+ setup({config: {...contentSearchConfig, contentSearchFieldKey: undefined}});
+ openSheet();
+ expect(within(sheet()).queryByRole('searchbox')).toBeNull();
+ expect(within(sheet()).getByRole('button', {name: 'Status'})).toBeTruthy();
+ });
+});
+
+// =============================================================================
+// Value types (FR17, FR21)
+// =============================================================================
+
+describe('PowerSearch sheet value types (FR17)', () => {
+ function setupValues(
+ props: Partial<PowerSearchProps> & {presentation?: Presentation} = {},
+ ) {
+ 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: the Tokenizer's sheet, titled with the field, creates free-text values (FR21)", async () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('ID');
+ expect(within(sheet()).queryByRole('combobox')).toBeNull();
+ const tokenizerTrigger = within(sheet()).getByRole('button', {name: 'ID'});
+ expect(tokenizerTrigger).toHaveAttribute('aria-haspopup', 'dialog');
+ fireEvent.click(tokenizerTrigger);
+ const tokenizerSheet = await screen.findByRole('dialog', {name: 'ID'});
+ expect(tokenizerSheet).toBe(sheet());
+ fireEvent.change(within(tokenizerSheet).getByLabelText('Search ID'), {
+ target: {value: 'ABC-1'},
+ });
+ fireEvent.click(
+ await within(tokenizerSheet).findByRole('button', {name: 'Add ABC-1'}),
+ );
+ // Save closes only the topmost sheet and stages the values in the step.
+ fireEvent.click(within(tokenizerSheet).getByRole('button', {name: 'Save'}));
+ settleSheets();
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', {name: 'ID'})).toBeNull(),
+ );
+ expect(
+ within(sheet()).getByRole('heading', {name: 'ID is any of'}),
+ ).toBeTruthy();
+ expect(within(sheet()).getByRole('button', {name: /^ID/})).toHaveFocus();
+ // Escape on the unchanged sheet dismisses only that sheet; the value step
+ // keeps its staged value.
+ fireEvent.click(within(sheet()).getByRole('button', {name: /^ID/}));
+ await screen.findByRole('dialog', {name: 'ID'});
+ fireEvent.keyDown(document.activeElement ?? document.body, {key: 'Escape'});
+ settleSheets();
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', {name: 'ID'})).toBeNull(),
+ );
+ expect(
+ within(sheet()).getByRole('heading', {name: 'ID is any of'}),
+ ).toBeTruthy();
+ addFilter();
+ expect(onChange).toHaveBeenCalledWith(
+ [
+ {
+ field: 'ids',
+ operator: 'in',
+ value: {type: 'string_list', value: ['ABC-1']},
+ },
+ ],
+ 'add',
+ 0,
+ );
+ });
+
+ it('integer: number input stages as typed', () => {
+ 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('integer: clearing the field unstages the value and disables Add filter', () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Lines');
+ const input = within(sheet()).getByRole('spinbutton', {name: 'Value'});
+ fireEvent.input(input, {target: {value: '1'}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeEnabled();
+ // Delete the digit: nothing stands to confirm.
+ fireEvent.input(input, {target: {value: ''}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeDisabled();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Add filter'}));
+ expect(onChange).not.toHaveBeenCalled();
+ // Not a number either: still nothing.
+ fireEvent.input(input, {target: {value: '-'}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeDisabled();
+ fireEvent.input(input, {target: {value: '12'}});
+ expect(
+ within(sheet()).getByRole('button', {name: 'Add filter'}),
+ ).toBeEnabled();
+ });
+
+ 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: the date input shows the stored day in the field's zone, as the popover presentation reads it", () => {
+ 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_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(choice('7 days ago')).toBeChecked();
+ 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/);
+ // The popover presentation's editor labels the range with the catalog's
+ // lowercase noun; the sheet reuses that editor.
+ const range = within(sheet()).getByRole('button', {
+ name: /date range.*Mar 1, 2024/i,
+ });
+ expect(range).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it("entity_list: the Tokenizer's sheet picks entities from the search source (FR21)", async () => {
+ const {onChange} = setupValues();
+ openAddFlow();
+ tapRow('Assignee');
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Assignee'}));
+ const tokenizerSheet = await screen.findByRole('dialog', {
+ name: 'Assignee',
+ });
+ fireEvent.click(
+ await within(tokenizerSheet).findByRole('checkbox', {
+ name: 'Ada Lovelace',
+ }),
+ );
+ fireEvent.click(within(tokenizerSheet).getByRole('button', {name: 'Save'}));
+ settleSheets();
+ await waitFor(() =>
+ expect(screen.queryByRole('dialog', {name: 'Assignee'})).toBeNull(),
+ );
+ 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();
+ });
+});
+
+// =============================================================================
+// Values read the same everywhere
+// =============================================================================
+
+describe('PowerSearch sheet value text', () => {
+ // 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 a
+ // date differently from the popover presentation's token.
+ const BOUNDARY_SECONDS = 1710039600;
+ const dateFilter: PowerSearchFilter = {
+ field: 'created',
+ operator: 'after',
+ value: {type: 'date_absolute', unixSeconds: BOUNDARY_SECONDS},
+ };
+
+ // The value text the popover presentation's token shows for each filter:
+ // the token's end content, after its "{Field}: {operator}" label.
+ function popoverTokenValues(
+ filters: ReadonlyArray<PowerSearchFilter>,
+ timezoneID?: string,
+ ): string[] {
+ const {unmount} = render(
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={filters}
+ onChange={() => {}}
+ timezoneID={timezoneID}
+ />,
+ );
+ const texts = filters.map(filter => {
+ const field = valueTypesConfig.fields.find(f => f.key === filter.field)!;
+ const label = screen.getByText(new RegExp(`^${field.label}: `));
+ let node: HTMLElement | null = label;
+ while (node && node.textContent === label.textContent) {
+ node = node.parentElement;
+ }
+ const whole = node?.textContent ?? '';
+ return whole.slice(label.textContent.length).trim();
+ });
+ unmount();
+ return texts;
+ }
+
+ it.each([['UTC'], ['Asia/Tokyo'], ['Pacific/Honolulu'], [undefined]])(
+ 'shows a date on the trigger token, in the Filters row and in the removal announcement exactly as the popover token shows it (timezoneID %s)',
+ async timezoneID => {
+ const [day] = popoverTokenValues([dateFilter], timezoneID);
+ expect(day).toMatch(/^Mar (9|10), 2024$/);
+ const spy = mockModalDialogs();
+ try {
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([dateFilter]);
+ return (
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ timezoneID={timezoneID}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ // The sheet presentation's token is the popover's token.
+ expect(within(field()).getByText(day)).toBeTruthy();
+ // The Filters row reads the same value, bold.
+ openSheet();
+ const row = within(sheet()).getByRole('button', {
+ name: `Created is after ${day}`,
+ });
+ expect(within(row).getByText(day)).toHaveStyle({
+ fontWeight: 'var(--font-weight-bold)',
+ });
+ // And the removal announcement names the row's text.
+ fireEvent.click(removeButton('Created'));
+ const filtersDialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ `Removed Created is after ${day}`,
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ },
+ );
+
+ it('reads a date into the editor as the popover presentation does (FR17)', () => {
+ setup({
+ config: valueTypesConfig,
+ filters: [dateFilter],
+ timezoneID: 'Pacific/Honolulu',
+ });
+ openEditFlow(/^Created is after/);
+ // Both presentations' date editors read the instant's UTC day; the
+ // token and row may name a neighbouring day in an off-UTC zone (the
+ // record's known gap).
+ expect(within(sheet()).getByRole('combobox', {name: 'Date'})).toHaveValue(
+ 'March 10, 2024',
+ );
+ });
+
+ it("resolves the sheet's date-range and nested summaries through the catalog with the popover token's words", () => {
+ // The row's value resolves "date range" and "{n} filters" through
+ // `@astryx.powersearch.valueEditor.*` (ICU plural) so a locale can
+ // translate them, while in English they stay the popover token's words.
+ // (A list collapses to "{n} items" only under the token's width budget;
+ // the untruncated row lists it in full.)
+ const nestedConfig: PowerSearchConfig = {
+ name: 'NestedSummary',
+ fields: [
+ ...valueTypesConfig.fields,
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [{key: 'all', label: 'matches', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const filters: PowerSearchFilter[] = [
+ {
+ field: 'window',
+ operator: 'between',
+ value: {
+ type: 'date_range',
+ value: {
+ start: {type: 'ABSOLUTE', unixSeconds: 0},
+ end: {type: 'ABSOLUTE', unixSeconds: 86400},
+ },
+ },
+ },
+ {
+ field: 'group',
+ operator: 'all',
+ value: {
+ type: 'nested',
+ value: [
+ {
+ field: 'title',
+ operator: 'contains',
+ value: {type: 'string', value: 'a'},
+ },
+ ],
+ },
+ },
+ ];
+ setup({config: nestedConfig, filters});
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {
+ name: 'Window is between date range',
+ }),
+ ).toBeTruthy();
+ // A nested filter's row (a button with a trailing remove action, FR12)
+ // reads its value as the token's.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Group matches 1 filter'}),
+ ).toBeTruthy();
+ });
+
+ it("reads a relative-date value on the Filters row and in Removed as the value step's choice row does", async () => {
+ const spy = mockModalDialogs();
+ try {
+ const relative: PowerSearchFilter = {
+ field: 'age',
+ operator: 'newer',
+ value: {type: 'date_relative', value: '3d_ago'},
+ };
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([relative]);
+ return (
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ );
+ }
+ render(<Harness />);
+ // The trigger shows the popover token as it is: the stored key.
+ expect(within(field()).getByText('3d_ago')).toBeTruthy();
+ openSheet();
+ const row = within(sheet()).getByRole('button', {
+ name: 'Age is newer than 3 days ago',
+ });
+ fireEvent.click(row);
+ expect(choice('3 days ago')).toBeChecked();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Cancel'}));
+ // The value step finishes its exit before the removal.
+ settleSheets();
+ fireEvent.click(removeButton('Age'));
+ const filtersDialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed Age is newer than 3 days ago',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('renders the Filters row and the Removed text through one labelValue message, so a reordering locale keeps them consistent (INV1a)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([openFilter]);
+ return (
+ <InternationalizationProvider locale="en" overrides={REORDERED}>
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </InternationalizationProvider>
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ const row = within(sheet()).getByRole('button', {
+ name: 'Open (Status is)',
+ });
+ expect(within(row).getByText('Open')).toHaveStyle({
+ fontWeight: 'var(--font-weight-bold)',
+ });
+ fireEvent.click(removeButton('Status'));
+ const filtersDialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed Open (Status is)',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it('announces Clear all and a changed count through one catalog message a locale can reorder (INV1a)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ function Harness() {
+ const [filters, setFilters] = useState<
+ ReadonlyArray<PowerSearchFilter>
+ >([openFilter]);
+ return (
+ <InternationalizationProvider locale="en" overrides={REORDERED}>
+ <PowerSearch
+ config={config}
+ filters={filters}
+ onChange={next => setFilters(next)}
+ resultCount={filters.length === 0 ? 240 : 12}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </InternationalizationProvider>
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ const filtersDialog = sheet();
+ fireEvent.click(within(sheet()).getByRole('button', {name: 'Clear all'}));
+ confirmClearAll();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)?.textContent ?? '').toContain(
+ '240 results — all filters removed',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it.each([
+ [1e21, '1e+21'],
+ [1e-7, '1e-7'],
+ [-0, '0'],
+ [2.3456, '2.3456'],
+ ])(
+ 'reads a number on the Filters row exactly as the token does in English, %s (FR12)',
+ (value, text) => {
+ setup({
+ config: valueTypesConfig,
+ filters: [
+ {field: 'cost', operator: 'gt', value: {type: 'float', value}},
+ ],
+ });
+ expect(within(field()).getByText(text)).toBeTruthy();
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {name: `Cost > ${text}`}),
+ ).toBeTruthy();
+ },
+ );
+
+ it("reads a number with the locale's digits and decimal mark where they differ from the token's, differing only in notation (FR12)", () => {
+ render(
+ <InternationalizationProvider locale="de">
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={[
+ {
+ field: 'cost',
+ operator: 'gt',
+ value: {type: 'float', value: 1e-7},
+ },
+ {
+ field: 'lines',
+ operator: 'gt',
+ value: {type: 'integer', value: -0},
+ },
+ {
+ field: 'cost',
+ operator: 'gt',
+ value: {type: 'float', value: 1e-21},
+ },
+ ]}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </InternationalizationProvider>,
+ );
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Cost > 0,0000001'}),
+ ).toBeTruthy();
+ expect(
+ within(sheet()).getByRole('button', {name: 'Lines is greater than -0'}),
+ ).toBeTruthy();
+ // No rounding: the fraction cap is Intl's maximum.
+ expect(
+ within(sheet()).getByRole('button', {
+ name: 'Cost > 0,000000000000000000001',
+ }),
+ ).toBeTruthy();
+ // The token keeps its own text.
+ expect(within(field()).getByText('1e-7')).toBeTruthy();
+ expect(within(field()).getByText('0')).toBeTruthy();
+ });
+
+ it('formats a list and a number on the Filters row and in Removed in the provider locale (INV1a, INV8)', async () => {
+ const spy = mockModalDialogs();
+ try {
+ const filters: PowerSearchFilter[] = [
+ {
+ field: 'ids',
+ operator: 'in',
+ value: {type: 'string_list', value: ['a', 'b', 'c']},
+ },
+ {
+ field: 'lines',
+ operator: 'gt',
+ value: {type: 'integer', value: 1234567},
+ },
+ {field: 'cost', operator: 'gt', value: {type: 'float', value: 2.3456}},
+ ];
+ function Harness() {
+ const [current, setCurrent] =
+ useState<ReadonlyArray<PowerSearchFilter>>(filters);
+ return (
+ <InternationalizationProvider locale="de">
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={current}
+ onChange={next => setCurrent(next)}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </InternationalizationProvider>
+ );
+ }
+ render(<Harness />);
+ openSheet();
+ // German list separators and digit grouping, not a literal ", " and
+ // `String()`; the popover token keeps its own literals (known gap).
+ const list = within(sheet()).getByRole('button', {
+ name: 'ID is any of a, b und c',
+ });
+ // Provider digits and decimal mark, but no grouping and no rounding,
+ // so in English the row reads exactly as the token does.
+ expect(
+ within(sheet()).getByRole('button', {
+ name: 'Lines is greater than 1234567',
+ }),
+ ).toBeTruthy();
+ expect(within(field()).getByText('a, b, c')).toBeTruthy();
+ expect(within(field()).getByText('1234567')).toBeTruthy();
+ // A float: the locale's decimal mark, no rounding.
+ expect(
+ within(sheet()).getByRole('button', {name: 'Cost > 2,3456'}),
+ ).toBeTruthy();
+ expect(within(field()).getByText('2.3456')).toBeTruthy();
+ fireEvent.click(
+ within(list.closest('li')!).getByRole('button', {
+ name: 'Remove ID filter',
+ }),
+ );
+ const filtersDialog = sheet();
+ await waitFor(() =>
+ expect(modalLiveRegion(filtersDialog)).toHaveTextContent(
+ 'Removed ID is any of a, b und c',
+ ),
+ );
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
+ it.each([
+ ['en', 'Bug, Feature, Docs'],
+ ['zh-CN', 'Bug、Feature、Docs'],
+ ['ja-JP', 'Bug、Feature、Docs'],
+ ['de-DE', 'Bug, Feature und Docs'],
+ ])(
+ 'joins a list value on the Filters row with a narrow conjunction list in %s, so every value stays separated (FR12)',
+ (locale, text) => {
+ render(
+ <InternationalizationProvider locale={locale}>
+ <PowerSearch
+ config={valueTypesConfig}
+ filters={[
+ {
+ field: 'ids',
+ operator: 'in',
+ value: {type: 'string_list', value: ['Bug', 'Feature', 'Docs']},
+ },
+ ]}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />
+ </InternationalizationProvider>,
+ );
+ openSheet();
+ expect(
+ within(sheet()).getByRole('button', {name: `ID is any of ${text}`}),
+ ).toBeTruthy();
+ // The token keeps its literal join (known gap).
+ expect(within(field()).getByText('Bug, Feature, Docs')).toBeTruthy();
+ },
+ );
+
+ it("formats every value type on a Filters row with the popover token's words", () => {
+ const filters: PowerSearchFilter[] = [
+ {
+ field: 'ids',
+ operator: 'in',
+ value: {type: 'string_list', value: ['a', 'b']},
+ },
+ {field: 'lines', operator: 'gt', value: {type: 'integer', value: 7}},
+ {
+ field: 'window',
+ operator: 'between',
+ value: {
+ type: 'date_range',
+ value: {
+ start: {type: 'ABSOLUTE', unixSeconds: 0},
+ end: {type: 'ABSOLUTE', unixSeconds: 86400},
+ },
+ },
+ },
+ ];
+ const popover = popoverTokenValues(filters);
+ expect(popover).toEqual(['a, b', '7', 'date range']);
+ setup({config: valueTypesConfig, filters});
+ openSheet();
+ const rows = within(sheet()).getAllByRole('button', {
+ name: /^(ID|Lines|Window) /,
+ });
+ expect(
+ rows.map(row => row.textContent?.replace(/\s+/g, ' ').trim()),
+ ).toEqual([
+ `ID is any of ${popover[0]}`,
+ `Lines is greater than ${popover[1]}`,
+ `Window is between ${popover[2]}`,
+ ]);
+ });
+});
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+describe('powerSearchSheetUtils', () => {
+ 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("offers the popover presentation's suggestions, nested fields included (FR13)", () => {
+ const withNested: PowerSearchConfig = {
+ ...contentSearchConfig,
+ fields: [
+ ...contentSearchConfig.fields,
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [{key: 'all', label: 'all of', value: {type: 'nested'}}],
+ },
+ ],
+ };
+ const {result} = renderHook(() => {
+ const internal = useInternalConfig(withNested);
+ const source = usePowerSearchSource(internal, 10);
+ return createSheetSuggestionSource(internal, source);
+ });
+ expect(result.current.bootstrap().map(item => item.id)).toEqual([
+ 'status',
+ 'author',
+ 'unassigned',
+ 'group',
+ 'labels',
+ ]);
+ const results = result.current.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'},
+ },
+ });
+ expect(result.current.search('Group')[0]).toMatchObject({
+ auxiliaryData: {fieldKey: 'group'},
+ });
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx b/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx
new file mode 100644
index 0000000000..c1b3dca268
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchBottomSheet.tsx
@@ -0,0 +1,2515 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file PowerSearchBottomSheet.tsx
+ * @input The field's InternalConfig, filters, onChange, the field typeahead
+ * source, and the sheet options PowerSearch forwards; BottomSheet,
+ * Button, EmptyState, Heading, Icon, IconButton, Indicator, List,
+ * RadioList, Text, TextInput, PowerSearchValueEditor, the internal sheet
+ * confirmation and search-drag owners, i18n
+ * @output Exports PowerSearchBottomSheet — the touch surface of
+ * `PowerSearch experimental.presentation="bottom-sheet"`: a Filters sheet
+ * with editable rows and trailing remove actions, Add filter in its fixed
+ * header and Clear all / Done in its fixed footer, an Add filter sheet with
+ * grouped field rows or the content search with inline suggestions, and a
+ * value step that stages field → operator → value and confirms from its
+ * footer
+ * @position Internal presentation surface of PowerSearch. Loaded on demand by
+ * PowerSearch.tsx so the popover presentation never carries it. The
+ * trigger lives in PowerSearch.tsx.
+ *
+ * The three steps are sibling standalone BottomSheets that stack: each step
+ * opens above the sheet that led to it, which stays open beneath as a covered
+ * sheet, so no sheet needs a Back action. A dismissal closes only the top
+ * sheet and reveals the step beneath; dismissing the bottom sheet ends the
+ * flow. A list value's Tokenizer opens its own sheet above the value step, as
+ * the top sheet of the stack.
+ *
+ * The sheets pad their own content (`padding={0}` on BottomSheet). The
+ * Filters and Add filter sheets keep their header and footer fixed around a
+ * scroll viewport that reaches the sheet edge; its content publishes the
+ * padding as container padding so `edge="bleed"` lists run edge to edge with
+ * row text on the header's inset. The sheets are pinned tall: 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/core/src/PowerSearch/PowerSearch.tsx (the trigger and the lazy host)
+ * - /docs/specs/components/PowerSearch/PowerSearch.spec.md (FR10–FR21, AR4–AR6, PR5)
+ */
+
+import React, {
+ useCallback,
+ useEffect,
+ useId,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+ type SVGProps,
+} from 'react';
+import {flushSync} from 'react-dom';
+import * as stylex from '@stylexjs/stylex';
+import {BottomSheet} from '../BottomSheet/BottomSheet';
+import {Button} from '../Button/Button';
+import {EmptyState} from '../EmptyState/EmptyState';
+import {Heading} from '../Heading/Heading';
+import {Icon} from '../Icon/Icon';
+import {IconButton} from '../IconButton/IconButton';
+import {CheckboxIndicator} from '../Indicator/CheckboxIndicator';
+import {RadioIndicator} from '../Indicator/RadioIndicator';
+import {focusOutlineStyles} from '../utils/focusOutline.stylex';
+import {isRenderable} from '../utils/isRenderable';
+import {containerPaddingInlineVarStyles} from '../Layout/padding.stylex';
+import {List} from '../List/List';
+import {ListItem} from '../List/ListItem';
+import {RadioList} from '../RadioList/RadioList';
+import {RadioListItem} from '../RadioList/RadioListItem';
+import {Text} from '../Text/Text';
+import {TextInput} from '../TextInput/TextInput';
+import type {SearchSource} from '../Typeahead/types';
+import {useAnnounce, type AnnounceFn} from '../hooks/useAnnounce';
+import type {TranslatorFn} from '../i18n';
+import {useListFormatter} from '../i18n/useListFormatter';
+import {useLocale} from '../i18n/useLocale';
+import {SheetConfirmation} from '../internal/SheetConfirmation';
+import {useDismissSearchOnTouchDrag} from '../internal/useDismissSearchOnTouchDrag';
+import {
+ colorVars,
+ fontWeightVars,
+ radiusVars,
+ spacingVars,
+} from '../theme/tokens.stylex';
+import {isImeKeyEvent} from '../utils/ime';
+import {rtlStyles} from '../utils/rtlStyles';
+import {formatTokenValueText} from './formatTokenValue';
+
+function resolveRelativeDateLabel(
+ operatorValue: OperatorValue & {type: 'date_relative'},
+ value: string,
+ t: TranslatorFn,
+ buildRelativeDateOptions: PowerSearchSheetEditors['buildRelativeDateOptions'],
+): string {
+ return (
+ buildRelativeDateOptions(operatorValue, t).find(
+ option => option.value === value,
+ )?.label ?? value
+ );
+}
+
+// A placeholder the Filters row formats `labelValue` with, then splits on, so
+// the value segment can render bold inside the catalog's ordering. A private
+// use code point: never part of a label or value.
+const ROW_VALUE_SLOT = '\uE000';
+import type {
+ buildRelativeDateOptions,
+ PowerSearchValueEditor,
+} from './PowerSearchValueEditor';
+import type {NestedEditor} from './PowerSearchEditPopover';
+import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';
+import {useInternalListFocus} from '../hooks/useListFocus';
+import {useMergedRefs} from '../hooks/useMergedRefs';
+import {groupItems} from '../utils/groupItems';
+import {
+ createSheetSuggestionSource,
+ fieldMatchesQuery,
+ createFilterIdentities,
+ filterSignature,
+ isSupportedOperator,
+ nearestEditableIndex,
+ resolveFilterIdentityIndex,
+} from './powerSearchSheetUtils';
+import {resolveOperatorLabel} from './resolveOperatorLabel';
+import type {InternalConfig} from './useInternalConfig';
+import type {
+ FilterValue,
+ OperatorValue,
+ PartialFilter,
+ PowerSearchChangeType,
+ PowerSearchComponents,
+ PowerSearchConfig,
+ PowerSearchField,
+ PowerSearchFilter,
+ PowerSearchItem,
+ PowerSearchOperator,
+} from './types';
+import {
+ registerEnglishFallback,
+ useComponentTranslator,
+} from '../i18n/useComponentTranslator';
+import english from '../i18n/generated-english/PowerSearch/PowerSearchBottomSheet.generated';
+
+registerEnglishFallback(english);
+
+// =============================================================================
+// Props
+// =============================================================================
+
+/**
+ * The popover presentation's editors, which the value step reuses. They come
+ * from PowerSearch.tsx, whose module graph already loads them for the popover
+ * presentation. Imported here, they and every component they reach would join
+ * this lazily imported graph, whose modules must import Core directly and
+ * never through a barrel.
+ */
+export interface PowerSearchSheetEditors {
+ NestedEditor: typeof NestedEditor;
+ PowerSearchValueEditor: typeof PowerSearchValueEditor;
+ buildRelativeDateOptions: typeof buildRelativeDateOptions;
+}
+
+export interface PowerSearchBottomSheetProps {
+ /** Whether the flow is open; the trigger in PowerSearch.tsx owns it. */
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ /**
+ * The trigger: where focus returns when the flow closes, whichever step
+ * closed it and however it opened (a tap on a token included).
+ */
+ finalFocusRef: RefObject<HTMLElement | null>;
+ /**
+ * The field's formatted result count, announced from inside the open
+ * sheet's dialog when it changes while the flow is open. `useAnnounce`
+ * routes a message by where its caller is, so the owner above the sheets
+ * cannot reach the dialog's region.
+ */
+ resultCountText?: string | null;
+ config: InternalConfig;
+ /** The caller's config, handed to Editor overrides as they expect it. */
+ configProp: PowerSearchConfig;
+ filters: ReadonlyArray<PowerSearchFilter>;
+ onChange: (
+ filters: ReadonlyArray<PowerSearchFilter>,
+ changeType: PowerSearchChangeType,
+ index: number,
+ ) => void;
+ /** The field typeahead source; the content search lists its suggestions. */
+ searchSource: SearchSource<PowerSearchItem>;
+ /** Placeholder of the content search. */
+ placeholder: string;
+ isReadOnly: boolean;
+ isDisabled: boolean;
+ hasClear: boolean;
+ maxOperatorMenuItems?: number;
+ maxSearchResults: number;
+ /** The caller's confirm label; the step picks a default per mode. */
+ saveButtonLabel?: string;
+ components?: PowerSearchComponents;
+ editors: PowerSearchSheetEditors;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+// The trailing plus a field row shows when choosing it adds the filter at
+// once, and the Add filter actions' glyph. Core's default icon set has no plus.
+function PlusIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.5}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ {...props}>
+ <path d="M5 12h14" />
+ <path d="M12 5v14" />
+ </svg>
+ );
+}
+
+const styles = stylex.create({
+ // 44px touch targets for every sheet action, without resizing inputs.
+ touchAction: {
+ minHeight: 44,
+ },
+ // A sheet action drawn smaller than 44px keeps its drawn size and grows
+ // only its hit area to 44px, under a coarse pointer. The custom properties
+ // carry the media condition because StyleX allows plain values inside a
+ // pseudo-element. On a fine pointer the overlay is not generated, so it
+ // never takes hover from the action's own content.
+ touchHitArea: {
+ '--_power-search-sheet-hit-inset': {
+ default: '0px',
+ '@media (pointer: coarse)': 'min(0px, calc((100% - 44px) / 2))',
+ },
+ '--_power-search-sheet-hit-content': {
+ default: 'none',
+ '@media (pointer: coarse)': '""',
+ },
+ '::after': {
+ content: 'var(--_power-search-sheet-hit-content)',
+ position: 'absolute',
+ inset: 'var(--_power-search-sheet-hit-inset)',
+ },
+ },
+ // Scopes the sticky header's and footer's layer to this sheet's content:
+ // the List rows are `position: relative` and come after the header, so
+ // without a layer of its own the header is painted under the rows that
+ // scroll beneath it. Isolating the content keeps that z-index inside it, so
+ // the sheet's grab handle (z-index 1 on the panel, outside this wrapper)
+ // still paints above.
+ sheet: {
+ display: 'flex',
+ flexDirection: 'column',
+ minHeight: '100%',
+ isolation: 'isolate',
+ },
+ // The Filters and Add filter sheets fill the panel and scroll only their
+ // viewport, so the header and footer stay fixed.
+ sheetWithFixedFooter: {
+ height: '100%',
+ overflow: 'hidden',
+ },
+ header: {
+ position: 'sticky',
+ insetBlockStart: 0,
+ // Above the rows that scroll under it, within the isolated sheet content.
+ zIndex: 1,
+ 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.
+ body: {
+ flexGrow: 1,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlockEnd: spacingVars['--spacing-4'],
+ },
+ // The viewport reaches the sheet edge, so its scrollbar does too; the
+ // content inside it carries the body's padding.
+ scrollViewport: {
+ flexGrow: 1,
+ minHeight: 0,
+ overflowY: 'auto',
+ overscrollBehaviorY: 'contain',
+ },
+ scrollContent: {
+ minHeight: '100%',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: spacingVars['--spacing-4'],
+ paddingInline: spacingVars['--spacing-4'],
+ paddingBlockEnd: spacingVars['--spacing-4'],
+ },
+ footer: {
+ position: 'sticky',
+ insetBlockEnd: 0,
+ zIndex: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: spacingVars['--spacing-2'],
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-4'],
+ backgroundColor: colorVars['--color-background-surface'],
+ },
+ fixedFooter: {
+ position: 'relative',
+ insetBlockEnd: 'auto',
+ flexShrink: 0,
+ },
+ footerEqualAction: {
+ flexGrow: 1,
+ flexBasis: 0,
+ minWidth: 0,
+ minHeight: 44,
+ },
+ footerSoleAction: {
+ flexGrow: 1,
+ },
+ empty: {
+ paddingBlock: spacingVars['--spacing-6'],
+ textAlign: 'center',
+ },
+ emptyState: {
+ flexGrow: 1,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ },
+ // With more than one section in the value step, each section is a muted
+ // container. Its inline padding is published as container padding, so
+ // choice rows run edge to edge inside the section.
+ controlSection: {
+ padding: spacingVars['--spacing-3'],
+ borderRadius: radiusVars['--radius-container'],
+ backgroundColor: colorVars['--color-background-muted'],
+ },
+ // The operator radios put their indicator at the row's end, as the choice
+ // rows do.
+ trailingControlRow: {
+ flexDirection: 'row-reverse',
+ },
+ // The built-in nested editor's sub-filter rows collapse from one line to
+ // wrapped lines under a container query on the popover's own container;
+ // the sheet renders no such container, so the editor's tree root is the
+ // query container here, and at phone widths the rows wrap instead of
+ // running past the sheet's edge.
+ nestedEditorContainer: {
+ containerType: 'inline-size',
+ overflow: 'hidden',
+ },
+ rowValue: {
+ fontWeight: fontWeightVars['--font-weight-bold'],
+ },
+ // Choice rows run edge to edge on the inset of the surface that holds them,
+ // the body or a muted section, with no dividers: the group reaches into
+ // that padding and each row pads back out to it.
+ choiceList: {
+ display: 'flex',
+ flexDirection: 'column',
+ marginInlineStart: 'calc(-1 * var(--container-padding-inline-start, 0px))',
+ marginInlineEnd: 'calc(-1 * var(--container-padding-inline-end, 0px))',
+ width:
+ 'calc(100% + var(--container-padding-inline-start, 0px) + var(--container-padding-inline-end, 0px))',
+ },
+ choiceRow: {
+ display: 'flex',
+ alignItems: 'center',
+ gap: spacingVars['--spacing-3'],
+ width: '100%',
+ minHeight: 44,
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInlineStart: 'var(--container-padding-inline-start, 0px)',
+ paddingInlineEnd: 'var(--container-padding-inline-end, 0px)',
+ borderWidth: 0,
+ borderRadius: 0,
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-primary'],
+ fontFamily: 'inherit',
+ textAlign: 'start',
+ cursor: {
+ default: 'pointer',
+ ':is([aria-disabled="true"])': 'default',
+ },
+ },
+ // An aria-disabled row gets no system disabled paint in forced colors;
+ // GrayText is the platform's disabled affordance there.
+ choiceRowDisabled: {
+ color: {
+ default: colorVars['--color-text-secondary'],
+ '@media (forced-colors: active)': 'GrayText',
+ },
+ },
+ choiceIcon: {
+ display: 'inline-flex',
+ flexShrink: 0,
+ },
+ choiceLabel: {
+ flexGrow: 1,
+ minWidth: 0,
+ },
+ editorInput: {
+ paddingBlockStart: spacingVars['--spacing-1'],
+ },
+});
+
+// =============================================================================
+// 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;
+ /**
+ * After a removal, focus goes to the row's trailing remove action, so a
+ * run of removals needs no re-aiming; otherwise to the row.
+ */
+ readonly part?: 'remove';
+ }
+ | {readonly type: 'field'; readonly fieldKey: string};
+
+interface FilterDraft {
+ readonly mode: 'create' | 'edit';
+ /**
+ * Counts the value steps opened in this flow. Part of the editor's `key`:
+ * the step's sheet stays mounted between openings, and an editor that
+ * reads its filter on mount (the built-in nested editor, a caller's
+ * override) must remount per opened filter, not per field and operator —
+ * two groups on one field would otherwise share one editor's state.
+ */
+ readonly generation: number;
+ /** Control within the Add filter 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;
+// Empty-query browsing keeps the popover presentation's safety ceiling.
+const MAX_BROWSE_MENU_ITEMS = 1000;
+
+// =============================================================================
+// Choice rows (enum, enum_list, date_relative)
+// =============================================================================
+
+/**
+ * Rendered inside a step's BottomSheet so that `useAnnounce` resolves the
+ * sheet's dialog as the enclosing modal; publishes that
+ * dialog's `announce` to the flow above through `onAnnounceChange` while
+ * mounted. Renders nothing.
+ */
+function SheetAnnouncer({
+ onAnnounceChange,
+}: {
+ onAnnounceChange: (announce: AnnounceFn | null) => void;
+}) {
+ const announce = useAnnounce();
+ // Hands this dialog's announce function up; the cleanup withdraws it when
+ // the step changes or the flow closes.
+ useEffect(() => {
+ onAnnounceChange(announce);
+ return () => {
+ onAnnounceChange(null);
+ };
+ }, [announce, onAnnounceChange]);
+ return null;
+}
+
+/**
+ * The value step's "This filter is no longer available" message, rendered
+ * inside the step's dialog. The shared own-content module reads the rendered
+ * text and speaks it once per opened filter while the step is the open one.
+ * Called from inside the sheet's dialog, `useAnnounce` routes it into the
+ * dialog. The message is plain text, not an EmptyState, so nothing announces
+ * it a second time.
+ */
+function SheetEmptyMessage({
+ id,
+ message,
+ occasion,
+ isShown,
+}: {
+ id?: string;
+ message: string;
+ occasion: string;
+ /**
+ * Whether the message's step is the open one. A sheet beneath another, or
+ * closed with its body retained, speaks nothing, and the hook re-arms so
+ * the same occasion is spoken again when the step reopens on it.
+ */
+ isShown: boolean;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ useAnnounceRenderedText(ref, isShown, occasion);
+ return (
+ <div ref={ref} id={id} {...stylex.props(styles.empty)}>
+ <Text type="supporting" color="secondary">
+ {message}
+ </Text>
+ </div>
+ );
+}
+
+interface ChoiceItem {
+ readonly value: string;
+ readonly label: string;
+ readonly icon?: ReactNode;
+}
+
+// A radio group's one tab stop: the checked row, else the first.
+function radioTabStopOrder(list: HTMLElement): ReadonlyArray<HTMLElement> {
+ const rows = Array.from(list.querySelectorAll<HTMLElement>('[role="radio"]'));
+ const checked = rows.find(row => row.getAttribute('aria-checked') === 'true');
+ return checked == null
+ ? rows
+ : [checked, ...rows.filter(row => row !== checked)];
+}
+
+/**
+ * Closed vocabularies render as full-width rows with a trailing check instead
+ * of the popover presentation's Selector or Tokenizer: a dropdown layer inside
+ * a sheet stacks a second overlay on a surface the person is already inside.
+ */
+function ChoiceRows({
+ items,
+ selected,
+ isDisabled,
+ isMultiple,
+ label,
+ onToggle,
+}: {
+ items: ReadonlyArray<ChoiceItem>;
+ selected: ReadonlySet<string>;
+ isDisabled?: boolean;
+ /** `enum_list`: checkbox rows that toggle. Otherwise radio rows. */
+ isMultiple: boolean;
+ /** The group's accessible name: the field label. */
+ label: string;
+ onToggle: (value: string, isSelected: boolean) => void;
+}) {
+ // The rows carry their state as state, not as a name suffix: `radio` rows
+ // in a `radiogroup` for a single choice, `checkbox` rows in a `group` for
+ // `enum_list`, each with `aria-checked`, as the Tokenizer's sheet rows do.
+ // Disabled rows stay focusable with `aria-disabled`.
+ //
+ // Keyboard: a radio group is one tab stop — the checked row, else the
+ // first — and the arrow keys move focus and check the row they land on,
+ // wrapping; Home and End move to and check the first and last row. The
+ // shared list focus owns the tab stop and the moves; a row that takes focus
+ // from an arrow, Home or End is checked here. Space and Enter check the
+ // focused radio row and toggle a checkbox row: each row is a native
+ // `button`, whose activation fires `onClick` for both keys. A checkbox row
+ // is its own tab stop.
+ const isKeyMoveRef = useRef(false);
+ const {listRef, handleKeyDown, handleFocus} =
+ useInternalListFocus<HTMLDivElement>({
+ itemSelector: '[role="radio"]',
+ orientation: 'both',
+ hasRovingTabIndex: !isMultiple,
+ tabStopOrder: radioTabStopOrder,
+ });
+ const handleRadioKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ isKeyMoveRef.current = true;
+ try {
+ handleKeyDown(event);
+ } finally {
+ isKeyMoveRef.current = false;
+ }
+ };
+ const handleRadioFocus = (event: React.FocusEvent<HTMLDivElement>) => {
+ handleFocus(event);
+ if (!isKeyMoveRef.current || isDisabled) {
+ return;
+ }
+ const value = (event.target as HTMLElement).closest<HTMLElement>(
+ '[role="radio"]',
+ )?.dataset.value;
+ if (value != null && !selected.has(value)) {
+ onToggle(value, false);
+ }
+ };
+ return (
+ <div
+ ref={listRef}
+ role={isMultiple ? 'group' : 'radiogroup'}
+ aria-label={label}
+ onKeyDown={isMultiple ? undefined : handleRadioKeyDown}
+ onFocus={isMultiple ? undefined : handleRadioFocus}
+ {...stylex.props(styles.choiceList)}>
+ {items.map(item => {
+ const isSelected = selected.has(item.value);
+ return (
+ <button
+ key={item.value}
+ type="button"
+ role={isMultiple ? 'checkbox' : 'radio'}
+ aria-checked={isSelected}
+ aria-disabled={isDisabled || undefined}
+ data-value={item.value}
+ onClick={() => {
+ if (!isDisabled) {
+ onToggle(item.value, isSelected);
+ }
+ }}
+ {...stylex.props(
+ focusOutlineStyles.focusVisible,
+ styles.choiceRow,
+ isDisabled && styles.choiceRowDisabled,
+ )}>
+ {isRenderable(item.icon) && (
+ <span aria-hidden="true" {...stylex.props(styles.choiceIcon)}>
+ {item.icon}
+ </span>
+ )}
+ <Text
+ type="body"
+ color={isDisabled ? 'inherit' : undefined}
+ xstyle={styles.choiceLabel}>
+ {item.label}
+ </Text>
+ {isMultiple ? (
+ <CheckboxIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
+ isDisabled={isDisabled}
+ />
+ ) : (
+ <RadioIndicator
+ state={isSelected ? 'checked' : 'unchecked'}
+ size="md"
+ isDisabled={isDisabled}
+ />
+ )}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/**
+ * The value control for one filter inside the value step. Closed vocabularies
+ * are rows here; every other type is the popover presentation's own editor in
+ * its sheet presentation.
+ */
+function SheetValueEditor({
+ operatorValue,
+ filterValue,
+ onChange,
+ onUnstage,
+ config,
+ fieldLabel,
+ isDisabled,
+ maxMenuItems,
+ editors,
+}: {
+ operatorValue: OperatorValue;
+ filterValue: FilterValue | undefined;
+ onChange: (value: FilterValue) => void;
+ onUnstage: () => void;
+ config: InternalConfig;
+ fieldLabel: string;
+ isDisabled: boolean;
+ maxMenuItems?: number;
+ editors: PowerSearchSheetEditors;
+}) {
+ const {buildRelativeDateOptions, PowerSearchValueEditor} = editors;
+ const t = useComponentTranslator();
+ 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]);
+
+ switch (operatorValue.type) {
+ case 'empty':
+ case 'nested':
+ return null;
+ case 'enum':
+ return (
+ <ChoiceRows
+ items={operatorValue.values}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ isMultiple={false}
+ label={fieldLabel}
+ onToggle={value => onChange({type: 'enum', value})}
+ />
+ );
+ case 'enum_list':
+ return (
+ <ChoiceRows
+ items={operatorValue.values}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ isMultiple
+ label={fieldLabel}
+ 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 'date_relative':
+ return (
+ <ChoiceRows
+ items={buildRelativeDateOptions(operatorValue, t)}
+ selected={selectedValues}
+ isDisabled={isDisabled}
+ isMultiple={false}
+ label={fieldLabel}
+ onToggle={value => onChange({type: 'date_relative', value})}
+ />
+ );
+ case 'string':
+ case 'string_list':
+ case 'integer':
+ case 'float':
+ case 'time':
+ case 'date_absolute':
+ case 'date_range':
+ case 'entity_list':
+ case 'custom':
+ return (
+ <div {...stylex.props(styles.editorInput)}>
+ <PowerSearchValueEditor
+ operatorValue={operatorValue}
+ filterValue={filterValue}
+ onChange={onChange}
+ onUnstage={onUnstage}
+ config={config}
+ maxMenuItems={maxMenuItems}
+ isDisabled={isDisabled}
+ presentation="bottom-sheet"
+ fieldLabel={fieldLabel}
+ />
+ </div>
+ );
+ }
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * The sheet flow of PowerSearch's touch presentation: Filters, Add filter,
+ * and the value step, as standalone sheets that stack, each open beneath the
+ * step it led to.
+ */
+export function PowerSearchBottomSheet({
+ isOpen,
+ onOpenChange,
+ finalFocusRef,
+ resultCountText,
+ config,
+ configProp,
+ filters,
+ onChange,
+ searchSource,
+ placeholder,
+ isReadOnly,
+ isDisabled,
+ hasClear,
+ maxOperatorMenuItems,
+ maxSearchResults,
+ saveButtonLabel: saveButtonLabelFromProps,
+ components: componentOverrides,
+ editors,
+}: PowerSearchBottomSheetProps) {
+ const {NestedEditor} = editors;
+ const t = useComponentTranslator();
+ const locale = useLocale();
+ const formatList = useListFormatter();
+ const isInteractive = !isDisabled && !isReadOnly;
+
+ const contentSearchFieldKey = config.config.contentSearchFieldKey;
+ const contentSearchOperator =
+ contentSearchFieldKey == null
+ ? undefined
+ : config.getDefaultOperator(contentSearchFieldKey);
+ const hasContentSearch = contentSearchOperator?.value.type === 'string';
+ const suggestionSource = useMemo(
+ () => createSheetSuggestionSource(config, searchSource),
+ [config, searchSource],
+ );
+
+ const contentResultsId = useId();
+ const managerAddButtonRef = useRef<HTMLButtonElement>(null);
+ const contentSearchRef = useRef<HTMLDivElement>(null);
+ const fieldSearchRef = useRef<HTMLDivElement>(null);
+ // The Add filter sheet's panel: the fallback focus target when the control
+ // a step came from is gone — its first focusable control, which is the
+ // search field when one shows, else the first field row.
+ const fieldsSheetRef = useRef<HTMLDivElement>(null);
+ // The content search and its suggestion rows are one vertical list for the
+ // arrow keys: ArrowDown from the searchbox reaches the first suggestion,
+ // ArrowUp from the first suggestion returns to the searchbox, and the ends
+ // do not wrap. Home and End stay with the searchbox's caret.
+ const contentListFocus = useInternalListFocus<HTMLDivElement>({
+ itemSelector: `[role="searchbox"], [id="${contentResultsId}"] button`,
+ wrap: false,
+ hasHomeEnd: false,
+ });
+ const fieldsSheetCallbackRef = useMergedRefs(
+ fieldsSheetRef,
+ contentListFocus.listRef,
+ );
+ const handleContentListKeyDown = (event: React.KeyboardEvent) => {
+ if (!isImeKeyEvent(event.nativeEvent)) {
+ contentListFocus.handleKeyDown(event);
+ }
+ };
+ const manageSheetRef = useRef<HTMLDivElement>(null);
+ // Where focus was inside the Filters or Add filter sheet, read on every
+ // focus change there, so a controlled update that unmounts the focused
+ // control (a filter's row, a dropped field's row, Clear all after the last
+ // filter) can put focus on the nearest remaining row by that index, else
+ // the sheet's first control, else the sheet panel. A removed element
+ // fires no blur, so the position is what the effect below reads.
+ const lastSheetFocusRef = useRef<{
+ sheet: 'manage' | 'fields';
+ rowIndex: number | null;
+ } | null>(null);
+ // One index space for the record and the recovery: rows that are buttons
+ // (a plain read-only row is passed over, as the removal and Apply/Cancel
+ // rules pass it over), in document order.
+ const buttonRowsOf = (panel: HTMLElement): HTMLElement[] =>
+ Array.from(panel.querySelectorAll<HTMLLIElement>('li'))
+ .map(row => row.querySelector<HTMLElement>('button'))
+ .filter((button): button is HTMLElement => button != null);
+ const noteSheetFocus = useCallback(
+ (sheet: 'manage' | 'fields') => (event: React.FocusEvent) => {
+ const row = (event.target as HTMLElement).closest('li');
+ const button = row?.querySelector<HTMLElement>('button') ?? null;
+ const rowIndex =
+ button == null
+ ? -1
+ : buttonRowsOf(event.currentTarget as HTMLElement).indexOf(button);
+ lastSheetFocusRef.current = {
+ sheet,
+ rowIndex: rowIndex === -1 ? null : rowIndex,
+ };
+ },
+ [],
+ );
+ const managerRowsRef = useRef(new Map<number, HTMLLIElement>());
+ const fieldRowsRef = useRef(new Map<string, HTMLLIElement>());
+ const latestFiltersRef = useRef(filters);
+ const pendingSheetFocusRef = useRef<PendingSheetFocus | null>(null);
+ const pendingMutationFocusRef = useRef(false);
+
+ // The step an open starts on: Add filter directly when an interactive field
+ // has nothing to manage yet, otherwise Filters. Neither search field takes
+ // focus on open, so the software keyboard stays down until the person taps
+ // the search. Add filter opened directly is the flow's entry point: no
+ // Filters sheet beneath it, and Done in its footer.
+ const isEntryAddFilter = filters.length === 0 && isInteractive;
+ const [step, setStep] = useState<SheetStep | null>(() =>
+ isOpen ? (isEntryAddFilter ? 'fields' : 'manage') : null,
+ );
+ const [fieldPickerOrigin, setFieldPickerOrigin] = useState<
+ 'manage' | 'trigger'
+ >(() => (isOpen && isEntryAddFilter ? 'trigger' : 'manage'));
+ // The current step, read by the sheets' close reports and by a removal that
+ // decides where to speak.
+ const stepRef = useRef(step);
+ useLayoutEffect(() => {
+ stepRef.current = step;
+ }, [step]);
+ // The draft outlives a step change on purpose: a closing value step stays
+ // presented through its exit, and clearing the draft with the step would
+ // blank that sheet mid-transition.
+ const [draft, setDraft] = useState<FilterDraft | null>(null);
+ const draftGenerationRef = useRef(0);
+ const nextDraftGeneration = useCallback(() => {
+ draftGenerationRef.current += 1;
+ return draftGenerationRef.current;
+ }, []);
+ const [fieldQuery, setFieldQuery] = useState('');
+ const [contentQuery, setContentQuery] = useState('');
+ const [isClearConfirmationOpen, setIsClearConfirmationOpen] = useState(false);
+ const clearAllButtonRef = useRef<HTMLButtonElement>(null);
+ // Set while Clear all commits, so the result count that changes in that
+ // commit is spoken with Clear all's outcome, as one message.
+ const isClearingRef = useRef(false);
+
+ // `useAnnounce` delivers inside the open Astryx modal that encloses its
+ // caller, and this component renders above the
+ // sheets, so it cannot call the hook itself. Each step's body renders a
+ // `SheetAnnouncer` inside its BottomSheet, which publishes the dialog's own
+ // `announce` here while that step is the active one; the effects below
+ // speak through it, so every message about a sheet's content is delivered
+ // in that sheet's dialog.
+ const announceRef = useRef<AnnounceFn | null>(null);
+ const handleAnnounceChange = useCallback((next: AnnounceFn | null) => {
+ announceRef.current = next;
+ }, []);
+ const announce = useCallback((message: string) => {
+ announceRef.current?.(message);
+ }, []);
+ const pendingAnnouncementRef = useRef<string | null>(null);
+
+ // The controlled `isOpen` opens and closes the flow; the step follows it in
+ // the render that sees the change, not an effect, so the entry step's sheet
+ // opens in the same commit as the flow (React's adjust-state-on-
+ // prop-change pattern). Closing from outside — the field became disabled —
+ // ends the flow wherever it was, the Clear all confirmation included.
+ const [wasOpen, setWasOpen] = useState(isOpen);
+ if (isOpen !== wasOpen) {
+ setWasOpen(isOpen);
+ if (isOpen) {
+ setFieldQuery('');
+ setContentQuery('');
+ setStep(isEntryAddFilter ? 'fields' : 'manage');
+ setFieldPickerOrigin(isEntryAddFilter ? 'trigger' : 'manage');
+ } else {
+ setStep(null);
+ setIsClearConfirmationOpen(false);
+ }
+ }
+
+ const closeFlow = useCallback(() => {
+ pendingSheetFocusRef.current = null;
+ setStep(null);
+ onOpenChange(false);
+ }, [onOpenChange]);
+
+ // Whether a Filters row is a button: the field interactive and the
+ // filter not read-only. The row opens the value step — the editor for its
+ // operator's value type, the built-in nested editor for a `nested` one, or
+ // for a filter the config no longer knows the unavailable state — and its
+ // trailing remove action removes it, as the popover's token has its × for
+ // it.
+ const isRowButton = useCallback(
+ (filter: PowerSearchFilter): boolean => !filter.isReadOnly && isInteractive,
+ [isInteractive],
+ );
+
+ // ------------------------------------------------------------------ focus --
+
+ // The control a step change named also becomes where the closing step
+ // sheets return focus when their exit ends: a closing sheet that held focus
+ // keeps it until then, and BottomSheet then returns it, so the named control
+ // receives it even when the first move could not land. With no control
+ // named, the closing steps return focus as the flow does.
+ const stepReturnTargetRef = useRef<HTMLElement | null>(null);
+ const stepFinalFocusRef = useMemo<React.RefObject<HTMLElement | null>>(
+ () => ({
+ get current() {
+ return stepReturnTargetRef.current ?? finalFocusRef.current;
+ },
+ }),
+ [finalFocusRef],
+ );
+ const placeFocus = (element: HTMLElement | null | undefined) => {
+ if (element == null) {
+ return;
+ }
+ stepReturnTargetRef.current = element;
+ element.focus({preventScroll: true});
+ };
+ const focusPendingSheetTarget = useCallback(() => {
+ const target = pendingSheetFocusRef.current;
+ if (target == null) {
+ return;
+ }
+ pendingSheetFocusRef.current = null;
+ if (target.type === 'manager-add') {
+ placeFocus(managerAddButtonRef.current);
+ return;
+ }
+ // Add filter's fallback: a controlled update may have removed the field
+ // whose row opened the step, or the content-search field itself; the
+ // sheet's first focusable control then takes focus — the search field
+ // when one shows, else the first field row.
+ const firstFieldsControl = () => {
+ const panel = fieldsSheetRef.current;
+ return (
+ panel?.querySelector<HTMLElement>('input') ??
+ panel?.querySelector<HTMLElement>('li button') ??
+ panel?.querySelector<HTMLElement>('button') ??
+ null
+ );
+ };
+ if (target.type === 'content-search') {
+ placeFocus(
+ contentSearchRef.current?.querySelector<HTMLInputElement>('input') ??
+ firstFieldsControl(),
+ );
+ return;
+ }
+ if (target.type === 'field') {
+ placeFocus(
+ fieldRowsRef.current
+ .get(target.fieldKey)
+ ?.querySelector<HTMLButtonElement>('button') ?? firstFieldsControl(),
+ );
+ return;
+ }
+ // The row the step came from, followed across a controlled reorder or
+ // clone; when a controlled update removed it, or left two filters it
+ // could be, the nearest remaining row that is a button, as after a
+ // removal; else Add filter.
+ const index =
+ resolveFilterIdentityIndex(
+ latestFiltersRef.current,
+ target.sourceFilter,
+ target.sourceSignature,
+ target.preferredIndex,
+ ) ??
+ nearestEditableIndex(
+ latestFiltersRef.current,
+ target.preferredIndex,
+ isRowButton,
+ );
+ const row = index == null ? null : managerRowsRef.current.get(index);
+ const rowButton =
+ target.part === 'remove'
+ ? (row?.querySelector<HTMLButtonElement>('[data-sheet-remove]') ??
+ row?.querySelector<HTMLButtonElement>('button'))
+ : row?.querySelector<HTMLButtonElement>('button');
+ placeFocus(rowButton ?? managerAddButtonRef.current);
+ }, [isRowButton]);
+
+ // A controlled update that unmounts the focused control of the Filters or
+ // Add filter sheet leaves focus on the page body inside the open modal.
+ // Read before paint on every commit of an open step: when focus is no
+ // longer inside the sheet's dialog, the nearest remaining row by the last
+ // focused index takes it, else the sheet's first control, else its panel.
+ // The pending-target effects below run after and win when a step
+ // change named a control.
+ useLayoutEffect(() => {
+ const last = lastSheetFocusRef.current;
+ if (step !== 'manage' && step !== 'fields') {
+ return;
+ }
+ if (last == null || last.sheet !== step) {
+ return;
+ }
+ const panel =
+ step === 'manage' ? manageSheetRef.current : fieldsSheetRef.current;
+ const dialog = panel?.closest('dialog');
+ const active = document.activeElement;
+ if (
+ panel == null ||
+ dialog == null ||
+ (active != null && active !== document.body && dialog.contains(active))
+ ) {
+ return;
+ }
+ const rowButtons = buttonRowsOf(panel);
+ let target: HTMLElement | null = null;
+ if (last.rowIndex != null && rowButtons.length > 0) {
+ // The following button row, else the last.
+ target = rowButtons[Math.min(last.rowIndex, rowButtons.length - 1)];
+ }
+ target ??=
+ panel.querySelector<HTMLElement>('input') ??
+ rowButtons[0] ??
+ panel.querySelector<HTMLElement>('button') ??
+ null;
+ if (target != null) {
+ target.focus({preventScroll: true});
+ } else {
+ const focusable = dialog.querySelector<HTMLElement>('[tabindex="-1"]');
+ (focusable ?? dialog).focus({preventScroll: true});
+ }
+ });
+
+ // Both Effects move focus inside the entering sheet — the external system
+ // is the document's focus — to the control the step named. They run after
+ // the entering sheet's own
+ // panel focus (child effects commit first), so the intended control wins,
+ // and they acquire nothing, so they need no cleanup. 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]);
+
+ // A target still pending when the flow closes, such as a commit that
+ // disabled the field, never carries into the next open.
+ useEffect(() => {
+ if (step == null) {
+ stepReturnTargetRef.current = null;
+ pendingSheetFocusRef.current = null;
+ return;
+ }
+ // A step that opens starts with no named return target; a return to
+ // Filters keeps the one its commit, or its removal, has just named.
+ if (step !== 'manage') {
+ stepReturnTargetRef.current = null;
+ }
+ focusPendingSheetTarget();
+ }, [focusPendingSheetTarget, step]);
+
+ // An announcement queued by a step change — a suggestion or a removal that
+ // changed the filters — is spoken in the commit that shows the next step,
+ // so it lands in that step's dialog region rather than the one about to
+ // close. It synchronizes the live region named above and acquires nothing.
+ useEffect(() => {
+ const message = pendingAnnouncementRef.current;
+ if (step != null && message != null) {
+ pendingAnnouncementRef.current = null;
+ announce(message);
+ }
+ }, [announce, step]);
+
+ // ----------------------------------------------------------------- fields --
+
+ // Every visible field lists: the value step edits every operator's value,
+ // `nested` through the popover's built-in editor.
+ const fields = useMemo(() => config.getVisibleFields(), [config]);
+
+ 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]);
+
+ // Ungrouped fields first, then each group in first-appearance order — the
+ // same grouping the popover presentation's field suggestions use
+ // (`groupItems` with `ungroupedFirst`), so the two presentations
+ // list a config's fields in one order.
+ const groupedFields = useMemo(
+ () =>
+ matchingFields.length === 0
+ ? []
+ : groupItems(
+ matchingFields.map(field => ({
+ id: field.key,
+ label: field.label,
+ auxiliaryData: {group: field.group},
+ field,
+ })),
+ {ungroupedFirst: true},
+ ).map(
+ group =>
+ [
+ group.heading ?? '',
+ group.items.map(item => item.field),
+ ] as const,
+ ),
+ [matchingFields],
+ );
+
+ const isFieldSearchShown = fields.length >= SEARCHABLE_FIELD_COUNT;
+
+ // A field whose only operator takes an `empty` value is a one-tap filter:
+ // its row adds it with no value step, and shows a plus, not a chevron.
+ const isImmediateAddField = useCallback(
+ (field: PowerSearchField): boolean => {
+ const operators = config.getVisibleOperators(field.key);
+ return operators.length === 1 && operators[0].value.type === 'empty';
+ },
+ [config],
+ );
+
+ // The steps stack: each opens above the sheet that led to it, which stays
+ // open beneath. Add filter entered directly has no Filters sheet beneath.
+ const isFieldPickerDirectEntry = fieldPickerOrigin === 'trigger';
+ const isManageSheetOpen =
+ step === 'manage' ||
+ (step === 'fields' && !isFieldPickerDirectEntry) ||
+ (step === 'value' && (draft?.mode === 'edit' || !isFieldPickerDirectEntry));
+ const isFieldsSheetOpen =
+ step === 'fields' || (step === 'value' && draft?.mode === 'create');
+
+ // The suggestions derive synchronously from the config, so a list never
+ // waits on a request: an empty list means an empty result, not a pending
+ // one. They stay listed while the value step covers Add filter.
+ const contentResults = useMemo(() => {
+ if (!isFieldsSheetOpen || !hasContentSearch || !isInteractive) {
+ return [];
+ }
+ const results =
+ contentQuery.trim() === ''
+ ? suggestionSource.bootstrap()
+ : suggestionSource.search(contentQuery);
+ return results.slice(0, MAX_BROWSE_MENU_ITEMS);
+ }, [
+ contentQuery,
+ hasContentSearch,
+ isFieldsSheetOpen,
+ isInteractive,
+ suggestionSource,
+ ]);
+
+ // The field's result count, while a sheet is open: the owner's own Effect
+ // is quiet then, so the change is spoken here, inside the dialog. Only a
+ // change after the flow opened is spoken.
+ const announcedResultCountRef = useRef(resultCountText);
+ // The latest result count, for Clear all's handler to read after its
+ // commit has flushed.
+ const latestResultCountRef = useRef(resultCountText);
+ useLayoutEffect(() => {
+ latestResultCountRef.current = resultCountText;
+ }, [resultCountText]);
+ useEffect(() => {
+ if (
+ isClearingRef.current ||
+ resultCountText === announcedResultCountRef.current
+ ) {
+ return;
+ }
+ announcedResultCountRef.current = resultCountText;
+ if (step != null && resultCountText != null) {
+ announce(resultCountText);
+ }
+ }, [announce, resultCountText, step]);
+
+ // ------------------------------------------------------------------ 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) : []),
+ [config, draft],
+ );
+
+ // The two parts of a Filters row's text for `filter`: "{field} {operator}"
+ // as one catalog message, and the value as the popover presentation's
+ // token shows it — the same function, so the same words and the same zone
+ // handling, before the token's width budget. The rows render these, and
+ // the removal announcement joins them, so the three can never
+ // disagree.
+ const describeFilterParts = useCallback(
+ (filter: PowerSearchFilter): {label: string; value: string | null} => {
+ const field = config.getField(filter.field);
+ const operator = config.getOperator(filter.field, filter.operator);
+ // A filter whose field or operator the config no longer has still
+ // lists, by its raw keys, as its token does on the trigger; its row
+ // opens the unavailable step, and its trailing remove action removes
+ // it.
+ const fieldLabel = field?.label ?? filter.field;
+ const operatorLabel =
+ operator == null ? filter.operator : resolveOperatorLabel(operator, t);
+ const label = operatorLabel
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
+ field: fieldLabel,
+ operator: operatorLabel,
+ })
+ : fieldLabel;
+ if (operator == null) {
+ return {label, value: null};
+ }
+ // A relative-date value is stored as a key (`3d_ago`); the row reads it
+ // as the value step's choice row does ("3 days ago"), through the
+ // catalog's relative-date messages, so the sheet agrees with itself. The popover token
+ // shows the stored key (a known gap of the record).
+ const value =
+ operator.value.type === 'date_relative' &&
+ filter.value.type === 'date_relative'
+ ? resolveRelativeDateLabel(
+ operator.value,
+ filter.value.value,
+ t,
+ editors.buildRelativeDateOptions,
+ )
+ : formatTokenValueText(
+ operator.value,
+ filter.value,
+ Number.MAX_SAFE_INTEGER,
+ locale,
+ t,
+ formatList,
+ );
+ return {label, value};
+ },
+ [config, editors, formatList, locale, t],
+ );
+ const describeFilter = useCallback(
+ (filter: PowerSearchFilter): string => {
+ const parts = describeFilterParts(filter);
+ return parts.value
+ ? t('@astryx.powersearch.sheet.labelValue', {
+ label: parts.label,
+ value: parts.value,
+ })
+ : parts.label;
+ },
+ [describeFilterParts, t],
+ );
+
+ const openFieldList = useCallback(() => {
+ if (!isInteractive) {
+ return;
+ }
+ setFieldPickerOrigin('manage');
+ setFieldQuery('');
+ setContentQuery('');
+ pendingSheetFocusRef.current = null;
+ setStep('fields');
+ }, [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
+ ) {
+ // A controlled update removed the edited filter, or left two it
+ // could be, or made it read-only: nothing is written, and focus
+ // returns to the nearest row that is a button around where it was,
+ // else Add filter.
+ pendingSheetFocusRef.current =
+ next.sourceFilter != null &&
+ next.sourceSignature != null &&
+ next.filterIndex != null
+ ? {
+ type: 'manager-filter',
+ sourceFilter: next.sourceFilter,
+ sourceSignature: next.sourceSignature,
+ preferredIndex: next.filterIndex,
+ }
+ : {type: 'manager-add'};
+ 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 person
+ // came from.
+ const openCreateEditor = useCallback(
+ (
+ field: PowerSearchField,
+ operator: PowerSearchOperator,
+ returnFocus: 'field' | 'content-search' = 'field',
+ ) => {
+ setDraft({
+ mode: 'create',
+ generation: nextDraftGeneration(),
+ returnFocus,
+ field: field.key,
+ operator: operator.key,
+ value: operator.value.type === 'empty' ? {type: 'empty'} : undefined,
+ });
+ pendingSheetFocusRef.current = null;
+ setStep('value');
+ },
+ [nextDraftGeneration],
+ );
+
+ const handleFieldSelect = useCallback(
+ (field: PowerSearchField) => {
+ if (!isInteractive) {
+ return;
+ }
+ // A one-tap filter has nothing to stage: choosing its field adds it
+ // and returns to Filters.
+ if (isImmediateAddField(field)) {
+ const [operator] = config.getVisibleOperators(field.key);
+ const nextFilter: PowerSearchFilter = {
+ field: field.key,
+ operator: operator.key,
+ value: {type: 'empty'},
+ };
+ pendingSheetFocusRef.current = {
+ type: 'manager-filter',
+ sourceFilter: nextFilter,
+ sourceSignature: filterSignature(nextFilter),
+ preferredIndex: filters.length,
+ };
+ pendingMutationFocusRef.current = true;
+ onChange([...filters, nextFilter], 'add', filters.length);
+ pendingAnnouncementRef.current = t('@astryx.tokenizer.tokenAdded', {
+ label: describeFilter(nextFilter),
+ });
+ setStep('manage');
+ return;
+ }
+ const operator =
+ config.getDefaultOperator(field.key) ?? field.operators[0];
+ if (operator == null) {
+ return;
+ }
+ openCreateEditor(field, operator);
+ },
+ [
+ config,
+ describeFilter,
+ filters,
+ isImmediateAddField,
+ isInteractive,
+ onChange,
+ openCreateEditor,
+ t,
+ ],
+ );
+
+ const handleContentSuggestionSelect = useCallback(
+ (item: PowerSearchItem | 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) {
+ 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);
+ // The same announcement the popover presentation's typeahead add
+ // makes, so assistive technology hears one phrase for one outcome;
+ // spoken once the Filters sheet is the open dialog.
+ pendingAnnouncementRef.current = t('@astryx.tokenizer.tokenAdded', {
+ label: item.label,
+ });
+ setStep('manage');
+ return;
+ }
+ openCreateEditor(field, operator, 'content-search');
+ },
+ [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',
+ generation: nextDraftGeneration(),
+ filterIndex: index,
+ sourceFilter: filter,
+ sourceSignature: filterSignature(filter),
+ field: filter.field,
+ operator: filter.operator,
+ value: filter.value,
+ });
+ pendingSheetFocusRef.current = null;
+ setStep('value');
+ },
+ [filters, isInteractive, nextDraftGeneration],
+ );
+
+ 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, isRowButton);
+ 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,
+ part: 'remove',
+ };
+ }
+ pendingMutationFocusRef.current = true;
+ onChange(nextFilters, 'remove', index);
+ // The popover presentation's token × announces the same phrase. A
+ // removal from a Filters row stays in that sheet and speaks at once; a
+ // caller's Editor that removes while returning to Filters speaks once
+ // the Filters sheet is the open dialog.
+ const message = t('@astryx.tokenizer.tokenRemoved', {
+ label: describeFilter(filter),
+ });
+ if (stepRef.current === 'manage') {
+ announce(message);
+ } else {
+ pendingAnnouncementRef.current = message;
+ }
+ },
+ [
+ announce,
+ describeFilter,
+ filters,
+ isInteractive,
+ isRowButton,
+ onChange,
+ t,
+ ],
+ );
+
+ // Closing Clear all's confirmation. Kept, focus returns to Clear all.
+ // Confirmed, Clear all removes the filters the person can edit and keeps
+ // read-only ones, which are the consumer's: one `remove` at the first
+ // removed index. The Filters sheet stays open for further editing. The
+ // confirmation must be gone before focus moves into the sheet and the
+ // outcome is routed into the sheet's region, so its close is flushed
+ // first. The outcome is "Editable filters removed" while a read-only filter
+ // remains, otherwise "All filters removed", joined with a result count that
+ // changed in the same commit as one catalog message; focus moves to the
+ // sheet's first remaining control: a kept read-only row has none, so Add
+ // filter.
+ const closeClearConfirmation = (confirmed: boolean) => {
+ const kept = filters.filter(filter => filter.isReadOnly);
+ const firstRemovedIndex = filters.findIndex(filter => !filter.isReadOnly);
+ const isClearing = confirmed && isInteractive && firstRemovedIndex >= 0;
+ isClearingRef.current = isClearing;
+ try {
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the confirmation must be gone before focus moves into the sheet and the words are routed into it
+ flushSync(() => {
+ setIsClearConfirmationOpen(false);
+ if (isClearing) {
+ onChange(kept, 'remove', firstRemovedIndex);
+ }
+ });
+ } finally {
+ isClearingRef.current = false;
+ }
+ if (!isClearing) {
+ clearAllButtonRef.current?.focus();
+ return;
+ }
+ managerAddButtonRef.current?.focus({preventScroll: true});
+ const resultCount = latestResultCountRef.current;
+ const changedCount =
+ resultCount !== announcedResultCountRef.current ? resultCount : null;
+ announcedResultCountRef.current = resultCount;
+ if (kept.length > 0) {
+ announce(
+ changedCount == null
+ ? t('@astryx.powersearch.editableFiltersRemoved')
+ : t('@astryx.powersearch.sheet.editableFiltersClearedWithCount', {
+ resultCount: changedCount,
+ }),
+ );
+ } else {
+ announce(
+ changedCount == null
+ ? t('@astryx.powersearch.allFiltersRemoved')
+ : t('@astryx.powersearch.sheet.filtersClearedWithCount', {
+ resultCount: changedCount,
+ }),
+ );
+ }
+ };
+
+ 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}));
+ }, []);
+ // The number input's draft was cleared or stopped parsing: nothing stands
+ // to confirm, so the confirm action disables again.
+ const handleDraftUnstage = useCallback(() => {
+ setDraft(current =>
+ current == null ? current : {...current, value: undefined},
+ );
+ }, []);
+
+ 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]);
+
+ // Each step sheet is controlled by `step`; a sheet only ever asks to close
+ // (a dismissal its `purpose` allows: Escape, the scrim, a swipe, a platform
+ // close request), which only the top sheet of the stack receives. Closing
+ // the top step reveals the step beneath it; closing the bottom one ends the
+ // flow. A stale report from a step that is no longer current is ignored.
+ // Every step change goes through the handlers above.
+ const handleManageOpenChange = useCallback(
+ (isSheetOpen: boolean) => {
+ if (!isSheetOpen && stepRef.current === 'manage') {
+ closeFlow();
+ }
+ },
+ [closeFlow],
+ );
+ const handleFieldsOpenChange = useCallback(
+ (isSheetOpen: boolean) => {
+ if (isSheetOpen || stepRef.current !== 'fields') {
+ return;
+ }
+ if (fieldPickerOrigin === 'trigger') {
+ closeFlow();
+ return;
+ }
+ queueManagerAddFocus();
+ setStep('manage');
+ },
+ [closeFlow, fieldPickerOrigin, queueManagerAddFocus],
+ );
+ const handleValueOpenChange = useCallback(
+ (isSheetOpen: boolean) => {
+ if (!isSheetOpen && stepRef.current === 'value') {
+ returnFromValue();
+ }
+ },
+ [returnFromValue],
+ );
+
+ // ---------------------------------------------------------------- render --
+
+ // Rows are keyed by filter identity, not position: a parent's reorder or a
+ // removal above the focused row then moves elements instead of remounting
+ // them, and focus stays on the same filter. Only a filter that is
+ // itself removed loses its element, and the re-home effect above takes
+ // over.
+ const [filterIdentities] = useState(createFilterIdentities);
+ const filterIds = filterIdentities.next(filters);
+ const filterRows = filters.map((filter, index) => {
+ const {label, value} = describeFilterParts(filter);
+ const isEditable = isRowButton(filter);
+ // The row reads from the same catalog message the removal announcement
+ // uses (`labelValue`), so a locale that reorders it reorders both: the
+ // message is formatted with a placeholder for the value, and the text
+ // either side of that placeholder wraps the bold value.
+ let displayLabel: ReactNode = label;
+ if (value) {
+ const [before, after] = t('@astryx.powersearch.sheet.labelValue', {
+ label,
+ value: ROW_VALUE_SLOT,
+ }).split(ROW_VALUE_SLOT);
+ displayLabel = (
+ <>
+ {before}
+ <span {...stylex.props(styles.rowValue)}>{value}</span>
+ {after}
+ </>
+ );
+ }
+ return {
+ displayLabel,
+ filter,
+ index,
+ isEditable,
+ key: `filter-${filterIds[index]}`,
+ };
+ });
+
+ const hasRemovableFilter = filters.some(filter => !filter.isReadOnly);
+ const isClearAllShown = hasClear && isInteractive && hasRemovableFilter;
+
+ const EditorOverride =
+ draftOperator != null
+ ? componentOverrides?.[draftOperator.value.type]?.Editor
+ : undefined;
+
+ const draftOperatorLabel =
+ draftOperator == null ? '' : resolveOperatorLabel(draftOperator, t);
+ // The title names the filter's own operator when the step offers no
+ // Operator group: one visible operator, or an operator the config no longer
+ // lists as visible. The step then never shows another operator's name.
+ const showsOperatorGroup =
+ draftOperators.length > 1 &&
+ draftOperator != null &&
+ draftOperators.includes(draftOperator);
+ // The title — the dialog's name — reads the field and operator as
+ // the Filters row does: by their labels, or, for a filter whose field or
+ // operator the config no longer has, by the raw keys the row shows.
+ const editorTitle =
+ draft == null
+ ? t('@astryx.powersearch.sheet.addFilter')
+ : draftField == null || (draftOperator == null && draft.operator != null)
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
+ field: draftField?.label ?? draft.field,
+ operator:
+ draftOperatorLabel !== ''
+ ? draftOperatorLabel
+ : (draft.operator ?? ''),
+ }).trim()
+ : !showsOperatorGroup && draftOperatorLabel !== ''
+ ? t('@astryx.powersearch.sheet.fieldOperator', {
+ field: draftField.label,
+ operator: draftOperatorLabel,
+ })
+ : draftField.label;
+ const saveButtonLabel =
+ saveButtonLabelFromProps ??
+ (draft?.mode === 'edit'
+ ? t('@astryx.powersearch.editor.apply')
+ : t('@astryx.powersearch.sheet.addFilter'));
+
+ // Every sheet body: padded, and publishing that padding to its lists.
+ const bodyProps = stylex.props(
+ styles.body,
+ containerPaddingInlineVarStyles[4],
+ );
+ const scrollContentProps = stylex.props(
+ styles.scrollContent,
+ containerPaddingInlineVarStyles[4],
+ );
+ const controlSectionProps = stylex.props(
+ styles.controlSection,
+ containerPaddingInlineVarStyles[3],
+ );
+
+ // A vertical touch drag on the Add filter rows moves focus off a focused
+ // search to the sheet, so the software keyboard leaves and the rows can be
+ // read.
+ const fieldPickerDragProps = useDismissSearchOnTouchDrag(
+ () => [
+ contentSearchRef.current?.querySelector('input'),
+ fieldSearchRef.current?.querySelector('input'),
+ ],
+ () => fieldsSheetRef.current?.closest<HTMLElement>('[tabindex="-1"]'),
+ );
+
+ const isEditorDisabled = isDisabled || isReadOnly;
+ const isSaveDisabled =
+ isEditorDisabled || draft?.operator == null || draft.value == null;
+ // The step has something to edit when the field and operator still exist
+ // (a controlled config update can remove either). A caller's `Editor`
+ // override replaces the body for its value type with the props the popover
+ // hands it; otherwise a `nested` value takes the popover's built-in
+ // NestedEditor and every other type the sheet's own control.
+ const isDraftRenderable =
+ draft != null && draftField != null && draftOperator != null;
+ const isDraftNested =
+ isDraftRenderable && !isSupportedOperator(draftOperator);
+ // A controlled config update that removes the field or operator being
+ // edited replaces the step's body with the unavailable state while focus
+ // may be on one of the body's controls, which unmount without a blur. Focus
+ // then moves to Cancel, the way back to the Filters row whose remove action
+ // is the removal path, so it never falls to the page body inside the open
+ // sheet. The message itself is announced by its rendered element.
+ const cancelButtonRef = useRef<HTMLButtonElement>(null);
+ const wasDraftRenderableRef = useRef(isDraftRenderable);
+ useLayoutEffect(() => {
+ const becameUnavailable =
+ wasDraftRenderableRef.current && !isDraftRenderable && draft != null;
+ wasDraftRenderableRef.current = isDraftRenderable;
+ if (!becameUnavailable || step !== 'value') {
+ return;
+ }
+ const active = document.activeElement;
+ const dialog = cancelButtonRef.current?.closest('dialog');
+ if (dialog != null && active != null && dialog.contains(active)) {
+ return;
+ }
+ cancelButtonRef.current?.focus();
+ }, [draft, isDraftRenderable, step]);
+ // The operator group stays outside either editor, so switching operators
+ // swaps the body — a `nested` operator beside a plain one included.
+ const operatorGroup = isDraftRenderable && showsOperatorGroup && (
+ <RadioList
+ label={t('@astryx.powersearch.editor.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={t('@astryx.powersearch.sheet.fieldOperator', {
+ field: draftField.label,
+ operator: resolveOperatorLabel(operator, t),
+ })}
+ value={operator.key}
+ xstyle={styles.trailingControlRow}
+ />
+ ))}
+ </RadioList>
+ );
+ // The step's Operator group owns the operator choice, so the built-in
+ // nested editor's root operator picker is hidden and its root shows the
+ // checked operator's label.
+ const nestedOperatorOptions = useMemo(
+ () =>
+ draftOperator == null
+ ? []
+ : [
+ {
+ value: draftOperator.key,
+ label: resolveOperatorLabel(draftOperator, t),
+ },
+ ],
+ [draftOperator, t],
+ );
+ const handleNestedDraftChange = useCallback((next: PartialFilter) => {
+ setDraft(current =>
+ current == null ? current : {...current, value: next.value},
+ );
+ }, []);
+
+ const valueEditor =
+ isDraftRenderable &&
+ (isDraftNested ? (
+ <NestedEditor
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
+ config={config}
+ partialFilter={{
+ field: draft.field,
+ operator: draft.operator,
+ value: draft.value,
+ }}
+ operatorOptions={nestedOperatorOptions}
+ hasRootOperatorPicker={false}
+ onOperatorChange={() => {}}
+ onPartialFilterChange={handleNestedDraftChange}
+ maxMenuItems={maxOperatorMenuItems}
+ isReadOnly={isEditorDisabled}
+ xstyle={styles.nestedEditorContainer}
+ />
+ ) : (
+ <SheetValueEditor
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
+ operatorValue={draftOperator.value}
+ filterValue={draft.value}
+ onChange={handleDraftValueChange}
+ onUnstage={handleDraftUnstage}
+ config={config}
+ fieldLabel={draftField.label}
+ isDisabled={isEditorDisabled}
+ maxMenuItems={maxOperatorMenuItems}
+ editors={editors}
+ />
+ ));
+
+ return (
+ <>
+ <BottomSheet
+ isOpen={isManageSheetOpen}
+ onOpenChange={handleManageOpenChange}
+ finalFocusRef={finalFocusRef}
+ label={t('@astryx.powersearch.sheet.filtersTitle')}
+ height="tall"
+ padding={0}>
+ <div
+ ref={manageSheetRef}
+ onFocus={noteSheetFocus('manage')}
+ {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>
+ {step === 'manage' && (
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
+ )}
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.headerRow)}>
+ <div {...stylex.props(styles.headerText)}>
+ <Heading level={3}>
+ {t('@astryx.powersearch.sheet.filtersTitle')}
+ </Heading>
+ </div>
+ {isInteractive && filterRows.length > 0 && (
+ <Button
+ ref={managerAddButtonRef}
+ label={t('@astryx.powersearch.sheet.addFilter')}
+ icon={<Icon icon={PlusIcon} size="sm" />}
+ isIconOnly
+ variant="secondary"
+ size="md"
+ xstyle={styles.touchHitArea}
+ onClick={openFieldList}
+ />
+ )}
+ </div>
+ </div>
+ <div {...stylex.props(styles.scrollViewport)}>
+ <div {...scrollContentProps}>
+ {filterRows.length === 0 ? (
+ // With no filter the single thing to do is the only visible
+ // action. Mounted only while the sheet is open, so its text
+ // is spoken in this sheet when it appears.
+ isManageSheetOpen && (
+ <EmptyState
+ title={t('@astryx.powersearch.sheet.noFilters')}
+ description={t(
+ '@astryx.powersearch.sheet.noFiltersDescription',
+ )}
+ headingLevel={4}
+ icon={<Icon icon="funnel" size="lg" color="secondary" />}
+ xstyle={styles.emptyState}
+ actions={
+ isInteractive ? (
+ <Button
+ ref={managerAddButtonRef}
+ label={t('@astryx.powersearch.sheet.addFilter')}
+ icon={<Icon icon={PlusIcon} size="sm" />}
+ variant="primary"
+ size="lg"
+ xstyle={styles.touchHitArea}
+ onClick={openFieldList}
+ />
+ ) : undefined
+ }
+ />
+ )
+ ) : (
+ <List hasDividers density="spacious" edge="bleed">
+ {filterRows.map(row => {
+ const operator = config.getOperator(
+ row.filter.field,
+ row.filter.operator,
+ );
+ const fieldLabel =
+ config.getField(row.filter.field)?.label ??
+ row.filter.field;
+ // A one-tap filter has no value to edit: its row removes
+ // it.
+ const isOneTap = operator?.value.type === 'empty';
+ const removeLabel = t(
+ '@astryx.powersearch.sheet.removeFilter',
+ {field: fieldLabel},
+ );
+ 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={
+ row.isEditable
+ ? isOneTap
+ ? () => handleRemoveFilter(row.index)
+ : () => handleFilterEdit(row.index)
+ : undefined
+ }
+ endContent={
+ row.isEditable ? (
+ <IconButton
+ data-sheet-remove=""
+ label={removeLabel}
+ tooltip={removeLabel}
+ icon={<Icon icon="close" size="sm" />}
+ variant="ghost"
+ size="md"
+ xstyle={styles.touchHitArea}
+ onClick={event => {
+ event.stopPropagation();
+ handleRemoveFilter(row.index);
+ }}
+ />
+ ) : undefined
+ }
+ />
+ );
+ })}
+ </List>
+ )}
+ </div>
+ </div>
+ {filterRows.length > 0 && (
+ <div {...stylex.props(styles.footer, styles.fixedFooter)}>
+ {isClearAllShown && (
+ <Button
+ ref={clearAllButtonRef}
+ label={t('@astryx.powersearch.sheet.clearAll')}
+ variant="secondary"
+ size="lg"
+ xstyle={styles.footerEqualAction}
+ onClick={() => setIsClearConfirmationOpen(true)}
+ />
+ )}
+ <Button
+ label={t('@astryx.powersearch.sheet.done')}
+ variant="primary"
+ size="lg"
+ xstyle={
+ isClearAllShown
+ ? styles.footerEqualAction
+ : [styles.footerSoleAction, styles.touchHitArea]
+ }
+ onClick={closeFlow}
+ width={isClearAllShown ? undefined : '100%'}
+ />
+ </div>
+ )}
+ </div>
+ </BottomSheet>
+
+ <BottomSheet
+ isOpen={isFieldsSheetOpen}
+ onOpenChange={handleFieldsOpenChange}
+ finalFocusRef={stepFinalFocusRef}
+ label={t('@astryx.powersearch.sheet.addFilter')}
+ height="tall"
+ padding={0}>
+ <div
+ ref={fieldsSheetCallbackRef}
+ onFocus={noteSheetFocus('fields')}
+ onKeyDown={hasContentSearch ? handleContentListKeyDown : undefined}
+ {...stylex.props(styles.sheet, styles.sheetWithFixedFooter)}>
+ {step === 'fields' && (
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
+ )}
+ <div {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.headerRow)}>
+ <div {...stylex.props(styles.headerText)}>
+ <Heading level={3}>
+ {t('@astryx.powersearch.sheet.addFilter')}
+ </Heading>
+ </div>
+ </div>
+ {hasContentSearch ? (
+ <div ref={contentSearchRef}>
+ <TextInput
+ label={t('@astryx.powersearch.sheet.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]);
+ }
+ }}
+ placeholder={placeholder}
+ hasClear
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
+ isDisabled={!isInteractive}
+ size="lg"
+ width="100%"
+ />
+ </div>
+ ) : isFieldSearchShown ? (
+ <div ref={fieldSearchRef}>
+ <TextInput
+ label={t('@astryx.powersearch.sheet.searchFields')}
+ isLabelHidden
+ placeholder={t(
+ '@astryx.powersearch.sheet.searchFieldsPlaceholder',
+ )}
+ value={fieldQuery}
+ onChange={setFieldQuery}
+ startIcon={<Icon icon="search" size="sm" color="secondary" />}
+ isDisabled={!isInteractive}
+ size="lg"
+ width="100%"
+ />
+ </div>
+ ) : null}
+ </div>
+ <div
+ {...stylex.props(styles.scrollViewport)}
+ {...fieldPickerDragProps}>
+ <div {...scrollContentProps}>
+ {hasContentSearch ? (
+ contentResults.length > 0 ? (
+ <List
+ id={contentResultsId}
+ aria-label={t('@astryx.powersearch.sheet.searchResults')}
+ hasDividers
+ density="spacious"
+ edge="bleed">
+ {contentResults.map(item => (
+ <ListItem
+ key={item.id}
+ label={item.label}
+ isDisabled={!isInteractive}
+ onClick={() => handleContentSuggestionSelect(item)}
+ />
+ ))}
+ </List>
+ ) : contentQuery.trim() !== '' ? (
+ // The searchbox's `aria-controls` target while nothing
+ // lists. The empty state mounts only while this step is the
+ // open one and is spoken from its rendered text, once per
+ // query that matches nothing.
+ <div id={contentResultsId}>
+ {step === 'fields' && (
+ <EmptyState
+ key={contentQuery}
+ icon={
+ <Icon icon="search" size="lg" color="secondary" />
+ }
+ title={t('@astryx.powersearch.sheet.noResults')}
+ description={t(
+ '@astryx.powersearch.sheet.tryDifferentSearch',
+ )}
+ headingLevel={4}
+ isCompact
+ xstyle={styles.emptyState}
+ />
+ )}
+ </div>
+ ) : (
+ // An empty query with no bootstrap suggestion: the results
+ // region exists, empty, so the searchbox's `aria-controls`
+ // always names an element in the document.
+ <div id={contentResultsId} />
+ )
+ ) : groupedFields.length === 0 ? (
+ // A search outcome: only a non-empty query that matches
+ // nothing shows it; a config with no field lists nothing.
+ normalizedFieldQuery !== '' &&
+ step === 'fields' && (
+ <EmptyState
+ key={normalizedFieldQuery}
+ icon={<Icon icon="search" size="lg" color="secondary" />}
+ title={t('@astryx.powersearch.sheet.noMatchingFields')}
+ description={t(
+ '@astryx.powersearch.sheet.tryDifferentSearch',
+ )}
+ headingLevel={4}
+ isCompact
+ xstyle={styles.emptyState}
+ />
+ )
+ ) : (
+ groupedFields.map(([group, groupFields]) => (
+ <List
+ key={group}
+ hasDividers
+ density="spacious"
+ header={
+ <Heading level={4}>
+ {group === ''
+ ? t('@astryx.powersearch.sheet.ungroupedFields')
+ : group}
+ </Heading>
+ }
+ 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={
+ isImmediateAddField(field) ? (
+ <Icon icon={PlusIcon} size="sm" color="secondary" />
+ ) : (
+ <Icon
+ icon="chevronRight"
+ size="sm"
+ color="secondary"
+ xstyle={rtlStyles.mirror}
+ />
+ )
+ }
+ onClick={() => handleFieldSelect(field)}
+ />
+ ))}
+ </List>
+ ))
+ )}
+ </div>
+ </div>
+ {isFieldPickerDirectEntry && (
+ <div {...stylex.props(styles.footer, styles.fixedFooter)}>
+ <Button
+ label={t('@astryx.powersearch.sheet.done')}
+ variant="primary"
+ width="100%"
+ xstyle={styles.touchAction}
+ onClick={closeFlow}
+ />
+ </div>
+ )}
+ </div>
+ </BottomSheet>
+
+ <BottomSheet
+ isOpen={step === 'value'}
+ onOpenChange={handleValueOpenChange}
+ finalFocusRef={stepFinalFocusRef}
+ label={editorTitle}
+ height="tall"
+ padding={0}
+ purpose="info">
+ <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}>
+ {step === 'value' && (
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
+ )}
+ {operatorGroup && (
+ <div {...controlSectionProps}>{operatorGroup}</div>
+ )}
+ <EditorOverride
+ key={`${draft.generation}-${draft.field}-${draft.operator}`}
+ 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}
+ />
+ </div>
+ ) : (
+ <>
+ <div {...bodyProps}>
+ {step === 'value' && (
+ <SheetAnnouncer onAnnounceChange={handleAnnounceChange} />
+ )}
+ {isDraftRenderable ? (
+ // A lone editor sits on the sheet's surface; with the
+ // Operator group above it, each section is a muted
+ // container.
+ operatorGroup ? (
+ <>
+ <div {...controlSectionProps}>{operatorGroup}</div>
+ <div {...controlSectionProps}>{valueEditor}</div>
+ </>
+ ) : (
+ valueEditor
+ )
+ ) : (
+ // A controlled config update removed the field or operator
+ // being edited: say so (the element's rendered text is
+ // announced, once per opened filter, while this step is the
+ // open one) and keep a way out.
+ draft != null && (
+ <SheetEmptyMessage
+ message={t('@astryx.powersearch.sheet.filterUnavailable')}
+ occasion={String(draft.generation)}
+ isShown={step === 'value'}
+ />
+ )
+ )}
+ </div>
+ <div {...stylex.props(styles.footer)}>
+ {isReadOnly ? (
+ <Button
+ ref={cancelButtonRef}
+ label={t('@astryx.powersearch.editor.cancel')}
+ variant="secondary"
+ width="100%"
+ xstyle={[styles.footerSoleAction, styles.touchHitArea]}
+ onClick={returnFromValue}
+ />
+ ) : (
+ <>
+ <Button
+ ref={cancelButtonRef}
+ label={t('@astryx.powersearch.editor.cancel')}
+ variant="secondary"
+ size="lg"
+ xstyle={styles.footerEqualAction}
+ onClick={returnFromValue}
+ />
+ {isDraftRenderable && (
+ <Button
+ label={saveButtonLabel}
+ variant="primary"
+ size="lg"
+ isDisabled={isSaveDisabled}
+ xstyle={styles.footerEqualAction}
+ onClick={handleSave}
+ />
+ )}
+ </>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ </BottomSheet>
+
+ {isClearConfirmationOpen && (
+ <SheetConfirmation
+ isOpen
+ onOpenChange={isConfirmationOpen => {
+ if (!isConfirmationOpen) {
+ closeClearConfirmation(false);
+ }
+ }}
+ title={t('@astryx.powersearch.sheet.clearAllTitle')}
+ description={t('@astryx.powersearch.sheet.clearAllDescription')}
+ actionLabel={t('@astryx.powersearch.sheet.clearAllConfirm')}
+ cancelLabel={t('@astryx.powersearch.sheet.clearAllCancel')}
+ onAction={() => closeClearConfirmation(true)}
+ />
+ )}
+ </>
+ );
+}
+
+PowerSearchBottomSheet.displayName = 'PowerSearchBottomSheet';
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
index 124e0d1296..bcf7cd54d9 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
@@ -5,7 +5,8 @@
/**
* @file PowerSearchEditPopover.tsx
* @input InternalConfig, PartialFilter
- * @output Edit popover content with field/operator selectors and value editor
+ * @output Edit popover content with field/operator selectors and value editor;
+ * the built-in NestedEditor the sheet presentation's value step shares
* @position Sub-component; consumed by PowerSearch
*
* SYNC: When modified, update:
@@ -384,7 +385,7 @@ function NestedSubFilterRow({
// Nested editor
// =============================================================================
-interface NestedEditorProps {
+export interface NestedEditorProps {
config: InternalConfig;
partialFilter: PartialFilter;
operatorOptions: {value: string; label: string}[];
@@ -392,9 +393,25 @@ interface NestedEditorProps {
onPartialFilterChange: (filter: PartialFilter) => void;
maxMenuItems?: number;
isReadOnly: boolean;
+ /** Styles for the editor's tree root (the sheet makes it a query container). */
+ xstyle?: stylex.StyleXStyles;
+ /**
+ * Whether the tree root offers the group-operator picker when the field has
+ * several operators. The popover shows it; the sheet presentation's value
+ * step owns the operator choice in its own Operator group and hides it.
+ * @default true
+ */
+ hasRootOperatorPicker?: boolean;
}
-function NestedEditor({
+/**
+ * The built-in editor for a `nested` value: a tree of sub-filters with Add,
+ * field/operator/value rows and removal. The popover renders it below its
+ * field selector; the sheet presentation's value step renders the same editor
+ * in its body, so a `nested` filter is created
+ * and edited the same way in both presentations.
+ */
+export function NestedEditor({
config,
partialFilter,
operatorOptions,
@@ -402,6 +419,8 @@ function NestedEditor({
onPartialFilterChange,
maxMenuItems,
isReadOnly,
+ xstyle,
+ hasRootOperatorPicker = true,
}: NestedEditorProps) {
const t = useComponentTranslator();
const [subFilters, setSubFilters] = useState<EditablePartialFilter[]>(() => {
@@ -587,7 +606,7 @@ function NestedEditor({
const rootLabel = (
<div {...stylex.props(styles.nestedRootLabel)}>
- {operatorOptions.length > 1 ? (
+ {hasRootOperatorPicker && operatorOptions.length > 1 ? (
<div {...stylex.props(styles.operatorSelector)}>
<Selector
label={t('@astryx.powersearch.editor.groupOperator')}
@@ -600,7 +619,10 @@ function NestedEditor({
/>
</div>
) : (
- (operatorOptions[0]?.label ?? t('@astryx.powersearch.editor.group'))
+ (operatorOptions.find(option => option.value === partialFilter.operator)
+ ?.label ??
+ operatorOptions[0]?.label ??
+ t('@astryx.powersearch.editor.group'))
)}
</div>
);
@@ -614,7 +636,7 @@ function NestedEditor({
},
];
- return <TreeList items={items} density="balanced" />;
+ return <TreeList items={items} density="balanced" xstyle={xstyle} />;
}
// =============================================================================
diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
index 55194a672e..4c54976981 100644
--- a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
@@ -4,9 +4,12 @@
/**
* @file PowerSearchValueEditor.tsx
- * @input OperatorValue, FilterValue, onChange callback
+ * @input OperatorValue, FilterValue, onChange callback, and the presentation
+ * the editor renders in
* @output Renders the appropriate editor for a filter value type
- * @position Sub-component; consumed by PowerSearchEditPopover
+ * @position Sub-component; consumed by PowerSearchEditPopover (popover
+ * presentation) and PowerSearchBottomSheet (sheet presentation, which
+ * renders the closed vocabularies as rows itself)
*
* SYNC: When modified, update:
* - /packages/core/src/PowerSearch/index.ts
@@ -43,9 +46,10 @@ import {DateRangeInput, type DateRange} from '../DateRangeInput';
import {resolveDateTimeRangePart} from './resolveDateTimeRangePart';
import {TimeInput} from '../TimeInput';
import {Selector} from '../Selector';
-import {Tokenizer} from '../Tokenizer';
+import {Tokenizer} from '../Tokenizer/Tokenizer';
import {Typeahead} from '../Typeahead';
import {useLocale} from '../i18n';
+import type {TranslatorFn} from '../i18n';
import {
registerEnglishFallback,
useComponentTranslator,
@@ -64,8 +68,30 @@ export interface PowerSearchValueEditorProps {
maxMenuItems?: number;
isDisabled?: boolean;
timezoneID?: string;
+ /**
+ * Called when a staged value no longer stands — the number input's draft is
+ * empty or does not parse — so the sheet presentation's confirm action
+ * disables again. Only the `bottom-sheet` presentation stages as typed; the
+ * popover commits on blur or Enter and never calls this.
+ */
+ onUnstage?: () => void;
+ /**
+ * Where the editor renders. In the `bottom-sheet` presentation the inputs
+ * fill the sheet's width, number inputs stage every parseable keystroke
+ * (the sheet's footer confirms; there is no Enter-to-save), the date range
+ * shows one month, and list values open the Tokenizer's own sheet titled
+ * with `fieldLabel`.
+ * @default 'popover'
+ */
+ presentation?: 'popover' | 'bottom-sheet';
+ /** The field's label; names the Tokenizer sheet in the sheet presentation. */
+ fieldLabel?: string;
}
+type EditorPresentation = NonNullable<
+ PowerSearchValueEditorProps['presentation']
+>;
+
// =============================================================================
// Helpers
// =============================================================================
@@ -113,6 +139,7 @@ function StringEditor({
onEnter: _onEnter,
maxMenuItems,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'string'};
filterValue: FilterValue | undefined;
@@ -120,8 +147,10 @@ function StringEditor({
onEnter?: () => void;
maxMenuItems?: number;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
+ const width = presentation === 'bottom-sheet' ? '100%' : undefined;
const currentValue = filterValue?.type === 'string' ? filterValue.value : '';
// When a searchSource is provided, render a typeahead instead of a plain
@@ -148,6 +177,7 @@ function StringEditor({
placeholder={t('@astryx.powersearch.valueEditor.searchPlaceholder')}
debounceMs={150}
maxMenuItems={maxMenuItems}
+ width={width}
/>
);
}
@@ -162,6 +192,7 @@ function StringEditor({
onChange={(value: string) => {
onChange({type: 'string', value});
}}
+ width={width}
/>
);
}
@@ -172,14 +203,19 @@ function StringListEditor({
onChange,
maxMenuItems,
isDisabled,
+ presentation,
+ fieldLabel,
}: {
operatorValue: OperatorValue & {type: 'string_list'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue) => void;
maxMenuItems?: number;
isDisabled?: boolean;
+ presentation: EditorPresentation;
+ fieldLabel?: string;
}) {
const t = useComponentTranslator();
+ const isSheet = presentation === 'bottom-sheet';
const currentValue: SearchableItem[] = useMemo(() => {
if (filterValue?.type !== 'string_list') {
return [];
@@ -203,9 +239,16 @@ function StringListEditor({
const hasCreate =
operatorValue.isArbitraryStringAllowed || !operatorValue.searchSource;
+ // In the sheet presentation the list value edits through the Tokenizer's
+ // own sheet, titled with the field's label; a popover menu inside a sheet
+ // would stack a second anchored layer on a surface the person is already in.
return (
<Tokenizer
- label={t('@astryx.powersearch.valueEditor.values')}
+ label={
+ isSheet && fieldLabel != null
+ ? fieldLabel
+ : t('@astryx.powersearch.valueEditor.values')
+ }
isLabelHidden
isDisabled={isDisabled}
searchSource={source}
@@ -220,6 +263,8 @@ function StringListEditor({
debounceMs={operatorValue.searchSource ? 150 : 0}
hasCreate={hasCreate}
maxMenuItems={maxMenuItems}
+ width={isSheet ? '100%' : undefined}
+ experimental={isSheet ? {presentation: 'bottom-sheet'} : undefined}
/>
);
}
@@ -231,6 +276,8 @@ function useNumberEditorHandlers({
isIntegerOnly,
onChange,
onEnter,
+ onUnstage,
+ stagesAsTyped,
}: {
valueType: 'integer' | 'float';
min?: number;
@@ -238,6 +285,14 @@ function useNumberEditorHandlers({
isIntegerOnly: boolean;
onChange: (value: FilterValue, shouldSave?: boolean) => void;
onEnter?: () => void;
+ onUnstage?: () => void;
+ /**
+ * Stage every keystroke the input would commit, and unstage when the draft
+ * stops parsing. The sheet presentation confirms from its footer, so the
+ * confirm action must enable while the person is still typing and disable
+ * again over an empty field; the popover commits on blur or Enter.
+ */
+ stagesAsTyped: boolean;
}) {
const locale = useLocale();
const pendingDecisionRef = useRef<NumberInputCommitDecision | null>(null);
@@ -259,12 +314,30 @@ function useNumberEditorHandlers({
}, []);
const handleInput = useCallback(
(event: FormEvent<HTMLElement>) => {
- pendingDecisionRef.current = resolveNumberInputCommit(
+ const decision = resolveNumberInputCommit(
(event.currentTarget as HTMLInputElement).value,
{min, max, isIntegerOnly, locale, hasClear: false},
);
+ pendingDecisionRef.current = decision;
+ if (stagesAsTyped) {
+ if (decision.type === 'commit') {
+ onChange(toFilterValue(decision.value));
+ } else {
+ // Cleared, or not a number: nothing stands to confirm.
+ onUnstage?.();
+ }
+ }
},
- [isIntegerOnly, locale, max, min],
+ [
+ isIntegerOnly,
+ locale,
+ max,
+ min,
+ onChange,
+ onUnstage,
+ stagesAsTyped,
+ toFilterValue,
+ ],
);
const handleEnter = useCallback(() => {
const decision = pendingDecisionRef.current;
@@ -292,13 +365,17 @@ function IntegerEditor({
filterValue,
onChange,
onEnter,
+ onUnstage,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'integer'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue, shouldSave?: boolean) => void;
onEnter?: () => void;
+ onUnstage?: () => void;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
const currentValue =
@@ -310,6 +387,8 @@ function IntegerEditor({
isIntegerOnly: true,
onChange,
onEnter,
+ onUnstage,
+ stagesAsTyped: presentation === 'bottom-sheet',
});
return (
@@ -328,6 +407,7 @@ function IntegerEditor({
units={operatorValue.units}
isIntegerOnly
placeholder={t('@astryx.powersearch.valueEditor.enterNumberPlaceholder')}
+ width={presentation === 'bottom-sheet' ? '100%' : undefined}
/>
);
}
@@ -337,13 +417,17 @@ function FloatEditor({
filterValue,
onChange,
onEnter,
+ onUnstage,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'float'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue, shouldSave?: boolean) => void;
onEnter?: () => void;
+ onUnstage?: () => void;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
const currentValue =
@@ -355,6 +439,8 @@ function FloatEditor({
isIntegerOnly: false,
onChange,
onEnter,
+ onUnstage,
+ stagesAsTyped: presentation === 'bottom-sheet',
});
return (
@@ -372,6 +458,7 @@ function FloatEditor({
max={operatorValue.maxValue}
units={operatorValue.units}
placeholder={t('@astryx.powersearch.valueEditor.enterNumberPlaceholder')}
+ width={presentation === 'bottom-sheet' ? '100%' : undefined}
/>
);
}
@@ -381,11 +468,13 @@ function TimeEditor({
filterValue,
onChange,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'time'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue) => void;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
const currentValue =
@@ -406,6 +495,7 @@ function TimeEditor({
}}
min={operatorValue.minValue as ISOTimeString | undefined}
max={operatorValue.maxValue as ISOTimeString | undefined}
+ width={presentation === 'bottom-sheet' ? '100%' : undefined}
/>
);
}
@@ -414,11 +504,13 @@ function DateAbsoluteEditor({
filterValue,
onChange,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'date_absolute'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue) => void;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
// Convert unixSeconds to ISO date string for the date input
@@ -442,10 +534,69 @@ function DateAbsoluteEditor({
onChange({type: 'date_absolute', unixSeconds});
}
}}
+ width={presentation === 'bottom-sheet' ? '100%' : undefined}
/>
);
}
+const RELATIVE_DATE_UNITS = [
+ {
+ unit: 'day',
+ plural: 'days',
+ amounts: [1, 3, 7, 14, 30],
+ ago: '@astryx.powersearch.sheet.relativeDaysAgo',
+ fromNow: '@astryx.powersearch.sheet.relativeDaysFromNow',
+ },
+ {
+ unit: 'week',
+ plural: 'weeks',
+ amounts: [1, 2, 4],
+ ago: '@astryx.powersearch.sheet.relativeWeeksAgo',
+ fromNow: '@astryx.powersearch.sheet.relativeWeeksFromNow',
+ },
+ {
+ unit: 'month',
+ plural: 'months',
+ amounts: [1, 3, 6, 12],
+ ago: '@astryx.powersearch.sheet.relativeMonthsAgo',
+ fromNow: '@astryx.powersearch.sheet.relativeMonthsFromNow',
+ },
+] as const;
+
+/**
+ * The relative-date choices an operator offers, in display order. Shared by
+ * the popover's Selector and the sheet presentation's rows so both list the
+ * same values. With `t` the labels resolve through the catalog's ICU plural
+ * messages (the sheet presentation's rows); without it they are the popover
+ * editor's own literals. In English the two read identically.
+ */
+export function buildRelativeDateOptions(
+ operatorValue: OperatorValue & {type: 'date_relative'},
+ t?: TranslatorFn,
+): {value: string; label: string}[] {
+ const result: {value: string; label: string}[] = [];
+ for (const {unit, plural, amounts, ago, fromNow} of RELATIVE_DATE_UNITS) {
+ for (const amount of amounts) {
+ const unitWord = amount === 1 ? unit : plural;
+ if (operatorValue.isPastAllowed !== false) {
+ result.push({
+ value: `${amount}${unit[0]}_ago`,
+ label: t ? t(ago, {count: amount}) : `${amount} ${unitWord} ago`,
+ });
+ }
+ if (operatorValue.isFutureAllowed !== false) {
+ result.push({
+ value: `${amount}${unit[0]}_from_now`,
+ label: t
+ ? t(fromNow, {count: amount})
+ : `${amount} ${unitWord} from now`,
+ });
+ }
+ }
+ }
+ return result;
+}
+
function DateRelativeEditor({
operatorValue,
filterValue,
@@ -461,37 +612,18 @@ function DateRelativeEditor({
const currentValue =
filterValue?.type === 'date_relative' ? filterValue.value : undefined;
- const options = useMemo(() => {
- const result: {value: string; label: string}[] = [];
- const units = [
- {unit: 'day', plural: 'days'},
- {unit: 'week', plural: 'weeks'},
- {unit: 'month', plural: 'months'},
- ];
- for (const {unit, plural} of units) {
- const amounts =
- unit === 'day'
- ? [1, 3, 7, 14, 30]
- : unit === 'week'
- ? [1, 2, 4]
- : [1, 3, 6, 12];
- for (const amount of amounts) {
- if (operatorValue.isPastAllowed !== false) {
- result.push({
- value: `${amount}${unit[0]}_ago`,
- label: `${amount} ${amount === 1 ? unit : plural} ago`,
- });
- }
- if (operatorValue.isFutureAllowed !== false) {
- result.push({
- value: `${amount}${unit[0]}_from_now`,
- label: `${amount} ${amount === 1 ? unit : plural} from now`,
- });
- }
- }
- }
- return result;
- }, [operatorValue.isPastAllowed, operatorValue.isFutureAllowed]);
+ // The choices depend on the two flags only; a config that rebuilds its
+ // operator objects per render keeps the same memoized list.
+ const {isPastAllowed, isFutureAllowed} = operatorValue;
+ const options = useMemo(
+ () =>
+ buildRelativeDateOptions({
+ type: 'date_relative',
+ isPastAllowed,
+ isFutureAllowed,
+ }),
+ [isPastAllowed, isFutureAllowed],
+ );
return (
<Selector
@@ -511,11 +643,13 @@ function DateRangeEditor({
filterValue,
onChange,
isDisabled,
+ presentation,
}: {
operatorValue: OperatorValue & {type: 'date_range'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue) => void;
isDisabled?: boolean;
+ presentation: EditorPresentation;
}) {
const t = useComponentTranslator();
const currentValue = useMemo<DateRange | null>(() => {
@@ -569,6 +703,9 @@ function DateRangeEditor({
value={currentValue}
onChange={handleChange}
hasClear={false}
+ // A phone-wide sheet fits one month; the popover keeps the default.
+ numberOfMonths={presentation === 'bottom-sheet' ? 1 : undefined}
+ width={presentation === 'bottom-sheet' ? '100%' : undefined}
/>
</div>
);
@@ -671,14 +808,19 @@ function EntityListEditor({
onChange,
maxMenuItems,
isDisabled,
+ presentation,
+ fieldLabel,
}: {
operatorValue: OperatorValue & {type: 'entity_list'};
filterValue: FilterValue | undefined;
onChange: (value: FilterValue) => void;
maxMenuItems?: number;
isDisabled?: boolean;
+ presentation: EditorPresentation;
+ fieldLabel?: string;
}) {
const t = useComponentTranslator();
+ const isSheet = presentation === 'bottom-sheet';
const source = useMemo<SearchSource<SearchableItem>>(() => {
if (operatorValue.searchSource) {
return operatorValue.searchSource;
@@ -701,9 +843,15 @@ function EntityListEditor({
}));
}, [filterValue]);
+ // Sheet presentation: the Tokenizer's own sheet, titled with the field
+ // label, as for string_list.
return (
<Tokenizer
- label={t('@astryx.powersearch.valueEditor.entities')}
+ label={
+ isSheet && fieldLabel != null
+ ? fieldLabel
+ : t('@astryx.powersearch.valueEditor.entities')
+ }
isLabelHidden
isDisabled={isDisabled}
searchSource={source}
@@ -726,6 +874,8 @@ function EntityListEditor({
placeholder={t('@astryx.powersearch.valueEditor.searchPlaceholder')}
debounceMs={operatorValue.searchSource ? 150 : 0}
maxMenuItems={maxMenuItems}
+ width={isSheet ? '100%' : undefined}
+ experimental={isSheet ? {presentation: 'bottom-sheet'} : undefined}
/>
);
}
@@ -771,6 +921,9 @@ export function PowerSearchValueEditor({
onEnter,
maxMenuItems,
isDisabled,
+ onUnstage,
+ presentation = 'popover',
+ fieldLabel,
}: PowerSearchValueEditorProps) {
switch (operatorValue.type) {
case 'empty':
@@ -780,6 +933,7 @@ export function PowerSearchValueEditor({
return (
<StringEditor
isDisabled={isDisabled}
+ presentation={presentation}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -792,6 +946,8 @@ export function PowerSearchValueEditor({
return (
<StringListEditor
isDisabled={isDisabled}
+ presentation={presentation}
+ fieldLabel={fieldLabel}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -803,6 +959,8 @@ export function PowerSearchValueEditor({
return (
<IntegerEditor
isDisabled={isDisabled}
+ presentation={presentation}
+ onUnstage={onUnstage}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -814,6 +972,8 @@ export function PowerSearchValueEditor({
return (
<FloatEditor
isDisabled={isDisabled}
+ presentation={presentation}
+ onUnstage={onUnstage}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -825,6 +985,7 @@ export function PowerSearchValueEditor({
return (
<TimeEditor
isDisabled={isDisabled}
+ presentation={presentation}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -835,6 +996,7 @@ export function PowerSearchValueEditor({
return (
<DateAbsoluteEditor
isDisabled={isDisabled}
+ presentation={presentation}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -855,6 +1017,7 @@ export function PowerSearchValueEditor({
return (
<DateRangeEditor
isDisabled={isDisabled}
+ presentation={presentation}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
@@ -885,6 +1048,8 @@ export function PowerSearchValueEditor({
return (
<EntityListEditor
isDisabled={isDisabled}
+ presentation={presentation}
+ fieldLabel={fieldLabel}
operatorValue={operatorValue}
filterValue={filterValue}
onChange={onChange}
diff --git a/packages/core/src/PowerSearch/formatFilterValue.ts b/packages/core/src/PowerSearch/formatFilterValue.ts
index ab226bca18..9d9d2b07b2 100644
--- a/packages/core/src/PowerSearch/formatFilterValue.ts
+++ b/packages/core/src/PowerSearch/formatFilterValue.ts
@@ -32,10 +32,27 @@ function formatEnumLabel(
}
function formatNumber(value: number, locale: Locale, units?: string): string {
- const formatted = new Intl.NumberFormat(locale).format(value);
+ const formatted = formatSharedNumber(value, locale);
return units ? `${formatted} ${units}` : formatted;
}
+/**
+ * A number in the provider locale's digits, decimal mark, and — unless the
+ * options say otherwise — grouping. The shared number helper for
+ * PowerSearch's own readings of a value — this module owns the raw `Intl`
+ * access.
+ */
+export function formatSharedNumber(
+ value: number,
+ locale: Locale,
+ options?: Pick<
+ Intl.NumberFormatOptions,
+ 'useGrouping' | 'maximumFractionDigits'
+ >,
+): string {
+ return new Intl.NumberFormat(locale, options).format(value);
+}
+
export function formatDateAbsolute(
unixSeconds: number,
locale: Locale,
diff --git a/packages/core/src/PowerSearch/formatTokenValue.ts b/packages/core/src/PowerSearch/formatTokenValue.ts
new file mode 100644
index 0000000000..6a4846e2bf
--- /dev/null
+++ b/packages/core/src/PowerSearch/formatTokenValue.ts
@@ -0,0 +1,215 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @fileoverview The text a PowerSearch filter token shows for a value.
+ *
+ * @input `OperatorValue`, `FilterValue`, a width budget, and the locale.
+ * @output `formatTokenValueText` — one string, or null for an empty value.
+ * @position Shared by the token itself (`PowerSearch.tsx`) and the sheet
+ * presentation's Filters rows and removal announcement
+ * (`PowerSearchBottomSheet.tsx`), so every reading of a value on the field
+ * uses the same words and the same zone handling.
+ */
+
+import type {OperatorValue, FilterValue, EnumItem} from './types';
+import type {Locale, TranslatorFn} from '../i18n';
+import {truncateCharacters} from '../utils/characters';
+import {
+ formatDateAbsoluteCompact,
+ formatSharedNumber,
+} from './formatFilterValue';
+import {registerEnglishFallback} from '../i18n/englishFallback';
+import english from '../i18n/generated-english/PowerSearch/formatTokenValue.generated';
+
+registerEnglishFallback(english);
+
+type ListFormatFn = (items: ReadonlyArray<string>) => string;
+
+function truncateString(value: string, limit: number): string {
+ // Same semantics as before — strings within limit + 3 pass through, longer
+ // ones cut to limit + '...' — but counted in characters, not code units.
+ return truncateCharacters(value, limit + 3, '...');
+}
+
+function getEnumLabel(values: ReadonlyArray<EnumItem>, value: string): string {
+ return values.find(v => v.value === value)?.label ?? value;
+}
+
+// Intl's maximum fraction cap: no number the row formats is rounded.
+const MAX_FRACTION_DIGITS = 100;
+
+// Whether a locale writes a number with the token's own numerals: Latin
+// digits and a `.` decimal mark, so `String(value)` is already the locale's
+// reading. Probed once per locale through the shared number helper.
+const tokenNumeralLocales = new Map<string, boolean>();
+function usesTokenNumerals(locale: Locale): boolean {
+ let uses = tokenNumeralLocales.get(locale);
+ if (uses == null) {
+ uses =
+ formatSharedNumber(1234567.5, locale, {
+ useGrouping: false,
+ maximumFractionDigits: MAX_FRACTION_DIGITS,
+ }) === '1234567.5';
+ tokenNumeralLocales.set(locale, uses);
+ }
+ return uses;
+}
+
+// A number as the token reads it. Where the locale writes Latin digits and a
+// `.` decimal mark, use the token's own text, `String(value)`. Elsewhere, use
+// the locale's digits and decimal mark, with no grouping and no rounding: the
+// fraction cap is Intl's maximum, so `1e-21` keeps its digits.
+function formatNumberAsToken(value: number, locale: Locale): string {
+ return usesTokenNumerals(locale)
+ ? String(value)
+ : formatSharedNumber(value, locale, {
+ useGrouping: false,
+ maximumFractionDigits: MAX_FRACTION_DIGITS,
+ });
+}
+
+// The summaries, lists, and numbers the token writes as English literals, and
+// the locale-aware readings of the same: with a translator (the sheet
+// presentation's rows and announcements) the summaries resolve through the
+// catalog, lists through the provider locale's list format, and numbers
+// through its number format; without one they stay the token's own literals,
+// the released popover token's text. In English the two read identically.
+function itemsSummary(count: number, t: TranslatorFn | undefined): string {
+ return t
+ ? t('@astryx.powersearch.valueEditor.itemsCount', {count})
+ : // eslint-disable-next-line @astryx/no-hardcoded-i18n-string -- the popover token's released English text; translating it is a separate stable change
+ `${count} items`;
+}
+
+function formatListText(
+ labels: ReadonlyArray<string>,
+ maxLength: number,
+ t: TranslatorFn | undefined,
+ formatList: ListFormatFn | undefined,
+): string | null {
+ if (labels.length === 0) {
+ return null;
+ }
+ if (labels.length === 1) {
+ return truncateString(labels[0], maxLength);
+ }
+ const totalLength = labels.reduce((sum, s) => sum + s.length, 0);
+ if (totalLength > maxLength) {
+ return itemsSummary(labels.length, t);
+ }
+ return formatList ? formatList(labels) : labels.join(', ');
+}
+
+/**
+ * The text a filter token shows for a value: the one place that decides how
+ * a value reads on the field, so every other reading of the same value —
+ * the sheet presentation's Filters rows and its removal announcement — can
+ * use the same words and the same zone handling. `maxLength` is the token's
+ * width budget; pass `Number.MAX_SAFE_INTEGER` for the untruncated text.
+ * With `t`, the list, date-range and nested summaries resolve through the
+ * catalog (`@astryx.powersearch.valueEditor.*`); without it they are the
+ * token's own literals. With `formatList` (the provider's list formatter),
+ * several labels join as a list in the locale; without it they join with
+ * the token's literal ", ".
+ */
+export function formatTokenValueText(
+ operatorValue: OperatorValue,
+ filterValue: FilterValue,
+ maxLength: number,
+ locale: Locale,
+ t?: TranslatorFn,
+ formatList?: ListFormatFn,
+): string | null {
+ switch (filterValue.type) {
+ case 'empty':
+ return null;
+
+ case 'string':
+ return truncateString(filterValue.value, maxLength);
+
+ case 'integer':
+ case 'float':
+ return t
+ ? formatNumberAsToken(filterValue.value, locale)
+ : String(filterValue.value);
+
+ case 'enum':
+ if (operatorValue.type === 'enum') {
+ return truncateString(
+ getEnumLabel(operatorValue.values, filterValue.value),
+ maxLength,
+ );
+ }
+ return truncateString(filterValue.value, maxLength);
+
+ case 'string_list':
+ return formatListText(filterValue.value, maxLength, t, formatList);
+
+ case 'enum_list': {
+ const items = filterValue.value;
+ if (items.length === 0) {
+ return null;
+ }
+ if (operatorValue.type === 'enum_list') {
+ return formatListText(
+ items.map(v => getEnumLabel(operatorValue.values, v)),
+ maxLength,
+ t,
+ formatList,
+ );
+ }
+ if (items.length === 1) {
+ return truncateString(items[0], maxLength);
+ }
+ return itemsSummary(items.length, t);
+ }
+
+ case 'entity_list':
+ return formatListText(
+ filterValue.value.map(e => e.label),
+ maxLength,
+ t,
+ formatList,
+ );
+
+ case 'time':
+ return filterValue.value;
+
+ case 'date_absolute':
+ return truncateString(
+ formatDateAbsoluteCompact(filterValue.unixSeconds, locale),
+ maxLength,
+ );
+
+ case 'date_relative':
+ return truncateString(filterValue.value, maxLength);
+
+ case 'date_range':
+ if (t) {
+ return t('@astryx.powersearch.valueEditor.dateRange');
+ }
+ // eslint-disable-next-line @astryx/no-hardcoded-i18n-string -- the popover token's released English text; translating it is a separate stable change
+ return 'date range';
+
+ case 'custom':
+ if (operatorValue.type === 'custom') {
+ return truncateString(
+ operatorValue.getString(filterValue.value),
+ maxLength,
+ );
+ }
+ return filterValue.value;
+
+ case 'nested': {
+ const count = filterValue.value.length;
+ if (t) {
+ return t('@astryx.powersearch.valueEditor.filtersCount', {count});
+ }
+ // eslint-disable-next-line @astryx/no-hardcoded-i18n-string -- the popover token's released English text; translating it is a separate stable change
+ return count === 1 ? '1 filter' : `${count} filters`;
+ }
+
+ default:
+ return null;
+ }
+}
diff --git a/packages/core/src/PowerSearch/powerSearchSheetUtils.ts b/packages/core/src/PowerSearch/powerSearchSheetUtils.ts
new file mode 100644
index 0000000000..b327a17f56
--- /dev/null
+++ b/packages/core/src/PowerSearch/powerSearchSheetUtils.ts
@@ -0,0 +1,224 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file powerSearchSheetUtils.ts
+ * @input PowerSearch config/filter types and the field typeahead source
+ * @output Pure helpers for the sheet presentation: which operators the
+ * sheet's own controls edit, field matching, filter identity tracking
+ * across controlled re-renders, the focus target after a removal, and the
+ * content search's suggestion source over the field typeahead
+ * @position Helper module; consumed by PowerSearchBottomSheet.tsx and its
+ * tests
+ */
+
+import type {SearchSource} from '../Typeahead/types';
+import type {InternalConfig} from './useInternalConfig';
+import type {
+ PowerSearchField,
+ PowerSearchFilter,
+ PowerSearchItem,
+ PowerSearchOperator,
+} from './types';
+
+// =============================================================================
+// Operators and fields
+// =============================================================================
+
+/**
+ * Whether the value step edits an operator's value with a sheet-native
+ * control (choice rows, or the popover's editor in its sheet presentation).
+ * A `nested` value is the exception: it is edited by the popover's built-in
+ * NestedEditor, rendered in the step's body,
+ * so every operator opens an editable step and no field is left out.
+ */
+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
+ );
+}
+
+/** Synchronous suggestion source; the sheet renders results inline. */
+export interface SheetSuggestionSource {
+ search(query: string): PowerSearchItem[];
+ bootstrap(): PowerSearchItem[];
+}
+
+/**
+ * The field typeahead source as the content search's rows: the popover
+ * presentation's own suggestions, minus any whose field the config no longer
+ * knows. That source resolves synchronously from the config; a promise (none
+ * today) yields no rows rather than a stale list.
+ */
+export function createSheetSuggestionSource(
+ config: InternalConfig,
+ source: SearchSource<PowerSearchItem>,
+): SheetSuggestionSource {
+ // Every suggestion whose field the config knows is offered: the value step
+ // edits every operator, `nested` included.
+ const isEditable = (item: PowerSearchItem): boolean => {
+ const aux = item.auxiliaryData;
+ return aux != null && config.getField(aux.fieldKey) != null;
+ };
+ const settle = (
+ results: PowerSearchItem[] | Promise<PowerSearchItem[]>,
+ ): PowerSearchItem[] =>
+ Array.isArray(results) ? results.filter(isEditable) : [];
+ return {
+ search: query => settle(source.search(query)),
+ bootstrap: () => settle(source.bootstrap()),
+ };
+}
+
+// =============================================================================
+// 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';
+}
+
+/**
+ * Stable identities for the Filters rows across controlled updates, so a row
+ * keeps its element — and its focus — when the parent reorders the filters or
+ * removes one above it. A filter object seen before keeps its
+ * id; a new object takes the id of a filter from the previous update with the
+ * same signature that no present object claims (a parent that clones its
+ * values on every change); anything else mints a new id. Two equal filters
+ * are told apart by order. Call `next` once per render with the current list.
+ */
+export function createFilterIdentities(): {
+ next: (filters: ReadonlyArray<PowerSearchFilter>) => number[];
+} {
+ const byObject = new WeakMap<PowerSearchFilter, number>();
+ let previousBySignature = new Map<string, number[]>();
+ let nextId = 0;
+ return {
+ next(filters) {
+ const used = new Set<number>();
+ const ids: (number | null)[] = filters.map(filter => {
+ const known = byObject.get(filter);
+ if (known == null || used.has(known)) {
+ return null;
+ }
+ used.add(known);
+ return known;
+ });
+ const bySignature = new Map<string, number[]>();
+ filters.forEach((filter, index) => {
+ const signature = filterSignature(filter);
+ let id = ids[index];
+ if (id == null) {
+ id =
+ previousBySignature
+ .get(signature)
+ ?.find(candidate => !used.has(candidate)) ?? nextId++;
+ used.add(id);
+ byObject.set(filter, id);
+ ids[index] = id;
+ }
+ bySignature.set(signature, [...(bySignature.get(signature) ?? []), id]);
+ });
+ previousBySignature = bySignature;
+ return ids as number[];
+ },
+ };
+}
+
+/** 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 step 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`, focus should land on the
+ * nearest remaining row that is a button, preferring the one after it.
+ * `isRowButton` is the Filters sheet's own rule for which rows are buttons:
+ * the field interactive and the filter not read-only (a `nested` or stale
+ * filter's row is a button too).
+ */
+export function nearestEditableIndex(
+ nextFilters: ReadonlyArray<PowerSearchFilter>,
+ removedIndex: number,
+ isRowButton: (filter: PowerSearchFilter) => boolean = filter =>
+ !filter.isReadOnly,
+): number | undefined {
+ const editableIndices = nextFilters.flatMap((candidate, candidateIndex) =>
+ isRowButton(candidate) ? [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);
+}
diff --git a/packages/core/src/RadioList/RadioList.tsx b/packages/core/src/RadioList/RadioList.tsx
index 3ab2a19c35..70bbaeb9b8 100644
--- a/packages/core/src/RadioList/RadioList.tsx
+++ b/packages/core/src/RadioList/RadioList.tsx
@@ -29,9 +29,10 @@ import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
import {Field} from '../Field/Field';
import type {InputStatus} from '../Field/types';
-import {useTooltip} from '../Tooltip';
+import {useTooltip} from '../Tooltip/useTooltip';
import {useResolvedRequired} from '../hooks/useResolvedRequired';
-import {composeEventHandlers, mergeProps} from '../utils';
+import {composeEventHandlers} from '../utils/composeEventHandlers';
+import {mergeProps} from '../utils/mergeProps';
import {joinAriaIDs} from '../utils/inputAria';
import {
type FieldInputBaseProps,
diff --git a/packages/core/src/RadioList/RadioListItem.tsx b/packages/core/src/RadioList/RadioListItem.tsx
index 08ebd594f0..64e64b09f1 100644
--- a/packages/core/src/RadioList/RadioListItem.tsx
+++ b/packages/core/src/RadioList/RadioListItem.tsx
@@ -26,12 +26,14 @@ import {RadioListContext} from './RadioList';
import {RadioListReasonContext} from './RadioListReasonContext';
import {joinAriaIDs} from '../utils/inputAria';
import {colorVars, radiusVars} from '../theme/tokens.stylex';
-import {mergeProps, isRenderable, rtlStyles} from '../utils';
+import {isRenderable} from '../utils/isRenderable';
+import {mergeProps} from '../utils/mergeProps';
+import {rtlStyles} from '../utils/rtlStyles';
import {indicatorScope} from '../Indicator/indicator.markers.stylex';
import {useIndicatorFocusRing} from '../hooks/useIndicatorFocusRing';
import {usePressFeedback} from '../hooks/usePressFeedback';
-import {useIndicator} from '../Indicator';
-import {Item, type ItemAlign} from '../Item';
+import {useIndicator} from '../Indicator/useIndicator';
+import {Item, type ItemAlign} from '../Item/Item';
import {themeProps} from '../utils/themeProps';
// The touch press's paint, declared by the shared overlay styles on the
diff --git a/packages/core/src/TextInput/TextInput.tsx b/packages/core/src/TextInput/TextInput.tsx
index f76973b079..41d6df3258 100644
--- a/packages/core/src/TextInput/TextInput.tsx
+++ b/packages/core/src/TextInput/TextInput.tsx
@@ -35,21 +35,22 @@ import {
typographyVars,
typeScaleVars,
} from '../theme/tokens.stylex';
+import {Field} from '../Field/Field';
+import {InputClearButton} from '../Field/InputClearButton';
import {
- Field,
- InputClearButton,
- type InputStatus,
inputWrapperStyles,
inputStatusBorderStyles,
inputStatusHoverShadowStyles,
inputStatusFocusWithinStyles,
-} from '../Field';
-import {renderIconSlot, type IconType} from '../Icon';
+} from '../Field/inputStyles.stylex';
+import type {InputStatus} from '../Field/types';
+import {renderIconSlot, type IconType} from '../Icon/Icon';
import {isRenderable} from '../utils/isRenderable';
-import {Spinner} from '../Spinner';
-import {useTooltip} from '../Tooltip';
-import {VisuallyHidden} from '../VisuallyHidden';
-import {getInputARIA, isImeKeyEvent} from '../utils';
+import {Spinner} from '../Spinner/Spinner';
+import {useTooltip} from '../Tooltip/useTooltip';
+import {VisuallyHidden} from '../VisuallyHidden/VisuallyHidden';
+import {getInputARIA} from '../utils/inputAria';
+import {isImeKeyEvent} from '../utils/ime';
import {
textEntryTraitAttributes,
type TextEntryTraitProps,
@@ -109,7 +110,7 @@ export type {
InputStatus as TextInputStatus,
InputStatusType as TextInputStatusType,
} from '../Field';
-import {mergeProps} from '../utils';
+import {mergeProps} from '../utils/mergeProps';
import {useSize} from '../SizeContext/SizeContext';
import {useInputContainer} from '../hooks/useInputContainer';
import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
diff --git a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
index b02be2cb40..516c0d1738 100644
--- a/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
+++ b/packages/core/src/hooks/useAnnounceRenderedText.adopters.test.tsx
@@ -66,6 +66,7 @@ const {MultiSelector} = await import('../MultiSelector');
const {CommandPalette} = await import('../CommandPalette');
const {BaseTypeahead} = await import('../Typeahead/BaseTypeahead');
const {Tokenizer} = await import('../Tokenizer/Tokenizer');
+const {PowerSearch} = await import('../PowerSearch/PowerSearch');
const {createStaticSource} = await import('../Typeahead/createStaticSource');
const {TooltipWithTriggerBehavior} = await import('../Tooltip/Tooltip');
@@ -204,6 +205,43 @@ const ADOPTERS: Record<string, () => Promise<void>> = {
});
await expectDelegated('Nothing called that');
},
+ 'PowerSearch/PowerSearchBottomSheet.tsx': async () => {
+ // The sheet's own content is its empty-result text — "No results found"
+ // for the content search, "No filters match your search" for the field
+ // search — and the value step's "This filter is no longer available";
+ // all plain text the shared module reads from the rendered element. The
+ // flow's `Added`, `Removed`, result-count and after-close messages are
+ // not rendered content and go through `useAnnounce` directly.
+ render(
+ <PowerSearch
+ config={{
+ name: 'Issues',
+ contentSearchFieldKey: 'author',
+ fields: [
+ {
+ key: 'author',
+ label: 'Author',
+ isValueMatchAllowed: false,
+ typeaheadMinQueryLength: 99,
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ ],
+ }}
+ filters={[]}
+ label="Filters"
+ isLabelHidden={false}
+ onChange={() => {}}
+ experimental={{presentation: 'bottom-sheet'}}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: /^Filters/}));
+ // A query equal to the field's label hides the free-text item, and the
+ // field is below its min query length: nothing lists.
+ fireEvent.change(await screen.findByRole('searchbox', {name: 'Search'}), {
+ target: {value: 'Author'},
+ });
+ await expectDelegated('No results found');
+ },
};
describe('own-content announcement adopters (react-component-runtime INV10)', () => {
diff --git a/packages/core/src/hooks/useInputStatusIcon.tsx b/packages/core/src/hooks/useInputStatusIcon.tsx
index f9a3928a4e..051ce9d398 100644
--- a/packages/core/src/hooks/useInputStatusIcon.tsx
+++ b/packages/core/src/hooks/useInputStatusIcon.tsx
@@ -15,9 +15,10 @@
import {useCallback, useEffect, useState} from 'react';
import type {ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {Icon, type IconName, type IconSize} from '../Icon';
+import {Icon, type IconSize} from '../Icon/Icon';
+import type {IconName} from '../Icon/globalIconRegistry';
import type {InputStatus, InputStatusType} from '../Field/types';
-import {useTooltip} from '../Tooltip';
+import {useTooltip} from '../Tooltip/useTooltip';
import {radiusVars} from '../theme/tokens.stylex';
import {themeProps} from '../utils/themeProps';
import {focusOutlineStyles} from '../utils/focusOutline.stylex';
diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.ts
index c39ae60eee..0bd9f307dc 100644
--- a/packages/core/src/theme/derivedVarRegistry.test.ts
+++ b/packages/core/src/theme/derivedVarRegistry.test.ts
@@ -340,6 +340,7 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
// properties a theme author sets on the component.
'--_thumbnail-hit-inset',
'--_input-clear-hit-inset',
+ '--_power-search-sheet-hit-inset',
// The interaction overlay's colour on the ::after layer of the cards:
// written by the component's own hover and mouse `:active` arms, never a
// value a theme author sets; the overlay colours themselves are the shared
@@ -351,6 +352,7 @@ const VARS_WITHOUT_DERIVED_MAPPING = new Set([
'--_press-paint',
'--_press-paint-image',
'--_input-clear-hit-content',
+ '--_power-search-sheet-hit-content',
// Placement and swipe lifecycle values are private Toast behavior. A theme
// author controls the surface transform/opacity as a whole, not these values.
'--_toast-slide-y',