Skip to content

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

Command palette and search modal revamp (#64364)

Uladzimir Havenchyk7c1f6a0e5fcf
diff --git a/e2e/support/helpers/e2e-command-palette-helpers.js b/e2e/support/helpers/e2e-command-palette-helpers.js
index 0b4c2e72a60..602c60a7a7b 100644
--- a/e2e/support/helpers/e2e-command-palette-helpers.js
+++ b/e2e/support/helpers/e2e-command-palette-helpers.js
@@ -21,7 +21,7 @@ export const pressHome = () => cy.realPress("{home}");
export const pressEnd = () => cy.realPress("{end}");
export const commandPaletteInput = () =>
- cy.findByPlaceholderText("Search for anything or jump somewhere…");
+ cy.findByPlaceholderText("Search for anything…");
export const commandPaletteSearch = (query, viewAll = true) => {
cy.intercept("GET", "/api/search?q=*").as("paletteSearch");
@@ -31,7 +31,7 @@ export const commandPaletteSearch = (query, viewAll = true) => {
if (viewAll) {
commandPalette()
- .findByRole("option", { name: /View and filter/ })
+ .findByRole("link", { name: /View and filter/ })
.click();
}
};
diff --git a/e2e/support/helpers/e2e-metabot-helpers.ts b/e2e/support/helpers/e2e-metabot-helpers.ts
index bd67fd318ff..835676a0a34 100644
--- a/e2e/support/helpers/e2e-metabot-helpers.ts
+++ b/e2e/support/helpers/e2e-metabot-helpers.ts
@@ -1,9 +1,5 @@
import type { StaticResponse } from "cypress/types/net-stubbing";
-import {
- commandPaletteAction,
- openCommandPalette,
-} from "./e2e-command-palette-helpers";
import { appBar } from "./e2e-ui-elements-helpers";
export function assertChatVisibility(visibility: "visible" | "not.visible") {
@@ -12,25 +8,12 @@ export function assertChatVisibility(visibility: "visible" | "not.visible") {
);
}
-export function openMetabotViaCommandPalette(assertVisibility = true) {
- if (assertVisibility) {
- assertChatVisibility("not.visible");
- }
-
- openCommandPalette();
- commandPaletteAction("Ask me to do something, or ask me a question").click();
-
- if (assertVisibility) {
- assertChatVisibility("visible");
- }
-}
-
export function openMetabotViaShortcutKey(assertVisibility = true) {
if (assertVisibility) {
assertChatVisibility("not.visible");
}
- cy.get("body").type("{ctrl+b}{cmd+b}");
+ cy.get("body").type("{ctrl+e}{cmd+e}");
if (assertVisibility) {
assertChatVisibility("visible");
@@ -42,7 +25,7 @@ export function closeMetabotViaShortcutKey(assertVisibility = true) {
assertChatVisibility("visible");
}
- cy.get("body").type("{ctrl+b}{cmd+b}");
+ cy.get("body").type("{ctrl+e}{cmd+e}");
if (assertVisibility) {
assertChatVisibility("not.visible");
diff --git a/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts b/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
index e22c9591742..542e6871822 100644
--- a/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
+++ b/e2e/test/scenarios/admin/datamodel/reproductions.cy.spec.ts
@@ -106,7 +106,7 @@ describe("issue 21984", () => {
H.commandPaletteButton().click();
H.commandPalette().within(() => {
- cy.findByText("Recent items").should("not.exist");
+ cy.findByText("Recents").should("not.exist");
});
});
});
diff --git a/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js
index 4a86d40b667..05dc061d19f 100644
--- a/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard-questions.cy.spec.js
@@ -455,7 +455,7 @@ describe("Dashboard > Dashboard Questions", () => {
);
H.commandPalette()
.findByText("Total Orders Dashboard Question")
- .parent()
+ .closest("a")
.findByText(/Orders in a dashboard/)
.should("be.visible");
H.closeCommandPalette();
diff --git a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
index 40c28167947..2c1506aef67 100644
--- a/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
+++ b/e2e/test/scenarios/dashboard/dashboard.cy.spec.js
@@ -218,7 +218,7 @@ describe("scenarios > dashboard", () => {
H.commandPaletteButton().click();
H.commandPalette().within(() => {
- cy.findByText("Recent items").should("exist");
+ cy.findByText("Recents").should("exist");
cy.findByRole("option", { name: "Orders in a dashboard" }).click();
});
diff --git a/e2e/test/scenarios/documents/comments.cy.spec.ts b/e2e/test/scenarios/documents/comments.cy.spec.ts
index 7903051e010..2e8972fe54e 100644
--- a/e2e/test/scenarios/documents/comments.cy.spec.ts
+++ b/e2e/test/scenarios/documents/comments.cy.spec.ts
@@ -645,7 +645,7 @@ H.describeWithSnowplowEE("document comments", () => {
cy.realType("bold italic strike code");
selectCharactersLeft("code".length);
- cy.realPress([META_KEY, "E"]);
+ cy.realPress([META_KEY, "e"]);
cy.realPress("ArrowLeft");
cy.realPress("ArrowLeft");
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.ts
index e55bbc1e4bf..3d16359e536 100644
--- a/e2e/test/scenarios/documents/documents.cy.spec.ts
+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts
@@ -327,6 +327,7 @@ H.describeWithSnowplowEE("documents", () => {
const originalText = "Lorem Ipsum and some more words";
const originalExact = new RegExp(`^${originalText}$`);
cy.get("@documentId").then((id) => cy.visit(`/document/${id}`));
+ cy.findByTestId("document-card-embed").should("contain", "37.65"); // wait for data loading
H.documentContent().contains(originalExact).click();
const modification = " etc.";
diff --git a/e2e/test/scenarios/metabot/metabot.cy.spec.ts b/e2e/test/scenarios/metabot/metabot.cy.spec.ts
index 7f3fda30ae9..f2aa20bf61b 100644
--- a/e2e/test/scenarios/metabot/metabot.cy.spec.ts
+++ b/e2e/test/scenarios/metabot/metabot.cy.spec.ts
@@ -196,14 +196,7 @@ d:{"finishReason":"stop","usage":{"promptTokens":4916,"completionTokens":8}}`,
H.openMetabotViaSearchButton();
H.expectUnstructuredSnowplowEvent({
event: "metabot_chat_opened",
- triggered_from: "search",
- });
- H.closeMetabotViaCloseButton();
-
- H.openMetabotViaCommandPalette();
- H.expectUnstructuredSnowplowEvent({
- event: "metabot_chat_opened",
- triggered_from: "command_palette",
+ triggered_from: "header",
});
H.closeMetabotViaCloseButton();
});
diff --git a/e2e/test/scenarios/onboarding/command-palette.cy.spec.js b/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
index eb2834e620b..3f450fd181c 100644
--- a/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
+++ b/e2e/test/scenarios/onboarding/command-palette.cy.spec.js
@@ -62,7 +62,7 @@ describe("command palette", () => {
cy.request(`/api/dashboard/${ORDERS_DASHBOARD_ID}`);
cy.visit("/");
- cy.findByRole("button", { name: /Search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
H.commandPalette().should("be.visible");
cy.findByRole("option", { name: "Orders in a dashboard" }).should(
"have.attr",
@@ -77,12 +77,12 @@ describe("command palette", () => {
H.commandPalette().within(() => {
H.commandPaletteInput().should("exist");
- cy.log("limit to 5 basic actions");
- cy.findByText("New question");
- cy.findByText("New SQL query");
- cy.findByText("New dashboard");
- cy.findByText("New collection");
- cy.findByText("New model");
+ cy.log("does not show actions if there is no search query");
+ cy.findByText("New question").should("not.exist");
+ cy.findByText("New SQL query").should("not.exist");
+ cy.findByText("New dashboard").should("not.exist");
+ cy.findByText("New collection").should("not.exist");
+ cy.findByText("New model").should("not.exist");
cy.findByText("New metric").should("not.exist");
cy.log("Should show recent items");
@@ -144,16 +144,30 @@ describe("command palette", () => {
.findByRole("option", { name: "Orders in a dashboard" })
.should("have.attr", "aria-selected", "true");
- H.pressPageDown();
+ H.commandPaletteInput().type("New");
+ H.commandPalette()
+ .findByText(/loading/i)
+ .should("not.exist");
+ H.commandPalette().findByText("No results for “New”").should("be.visible");
+
+ H.commandPalette()
+ .findByRole("option", { name: "New question" })
+ .should("have.attr", "aria-selected", "true");
+ cy.wait(100); // pressing page down too fast does nothing
+ H.pressPageDown();
H.commandPalette()
- .findByRole("option", { name: "New dashboard" })
+ .findByRole("option", { name: "New metric" })
.should("have.attr", "aria-selected", "true");
H.pressPageDown();
+ H.commandPalette()
+ .findByRole("option", { name: 'Search documentation for "New"' })
+ .should("have.attr", "aria-selected", "true");
+ H.pressPageUp();
H.commandPalette()
- .findByRole("option", { name: "New model" })
+ .findByRole("option", { name: "New metric" })
.should("have.attr", "aria-selected", "true");
H.pressPageUp();
@@ -162,21 +176,20 @@ describe("command palette", () => {
.should("have.attr", "aria-selected", "true");
H.pressEnd();
-
H.commandPalette()
- .findByRole("option", { name: "New model" })
+ .findByRole("option", { name: 'Search documentation for "New"' })
.should("have.attr", "aria-selected", "true");
H.pressHome();
H.commandPalette()
- .findByRole("option", { name: "Orders in a dashboard" })
+ .findByRole("option", { name: "New question" })
.should("have.attr", "aria-selected", "true");
});
it("should display search results in the order returned by the API", () => {
cy.visit("/");
- cy.findByRole("button", { name: /Search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
cy.intercept("/api/search?*").as("searchData");
H.commandPalette().within(() => {
@@ -187,12 +200,13 @@ describe("command palette", () => {
cy.get("@searchData").then(({ response }) => {
const results = response.body.data;
- results.forEach((result, index) => {
- // eslint-disable-next-line no-unsafe-element-filtering
- cy.findAllByRole("option")
- .eq(index + 2)
- .should("contain.text", result.name);
- });
+ cy.findAllByRole("option")
+ // filter out unrelated items, keep only options with data
+ .invoke("slice", 1, -2)
+ .should("have.length", results.length)
+ .each(($option, index) => {
+ cy.wrap($option).should("contain", results[index].name);
+ });
});
});
});
@@ -368,7 +382,7 @@ describe("command palette", () => {
it("Should have a new metric item", () => {
cy.visit("/");
- cy.findByRole("button", { name: /Search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
H.commandPalette().within(() => {
H.commandPaletteInput().should("exist").type("Me");
@@ -380,7 +394,7 @@ describe("command palette", () => {
it("should show the 'Report an issue' command palette item", () => {
cy.visit("/");
- cy.findByRole("button", { name: /Search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
H.commandPalette().within(() => {
H.commandPaletteInput().should("exist").type("Issue");
@@ -395,7 +409,7 @@ describe("command palette", () => {
it("should show the 'Create a new embed' command palette item", () => {
cy.visit("/");
- cy.findByRole("button", { name: /search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
H.commandPalette().within(() => {
H.commandPaletteInput().should("exist").type("new embed");
@@ -405,8 +419,9 @@ describe("command palette", () => {
it("should have a 'New document' item", () => {
cy.visit("/");
- cy.findByRole("button", { name: /search/ }).click();
+ cy.findByRole("button", { name: /search/i }).click();
H.commandPalette().within(() => {
+ H.commandPaletteInput().should("be.visible").type("new document");
cy.findByText("New document").should("be.visible").click();
cy.location("pathname").should("eq", "/document/new");
});
@@ -455,6 +470,7 @@ H.describeWithSnowplow("shortcuts", { tags: ["@actions"] }, () => {
event_detail: "create-new-collection",
});
H.openCommandPalette();
+ H.commandPaletteInput().should("be.visible").type("new dashboard");
H.commandPalette().findByRole("option", { name: "New dashboard" }).click();
cy.findByRole("dialog", { name: /dashboard/i }).should("exist");
cy.realPress("Escape");
diff --git a/enterprise/frontend/src/metabase-enterprise/comments/components/CommentEditor/CommentEditor.tsx b/enterprise/frontend/src/metabase-enterprise/comments/components/CommentEditor/CommentEditor.tsx
index fdb47410e2f..546d96e1f88 100644
--- a/enterprise/frontend/src/metabase-enterprise/comments/components/CommentEditor/CommentEditor.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/comments/components/CommentEditor/CommentEditor.tsx
@@ -155,7 +155,9 @@ export const CommentEditor = ({
editor.commands.blur();
}
};
- const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
+ const handleKeyDownCapture: KeyboardEventHandler<HTMLDivElement> = (
+ event,
+ ) => {
if (readonly) {
return;
}
@@ -166,6 +168,18 @@ export const CommentEditor = ({
}
};
+ // we have two different handlers and it is fine. handleKeyDownCapture works
+ // well with submitting data handleKeyDown is needed to prevent event to
+ // bubble to the global listener
+ const handleKeyDown: KeyboardEventHandler<HTMLDivElement> = (event) => {
+ // shortcut is used for code block extension, conflicts with global shortcut
+ // for opening metabot sidebar we have to stop event propagation as other
+ // variants didn't work or uglier that this solution
+ if ((event.ctrlKey || event.metaKey) && event.key === "e") {
+ event.stopPropagation();
+ }
+ };
+
return (
<Flex
align="center"
@@ -173,7 +187,8 @@ export const CommentEditor = ({
[S.readonly]: readonly,
[S.active]: active,
})}
- onKeyDownCapture={handleKeyDown}
+ onKeyDownCapture={handleKeyDownCapture}
+ onKeyDown={handleKeyDown}
>
<Box className={S.contentWrapper}>
<EditorContent
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/analytics.ts b/enterprise/frontend/src/metabase-enterprise/metabot/analytics.ts
index 9255f9eac6a..085d27c3c08 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/analytics.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/analytics.ts
@@ -1,7 +1,7 @@
import { trackSimpleEvent } from "metabase/lib/analytics";
export const trackMetabotChatOpened = (
- origin: "search" | "command_palette" | "keyboard_shortcut" | "native_editor",
+ origin: "header" | "command_palette" | "keyboard_shortcut" | "native_editor",
) => {
trackSimpleEvent({
event: "metabot_chat_opened",
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
index 414e6bfa222..ebc3fce7eb6 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/Metabot.tsx
@@ -19,7 +19,7 @@ export const MetabotAuthenticated = ({ hide }: MetabotProps) => {
useEffect(() => {
return tinykeys(window, {
- "$mod+b": (e) => {
+ "$mod+e": (e) => {
e.preventDefault(); // prevent FF from opening bookmark menu
if (!visible) {
trackMetabotChatOpened("keyboard_shortcut");
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx
new file mode 100644
index 00000000000..d4a629c4763
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAppBarButton.tsx
@@ -0,0 +1,47 @@
+import { t } from "ttag";
+
+import { METAKEY } from "metabase/lib/browser";
+import { ActionIcon, type ActionIconProps, Icon, Tooltip } from "metabase/ui";
+import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
+
+import { trackMetabotChatOpened } from "../analytics";
+
+interface MetabotAppBarButtonProps extends ActionIconProps {
+ className?: string;
+}
+
+export function MetabotAppBarButton({
+ className,
+ ...rest
+}: MetabotAppBarButtonProps) {
+ const metabot = useMetabotAgent();
+
+ const handleClick = () => {
+ if (!metabot.visible) {
+ trackMetabotChatOpened("header");
+ }
+
+ metabot.setVisible(!metabot.visible);
+ };
+
+ const label = t`Chat with Metabot (${METAKEY}+E)`;
+
+ return (
+ <Tooltip label={label}>
+ <ActionIcon
+ className={className}
+ variant="subtle"
+ c="var(--mb-color-text-primary)"
+ bd="1px solid var(--mb-color-border)"
+ p="sm"
+ h="2.25rem"
+ w="2.25rem"
+ aria-label={label}
+ onClick={handleClick}
+ {...rest}
+ >
+ <Icon name="metabot" />
+ </ActionIcon>
+ </Tooltip>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/MetabotSearchButton.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/MetabotSearchButton.tsx
deleted file mode 100644
index 5f91c5c9efd..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/MetabotSearchButton.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { VisualState, useKBar } from "kbar";
-import { useCallback } from "react";
-import { c, t } from "ttag";
-
-import useIsSmallScreen from "metabase/common/hooks/use-is-small-screen";
-import { METAKEY } from "metabase/lib/browser";
-import S from "metabase/nav/components/search/SearchButton/SearchButton.module.css";
-import { Button, Flex, Icon, Text, Tooltip, UnstyledButton } from "metabase/ui";
-import { useMetabotAgent } from "metabase-enterprise/metabot/hooks";
-
-import { trackMetabotChatOpened } from "../../analytics";
-
-export const MetabotSearchButton = () => {
- const kbar = useKBar();
- const metabot = useMetabotAgent();
-
- const { setVisualState } = kbar.query;
-
- const handleClick = useCallback(() => {
- setVisualState(VisualState.showing);
- }, [setVisualState]);
-
- const isSmallScreen = useIsSmallScreen();
-
- const label = c("'Search' here is a verb").t`Ask Metabot or search`;
-
- const tooltipMessage = metabot.visible ? t`Close Metabot` : t`Open Metabot`;
-
- if (isSmallScreen) {
- return (
- <Button
- h="36px"
- leftSection={<Icon name="metabot" />}
- variant="subtle"
- onClick={handleClick}
- color="text-medium"
- aria-label={label}
- />
- );
- }
-
- return (
- <Flex
- h="2.25rem"
- miw="15rem"
- justify="flex-start"
- align="center"
- style={{
- borderRadius: "var(--mantine-radius-default)",
- border: "1px solid var(--mb-color-border)",
- }}
- >
- <UnstyledButton
- className={S.iconButton}
- aria-label={t`Metabot`}
- onClick={() => {
- if (!metabot.visible) {
- trackMetabotChatOpened("search");
- }
-
- metabot.setVisible(!metabot.visible);
- }}
- >
- <Tooltip
- offset={{ mainAxis: 20 }}
- label={`${tooltipMessage} (${METAKEY}+b)`}
- >
- <Icon name="metabot" h="1rem" />
- </Tooltip>
- </UnstyledButton>
- <UnstyledButton
- className={S.searchTextButton}
- aria-label={label}
- onClick={handleClick}
- >
- <Text>{label}</Text>
- <Text className={S.shortcutText}>{`${METAKEY}+k`}</Text>
- </UnstyledButton>
- </Flex>
- );
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/index.tsx
deleted file mode 100644
index 3f866f298b2..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotSearchButton/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./MetabotSearchButton";
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index b01161452cb..e773923584f 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -1,23 +1,19 @@
-import { useMemo } from "react";
import { IndexRoute } from "react-router";
import { t } from "ttag";
import { createAdminRouteGuard } from "metabase/admin/utils";
import { AdminSettingsLayout } from "metabase/common/components/AdminLayout/AdminSettingsLayout";
import { Route } from "metabase/hoc/Title";
-import type { PaletteAction } from "metabase/palette/types";
import { PLUGIN_METABOT, PLUGIN_REDUCERS } from "metabase/plugins";
import { MetabotPurchasePage } from "metabase-enterprise/metabot/components/MetabotAdmin/MetabotPurchasePage";
import { hasPremiumFeature } from "metabase-enterprise/settings";
-import { trackMetabotChatOpened } from "./analytics";
import { Metabot } from "./components/Metabot";
import { MetabotAdminPage } from "./components/MetabotAdmin/MetabotAdminPage";
+import { MetabotAppBarButton } from "./components/MetabotAppBarButton";
import { getMetabotQuickLinks } from "./components/MetabotQuickLinks";
-import { MetabotSearchButton } from "./components/MetabotSearchButton";
import { MetabotToggleButton } from "./components/MetabotToggleButton";
import { MetabotContext, MetabotProvider, defaultContext } from "./context";
-import { useMetabotAgent } from "./hooks";
import { getMetabotVisible, metabotReducer } from "./state";
if (hasPremiumFeature("metabot_v3")) {
@@ -50,33 +46,9 @@ if (hasPremiumFeature("metabot_v3")) {
// TODO: make enterprise store + fix type
PLUGIN_METABOT.getMetabotVisible =
getMetabotVisible as unknown as typeof PLUGIN_METABOT.getMetabotVisible;
- PLUGIN_METABOT.useMetabotPalletteActions = (searchText: string) => {
- const { startNewConversation, visible } = useMetabotAgent();
- return useMemo(() => {
- const ret: PaletteAction[] = [
- {
- id: "initialize_metabot",
- name: searchText
- ? t`Ask Metabot, "${searchText}"`
- : t`Ask me to do something, or ask me a question`,
- section: "metabot",
- keywords: searchText,
- icon: "metabot",
- perform: () => {
- if (!visible) {
- trackMetabotChatOpened("command_palette");
- }
- startNewConversation(searchText);
- },
- },
- ];
- return ret;
- }, [searchText, startNewConversation, visible]);
- };
-
- PLUGIN_METABOT.SearchButton = MetabotSearchButton;
PLUGIN_METABOT.MetabotToggleButton = MetabotToggleButton;
+ PLUGIN_METABOT.MetabotAppBarButton = MetabotAppBarButton;
PLUGIN_REDUCERS.metabotPlugin = metabotReducer;
} else if (hasPremiumFeature("offer_metabase_ai")) {
diff --git a/frontend/src/metabase-types/analytics/event.ts b/frontend/src/metabase-types/analytics/event.ts
index 361d03cfb7b..de9118cf976 100644
--- a/frontend/src/metabase-types/analytics/event.ts
+++ b/frontend/src/metabase-types/analytics/event.ts
@@ -372,7 +372,7 @@ export type TableEditingEvent =
export type MetabotChatOpenedEvent = ValidateEvent<{
event: "metabot_chat_opened";
triggered_from:
- | "search"
+ | "header"
| "command_palette"
| "keyboard_shortcut"
| "native_editor";
diff --git a/frontend/src/metabase-types/api/search.ts b/frontend/src/metabase-types/api/search.ts
index f09c5ddc7c0..24e4bd78b54 100644
--- a/frontend/src/metabase-types/api/search.ts
+++ b/frontend/src/metabase-types/api/search.ts
@@ -89,7 +89,7 @@ export interface SearchResult<
table_schema: string | null;
collection_authority_level: "official" | null;
updated_at: string;
- moderated_status: string | null;
+ moderated_status: ModerationReviewStatus | null;
model_id: CardId | null;
model_name: string | null;
model_index_id: number | null;
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.styled.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.styled.tsx
index fb15fb6e7ca..6a3c6d4f844 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.styled.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.styled.tsx
@@ -21,22 +21,6 @@ export const AppBarRoot = styled.div<AppBarRootProps>`
transition: border-bottom-color 200ms ease;
`;
-export const AppBarLeftContainer = styled.div`
- display: flex;
- flex: 1 1 auto;
- align-items: center;
- min-width: 5rem;
-`;
-
-export const AppBarRightContainer = styled.div`
- display: flex;
- flex: 1 1 auto;
- align-items: center;
- gap: 1rem;
- max-width: 32.5rem;
- justify-content: flex-end;
-`;
-
interface AppBarInfoContainerProps {
isVisible?: boolean;
}
@@ -49,7 +33,3 @@ export const AppBarInfoContainer = styled.div<AppBarInfoContainerProps>`
transition: ${(props) =>
props.isVisible ? `opacity 0.5s` : `opacity 0.5s, visibility 0s`};
`;
-
-export const AppBarProfileLinkContainer = styled.div`
- color: var(--mb-color-text-light);
-`;
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
index f10fefec435..5c5a19b8d3d 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
@@ -3,6 +3,7 @@ import { t } from "ttag";
import { Nav as DetailViewNav } from "metabase/detail-view/components";
import { DETAIL_VIEW_PADDING_LEFT } from "metabase/detail-view/constants";
import { PLUGIN_METABOT } from "metabase/plugins";
+import { Box, Flex } from "metabase/ui";
import type { CollectionId } from "metabase-types/api";
import type { DetailViewState } from "metabase-types/store";
@@ -11,14 +12,9 @@ import QuestionLineage from "../../containers/QuestionLineage";
import NewItemButton from "../NewItemButton";
import { ProfileLink } from "../ProfileLink";
import { SearchBar } from "../search/SearchBar";
+import { SearchButton } from "../search/SearchButton/SearchButton";
-import {
- AppBarInfoContainer,
- AppBarLeftContainer,
- AppBarProfileLinkContainer,
- AppBarRightContainer,
- AppBarRoot,
-} from "./AppBarLarge.styled";
+import { AppBarInfoContainer, AppBarRoot } from "./AppBarLarge.styled";
import { AppBarLogo } from "./AppBarLogo";
import { AppBarToggle } from "./AppBarToggle";
@@ -70,7 +66,7 @@ const AppBarLarge = ({
isCommentSidebarOpen
}
>
- <AppBarLeftContainer>
+ <Flex align="center" miw="5rem" flex="1 1 auto">
<AppBarToggle
isNavBarEnabled={isNavBarEnabled}
isNavBarOpen={isNavBarOpen}
@@ -95,22 +91,25 @@ const AppBarLarge = ({
<CollectionBreadcrumbs />
) : null}
</AppBarInfoContainer>
- </AppBarLeftContainer>
+ </Flex>
{(isSearchVisible || isNewButtonVisible || isProfileLinkVisible) && (
- <AppBarRightContainer>
+ <Flex
+ align="center"
+ gap="sm"
+ justify="flex-end"
+ maw="32.5rem"
+ flex="1 1 auto"
+ >
{isSearchVisible &&
- (isEmbeddingIframe ? (
- <SearchBar />
- ) : (
- <PLUGIN_METABOT.SearchButton />
- ))}
+ (isEmbeddingIframe ? <SearchBar /> : <SearchButton mr="md" />)}
{isNewButtonVisible && <NewItemButton collectionId={collectionId} />}
+ {!isEmbeddingIframe && <PLUGIN_METABOT.MetabotAppBarButton />}
{isProfileLinkVisible && (
- <AppBarProfileLinkContainer aria-label={t`Settings menu`}>
+ <Box c="var(--mb-color-text-primary)" aria-label={t`Settings menu`}>
<ProfileLink onLogout={onLogout} />
- </AppBarProfileLinkContainer>
+ </Box>
)}
- </AppBarRightContainer>
+ </Flex>
)}
</AppBarRoot>
);
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.styled.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.styled.tsx
index 94b6ceb1115..418bf728a6a 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.styled.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.styled.tsx
@@ -3,10 +3,6 @@ import styled from "@emotion/styled";
import { APP_BAR_HEIGHT, APP_SUBHEADER_HEIGHT } from "metabase/nav/constants";
-export const AppBarRoot = styled.div`
- background-color: var(--mb-color-bg-white);
-`;
-
interface AppBarHeaderProps {
isSubheaderVisible?: boolean;
}
@@ -33,14 +29,6 @@ export const AppBarSubheader = styled.div<AppBarSubheaderProps>`
props.isNavBarOpen ? "var(--mb-color-border)" : "transparent"};
`;
-export const AppBarMainContainer = styled.div`
- display: flex;
- justify-content: space-between;
- align-items: center;
- gap: 1rem;
- height: 100%;
-`;
-
export const AppBarToggleContainer = styled.div`
flex: 0 0 auto;
`;
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx
index f2ad4f514e7..d743a659167 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx
@@ -3,20 +3,19 @@ import { useCallback, useState } from "react";
import { Nav as DetailViewNav } from "metabase/detail-view/components";
import { SearchBar } from "metabase/nav/components/search/SearchBar";
import { PLUGIN_METABOT } from "metabase/plugins";
-import { Flex } from "metabase/ui";
+import { Box, Flex } from "metabase/ui";
import type { DetailViewState } from "metabase-types/store";
import CollectionBreadcrumbs from "../../containers/CollectionBreadcrumbs";
import QuestionLineage from "../../containers/QuestionLineage";
import { ProfileLink } from "../ProfileLink";
+import { SearchButton } from "../search/SearchButton/SearchButton";
import { AppBarLogo } from "./AppBarLogo";
import {
AppBarHeader,
AppBarLogoContainer,
- AppBarMainContainer,
AppBarProfileLinkContainer,
- AppBarRoot,
AppBarSearchContainer,
AppBarSubheader,
AppBarToggleContainer,
@@ -70,10 +69,10 @@ const AppBarSmall = ({
}, []);
return (
- <AppBarRoot>
+ <Box bg="var(--mb-color-bg-white)">
{isHeaderVisible && (
<AppBarHeader isSubheaderVisible={isSubheaderVisible}>
- <AppBarMainContainer>
+ <Flex justify="space-between" align="center" gap="sm" h="100%">
<AppBarToggleContainer>
<AppBarToggle
isSmallAppBar
@@ -91,16 +90,17 @@ const AppBarSmall = ({
/>
) : (
<Flex justify="end">
- <PLUGIN_METABOT.SearchButton />
+ <SearchButton />
</Flex>
))}
</AppBarSearchContainer>
+ {!isEmbeddingIframe && <PLUGIN_METABOT.MetabotAppBarButton />}
{isProfileLinkVisible && (
<AppBarProfileLinkContainer>
<ProfileLink onLogout={onLogout} />
</AppBarProfileLinkContainer>
)}
- </AppBarMainContainer>
+ </Flex>
<AppBarLogoContainer isVisible={isLogoVisible && !isSearchActive}>
<AppBarLogo
isSmallAppBar
@@ -125,7 +125,7 @@ const AppBarSmall = ({
) : null}
</AppBarSubheader>
)}
- </AppBarRoot>
+ </Box>
);
};
diff --git a/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.jsx b/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.tsx
similarity index 73%
rename from frontend/src/metabase/nav/components/ProfileLink/ProfileLink.jsx
rename to frontend/src/metabase/nav/components/ProfileLink/ProfileLink.tsx
index aa98d143460..015ed62e688 100644
--- a/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.jsx
+++ b/frontend/src/metabase/nav/components/ProfileLink/ProfileLink.tsx
@@ -1,5 +1,4 @@
import cx from "classnames";
-import PropTypes from "prop-types";
import { useState } from "react";
import { t } from "ttag";
import _ from "underscore";
@@ -25,13 +24,15 @@ import {
getApplicationName,
getIsWhiteLabeling,
} from "metabase/selectors/whitelabel";
-import { ActionIcon, Icon, Menu, Tooltip } from "metabase/ui";
+import { ActionIcon, Icon, type IconName, Menu, Tooltip } from "metabase/ui";
+import type { MetabaseInfo } from "metabase-types/api";
+import type { AdminPath, State } from "metabase-types/store";
import { useHelpLink } from "./useHelpLink";
// generate the proper set of list items for the current user
// based on whether they're an admin or not
-const mapStateToProps = (state) => ({
+const mapStateToProps = (state: State) => ({
adminItems: getAdminPaths(state),
canAccessOnboardingPage: getCanAccessOnboardingPage(state),
isNewInstance: getIsNewInstance(state),
@@ -41,23 +42,39 @@ const mapDispatchToProps = {
openDiagnostics,
};
-export default connect(mapStateToProps, mapDispatchToProps)(ProfileLink);
+interface ProfileLinkProps {
+ adminItems: AdminPath[];
+ canAccessOnboardingPage: boolean;
+ isNewInstance: boolean;
+ onLogout: () => void;
+ openDiagnostics: () => void;
+}
+
+interface MenuItem {
+ title?: string;
+ icon?: IconName | null;
+ externalLink?: boolean;
+ link?: string;
+ action?: () => void;
+ separator?: boolean;
+ event?: string;
+}
-function ProfileLink({
+function ProfileLinkInner({
adminItems,
canAccessOnboardingPage,
isNewInstance,
onLogout,
openDiagnostics,
-}) {
- const [modalOpen, setModalOpen] = useState(null);
- const version = useSetting("version");
+}: ProfileLinkProps) {
+ const [modalOpen, setModalOpen] = useState<string | null>(null);
+ const version = useSetting("version") as MetabaseInfo["version"];
const applicationName = useSelector(getApplicationName);
const { tag, date, ...versionExtra } = version;
const helpLink = useHelpLink();
const dispatch = useDispatch();
- const openModal = (modalName) => {
+ const openModal = (modalName: string) => {
setModalOpen(modalName);
};
@@ -65,7 +82,7 @@ function ProfileLink({
setModalOpen(null);
};
- const generateOptionsForUser = () => {
+ const generateOptionsForUser = (): MenuItem[] => {
const showAdminSettingsItem = adminItems?.length > 0;
// If the instance is not new, we remove the link from the sidebar automatically and show it here instead!
@@ -130,7 +147,7 @@ function ProfileLink({
action: () => onLogout(),
event: `Navbar;Profile Dropdown;Logout`,
},
- ].filter(Boolean);
+ ].filter((item) => !!item);
};
// show trademark if application name is not whitelabeled
@@ -140,14 +157,16 @@ function ProfileLink({
const menuItems = generateOptionsForUser();
return (
- <div>
+ <>
<Menu position="bottom-end" shadow="md" width={200}>
<Menu.Target>
<Tooltip label={t`Settings`}>
<ActionIcon
- size="lg"
- variant="subtle"
- c="text-dark"
+ size="2.25rem"
+ p="sm"
+ variant="outline"
+ color="text-dark"
+ bd="1px solid var(--mb-color-border)"
aria-label={t`Settings`}
>
<Icon name="gear" size={16} />
@@ -170,20 +189,48 @@ function ProfileLink({
? ForwardRefLink
: "button";
+ const commonProps = {
+ leftSection: item.icon && <Icon name={item.icon} />,
+ onClick: () => {
+ if (item.action) {
+ item.action();
+ }
+ },
+ };
+
+ if (component === ForwardRefLink && item.link) {
+ return (
+ <Menu.Item<typeof ForwardRefLink>
+ key={item.title}
+ {...commonProps}
+ component={ForwardRefLink}
+ to={item.link}
+ >
+ {item.title}
+ </Menu.Item>
+ );
+ }
+
+ if (component === "a" && item.link) {
+ return (
+ <Menu.Item<"a">
+ key={item.title}
+ {...commonProps}
+ component="a"
+ href={item.link}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {item.title}
+ </Menu.Item>
+ );
+ }
+
return (
- <Menu.Item
+ <Menu.Item<"button">
key={item.title}
- leftSection={item.icon && <Icon name={item.icon} />}
- onClick={() => {
- if (item.action) {
- item.action();
- }
- }}
- component={component}
- href={item.link}
- to={item.link}
- target={item.externalLink ? "_blank" : undefined}
- rel={item.externalLink ? "noopener noreferrer" : undefined}
+ {...commonProps}
+ component="button"
>
{item.title}
</Menu.Item>
@@ -211,11 +258,11 @@ function ProfileLink({
<p className={cx(CS.textMedium, CS.textBold)}>
{t`Built on`} {date}
</p>
- {!/^v\d+\.\d+\.\d+$/.test(tag) && (
+ {tag && !/^v\d+\.\d+\.\d+$/.test(tag) && (
<div>
{_.map(versionExtra, (value, key) => (
<p key={key} className={cx(CS.textMedium, CS.textBold)}>
- {capitalize(key)}: {value}
+ {capitalize(key)}: {String(value)}
</p>
))}
</div>
@@ -247,14 +294,10 @@ function ProfileLink({
{modalOpen === "diagnostic" && (
<ErrorDiagnosticModalWrapper isModalOpen={true} onClose={closeModal} />
)}
- </div>
+ </>
);
}
-ProfileLink.propTypes = {
- adminItems: PropTypes.array,
- canAccessOnboardingPage: PropTypes.bool,
- isNewInstance: PropTypes.bool,
- onLogout: PropTypes.func.isRequired,
- openDiagnostics: PropTypes.func.isRequired,
-};
+const connector = connect(mapStateToProps, mapDispatchToProps);
+
+export const ProfileLink = connector(ProfileLinkInner);
diff --git a/frontend/src/metabase/nav/components/ProfileLink/index.ts b/frontend/src/metabase/nav/components/ProfileLink/index.ts
index 2a9576d8cd8..77459b2f2a7 100644
--- a/frontend/src/metabase/nav/components/ProfileLink/index.ts
+++ b/frontend/src/metabase/nav/components/ProfileLink/index.ts
@@ -1 +1 @@
-export { default as ProfileLink } from "./ProfileLink";
+export { ProfileLink } from "./ProfileLink";
diff --git a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.module.css b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.module.css
index d1d441738c7..1d76e22ef62 100644
--- a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.module.css
+++ b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.module.css
@@ -17,9 +17,14 @@
font-weight: bold;
gap: 0.25rem;
+ &:hover {
+ background-color: var(--mb-color-brand-light);
+ }
+
&:hover .shortcutText {
- color: var(--mb-color-text-light);
+ color: var(--mb-color-text-secondary);
transition: color 100ms ease;
+ background-color: var(--mb-color-background-hover);
}
}
@@ -27,4 +32,10 @@
color: transparent;
user-select: none;
transition: color 350ms ease;
+ border-radius: 2px;
+ height: 1rem;
+ width: 1rem;
+ font-weight: 400;
+ font-size: 12px;
+ line-height: 1rem;
}
diff --git a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
index e3fcd80c382..8fca7dd5f64 100644
--- a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
+++ b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx
@@ -4,9 +4,10 @@ import { t } from "ttag";
import useIsSmallScreen from "metabase/common/hooks/use-is-small-screen";
import { METAKEY } from "metabase/lib/browser";
-import { Button, Icon, Tooltip } from "metabase/ui";
+import S from "metabase/nav/components/search/SearchButton/SearchButton.module.css";
+import { Button, type ButtonProps, Flex, Icon } from "metabase/ui";
-export const SearchButton = () => {
+export const SearchButton = (props: ButtonProps) => {
const kbar = useKBar();
const { setVisualState } = kbar.query;
@@ -27,25 +28,34 @@ export const SearchButton = () => {
aria-label="Search"
/>
);
- } else {
- return (
- <Tooltip label={`${t`Search...`} (${METAKEY}+k)`}>
- <Button
- h="36px"
- w="240px"
- leftSection={<Icon name="search" />}
- onClick={handleClick}
- // TODO: Adjust this with Mantine V7
- styles={{
- inner: {
- justifyContent: "start",
- },
- }}
- aria-label="Search"
- >
- {t`Search`}
- </Button>
- </Tooltip>
- );
}
+
+ return (
+ <Button
+ h="36px"
+ w="240px"
+ c="var(--mb-color-text-light)"
+ leftSection={<Icon name="search" c="var(--mb-color-text-primary)" />}
+ onClick={handleClick}
+ styles={{
+ inner: {
+ width: "100%",
+ },
+ label: {
+ display: "inline-flex",
+ justifyContent: "space-between",
+ width: "100%",
+ },
+ }}
+ className={S.searchTextButton}
+ aria-label="Search"
+ {...props}
+ >
+ <span>{t`Search...`}</span>
+ <Flex gap="xs">
+ <span className={S.shortcutText}>{METAKEY}</span>
+ <span className={S.shortcutText}>{t`K`}</span>
+ </Flex>
+ </Button>
+ );
};
diff --git a/frontend/src/metabase/palette/components/Palette.module.css b/frontend/src/metabase/palette/components/Palette.module.css
new file mode 100644
index 00000000000..2b914d65531
--- /dev/null
+++ b/frontend/src/metabase/palette/components/Palette.module.css
@@ -0,0 +1,21 @@
+.input {
+ padding: var(--mantine-spacing-lg);
+ padding-left: 3.75rem;
+ font-size: 17px;
+ width: 100%;
+ border: none;
+ border-bottom: 1px solid var(--border-color);
+ border-top-left-radius: 0.5rem;
+ border-top-right-radius: 0.5rem;
+ color: var(--mb-color-text-dark);
+ line-height: 1rem;
+ outline: none;
+}
+
+.iconContainer {
+ pointer-events: none;
+}
+
+.viewAndFilterResults:hover {
+ text-decoration: underline;
+}
diff --git a/frontend/src/metabase/palette/components/Palette.styled.tsx b/frontend/src/metabase/palette/components/Palette.styled.tsx
deleted file mode 100644
index 668149e952a..00000000000
--- a/frontend/src/metabase/palette/components/Palette.styled.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-// eslint-disable-next-line no-restricted-imports
-import styled from "@emotion/styled";
-import { KBarSearch } from "kbar";
-
-export const PaletteInput = styled(KBarSearch)`
- padding: 0.75rem;
- font-weight: bold;
- width: 100%;
- border-radius: 0.5rem;
- border: 1px solid var(--mb-color-border);
- background: var(--mb-color-bg-light);
- color: var(--mb-color-text-dark);
- line-height: 1rem;
-
- &:focus {
- outline: 1px solid var(--mb-color-brand);
- }
-`;
diff --git a/frontend/src/metabase/palette/components/Palette.tsx b/frontend/src/metabase/palette/components/Palette.tsx
index b10f39c2220..27af41f0609 100644
--- a/frontend/src/metabase/palette/components/Palette.tsx
+++ b/frontend/src/metabase/palette/components/Palette.tsx
@@ -1,30 +1,33 @@
-import { KBarPortal, VisualState, useKBar } from "kbar";
+import { KBarPortal, KBarSearch, VisualState, useKBar } from "kbar";
import { type HTMLAttributes, forwardRef, useEffect, useRef } from "react";
-import { type PlainRoute, withRouter } from "react-router";
+import {
+ type PlainRoute,
+ type WithRouterProps,
+ withRouter,
+} from "react-router";
import { t } from "ttag";
import { useOnClickOutside } from "metabase/common/hooks/use-on-click-outside";
import { isWithinIframe } from "metabase/lib/dom";
import { useSelector } from "metabase/lib/redux";
import { getUser } from "metabase/selectors/user";
-import { Box, Card, Center, Overlay, type OverlayProps } from "metabase/ui";
+import {
+ Box,
+ Card,
+ Center,
+ Icon,
+ Overlay,
+ type OverlayProps,
+ Stack,
+ rem,
+} from "metabase/ui";
import { useCommandPalette } from "../hooks/useCommandPalette";
import { useCommandPaletteBasicActions } from "../hooks/useCommandPaletteBasicActions";
-import { PaletteInput } from "./Palette.styled";
-import { PaletteFooter } from "./PaletteFooter";
+import S from "./Palette.module.css";
import { PaletteResults } from "./PaletteResults";
-/**
- * Thin wrapper for useCommandPalette.
- * Limits re-render scope and provides an easy way to enable/disable entire hook.
- */
-const AdvancedPaletteActions = withRouter((props) => {
- useCommandPalette({ locationQuery: props.location.query });
- return null;
-});
-
/** Command palette */
export const Palette = withRouter((props) => {
const isLoggedIn = useSelector((state) => !!getUser(state));
@@ -44,35 +47,59 @@ export const Palette = withRouter((props) => {
}, [disabled, query]);
return (
- <>
- <KBarPortal>
- <PaletteContainer />
- </KBarPortal>
- {!disabled && <AdvancedPaletteActions />}
- </>
+ <KBarPortal>
+ <PaletteContainer disabled={disabled} />
+ </KBarPortal>
);
});
-const PaletteContainer = () => {
- const { query } = useKBar((state) => ({ actions: state.actions }));
- const ref = useRef(null);
+const PaletteContainer = withRouter(
+ ({ disabled, ...props }: WithRouterProps & { disabled: boolean }) => {
+ const { query } = useKBar((state) => ({ actions: state.actions }));
+ const ref = useRef(null);
- useOnClickOutside(ref, () => {
- query.setVisualState(VisualState.hidden);
- });
+ const locationQuery = props.location.query;
+ const { searchRequestId, searchResults, searchTerm } = useCommandPalette({
+ locationQuery,
+ disabled,
+ });
- return (
- <PaletteCard ref={ref}>
- <Box w="100%" p="1.5rem" pb="0">
- <PaletteInput
- defaultPlaceholder={t`Search for anything or jump somewhere…`}
- />
- </Box>
- <PaletteResults />
- <PaletteFooter />
- </PaletteCard>
- );
-};
+ useOnClickOutside(ref, () => {
+ query.setVisualState(VisualState.hidden);
+ });
+
+ return (
+ <PaletteCard ref={ref}>
+ <Stack gap={rem(4)} pb="lg">
+ <Box pos="relative">
+ <KBarSearch
+ className={S.input}
+ defaultPlaceholder={t`Search for anything…`}
+ />
+
+ <Stack
+ className={S.iconContainer}
+ align="center"
+ left={36} // align this icon with results icons
+ pos="absolute"
+ top={26}
+ >
+ <Icon c="text-dark" name="search" />
+ </Stack>
+ </Box>
+
+ <PaletteResults
+ align="stretch"
+ locationQuery={locationQuery}
+ searchRequestId={searchRequestId}
+ searchResults={searchResults}
+ searchTerm={searchTerm}
+ />
+ </Stack>
+ </PaletteCard>
+ );
+ },
+);
export const PaletteCard = forwardRef<
HTMLDivElement,
diff --git a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
index 611975a6c78..fe4162ac49b 100644
--- a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx
@@ -1,4 +1,5 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { Route } from "react-router";
import {
@@ -42,4 +43,14 @@ describe("command palette", () => {
await userEvent.keyboard("[ControlLeft>]k");
expect(screen.queryByTestId("command-palette")).not.toBeInTheDocument();
});
+
+ it("should not call recents API when palette is disabled", async () => {
+ setup({ routeProps: { disableCommandPalette: true } });
+
+ await userEvent.keyboard("[ControlLeft>]k");
+
+ expect(fetchMock.callHistory.called(/\/api\/activity\/recents/)).toBe(
+ false,
+ );
+ });
});
diff --git a/frontend/src/metabase/palette/components/PaletteFooter.tsx b/frontend/src/metabase/palette/components/PaletteFooter.tsx
deleted file mode 100644
index bc44b4f3418..00000000000
--- a/frontend/src/metabase/palette/components/PaletteFooter.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { t } from "ttag";
-
-import { Flex, Icon, Text } from "metabase/ui";
-
-export const PaletteFooter = () => {
- return (
- <Flex
- p=".5rem 1.5rem"
- gap="1.5rem"
- style={{
- borderTop: "1px solid var(--mb-color-border)",
- }}
- >
- <Flex gap=".33rem" c={"text-medium"} lh="1rem" align="center">
- <Icon name="sort" />
- <Text size="12px">{t`Select`}</Text>
- </Flex>
- </Flex>
- );
-};
diff --git a/frontend/src/metabase/palette/components/PaletteResultItem.tsx b/frontend/src/metabase/palette/components/PaletteResultItem.tsx
index 938708602fc..09b6c3ae7b5 100644
--- a/frontend/src/metabase/palette/components/PaletteResultItem.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultItem.tsx
@@ -1,9 +1,7 @@
-import { t } from "ttag";
-
import ExternalLink from "metabase/common/components/ExternalLink";
import Link from "metabase/common/components/Link";
import { PLUGIN_MODERATION } from "metabase/plugins";
-import { Box, Flex, Icon, Text } from "metabase/ui";
+import { Box, Flex, Group, Icon, Stack, Text } from "metabase/ui";
import type { PaletteActionImpl } from "../types";
import {
@@ -18,8 +16,7 @@ interface PaletteResultItemProps {
}
export const PaletteResultItem = ({ item, active }: PaletteResultItemProps) => {
- const icon = item.icon ? getCommandPaletteIcon(item, active) : null;
-
+ const icon = item.icon ? getCommandPaletteIcon(item) : null;
const subtext = item.extra?.subtext;
const content = (
@@ -28,21 +25,19 @@ export const PaletteResultItem = ({ item, active }: PaletteResultItemProps) => {
mx="1.5rem"
miw="0"
align="start"
- justify="space-between"
gap="0.5rem"
- fw={700}
style={{
cursor: item.disabled ? "default" : "pointer",
borderRadius: "0.5rem",
flexGrow: 1,
flexBasis: 0,
}}
- bg={active ? "var(--mb-color-brand)" : undefined}
- c={active ? "var(--mb-color-text-white)" : "var(--mb-color-text-dark)"}
+ bg={active ? "var(--mb-color-background-hover)" : undefined}
+ c="var(--mb-color-text-dark)"
aria-label={item.name}
aria-disabled={item.disabled ? true : false}
+ wrap="nowrap"
>
- {/** Icon Container */}
{icon && (
<Icon
{...icon}
@@ -51,82 +46,64 @@ export const PaletteResultItem = ({ item, active }: PaletteResultItemProps) => {
}}
/>
)}
- {/**Text container */}
- <Flex
- direction="column"
- style={{
- flexGrow: 1,
- flexBasis: 0,
- overflowX: "hidden",
- }}
- >
- <Box
- component="span"
- style={{
- textOverflow: "ellipsis",
- overflow: "hidden",
- whiteSpace: "nowrap",
- }}
- >
- <Text component="span" c="inherit" lh="1rem">
- {item.name}
- </Text>
- {item.extra?.moderatedStatus && (
- <PLUGIN_MODERATION.ModerationStatusIcon
- status={item.extra.moderatedStatus}
- filled
- size={14}
- color={
- active ? "var(--mb-color-text-white)" : "var(--mb-color-brand)"
- }
- style={{
- verticalAlign: "text-bottom",
- }}
- ml="0.5rem"
- />
- )}
+
+ <Stack gap="xs" flex="1" style={{ overflow: "hidden" }}>
+ <Flex align="center" gap="md" justify="space-between" wrap="nowrap">
+ <Group align="center" gap="sm" wrap="nowrap">
+ <Text c="inherit" component="span" lh="1rem" lineClamp={1} miw={0}>
+ {item.name}
+ </Text>
+
+ {item.extra?.moderatedStatus && (
+ <PLUGIN_MODERATION.ModerationStatusIcon
+ status={item.extra.moderatedStatus}
+ filled
+ size={14}
+ color="var(--mb-color-brand)"
+ style={{
+ verticalAlign: "text-bottom",
+ }}
+ />
+ )}
+ </Group>
+
{subtext && (
<Text
- component="span"
- ml="0.25rem"
+ flex="0 0 auto"
c={
active
- ? "var(--mb-color-brand-light)"
+ ? "var(--mb-color-text-medium)"
: "var(--mb-color-text-light)"
}
fz="0.75rem"
lh="1rem"
- fw="normal"
- style={{
- display: "inline-flex",
- alignItems: "center",
- }}
+ lineClamp={1}
+ maw="40%"
>
- — {subtext}
+ {subtext}
</Text>
)}
- </Box>
- <Text
- component="span"
- color={
- active ? "var(--mb-color-text-white)" : "var(--mb-color-text-light)"
- }
- fw="normal"
- style={{
- textOverflow: "ellipsis",
- overflow: "hidden",
- whiteSpace: "nowrap",
- }}
- >
- {item.subtitle}
- </Text>
- </Flex>
- {/** Active container */}
- {active && (
- <Flex aria-hidden gap="0.5rem" fw={400}>
- {t`Open`} <Icon name="enter_or_return" />
</Flex>
- )}
+
+ {item.subtitle && (
+ <Text
+ c={
+ active
+ ? "var(--mb-color-text-medium)"
+ : "var(--mb-color-text-light)"
+ }
+ component="span"
+ lh="1rem"
+ style={{
+ textOverflow: "ellipsis",
+ overflow: "hidden",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {item.subtitle}
+ </Text>
+ )}
+ </Stack>
</Flex>
);
if (item.extra?.href) {
diff --git a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
index 789763bdcbc..57cb049b0b2 100644
--- a/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultItem.unit.spec.tsx
@@ -53,18 +53,6 @@ describe("PaletteResultItem", () => {
);
});
- it("if active, icon color should always be white", async () => {
- setup({
- item: { icon: "model", extra: { iconColor: "accent1" } },
- active: true,
- });
-
- expect(await screen.findByRole("img", { name: /model/ })).toHaveAttribute(
- "color",
- "var(--mb-color-text-white)",
- );
- });
-
it("should not render an icon if none is provided", async () => {
setup({});
expect(screen.queryByRole("img")).not.toBeInTheDocument();
@@ -81,7 +69,7 @@ const setupInList = ({ item }: { item: Partial<PaletteActionImpl> }) => {
component={() => (
<PaletteResultList
items={items.map((item) => mockPaletteActionImpl(item))}
- onRender={({
+ renderItem={({
item,
active,
}: {
diff --git a/frontend/src/metabase/palette/components/PaletteResults.tsx b/frontend/src/metabase/palette/components/PaletteResults.tsx
index 3773d625ebd..56f5da6e4fb 100644
--- a/frontend/src/metabase/palette/components/PaletteResults.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResults.tsx
@@ -1,32 +1,60 @@
-import { useKBar, useMatches } from "kbar";
+/* eslint-disable no-color-literals */
+import type { Query } from "history";
+import { VisualState, useKBar, useMatches } from "kbar";
import { useEffect, useMemo } from "react";
+import { Link } from "react-router";
import { useKeyPressEvent } from "react-use";
import { t } from "ttag";
-import { Box, Flex } from "metabase/ui";
+import { trackSearchClick } from "metabase/search/analytics";
+import {
+ Flex,
+ Group,
+ Icon,
+ Skeleton,
+ Stack,
+ type StackProps,
+ Text,
+ rem,
+} from "metabase/ui";
+import type { SearchResponse } from "metabase-types/api";
import type { PaletteActionImpl } from "../types";
import { navigateActionIndex, processResults } from "../utils";
+import S from "./Palette.module.css";
import { PaletteResultItem } from "./PaletteResultItem";
import { PaletteResultList } from "./PaletteResultsList";
const PAGE_SIZE = 4;
-export const PaletteResults = () => {
+type Props = Omit<StackProps, "children"> & {
+ locationQuery: Query;
+ searchRequestId: string | undefined;
+ searchResults: SearchResponse | undefined;
+ searchTerm: string;
+};
+
+export const PaletteResults = ({
+ locationQuery,
+ searchRequestId,
+ searchResults,
+ searchTerm,
+ ...props
+}: Props) => {
// Used for finding actions within the list
const { query } = useKBar();
const { results } = useMatches();
const processedResults = useMemo(
- () => processResults(results as (PaletteActionImpl | string)[]),
- [results],
+ () => processResults(results as (PaletteActionImpl | string)[], searchTerm),
+ [results, searchTerm],
);
useEffect(() => {
- if (processedResults[0] === t`Search results`) {
- query.setActiveIndex(2);
+ if (processedResults[0] === t`Results`) {
+ query.setActiveIndex(1);
}
}, [processedResults, query]);
@@ -52,40 +80,69 @@ export const PaletteResults = () => {
);
});
+ if (processedResults.length === 0) {
+ return <PaletteResultsSkeleton />;
+ }
+
return (
- <Flex align="stretch" direction="column" p="0.75rem 0">
+ <Stack {...props}>
<PaletteResultList
items={processedResults} // items needs to be a stable reference, otherwise the activeIndex will constantly be hijacked
maxHeight={530}
- onRender={({
- item,
- active,
- }: {
- item: string | PaletteActionImpl;
- active: boolean;
- }) => {
+ renderItem={({ item, active }) => {
const isFirst = processedResults[0] === item;
return (
<Flex lh="1rem" pb="2px">
{typeof item === "string" ? (
- <Box
- px="1.5rem"
+ <Group
fz="14px"
- pt="1rem"
- pb="0.5rem"
- style={
- isFirst
- ? undefined
- : {
- borderTop: "1px solid var(--mb-color-border)",
- marginTop: "1rem",
- }
- }
+ justify="space-between"
+ px="lg"
+ pt="md"
+ pb="sm"
+ mt={isFirst ? undefined : "md"}
w="100%"
>
{item}
- </Box>
+
+ {item === t`Results` && searchResults?.data.length && (
+ <Text
+ c="brand"
+ component={Link}
+ fw={700}
+ id="search-results-metadata"
+ to={{
+ pathname: "search",
+ query: {
+ ...locationQuery,
+ q: searchTerm,
+ },
+ }}
+ className={S.viewAndFilterResults}
+ onClick={() => {
+ query.setVisualState(VisualState.hidden);
+
+ trackSearchClick({
+ itemType: "view_more",
+ position: 0,
+ context: "command-palette",
+ searchEngine: searchResults?.engine || "unknown",
+ requestId: searchRequestId,
+ entityModel: null,
+ entityId: null,
+ searchTerm,
+ });
+ }}
+ >
+ <Group align="center" gap={rem(4)}>
+ <span>{t`View and filter all ${searchResults?.total} results`}</span>
+
+ <Icon name="chevronright" size={12} />
+ </Group>
+ </Text>
+ )}
+ </Group>
) : (
<PaletteResultItem item={item} active={active} />
)}
@@ -93,6 +150,19 @@ export const PaletteResults = () => {
);
}}
/>
- </Flex>
+ </Stack>
);
};
+
+function PaletteResultsSkeleton() {
+ return (
+ <Stack my="3.75rem" mx="4rem">
+ <Skeleton bg="#F0EDED" height={20} radius={4} />
+ <Skeleton bg="#F0EDED" height={20} mt={16} radius={4} />
+ <Skeleton bg="#F0EDED" height={20} w="80%" mt={16} radius={4} />
+ <Skeleton bg="#F0EDED" height={20} w="80%" mt={16} radius={4} />
+ <Skeleton bg="#F0EDED" height={20} w="60%" mt={16} radius={4} />
+ <Skeleton bg="#F0EDED" height={20} w="60%" mt={16} radius={4} />
+ </Stack>
+ );
+}
diff --git a/frontend/src/metabase/palette/components/PaletteResultsList.tsx b/frontend/src/metabase/palette/components/PaletteResultsList.tsx
index d711e9c46ce..77950aeac56 100644
--- a/frontend/src/metabase/palette/components/PaletteResultsList.tsx
+++ b/frontend/src/metabase/palette/components/PaletteResultsList.tsx
@@ -8,7 +8,13 @@
*/
import { KBAR_LISTBOX, getListboxItemId, useKBar } from "kbar";
-import * as React from "react";
+import {
+ type MouseEvent,
+ cloneElement,
+ useCallback,
+ useEffect,
+ useRef,
+} from "react";
import type { PaletteActionImpl } from "../types";
import { navigateActionIndex } from "../utils";
@@ -22,17 +28,17 @@ interface RenderParams<T = PaletteActionImpl | string> {
interface PaletteResultListProps {
items: (PaletteActionImpl | string)[];
- onRender: (params: RenderParams) => React.ReactElement;
+ renderItem: (params: RenderParams) => React.ReactElement;
maxHeight?: number;
}
-export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
- const activeRef = React.useRef<HTMLDivElement>(null);
- const parentRef = React.useRef<HTMLDivElement>(null);
+export const PaletteResultList = (props: PaletteResultListProps) => {
+ const activeRef = useRef<HTMLDivElement>(null);
+ const parentRef = useRef<HTMLDivElement>(null);
// store a ref to all items so we do not have to pass
// them as a dependency when setting up event listeners.
- const itemsRef = React.useRef(props.items);
+ const itemsRef = useRef(props.items);
itemsRef.current = props.items;
const { query, search, currentRootActionId, activeIndex, options } = useKBar(
@@ -43,7 +49,7 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
}),
);
- React.useEffect(() => {
+ useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.isComposing) {
return;
@@ -95,7 +101,7 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
window.removeEventListener("keydown", handler, { capture: true });
}, [query]);
- React.useEffect(() => {
+ useEffect(() => {
if (activeIndex > 1) {
activeRef.current?.scrollIntoView({
behavior: "smooth",
@@ -106,7 +112,7 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
}
}, [activeIndex]);
- React.useEffect(() => {
+ 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`
@@ -120,8 +126,8 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
);
}, [search, currentRootActionId, props.items, query]);
- const execute = React.useCallback(
- (item: RenderParams["item"], e?: React.MouseEvent) => {
+ const execute = useCallback(
+ (item: RenderParams["item"], e?: MouseEvent) => {
if (typeof item === "string") {
return;
}
@@ -161,7 +167,7 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
onPointerMove: () =>
activeIndex !== index && query.setActiveIndex(index),
onPointerDown: () => query.setActiveIndex(index),
- onClick: (e: React.MouseEvent) => execute(item, e),
+ onClick: (e: MouseEvent) => execute(item, e),
};
const active = index === activeIndex;
@@ -174,8 +180,8 @@ export const PaletteResultList: React.FC<PaletteResultListProps> = (props) => {
key={typeof item === "string" ? item : item.id}
{...handlers}
>
- {React.cloneElement(
- props.onRender({
+ {cloneElement(
+ props.renderItem({
item,
active,
}),
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-ee.unit.spec.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-ee.unit.spec.tsx
index 7f9189dd92e..9228e6825be 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-ee.unit.spec.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/PaletteResults-ee.unit.spec.tsx
@@ -1,14 +1,8 @@
-import fetchMock from "fetch-mock";
-
import { screen, within } from "__support__/ui";
import { type CommonSetupProps, commonSetup } from "./setup";
const setup = (props: CommonSetupProps = {}) => {
- fetchMock.get("path:/api/ee/metabot-v3/v2/prompt-suggestions", {
- prompts: [],
- });
-
commonSetup({ ...props, isEE: true });
};
@@ -34,23 +28,5 @@ describe("PaletteResults EE", () => {
).findByRole("img", { name: /verified_filled/ }),
).toBeInTheDocument();
});
-
- it("should show the default metabot palette item", async () => {
- setup();
- expect(
- await screen.findByRole("option", {
- name: "Ask me to do something, or ask me a question",
- }),
- ).toBeInTheDocument();
- });
-
- it("should show the metabot palette item with interpolated query", async () => {
- setup({ query: "what is our aov" });
- expect(
- await screen.findByRole("option", {
- name: 'Ask Metabot, "what is our aov"',
- }),
- ).toBeInTheDocument();
- });
});
});
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 f8f59f92333..444c20afce1 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
@@ -13,13 +13,22 @@ const setup = (props: CommonSetupProps = {}) => {
};
describe("PaletteResults", () => {
- it("should show default actions", async () => {
+ it("should not show actions when there is no search query", () => {
setup();
+ expect(screen.queryByText("New dashboard")).not.toBeInTheDocument();
+ expect(screen.queryByText("New collection")).not.toBeInTheDocument();
+ expect(screen.queryByText("New model")).not.toBeInTheDocument();
+
+ expect(screen.queryByText("Results")).not.toBeInTheDocument();
+ });
+
+ it("should show actions when there is a search query", async () => {
+ setup({ query: "new" });
expect(await screen.findByText("New dashboard")).toBeInTheDocument();
expect(await screen.findByText("New collection")).toBeInTheDocument();
expect(await screen.findByText("New model")).toBeInTheDocument();
- expect(screen.queryByText("Search results")).not.toBeInTheDocument();
+ expect(screen.getByText("Results")).toBeInTheDocument();
});
//For some reason, New Question isn't showing up without searching. My guess is virtualization weirdness
@@ -30,7 +39,7 @@ describe("PaletteResults", () => {
it("should show you recent items", async () => {
setup();
- expect(await screen.findByText("Recent items")).toBeInTheDocument();
+ expect(await screen.findByText("Recents")).toBeInTheDocument();
expect(
await screen.findByRole("option", { name: "Bar Dashboard" }),
).toHaveTextContent("lame collection");
@@ -65,7 +74,7 @@ describe("PaletteResults", () => {
],
});
- expect(await screen.findByText("Recent items")).toBeInTheDocument();
+ expect(await screen.findByText("Recents")).toBeInTheDocument();
expect(
await screen.findAllByRole("option", { name: "My Awesome Data" }),
@@ -76,7 +85,7 @@ describe("PaletteResults", () => {
setup({ query: "Bar" });
await waitFor(async () => {
- expect(await screen.findByText("Search results")).toBeInTheDocument();
+ expect(await screen.findByText("Results")).toBeInTheDocument();
});
expect(
diff --git a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
index 6a0a77d75a0..ab6b96f9914 100644
--- a/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
+++ b/frontend/src/metabase/palette/components/test/PaletteResults/setup.tsx
@@ -34,7 +34,10 @@ import { PaletteResults } from "../../PaletteResults";
const TestComponent = withRouter(
({ q, ...props }: WithRouterProps & { q?: string; isLoggedIn: boolean }) => {
useCommandPaletteBasicActions(props);
- useCommandPalette({ locationQuery: props.location.query });
+ const { searchRequestId, searchResults, searchTerm } = useCommandPalette({
+ disabled: false,
+ locationQuery: props.location.query,
+ });
const { query } = useKBar();
@@ -45,7 +48,14 @@ const TestComponent = withRouter(
}
}, [q, query]);
- return <PaletteResults />;
+ return (
+ <PaletteResults
+ locationQuery={props.location.query}
+ searchRequestId={searchRequestId}
+ searchResults={searchResults}
+ searchTerm={searchTerm}
+ />
+ );
},
);
diff --git a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
index f25d86ba0e4..c6551b94b42 100644
--- a/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
+++ b/frontend/src/metabase/palette/hooks/useCommandPalette.tsx
@@ -15,7 +15,7 @@ import { getIcon } from "metabase/lib/icon";
import { getName } from "metabase/lib/name";
import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
-import { PLUGIN_CACHING, PLUGIN_METABOT } from "metabase/plugins";
+import { PLUGIN_CACHING } from "metabase/plugins";
import { trackSearchClick } from "metabase/search/analytics";
import {
getDocsSearchUrl,
@@ -24,7 +24,7 @@ import {
} from "metabase/selectors/settings";
import { canAccessSettings, getUserIsAdmin } from "metabase/selectors/user";
import { getShowMetabaseLinks } from "metabase/selectors/whitelabel";
-import { Icon, type IconName } from "metabase/ui";
+import { Group, Icon } from "metabase/ui";
import {
type RecentItem,
isRecentCollectionItem,
@@ -36,8 +36,10 @@ import type { PaletteAction } from "../types";
import { filterRecentItems } from "../utils";
export const useCommandPalette = ({
+ disabled = false,
locationQuery,
}: {
+ disabled: boolean;
locationQuery: Query;
}) => {
const dispatch = useDispatch();
@@ -84,17 +86,20 @@ export const useCommandPalette = ({
limit: 20,
},
{
- skip: !debouncedSearchText || !isSearchTypeaheadEnabled,
+ skip: !debouncedSearchText || !isSearchTypeaheadEnabled || disabled,
refetchOnMountOrArgChange: true,
},
);
- const { data: recentItems, refetch: refetchRecents } = useListRecentsQuery();
+ const { data: recentItems, refetch: refetchRecents } = useListRecentsQuery(
+ undefined,
+ { skip: disabled },
+ );
useEffect(() => {
- if (isVisible) {
+ if (isVisible && !disabled) {
refetchRecents();
}
- }, [isVisible, refetchRecents]);
+ }, [isVisible, refetchRecents, disabled]);
const adminPaths = useSelector(getAdminPaths);
const settingValues = useSelector(getSettings);
@@ -120,17 +125,18 @@ export const useCommandPalette = ({
return ret;
}, [debouncedSearchText, docsUrl]);
- const showDocsAction = showMetabaseLinks && hasQuery;
+ const showDocsAction = showMetabaseLinks && hasQuery && !disabled;
useRegisterActions(showDocsAction ? docsAction : [], [
docsAction,
showDocsAction,
]);
- const metabotActions = PLUGIN_METABOT.useMetabotPalletteActions(trimmedQuery);
- useRegisterActions(metabotActions, [metabotActions]);
-
const searchResultActions = useMemo<PaletteAction[]>(() => {
+ if (disabled) {
+ return [];
+ }
+
const searchLocation = {
pathname: "search",
query: {
@@ -173,63 +179,37 @@ export const useCommandPalette = ({
];
} else if (debouncedSearchText) {
if (searchResults?.data.length) {
- return [
- {
- id: `search-results-metadata`,
- name: t`View and filter all ${searchResults?.total} results`,
+ return searchResults.data.map((result, index) => {
+ const wrappedResult = Search.wrapEntity(result, dispatch);
+ const icon = getIcon(wrappedResult);
+ return {
+ id: `search-result-${result.model}-${result.id}`,
+ name: result.name,
+ subtitle: result.description || "",
+ icon: icon.name,
section: "search",
keywords: debouncedSearchText,
- icon: "link" as IconName,
+ priority: Priority.NORMAL - index,
perform: () => {
trackSearchClick({
- itemType: "view_more",
- position: 0,
+ itemType: "item",
+ position: index,
context: "command-palette",
searchEngine: searchResults?.engine || "unknown",
requestId: searchRequestId,
- entityModel: null,
- entityId: null,
+ entityModel: result.model,
+ entityId: typeof result.id === "number" ? result.id : null,
searchTerm: debouncedSearchText,
});
},
- priority: Priority.HIGH,
extra: {
- href: searchLocation,
+ moderatedStatus: result.moderated_status,
+ href: wrappedResult.getUrl?.(),
+ iconColor: icon.color,
+ subtext: getSearchResultSubtext(wrappedResult),
},
- },
- ].concat(
- searchResults.data.map((result, index) => {
- const wrappedResult = Search.wrapEntity(result, dispatch);
- const icon = getIcon(wrappedResult);
- return {
- id: `search-result-${result.model}-${result.id}`,
- name: result.name,
- subtitle: result.description || "",
- icon: icon.name,
- section: "search",
- keywords: debouncedSearchText,
- priority: Priority.NORMAL - index,
- perform: () => {
- trackSearchClick({
- itemType: "item",
- position: index,
- context: "command-palette",
- searchEngine: searchResults?.engine || "unknown",
- requestId: searchRequestId,
- entityModel: result.model,
- entityId: typeof result.id === "number" ? result.id : null,
- searchTerm: debouncedSearchText,
- });
- },
- extra: {
- moderatedStatus: result.moderated_status,
- href: wrappedResult.getUrl(),
- iconColor: icon.color,
- subtext: getSearchResultSubtext(wrappedResult),
- },
- };
- }),
- );
+ };
+ });
} else {
return [
{
@@ -244,6 +224,7 @@ export const useCommandPalette = ({
}
return [];
}, [
+ disabled,
dispatch,
debouncedSearchText,
searchQuery,
@@ -258,6 +239,10 @@ export const useCommandPalette = ({
useRegisterActions(searchResultActions, [searchResultActions]);
const recentItemsActions = useMemo<PaletteAction[]>(() => {
+ if (disabled) {
+ return [];
+ }
+
return (
filterRecentItems(recentItems ?? []).map((item) => {
const icon = getIcon(item);
@@ -278,7 +263,7 @@ export const useCommandPalette = ({
};
}) || []
);
- }, [recentItems]);
+ }, [disabled, recentItems]);
useRegisterActions(hasQuery ? [] : recentItemsActions, [
recentItemsActions,
@@ -286,6 +271,10 @@ export const useCommandPalette = ({
]);
const adminActions = useMemo<PaletteAction[]>(() => {
+ if (disabled) {
+ return [];
+ }
+
// Subpaths - i.e. paths to items within the main Admin tabs - are needed
// in the command palette but are not part of the main list of admin paths
const adminSubpaths = isAdmin
@@ -303,10 +292,10 @@ export const useCommandPalette = ({
href: adminPath.path,
},
}));
- }, [isAdmin, adminPaths]);
+ }, [disabled, isAdmin, adminPaths]);
const settingsActions = useMemo<PaletteAction[]>(() => {
- if (!canUserAccessSettings) {
+ if (disabled || !canUserAccessSettings) {
return [];
}
@@ -332,19 +321,26 @@ export const useCommandPalette = ({
href: `/admin/settings/${slug}`,
},
}));
- }, [canUserAccessSettings, isAdmin, settingValues]);
+ }, [disabled, canUserAccessSettings, isAdmin, settingValues]);
useRegisterActions(hasQuery ? [...adminActions, ...settingsActions] : [], [
adminActions,
settingsActions,
hasQuery,
]);
+
+ return {
+ searchRequestId,
+ searchResults,
+ searchTerm: debouncedSearchText,
+ };
};
export const getSearchResultSubtext = (wrappedSearchResult: any) => {
if (wrappedSearchResult.model === "indexed-entity") {
return jt`a record in ${(
<Icon
+ flex="0 0 auto"
key="icon"
name="model"
style={{
@@ -364,6 +360,7 @@ export const getSearchResultSubtext = (wrappedSearchResult: any) => {
return (
<>
<Icon
+ flex="0 0 auto"
name="dashboard"
style={{
verticalAlign: "bottom",
@@ -374,7 +371,7 @@ export const getSearchResultSubtext = (wrappedSearchResult: any) => {
</>
);
} else {
- return wrappedSearchResult.getCollection().name;
+ return wrappedSearchResult.getCollection?.()?.name;
}
};
@@ -385,24 +382,24 @@ export const getRecentItemSubtext = (item: RecentItem) => {
: item.database.name;
} else if (item.dashboard) {
return (
- <>
- <Icon name="dashboard" size={12} style={{ marginInline: "0.25rem" }} />
+ <Group align="center" gap="xs" wrap="nowrap">
+ <Icon flex="0 0 auto" name="dashboard" size={12} />
{item.dashboard.name}
- </>
+ </Group>
);
} else if (item.parent_collection.id === null) {
return (
- <>
- <Icon name="collection" size={12} style={{ marginInline: "0.25rem" }} />
+ <Group align="center" gap="xs" wrap="nowrap">
+ <Icon flex="0 0 auto" name="collection" size={12} />
{ROOT_COLLECTION.name}
- </>
+ </Group>
);
} else {
return (
- <>
- <Icon name="collection" size={12} style={{ marginInline: "0.25rem" }} />
+ <Group align="center" gap="xs" wrap="nowrap">
+ <Icon flex="0 0 auto" name="collection" size={12} />
{item.parent_collection.name}
- </>
+ </Group>
);
}
};
diff --git a/frontend/src/metabase/palette/utils.ts b/frontend/src/metabase/palette/utils.ts
index 9e6e21ecabf..baee0544d9d 100644
--- a/frontend/src/metabase/palette/utils.ts
+++ b/frontend/src/metabase/palette/utils.ts
@@ -11,6 +11,7 @@ import type { PaletteActionImpl } from "./types";
export const processResults = (
results: (string | PaletteActionImpl)[],
+ searchTerm: string,
): (string | PaletteActionImpl)[] => {
const groupedResults = _.groupBy(
results.filter((r): r is PaletteActionImpl => !(typeof r === "string")),
@@ -18,20 +19,16 @@ export const processResults = (
);
const actions = processSection(t`Actions`, groupedResults["basic"]);
- const metabotActions = processSection(t`Metabot`, groupedResults["metabot"]);
- const search = processSection(t`Search results`, groupedResults["search"]);
- const recent = processSection(t`Recent items`, groupedResults["recent"]);
+ const search = processSection(t`Results`, groupedResults["search"]);
+ const recent = processSection(t`Recents`, groupedResults["recent"]);
const admin = processSection(t`Admin`, groupedResults["admin"]);
const docs = processSection(t`Documentation`, groupedResults["docs"]);
- return [
- ...metabotActions,
- ...recent,
- ...actions.slice(0, 6),
- ...admin,
- ...search,
- ...docs,
- ];
+ if (searchTerm.trim().length === 0) {
+ return [...recent];
+ }
+
+ return [...recent, ...actions.slice(0, 6), ...admin, ...search, ...docs];
};
export const processSection = (
@@ -84,11 +81,10 @@ export const findClosestActionIndex = (
export const filterRecentItems: (items: RecentItem[]) => RecentItem[] = (
items,
-) => items.filter((item) => item.model !== "collection").slice(0, 5);
+) => items.filter((item) => item.model !== "collection").slice(0, 10);
export const getCommandPaletteIcon = (
item: PaletteActionImpl,
- isActive: boolean,
): { name: IconName; color: string } => {
const icon = {
name: item.icon as IconName,
@@ -97,14 +93,6 @@ export const getCommandPaletteIcon = (
: "var(--mb-color-brand)",
};
- if (isActive) {
- icon.color = "var(--mb-color-text-white)";
- }
-
- if (isActive && (item.icon === "folder" || item.icon === "collection")) {
- icon.name = "folder_filled";
- }
-
return icon;
};
diff --git a/frontend/src/metabase/palette/utils.unit.spec.ts b/frontend/src/metabase/palette/utils.unit.spec.ts
index 41757ee337b..2e86e577f21 100644
--- a/frontend/src/metabase/palette/utils.unit.spec.ts
+++ b/frontend/src/metabase/palette/utils.unit.spec.ts
@@ -71,39 +71,42 @@ describe("command palette utils", () => {
const testDoc = [createMockAction({ name: "doc action", section: "docs" })];
it("should limit to 6 actions including header", () => {
- const result = processResults(testActions);
+ const result = processResults(testActions, "xyz");
expect(result).toHaveLength(6);
expect(result[0]).toBe("Actions");
});
it("should not limit the other action types", () => {
- expect(processResults([...testActions, ...testSearch])).toHaveLength(12);
- expect(processResults([...testActions, ...testRecent])).toHaveLength(12);
expect(
- processResults([...testRecent, ...testAdmin, ...testDoc]),
+ processResults([...testActions, ...testSearch], "xyz"),
+ ).toHaveLength(12);
+ expect(
+ processResults([...testActions, ...testRecent], "xyz"),
+ ).toHaveLength(12);
+ expect(
+ processResults([...testRecent, ...testAdmin, ...testDoc], "xyz"),
).toHaveLength(19);
});
it("should add a header to doc", () => {
- expect(processResults([...testDoc])).toHaveLength(2);
+ expect(processResults([...testDoc], "xyz")).toHaveLength(2);
});
it("should enforce a specific order", () => {
- const results = processResults([
- ...testSearch,
- ...testDoc,
- ...testAdmin,
- ...testActions,
- ...testRecent,
- ]);
+ const results = processResults(
+ [
+ ...testSearch,
+ ...testDoc,
+ ...testAdmin,
+ ...testActions,
+ ...testRecent,
+ ],
+ "xyz",
+ );
const actionsIndex = results.findIndex((action) => action === "Actions");
- const searchIndex = results.findIndex(
- (action) => action === "Search results",
- );
- const recentsIndex = results.findIndex(
- (action) => action === "Recent items",
- );
+ const searchIndex = results.findIndex((action) => action === "Results");
+ const recentsIndex = results.findIndex((action) => action === "Recents");
const adminIndex = results.findIndex((action) => action === "Admin");
[recentsIndex, actionsIndex, adminIndex, searchIndex].forEach(
@@ -114,6 +117,11 @@ describe("command palette utils", () => {
},
);
});
+
+ it("should not show actions if there is no search query", () => {
+ const result = processResults(testActions, "");
+ expect(result).toHaveLength(0);
+ });
});
describe("navigateActionIndex", () => {
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index 5ad86dbb66a..b71e7618b7b 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -6,7 +6,6 @@ import React, {
type ReactNode,
type SetStateAction,
useCallback,
- useMemo,
} from "react";
import { t } from "ttag";
@@ -39,8 +38,6 @@ import type { ContentTranslationFunction } from "metabase/i18n/types";
import type { ColorName } from "metabase/lib/colors/types";
import { getIconBase } from "metabase/lib/icon";
import type { MetabotContext } from "metabase/metabot";
-import { SearchButton } from "metabase/nav/components/search/SearchButton";
-import type { PaletteAction } from "metabase/palette/types";
import {
NotFoundPlaceholder,
PluginPlaceholder,
@@ -705,28 +702,41 @@ export const PLUGIN_AI_ENTITY_ANALYSIS: PluginAIEntityAnalysis = {
chartAnalysisRenderFormats: {},
};
-export const PLUGIN_METABOT = {
+type PLUGIN_METABOT_TYPE = {
+ isEnabled: () => boolean;
+ Metabot: (props: { hide?: boolean }) => React.ReactElement | null;
+ defaultMetabotContextValue: MetabotContext;
+ MetabotContext: React.Context<MetabotContext>;
+ getMetabotProvider: () => ComponentType<{ children: React.ReactNode }>;
+ getAdminPaths: () => AdminPath[];
+ getAdminRoutes: () => React.ReactElement;
+ getMetabotRoutes: () => React.ReactElement | null;
+ MetabotAdminPage: ComponentType;
+ getMetabotVisible: (state: State) => boolean;
+ MetabotToggleButton: ComponentType<{ className?: string }>;
+ MetabotAppBarButton: ComponentType;
+};
+
+export const PLUGIN_METABOT: PLUGIN_METABOT_TYPE = {
isEnabled: () => false,
- Metabot: (_props: { hide?: boolean }) => null as React.ReactElement | null,
+ Metabot: () => null,
defaultMetabotContextValue,
MetabotContext: React.createContext(defaultMetabotContextValue),
getMetabotProvider: () => {
- return ({ children }: { children: React.ReactNode }) =>
+ return ({ children }) =>
React.createElement(
PLUGIN_METABOT.MetabotContext.Provider,
{ value: PLUGIN_METABOT.defaultMetabotContextValue },
children,
);
},
- useMetabotPalletteActions: (_searchText: string) =>
- useMemo(() => [] as PaletteAction[], []),
- getAdminPaths: () => [] as AdminPath[],
+ getAdminPaths: () => [],
getAdminRoutes: () => PluginPlaceholder as unknown as React.ReactElement,
- getMetabotRoutes: () => null as React.ReactElement | null,
+ getMetabotRoutes: () => null,
MetabotAdminPage: () => `placeholder`,
- getMetabotVisible: (_state: State) => false,
- SearchButton: SearchButton,
+ getMetabotVisible: () => false,
MetabotToggleButton: PluginPlaceholder,
+ MetabotAppBarButton: PluginPlaceholder,
};
type DashCardMenuItemGetter = (
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/table.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/table.svg
index 3cfae02f695..a8b9b72ee4b 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/table.svg
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/table.svg
@@ -1,3 +1,11 @@
<svg viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
- <path d="M3 3h2.5v2.5H3V3zM10.5 3H13v2.5h-2.5V3zM9.25 3h-2.5v2.5h2.5V3zM3 6.75h2.5v2.5H3v-2.5zM13 6.75h-2.5v2.5H13v-2.5zM6.75 6.75h2.5v2.5h-2.5v-2.5zM5.5 10.5H3V13h2.5v-2.5zM10.5 10.5H13V13h-2.5v-2.5zM9.25 10.5h-2.5V13h2.5v-2.5z" />
+ <path d="M2 2H5.33333V5.33333H2V2Z" />
+ <path d="M6.33333 2H9.66666V5.33333H6.33333V2Z" />
+ <path d="M14 2H10.6667V5.33333H14V2Z" />
+ <path d="M2 6.33333H5.33333V9.66666H2V6.33333Z" />
+ <path d="M9.66666 6.33333H6.33333V9.66666H9.66666V6.33333Z" />
+ <path d="M10.6667 6.33333H14V9.66666H10.6667V6.33333Z" />
+ <path d="M5.33333 10.6667H2V14H5.33333V10.6667Z" />
+ <path d="M6.33333 10.6667H9.66666V14H6.33333V10.6667Z" />
+ <path d="M14 10.6667H10.6667V14H14V10.6667Z" />
</svg>