Skip to content

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

Preserve search relevance order for command palette actions (#76146)

Oleh K7e10ccb93894
diff --git a/e2e/test/scenarios/onboarding/command-palette.cy.spec.js b/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
index 1a2188e49f3..b6f408b3c99 100644
--- a/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
+++ b/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
@@ -160,6 +160,8 @@ describe("command palette", () => {
.should("not.exist");
H.commandPalette().findByText("No results for “New”").should("be.visible");
+ // Every "New …" action matches "New" equally, so the default order applies
+ // and "New question" is first and selected by default.
H.commandPalette()
.findByRole("option", { name: "New question" })
.should("have.attr", "aria-selected", "true");
@@ -167,7 +169,7 @@ describe("command palette", () => {
cy.wait(100); // pressing page down too fast does nothing
H.pressPageDown();
H.commandPalette()
- .findByRole("option", { name: "New collection" })
+ .findByRole("option", { name: "New model" })
.should("have.attr", "aria-selected", "true");
H.pressPageDown();
@@ -177,7 +179,7 @@ describe("command palette", () => {
H.pressPageUp();
H.commandPalette()
- .findByRole("option", { name: "New collection" })
+ .findByRole("option", { name: "New model" })
.should("have.attr", "aria-selected", "true");
H.pressPageUp();
diff --git a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
index 094e61b92dc..a5a7a5a40f1 100644
--- a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
@@ -155,13 +155,39 @@ describe("command palette", () => {
await userEvent.type(input, "metric");
await screen.findByText("Loading...");
- expect(getSelectedOption()?.textContent).toBe("New metric");
+ expect(getSelectedOption()?.textContent).toBe("Browse metrics");
await userEvent.keyboard("{ArrowDown}");
- expect(getSelectedOption()?.textContent).toBe("Browse metrics");
+ expect(getSelectedOption()?.textContent).toBe("New metric");
await screen.findByText("Metric search result");
- expect(getSelectedOption()?.textContent).toBe("Browse metrics");
+ expect(getSelectedOption()?.textContent).toBe("New metric");
+ });
+
+ it("should rank the most relevant action first", async () => {
+ const getSelectedOption = () =>
+ screen
+ .getAllByRole("option")
+ .find((option) => option.getAttribute("aria-selected") === "true");
+
+ setup();
+ await userEvent.keyboard("[ControlLeft>]k");
+ await screen.findByTestId("command-palette");
+ const input = await screen.findByPlaceholderText(/search for anything/i);
+
+ // Every "New …" action matches "New" equally, so the default order wins and
+ // "New question" comes first.
+ await userEvent.type(input, "New");
+ await waitFor(() =>
+ expect(getSelectedOption()?.textContent).toBe("New question"),
+ );
+
+ // "New c" is a stronger match for "New collection", which should now win
+ // over the default order (metabase#76055).
+ await userEvent.type(input, " c");
+ await waitFor(() =>
+ expect(getSelectedOption()?.textContent).toBe("New collection"),
+ );
});
it("should initialize the search input from the search URL query (#71248)", async () => {
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
index 89bf9e39027..0e1bedc5d36 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-oss.unit.spec.tsx
@@ -26,8 +26,8 @@ describe("PaletteResults", () => {
it("should show actions when there is a search query", async () => {
setup({ query: "new" });
expect(await screen.findByText("New question")).toBeInTheDocument();
- expect(await screen.findByText("New SQL query")).toBeInTheDocument();
expect(await screen.findByText("New dashboard")).toBeInTheDocument();
+ expect(await screen.findByText("New collection")).toBeInTheDocument();
expect(await screen.findByText("Results")).toBeInTheDocument();
});
diff --git a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
index 571d7ec5ab9..c53ca3d527a 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPaletteBasicActions.tsx
@@ -33,6 +33,12 @@ import {
useRegisterShortcut,
} from "./useRegisterShortcut";
+/**
+ * Default ordering for the basic actions. kbar ranks matches by search
+ * relevance; we use this order only to break ties between equally-relevant
+ * matches (e.g. typing "New" matches every "New …" action equally) to keep
+ * them in stable order.
+ */
export const BASIC_ACTION_ORDER = [
"create-new-question",
"create-new-native-query",
@@ -54,6 +60,17 @@ export const BASIC_ACTION_ORDER = [
"navigate-browse-metric",
];
+// Small enough that it only orders actions whose relevance scores are equal,
+// without ever overriding a meaningfully better match.
+const PRIORITY_EPSILON = 0.0001;
+
+const getActionPriority = (id: string) => {
+ const index = BASIC_ACTION_ORDER.indexOf(id);
+ return index === -1
+ ? 0
+ : (BASIC_ACTION_ORDER.length - index) * PRIORITY_EPSILON;
+};
+
export const useCommandPaletteBasicActions = ({
isLoggedIn,
...props
@@ -222,8 +239,7 @@ export const useCommandPaletteBasicActions = ({
id: "navigate-embed-js",
section: "basic",
icon: "embed",
- keywords:
- "embed flow, new embed, embed js, modular embedding, guest embed",
+ keywords: "embed flow, embed js, modular embedding, guest embed",
perform: () =>
openNewModalWithProps({
id: "embed",
@@ -297,7 +313,10 @@ export const useCommandPaletteBasicActions = ({
},
];
- return [...actions, ...browseActions];
+ return [...actions, ...browseActions].map((action) => ({
+ ...action,
+ priority: getActionPriority(action.id),
+ }));
}, [
dispatch,
hasDataAccess,
diff --git a/frontend/src/metabase/palette/shortcuts/global.ts b/frontend/src/metabase/palette/shortcuts/global.ts
index 1728aa0281d..f553de3a7e0 100644
--- a/frontend/src/metabase/palette/shortcuts/global.ts
+++ b/frontend/src/metabase/palette/shortcuts/global.ts
@@ -16,7 +16,7 @@ export const globalShortcuts = {
return t`Create a native query`;
},
get keywords() {
- return t`add native query, add SQL, create SQL, new SQL`;
+ return t`add native query, add SQL, create SQL`;
},
shortcut: ["c n"],
shortcutGroup: "global" as const,
diff --git a/frontend/src/metabase/palette/utils.ts b/frontend/src/metabase/palette/utils.ts
index ebce3751d7f..df29c0a264a 100644
--- a/frontend/src/metabase/palette/utils.ts
+++ b/frontend/src/metabase/palette/utils.ts
@@ -5,16 +5,8 @@ import _ from "underscore";
import type { ColorName } from "metabase/ui/colors/types";
import type { IconName, RecentItem } from "metabase-types/api";
-import { BASIC_ACTION_ORDER } from "./hooks/useCommandPaletteBasicActions";
import type { PaletteActionImpl } from "./types";
-const BASIC_ACTION_ORDER_BY_NAME = BASIC_ACTION_ORDER.reduce<
- Record<string, number>
->((acc, actionName, index) => {
- acc[actionName] = index;
- return acc;
-}, {});
-
export const processResults = (
results: (string | PaletteActionImpl)[],
hasSearchTerm: boolean,
@@ -24,11 +16,7 @@ export const processResults = (
"section",
);
- const actions = processSection(
- t`Actions`,
- groupedResults["basic"],
- BASIC_ACTION_ORDER_BY_NAME,
- );
+ const actions = processSection(t`Actions`, groupedResults["basic"]);
const search = processSection(t`Results`, groupedResults["search"]);
const recent = processSection(t`Recents`, groupedResults["recent"]);
const admin = processSection(t`Admin`, groupedResults["admin"]);
@@ -51,18 +39,8 @@ export const processResults = (
export const processSection = (
sectionName: string,
items?: PaletteActionImpl[],
- sortOrder?: Record<string, number>,
) => {
if (items && items.length > 0) {
- if (sortOrder) {
- const sortedItems = [...items].sort((a, b) => {
- const aOrder = sortOrder[a.id] ?? Number.MAX_SAFE_INTEGER;
- const bOrder = sortOrder[b.id] ?? Number.MAX_SAFE_INTEGER;
- return aOrder - bOrder;
- });
-
- return [sectionName, ...sortedItems];
- }
return [sectionName, ...items];
} else {
return [];
diff --git a/frontend/src/metabase/palette/utils.unit.spec.ts b/frontend/src/metabase/palette/utils.unit.spec.ts
index f534a4b70e1..c73987c34ca 100644
--- a/frontend/src/metabase/palette/utils.unit.spec.ts
+++ b/frontend/src/metabase/palette/utils.unit.spec.ts
@@ -125,55 +125,25 @@ describe("command palette utils", () => {
expect(result).toHaveLength(0);
});
- it("should sort basic actions according to their order of registration", () => {
- // Random order of basic actions
- const actionIds = [
- "navigate-embed-js",
- "create-new-question",
- "navigate-trash",
- "create-new-metric",
- "navigate-home",
- "create-new-native-query",
- "navigate-browse-database",
- "create-new-dashboard",
- "navigate-user-settings",
+ it("should preserve the relevance order kbar computed for basic actions", () => {
+ // kbar returns basic actions already sorted by search relevance. For a
+ // query like "New c", "New collection" should rank first, so we must not
+ // re-sort by a static registration order (metabase#76055).
+ const relevanceOrderedIds = [
"create-new-collection",
- "navigate-browse-model",
- "download-diagnostics",
+ "create-new-native-query",
"create-new-document",
- "navigate-admin-settings",
- "navigate-personal-collection",
"create-new-model",
- "navigate-browse-metric",
];
- const actionsList = actionIds.map((id) =>
+ const actionsList = relevanceOrderedIds.map((id) =>
createMockAction({ id, name: id }),
);
const result = processResults(actionsList, true);
expect(result).toEqual([
"Actions",
- createMockAction({
- id: "create-new-question",
- name: "create-new-question",
- }),
- createMockAction({
- id: "create-new-native-query",
- name: "create-new-native-query",
- }),
- createMockAction({
- id: "create-new-dashboard",
- name: "create-new-dashboard",
- }),
- createMockAction({
- id: "create-new-document",
- name: "create-new-document",
- }),
- createMockAction({
- id: "create-new-collection",
- name: "create-new-collection",
- }),
+ ...relevanceOrderedIds.map((id) => createMockAction({ id, name: id })),
]);
});
});