Skip to content

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

TypeScript

fix(PowerSearch): use key-based remount instead of effect to reset edit popover state (#2265)

Andrey Goder7c822dcb3763
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
new file mode 100644
index 0000000000..5fe375840a
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.test.tsx
@@ -0,0 +1,217 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {
+ describe,
+ it,
+ expect,
+ vi,
+ beforeAll,
+ beforeEach,
+ afterAll,
+ afterEach,
+} from 'vitest';
+import {render, screen, fireEvent, act} from '@testing-library/react';
+import React, {useState} from 'react';
+import {XDSPowerSearch} from './XDSPowerSearch';
+import type {PowerSearchConfig, PowerSearchFilter} from './types';
+
+// =============================================================================
+// Test infrastructure
+// =============================================================================
+
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+let rafCallbacks: Array<FrameRequestCallback> = [];
+let rafId = 0;
+
+beforeAll(() => {
+ globalThis.ResizeObserver =
+ MockResizeObserver as unknown as typeof ResizeObserver;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.matches = function (selector: string) {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+beforeEach(() => {
+ rafCallbacks = [];
+ rafId = 0;
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ rafCallbacks.push(cb);
+ return ++rafId;
+ });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+afterAll(() => {
+ HTMLElement.prototype.matches = originalMatches;
+});
+
+function flushRAF() {
+ const cbs = rafCallbacks.splice(0);
+ cbs.forEach(cb => cb(performance.now()));
+}
+
+const testConfig: PowerSearchConfig = {
+ name: 'test',
+ fields: [
+ {
+ key: 'status',
+ label: 'Status',
+ operators: [{key: 'is', label: 'is', value: {type: 'string'}}],
+ },
+ {
+ key: 'priority',
+ label: 'Priority',
+ operators: [{key: 'equals', label: 'equals', value: {type: 'string'}}],
+ },
+ ],
+};
+
+function getEditPopoverText(container: HTMLElement): string {
+ // The edit popover is the one containing the Cancel/Apply buttons
+ const buttons = container.querySelectorAll('button');
+ for (const btn of buttons) {
+ if (btn.textContent === 'Cancel') {
+ const popover = btn.closest('[popover]');
+ return popover?.textContent ?? '';
+ }
+ }
+ return '';
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('XDSPowerSearch', () => {
+ it('edit popover resets state when switching between filter tokens', () => {
+ const filters: PowerSearchFilter[] = [
+ {field: 'status', operator: 'is', value: {type: 'string', value: 'open'}},
+ {
+ field: 'priority',
+ operator: 'equals',
+ value: {type: 'string', value: 'high'},
+ },
+ ];
+
+ function Harness() {
+ const [currentFilters, setCurrentFilters] = useState(filters);
+ return (
+ <XDSPowerSearch
+ config={testConfig}
+ filters={currentFilters}
+ onChange={newFilters => setCurrentFilters([...newFilters])}
+ />
+ );
+ }
+
+ const {container} = render(<Harness />);
+
+ // Both filter tokens should be rendered
+ const statusToken = screen.getByText('Status: is');
+ const priorityToken = screen.getByText('Priority: equals');
+
+ // Click the status token to open its edit popover
+ act(() => {
+ fireEvent.click(statusToken);
+ flushRAF();
+ });
+
+ // The edit popover should show "Status" as the selected field
+ expect(getEditPopoverText(container)).toContain('Status');
+
+ // Close the popover
+ act(() => {
+ fireEvent.click(screen.getByText('Cancel'));
+ flushRAF();
+ });
+
+ // Click the priority token
+ act(() => {
+ fireEvent.click(priorityToken);
+ flushRAF();
+ });
+
+ // The edit popover should now show "Priority", not stale "Status"
+ const popoverText = getEditPopoverText(container);
+ expect(popoverText).toContain('Priority');
+ expect(popoverText).toContain('equals');
+ });
+
+ it('edit popover shows correct filter after removing a preceding filter', () => {
+ const filters: PowerSearchFilter[] = [
+ {field: 'status', operator: 'is', value: {type: 'string', value: 'open'}},
+ {
+ field: 'priority',
+ operator: 'equals',
+ value: {type: 'string', value: 'high'},
+ },
+ ];
+
+ function Harness() {
+ const [currentFilters, setCurrentFilters] = useState(filters);
+ return (
+ <XDSPowerSearch
+ config={testConfig}
+ filters={currentFilters}
+ onChange={newFilters => setCurrentFilters([...newFilters])}
+ />
+ );
+ }
+
+ const {container} = render(<Harness />);
+
+ // Click the status token (index 0) to edit it
+ act(() => {
+ fireEvent.click(screen.getByText('Status: is'));
+ flushRAF();
+ });
+
+ // Delete the status filter via the Delete button in the popover
+ act(() => {
+ fireEvent.click(screen.getByText('Delete'));
+ flushRAF();
+ });
+
+ // Now only the priority filter remains (shifted to index 0)
+ expect(screen.queryByText('Status: is')).toBeNull();
+ const priorityToken = screen.getByText('Priority: equals');
+
+ // Click the priority token (now at index 0 — same index as the deleted filter)
+ act(() => {
+ fireEvent.click(priorityToken);
+ flushRAF();
+ });
+
+ // The edit popover should show "Priority", not stale "Status"
+ const popoverText = getEditPopoverText(container);
+ expect(popoverText).toContain('Priority');
+ expect(popoverText).toContain('equals');
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
index 1a1c5839e9..e65dedb69b 100644
--- a/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchEditPopover.tsx
@@ -594,11 +594,6 @@ export function PowerSearchEditPopover({
useState<PartialFilter>(initialFilter);
const valueEditorRef = useRef<HTMLDivElement>(null);
- // Reset state when filter changes (new popover opened)
- useEffect(() => {
- setPartialFilter(initialFilter);
- }, [initialFilter]);
-
// Focus the first focusable element inside the value editor after mount
useEffect(() => {
const frame = requestAnimationFrame(() => {
@@ -612,7 +607,7 @@ export function PowerSearchEditPopover({
focusable?.focus();
});
return () => cancelAnimationFrame(frame);
- }, [initialFilter]);
+ }, []);
const currentOperator = partialFilter.operator
? config.getOperator(partialFilter.field, partialFilter.operator)
diff --git a/packages/core/src/PowerSearch/XDSPowerSearch.tsx b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
index 0a35a476dc..788758c52e 100644
--- a/packages/core/src/PowerSearch/XDSPowerSearch.tsx
+++ b/packages/core/src/PowerSearch/XDSPowerSearch.tsx
@@ -880,9 +880,15 @@ export function XDSPowerSearch({
const mode = popoverState.type === 'editing' ? 'edit' : 'create';
+ const popoverKey =
+ popoverState.type === 'editing'
+ ? `edit-${popoverState.filterIndex}-${popoverPartialFilter.field}`
+ : `add-${popoverPartialFilter.field}`;
+
if (EditorOverride) {
return (
<EditorOverride
+ key={popoverKey}
config={configProp}
filter={popoverPartialFilter}
mode={mode}
@@ -896,6 +902,7 @@ export function XDSPowerSearch({
return (
<PowerSearchEditPopover
+ key={popoverKey}
config={config}
filter={popoverPartialFilter}
mode={mode}
@@ -907,7 +914,7 @@ export function XDSPowerSearch({
);
}, [
popoverPartialFilter,
- popoverState.type,
+ popoverState,
EditorOverride,
configProp,
config,
diff --git a/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx b/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx
index 1186a23c46..e678566900 100644
--- a/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx
+++ b/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx
@@ -35,6 +35,7 @@ export function XDSPowerSearchFilterEditor({
return (
<PowerSearchEditPopover
+ key={filter.field}
config={config}
filter={filter}
mode={mode}