Skip to content

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

TypeScript

fix(CommandPalette): handle rejected search and bootstrap (#10675)

Yusuf Suat Babacan824e71ea0123
diff --git a/.changeset/commandpalette-stays-open-with-no-results-when-a-rhjo.md b/.changeset/commandpalette-stays-open-with-no-results-when-a-rhjo.md
new file mode 100644
index 0000000000..d35834aed1
--- /dev/null
+++ b/.changeset/commandpalette-stays-open-with-no-results-when-a-rhjo.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] CommandPalette stays open with no results when a search or bootstrap request rejects
+@Varshavia
diff --git a/packages/core/src/CommandPalette/CommandPalette.test.tsx b/packages/core/src/CommandPalette/CommandPalette.test.tsx
index 5dcf25982b..be419158f6 100644
--- a/packages/core/src/CommandPalette/CommandPalette.test.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.test.tsx
@@ -10,7 +10,7 @@
import {describe, it, expect, vi, beforeEach} from 'vitest';
import {render, screen, waitFor, fireEvent, act} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import {useState} from 'react';
+import {Component, useState, type ReactNode} from 'react';
import {CommandPalette} from './CommandPalette';
import {CommandPaletteInput} from './CommandPaletteInput';
import {getFocusableElements} from '../hooks/useFocusTrap';
@@ -36,6 +36,21 @@ function NestedDismissible({onDismiss}: {onDismiss: () => void}) {
return null;
}
+class TestErrorBoundary extends Component<
+ {children: ReactNode},
+ {hasError: boolean}
+> {
+ state = {hasError: false};
+
+ static getDerivedStateFromError() {
+ return {hasError: true};
+ }
+
+ render(): ReactNode {
+ return this.state.hasError ? <p>Boundary fallback</p> : this.props.children;
+ }
+}
+
// Mock showModal and close since jsdom doesn't implement them
beforeEach(() => {
HTMLDialogElement.prototype.showModal = vi.fn(function (
@@ -740,6 +755,126 @@ describe('CommandPalette', () => {
}
});
+ describe('a rejected search source', () => {
+ const spinner = () => document.querySelector('.astryx-spinner');
+
+ const renderInsideBoundary = (source: SearchSource) =>
+ render(
+ <TestErrorBoundary>
+ <CommandPalette
+ isOpen={true}
+ onOpenChange={() => {}}
+ searchSource={source}
+ emptyBootstrapText="Type to search"
+ emptySearchText="No results"
+ />
+ </TestErrorBoundary>,
+ );
+
+ it('keeps the palette open with no results when bootstrap rejects', async () => {
+ let rejectBootstrap: (error: Error) => void = () => {};
+ renderInsideBoundary({
+ bootstrap: async () =>
+ new Promise<SearchableItem[]>((_, reject) => {
+ rejectBootstrap = reject;
+ }),
+ search: () => [],
+ });
+
+ await act(async () => {
+ rejectBootstrap(new Error('offline'));
+ });
+
+ expect(screen.queryByText('Boundary fallback')).not.toBeInTheDocument();
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ expect(screen.getByText('Type to search')).toBeInTheDocument();
+ expect(spinner()).not.toBeInTheDocument();
+ });
+
+ it('clears the results and ends the busy state when a search rejects', async () => {
+ const rejecters: ((error: Error) => void)[] = [];
+ renderInsideBoundary({
+ bootstrap: () => [{id: 'home', label: 'Home'}],
+ search: async () =>
+ new Promise<SearchableItem[]>((_, reject) => {
+ rejecters.push(reject);
+ }),
+ });
+ await screen.findByText('Home');
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'h'}});
+ await waitFor(() => expect(rejecters).toHaveLength(1));
+ await act(async () => {
+ rejecters[0](new Error('offline'));
+ });
+
+ expect(screen.queryByText('Boundary fallback')).not.toBeInTheDocument();
+ expect(screen.getByRole('combobox')).toHaveValue('h');
+ expect(screen.queryByText('Home')).not.toBeInTheDocument();
+ expect(screen.getByText('No results')).toBeInTheDocument();
+ expect(spinner()).not.toBeInTheDocument();
+ });
+
+ it('clears the results and ends the busy state when a search throws synchronously', async () => {
+ renderInsideBoundary({
+ bootstrap: () => [{id: 'home', label: 'Home'}],
+ search: () => {
+ throw new Error('offline');
+ },
+ });
+ await screen.findByText('Home');
+
+ await act(async () => {
+ fireEvent.change(screen.getByRole('combobox'), {
+ target: {value: 'h'},
+ });
+ });
+
+ expect(screen.queryByText('Boundary fallback')).not.toBeInTheDocument();
+ expect(screen.getByRole('combobox')).toHaveValue('h');
+ expect(screen.queryByText('Home')).not.toBeInTheDocument();
+ expect(screen.getByText('No results')).toBeInTheDocument();
+ expect(spinner()).not.toBeInTheDocument();
+ });
+
+ it('ignores a rejection from a superseded query', async () => {
+ const pending = new Map<
+ string,
+ {
+ resolve: (items: SearchableItem[]) => void;
+ reject: (error: Error) => void;
+ }
+ >();
+ renderInsideBoundary({
+ bootstrap: () => [],
+ search: async query =>
+ new Promise<SearchableItem[]>((resolve, reject) => {
+ pending.set(query, {resolve, reject});
+ }),
+ });
+
+ const input = screen.getByRole('combobox');
+ fireEvent.change(input, {target: {value: 'a'}});
+ await waitFor(() => expect(pending.has('a')).toBe(true));
+ fireEvent.change(input, {target: {value: 'ab'}});
+ await waitFor(() => expect(pending.has('ab')).toBe(true));
+
+ await act(async () => {
+ pending.get('ab')?.resolve([{id: 'about', label: 'About'}]);
+ });
+ await act(async () => {
+ pending.get('a')?.reject(new Error('aborted'));
+ });
+
+ expect(screen.queryByText('Boundary fallback')).not.toBeInTheDocument();
+ expect(await screen.findByText('About')).toBeInTheDocument();
+ expect(screen.getByRole('combobox')).toHaveValue('ab');
+ expect(screen.queryByText('No results')).not.toBeInTheDocument();
+ expect(spinner()).not.toBeInTheDocument();
+ });
+ });
+
describe('screen reader announcements', () => {
const politeRegion = () =>
document.querySelector('[data-astryx-live-region="polite"]');
diff --git a/packages/core/src/CommandPalette/CommandPalette.tsx b/packages/core/src/CommandPalette/CommandPalette.tsx
index da524a2bc6..2ac039583a 100644
--- a/packages/core/src/CommandPalette/CommandPalette.tsx
+++ b/packages/core/src/CommandPalette/CommandPalette.tsx
@@ -434,11 +434,17 @@ export function CommandPalette<T extends SearchableItem = SearchableItem>({
);
}
- const result = isBootstrap
- ? searchSource.bootstrap()
- : searchSource.search(query);
-
- const items = await Promise.resolve(result);
+ let items: T[] = [];
+ try {
+ const result = isBootstrap
+ ? searchSource.bootstrap()
+ : searchSource.search(query);
+
+ items = await Promise.resolve(result);
+ } catch {
+ // A failed request settles as an empty answer. React sends an
+ // uncaught error from this transition to the nearest error boundary.
+ }
if (searchVersionRef.current === version) {
if (!isBootstrap) {