Skip to content

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

TypeScript

fix(PowerSearch): replace an open value menu when the field or operator changes (#6357)

nynexman4464da998a2c5915
diff --git a/.changeset/powersearch-stale-value-menu.md b/.changeset/powersearch-stale-value-menu.md
new file mode 100644
index 0000000000..a2aa9b2873
--- /dev/null
+++ b/.changeset/powersearch-stale-value-menu.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] PowerSearch: switching the field or operator while a value menu is open now replaces the menu's contents instead of leaving the previous field's options showing. The value editor is keyed on the field and operator it edits, so editors for two fields sharing a value type no longer share one instance; nested sub-filter rows get the same treatment. BaseTypeahead also invalidates in-flight searches when its `searchSource` is replaced, so a late response from the old source can no longer populate the menu.
+
+@nynexman4464
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
index ed918004dd..a9801c120d 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
@@ -10,7 +10,14 @@ import {
afterAll,
afterEach,
} from 'vitest';
-import {render, screen, fireEvent, act} from '@testing-library/react';
+import {
+ render,
+ screen,
+ fireEvent,
+ act,
+ waitFor,
+ within,
+} from '@testing-library/react';
import React, {useState} from 'react';
import * as stylex from '@stylexjs/stylex';
import {spacingVars} from '../theme/tokens.stylex';
@@ -170,6 +177,148 @@ describe('PowerSearch', () => {
expect(popoverText).toContain('equals');
});
+ describe('value editor identity follows the field and operator', () => {
+ // Two fields with the same value type, so an unkeyed editor would be
+ // reused across the switch and keep the first field's menu contents.
+ const sameTypeConfig: PowerSearchConfig = {
+ name: 'test-same-type',
+ fields: [
+ {
+ key: 'creator',
+ label: 'Creator',
+ operators: [
+ {
+ key: 'is_any_of',
+ label: 'is any of',
+ value: {
+ type: 'enum_list',
+ values: [{value: 'creator-1', label: 'Creator Person'}],
+ },
+ },
+ ],
+ },
+ {
+ key: 'owner',
+ label: 'Owner',
+ operators: [
+ {
+ key: 'is_any_of',
+ label: 'is any of',
+ value: {
+ type: 'enum_list',
+ values: [{value: 'owner-1', label: 'Owner Person'}],
+ },
+ },
+ ],
+ },
+ ],
+ };
+
+ const creatorOption = () =>
+ screen.queryByRole('option', {name: 'Creator Person', hidden: true});
+ const ownerOption = () =>
+ screen.queryByRole('option', {name: 'Owner Person', hidden: true});
+
+ it('replaces an open value menu when the field changes', async () => {
+ function Harness() {
+ const internalConfig = useInternalConfig(sameTypeConfig);
+ return (
+ <PowerSearchEditPopover
+ config={internalConfig}
+ filter={{
+ field: 'creator',
+ operator: 'is_any_of',
+ value: {type: 'enum_list', value: []},
+ }}
+ mode="edit"
+ onSave={() => {}}
+ onCancel={() => {}}
+ />
+ );
+ }
+
+ render(<Harness />);
+
+ // Open the Creator value menu and leave it open.
+ fireEvent.focus(screen.getByRole('combobox', {name: 'Values'}));
+ await waitFor(() => expect(creatorOption()).toBeInTheDocument());
+
+ // Switch the field underneath the open menu.
+ fireEvent.click(screen.getByRole('combobox', {name: 'Field'}));
+ fireEvent.click(
+ screen.getByRole('option', {name: 'Owner', hidden: true}),
+ );
+ act(() => flushRAF());
+
+ // The old field's options are gone, the new field's are shown.
+ expect(creatorOption()).not.toBeInTheDocument();
+ await waitFor(() => expect(ownerOption()).toBeInTheDocument());
+ });
+
+ it('replaces an open value menu on a nested sub-filter row', async () => {
+ const nestedConfig: PowerSearchConfig = {
+ name: 'test-nested-same-type',
+ fields: [
+ {
+ key: 'group',
+ label: 'Group',
+ operators: [
+ {key: 'all_of', label: 'all of', value: {type: 'nested'}},
+ ],
+ },
+ ...sameTypeConfig.fields,
+ ],
+ };
+
+ function Harness() {
+ const internalConfig = useInternalConfig(nestedConfig);
+ return (
+ <PowerSearchEditPopover
+ config={internalConfig}
+ filter={{
+ field: 'group',
+ operator: 'all_of',
+ value: {
+ type: 'nested',
+ value: [
+ {
+ field: 'creator',
+ operator: 'is_any_of',
+ value: {type: 'enum_list', value: []},
+ },
+ ],
+ },
+ }}
+ mode="edit"
+ onSave={() => {}}
+ onCancel={() => {}}
+ />
+ );
+ }
+
+ render(<Harness />);
+
+ fireEvent.focus(screen.getByRole('combobox', {name: 'Values'}));
+ await waitFor(() => expect(creatorOption()).toBeInTheDocument());
+
+ // The nested row's own field selector is the one currently on
+ // "Creator"; the root selector stays on "Group".
+ const rowField = screen
+ .getAllByRole('combobox', {name: 'Field'})
+ .find(el => el.textContent === 'Creator');
+ expect(rowField).toBeDefined();
+ fireEvent.click(rowField!);
+ const rowListbox = document.getElementById(
+ rowField!.getAttribute('aria-controls')!,
+ )!;
+ fireEvent.click(
+ within(rowListbox).getByRole('option', {name: 'Owner', hidden: true}),
+ );
+
+ expect(creatorOption()).not.toBeInTheDocument();
+ });
+ });
+
it('edit popover shows correct filter after removing a preceding filter', () => {
const filters: PowerSearchFilter[] = [
{field: 'status', operator: 'is', value: {type: 'string', value: 'open'}},
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
index 500af1feed..794c1300c8 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
@@ -22,7 +22,10 @@ import {TreeList, type TreeListItemData} from '../TreeList';
import {useTranslator} from '../i18n';
import {isImeKeyEvent} from '../utils/ime';
import {spacingVars, typeScaleVars} from '../theme/tokens.stylex';
-import {PowerSearchValueEditor} from './PowerSearchValueEditor';
+import {
+ PowerSearchValueEditor,
+ type PowerSearchValueEditorProps,
+} from './PowerSearchValueEditor';
import {resolveOperatorLabel} from './resolveOperatorLabel';
import type {InternalConfig} from './useInternalConfig';
import type {
@@ -356,6 +359,7 @@ function NestedSubFilterRow({
{operatorValue && !isEmptyType && !isNestedType && (
<div {...stylex.props(styles.nestedRowValueEditor)}>
<PowerSearchValueEditor
+ key={valueEditorKey(subFilter)}
operatorValue={operatorValue}
filterValue={subFilter.value}
onChange={handleValueChange}
@@ -606,6 +610,54 @@ function NestedEditor({
return <TreeList items={items} density="balanced" />;
}
+// =============================================================================
+// Value editor cell
+// =============================================================================
+
+/**
+ * The value editor's identity is the (field, operator) pair it edits. Keying
+ * on it remounts the editor when either changes, so nothing an editor keeps
+ * privately — a Tokenizer's open menu, its query text, results fetched from
+ * the previous field's source — survives into the next field. Without the
+ * key, two fields sharing a value type (two `enum_list` fields, say) reuse
+ * one editor instance and the open menu keeps showing the old field's
+ * options.
+ */
+function valueEditorKey(filter: {field: string; operator?: string}): string {
+ return `${filter.field}\u0000${filter.operator ?? ''}`;
+}
+
+/**
+ * Wraps the value editor and moves focus into it once it mounts. Because the
+ * cell is keyed on the filter's field and operator, "mount" means both the
+ * popover opening and the user picking a different field or operator — the
+ * same focus handoff either way, so the freshly mounted editor can bootstrap
+ * its own suggestions.
+ */
+function ValueEditorCell(props: PowerSearchValueEditorProps) {
+ const ref = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ const frame = requestAnimationFrame(() => {
+ const container = ref.current;
+ if (!container) {
+ return;
+ }
+ const focusable = container.querySelector<HTMLElement>(
+ 'input:not([disabled]), button:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
+ );
+ focusable?.focus();
+ });
+ return () => cancelAnimationFrame(frame);
+ }, []);
+
+ return (
+ <div ref={ref} {...stylex.props(styles.valueEditor)}>
+ <PowerSearchValueEditor {...props} />
+ </div>
+ );
+}
+
// =============================================================================
// Main popover
// =============================================================================
@@ -625,22 +677,6 @@ export function PowerSearchEditPopover({
saveButtonLabelFromProps ?? t('@astryx.powersearch.editor.apply');
const [partialFilter, setPartialFilter] =
useState<PartialFilter>(initialFilter);
- const valueEditorRef = useRef<HTMLDivElement>(null);
-
- // Focus the first focusable element inside the value editor after mount
- useEffect(() => {
- const frame = requestAnimationFrame(() => {
- const container = valueEditorRef.current;
- if (!container) {
- return;
- }
- const focusable = container.querySelector<HTMLElement>(
- 'input:not([disabled]), button:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])',
- );
- focusable?.focus();
- });
- return () => cancelAnimationFrame(frame);
- }, []);
const currentOperator = partialFilter.operator
? config.getOperator(partialFilter.field, partialFilter.operator)
@@ -854,17 +890,16 @@ export function PowerSearchEditPopover({
</div>
)}
{operatorValue && !isEmptyType && (
- <div ref={valueEditorRef} {...stylex.props(styles.valueEditor)}>
- <PowerSearchValueEditor
- operatorValue={operatorValue}
- filterValue={partialFilter.value}
- onChange={handleValueChange}
- onEnter={handleSave}
- config={config}
- maxMenuItems={maxMenuItems}
- isDisabled={isReadOnly}
- />
- </div>
+ <ValueEditorCell
+ key={valueEditorKey(partialFilter)}
+ operatorValue={operatorValue}
+ filterValue={partialFilter.value}
+ onChange={handleValueChange}
+ onEnter={handleSave}
+ config={config}
+ maxMenuItems={maxMenuItems}
+ isDisabled={isReadOnly}
+ />
)}
</HStack>
</div>
diff --git a/packages/core/src/Typeahead/BaseTypeahead.spec.md b/packages/core/src/Typeahead/BaseTypeahead.spec.md
index ed40aa26e3..538f555bcb 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.spec.md
+++ b/packages/core/src/Typeahead/BaseTypeahead.spec.md
@@ -98,7 +98,7 @@ Draft requirements identify their observational or current-authority basis.
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------------------------------------------- |
| FR1 | The input is controlled by internal query state while `value` is caller-controlled; selecting a result calls `onChange(item)`, clears query/results, closes the popup, and returns focus to the input. | Current source and tests | verified shipped behavior |
| FR2 | Search starts only at the grapheme-count threshold, uses the configured debounce, and never presents an empty result for a query that was not searched. | Public API, current i18n character utility, tests | verified audit remediation |
-| FR3 | A newer query, selection, clear, or unmount invalidates stale asynchronous work. Escape hides the current popup but does not invalidate pending work, so a late response currently reopens it (retained violation). | Current source, focused retained-red probe, and tests | verified shipped behavior |
+| FR3 | A newer query, selection, clear, source replacement, or unmount invalidates stale asynchronous work. Escape hides the current popup but does not invalidate pending work, so a late response currently reopens it (retained violation). | Current source, focused retained-red probe, and tests | verified shipped behavior |
| FR4 | The popup is a named listbox whose result rows are options. A completed empty search renders one disabled option so the listbox retains a valid owned child. | APG combobox pattern, axe, tests | verified audit remediation |
| FR5 | Arrow keys wrap the highlight; Home/End move to the first/last option; Enter selects; Escape and Tab hide the current popup; IME-owned key events do not activate combobox commands. Escape dismissal is not durable while source work remains pending (FR3). | Current source and tests | verified shipped behavior; Escape gap retained |
| FR6 | Pending asynchronous source work sets `aria-busy` and renders one named Spinner unless the composed wrapper owns the busy indicator lane. | Current source, input-family FR7, tests | verified shipped behavior |
@@ -139,8 +139,9 @@ Draft requirements identify their observational or current-authority basis.
### Performance and resources
-- **PR1 — Search lifetime.** One generation counter rejects stale responses;
- debounce timers and optional source cancellation are cleared on replacement and
+- **PR1 — Search lifetime.** One generation counter rejects stale responses,
+ including responses from a source that has since been replaced; debounce
+ timers and optional source cancellation are cleared on replacement and
unmount.
## Accessibility contract
diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsx
index a9445ac3ca..4bff959e07 100644
--- a/packages/core/src/Typeahead/BaseTypeahead.tsx
+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx
@@ -533,9 +533,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
// Debounce ref
const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
- // Monotonic counter incremented on selection and query-clear. Async
- // searches that resolve after a selection compare their captured
- // generation to the current value and discard stale results.
+ // Monotonic counter incremented on selection, query-clear, and source
+ // replacement. Async searches that resolve afterwards compare their
+ // captured generation to the current value and discard stale results.
const searchGenRef = useRef(0);
// The generation at which results were last populated. handleFocus
// compares this to searchGenRef — if they differ, the cached results
@@ -987,12 +987,17 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({
const selectedKey =
value == null ? null : getKey(value.id, () => results.indexOf(value));
- // Cleanup timeout and cancel in-flight searches on unmount
+ // A replaced or unmounted source ends its search lifetime: drop the pending
+ // debounce, cancel in-flight work where the source supports it, and advance
+ // the generation so a late response from the old source can no longer
+ // commit results into a typeahead that is now reading a different source.
useEffect(() => {
return () => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
+ // eslint-disable-next-line @eslint-react/exhaustive-deps -- a counter, not a node: the cleanup must advance the live generation
+ searchGenRef.current++;
searchSource.cancel?.();
};
}, [searchSource]);
diff --git a/packages/core/src/Typeahead/Typeahead.test.tsx b/packages/core/src/Typeahead/Typeahead.test.tsx
index 62c0327b2b..a8976cfc3b 100644
--- a/packages/core/src/Typeahead/Typeahead.test.tsx
+++ b/packages/core/src/Typeahead/Typeahead.test.tsx
@@ -574,6 +574,59 @@ describe('Typeahead', () => {
expect(screen.getByText('Apple')).toBeInTheDocument();
expect(screen.queryByText('Avocado')).not.toBeInTheDocument();
});
+
+ it('discards a response from a source that was replaced while it was in flight', async () => {
+ let resolveOld: ((items: SearchableItem[]) => void) | null = null;
+ const oldSource: SearchSource = {
+ search: async () =>
+ new Promise<SearchableItem[]>(resolve => {
+ resolveOld = resolve;
+ }),
+ bootstrap: () => [],
+ };
+ const newSource: SearchSource = {
+ search: () => [{id: 'banana', label: 'Banana'}],
+ bootstrap: () => [],
+ };
+
+ const {rerender} = render(
+ <Typeahead
+ label="Fruit"
+ searchSource={oldSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'a'}});
+ await waitFor(() => expect(resolveOld).not.toBeNull());
+
+ // The source is swapped while the old search is still pending and no
+ // new query is typed. The stale response must not populate a menu that
+ // now reads from a different source.
+ rerender(
+ <Typeahead
+ label="Fruit"
+ searchSource={newSource}
+ value={null}
+ onChange={() => {}}
+ debounceMs={0}
+ />,
+ );
+
+ await act(async () => {
+ resolveOld!([{id: 'apple', label: 'Apple'}]);
+ });
+ expect(screen.queryByText('Apple')).not.toBeInTheDocument();
+
+ // Work started against the new source still lands normally.
+ fireEvent.change(input, {target: {value: 'ba'}});
+ await waitFor(() =>
+ expect(screen.getByText('Banana')).toBeInTheDocument(),
+ );
+ });
});
it('renders with label', () => {