Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Fix: Keyboard navigation annoyance in command palette (#67317)

github-actions[bot]add89065047a
diff --git a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
index e53d8f78d9d..105cc73500e 100644
--- a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
@@ -8,22 +8,32 @@ import {
setupSearchEndpoints,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
-import { createMockUser } from "metabase-types/api/mocks";
+import type { SearchResult } from "metabase-types/api";
+import {
+ createMockSearchResult,
+ createMockUser,
+} from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
import { Palette } from "./Palette";
const setup = ({
routeProps,
-}: { routeProps?: { disableCommandPalette?: boolean } } = {}) => {
+ searchResults = [],
+}: {
+ routeProps?: { disableCommandPalette?: boolean };
+ searchResults?: SearchResult[];
+} = {}) => {
setupDatabasesEndpoints([]);
- setupSearchEndpoints([]);
+ setupSearchEndpoints(searchResults);
setupRecentViewsEndpoints([]);
renderWithProviders(<Route path="/" component={Palette} {...routeProps} />, {
withKBar: true,
withRouter: true,
storeInitialState: createMockState({
- currentUser: createMockUser(),
+ currentUser: createMockUser({
+ permissions: { can_create_queries: true },
+ }),
}),
});
};
@@ -78,4 +88,29 @@ describe("command palette", () => {
?.request?.json(),
).toEqual({ value: "auto" });
});
+
+ it("should preserve user navigation selection when search results load", async () => {
+ const getSelectedOption = () =>
+ screen
+ .getAllByRole("option")
+ .find((option) => option.getAttribute("aria-selected") === "true");
+
+ setup({
+ searchResults: [createMockSearchResult({ name: "Metric search result" })],
+ });
+
+ await userEvent.keyboard("[ControlLeft>]k");
+ await screen.findByTestId("command-palette");
+ const input = await screen.findByPlaceholderText(/search for anything/i);
+ await userEvent.type(input, "metric");
+
+ await screen.findByText("Loading...");
+ expect(getSelectedOption()?.textContent).toBe("New metric");
+
+ await userEvent.keyboard("{ArrowDown}");
+ expect(getSelectedOption()?.textContent).toBe("Browse metrics");
+
+ await screen.findByText("Metric search result");
+ expect(getSelectedOption()?.textContent).toBe("Browse metrics");
+ });
});
diff --git a/frontend/src/metabase/palette/components/PaletteResultsList.tsx b/frontend/src/metabase/palette/components/PaletteResultsList.tsx
index 14243a9ec71..b440c6f9799 100644
--- a/frontend/src/metabase/palette/components/PaletteResultsList.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultsList.tsx
@@ -42,6 +42,8 @@ export const PaletteResultList = (props: PaletteResultListProps) => {
const itemsRef = useRef(props.items);
itemsRef.current = props.items;
+ const hasUserInteractedRef = useRef(false);
+
const { query, search, currentRootActionId, activeIndex, options } = useKBar(
(state) => ({
search: state.searchQuery,
@@ -58,6 +60,7 @@ export const PaletteResultList = (props: PaletteResultListProps) => {
if (event.key === "ArrowUp" || (event.ctrlKey && event.key === "p")) {
event.preventDefault();
event.stopPropagation();
+ hasUserInteractedRef.current = true;
query.setActiveIndex((index) => {
return navigateActionIndex(itemsRef.current, index, -1);
});
@@ -67,6 +70,7 @@ export const PaletteResultList = (props: PaletteResultListProps) => {
) {
event.preventDefault();
event.stopPropagation();
+ hasUserInteractedRef.current = true;
query.setActiveIndex((index) => {
return navigateActionIndex(itemsRef.current, index, 1);
});
@@ -113,18 +117,22 @@ export const PaletteResultList = (props: PaletteResultListProps) => {
}
}, [activeIndex]);
+ // Reset interaction tracking when search changes
+ useEffect(() => {
+ hasUserInteractedRef.current = false;
+ }, [search]);
+
useEffect(() => {
- // TODO(tim): fix scenario where async actions load in
- // and active index is reset to the first item. i.e. when
- // users register actions and bust the `useRegisterActions`
- // cache, we won't want to reset their active index as they
- // are navigating the list.
- query.setActiveIndex(
- // avoid setting active index on a group
- typeof props.items[START_INDEX] === "string"
- ? START_INDEX + 1
- : START_INDEX,
- );
+ // Only auto-set the active index if the user hasn't interacted yet.
+ // This prevents resetting their selection when async search results load in.
+ if (!hasUserInteractedRef.current) {
+ query.setActiveIndex(
+ // avoid setting active index on a group
+ typeof props.items[START_INDEX] === "string"
+ ? START_INDEX + 1
+ : START_INDEX,
+ );
+ }
}, [search, currentRootActionId, props.items, query]);
const execute = useCallback(
@@ -166,9 +174,16 @@ export const PaletteResultList = (props: PaletteResultListProps) => {
{props.items.map((item, index) => {
const handlers = typeof item !== "string" &&
item.disabled !== true && {
- onPointerMove: () =>
- activeIndex !== index && query.setActiveIndex(index),
- onPointerDown: () => query.setActiveIndex(index),
+ onPointerMove: () => {
+ if (activeIndex !== index) {
+ hasUserInteractedRef.current = true;
+ query.setActiveIndex(index);
+ }
+ },
+ onPointerDown: () => {
+ hasUserInteractedRef.current = true;
+ query.setActiveIndex(index);
+ },
onClick: (e: MouseEvent) => execute(item, e),
};
const active = index === activeIndex;
diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
index eb109571978..88221318a14 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
@@ -224,7 +224,7 @@ export const useCommandPaletteBasicActions = ({
},
{
id: "navigate-browse-metric",
- name: t`Browse Metrics`,
+ name: t`Browse metrics`,
section: "basic",
icon: "metric",
perform: () => {