The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Hydrate command palette search from URL (#74245)
Andersonf93a99cacba6
diff --git a/e2e/support/helpers/e2e-command-palette-helpers.js b/e2e/support/helpers/e2e-command-palette-helpers.jsindex 602c60a7a7b..f54a859b518 100644--- a/e2e/support/helpers/e2e-command-palette-helpers.js+++ b/e2e/support/helpers/e2e-command-palette-helpers.js@@ -26,7 +26,7 @@ export const commandPaletteInput = () =>export const commandPaletteSearch = (query, viewAll = true) => {cy.intercept("GET", "/api/search?q=*").as("paletteSearch");commandPaletteButton().click();- commandPaletteInput().type(query);+ commandPaletteInput().clear().type(query);cy.wait("@paletteSearch");if (viewAll) {diff --git a/e2e/test/scenarios/search/search-filters.cy.spec.js b/e2e/test/scenarios/search/search-filters.cy.spec.jsindex 441235f12e8..3625d386769 100644--- a/e2e/test/scenarios/search/search-filters.cy.spec.js+++ b/e2e/test/scenarios/search/search-filters.cy.spec.js@@ -95,6 +95,21 @@ describe("scenarios > search", () => {cy.findByText('Results for "orders"').should("exist");});});++ it("hydrates the command palette search from the URL (#71248)", () => {+ cy.visit("/search?q=products");+ cy.wait("@search");+ H.commandPaletteButton().should("contain.text", "products");++ cy.intercept("GET", "/api/search?q=products*").as("paletteSearch");+ H.commandPaletteButton().click();+ H.commandPaletteInput().should("have.value", "products");+ cy.wait("@paletteSearch");++ H.commandPalette().within(() => {+ cy.findByRole("option", { name: "Products" }).should("be.visible");+ });+ });});describe("type filter", () => {diff --git a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsxindex 62cb31cded5..dcef65dc91d 100644--- a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx+++ b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.tsx@@ -1,15 +1,24 @@import { VisualState, useKBar } from "kbar";import { useCallback } from "react";+import { withRouter } from "react-router";import { t } from "ttag";import { useIsSmallScreen } from "metabase/common/hooks/use-is-small-screen";-import S from "metabase/nav/components/search/SearchButton/SearchButton.module.css";+import type { SearchAwareLocation } from "metabase/search/types";+import { getSearchTextFromLocation } from "metabase/search/utils";import { Button, type ButtonProps, Flex, Icon } from "metabase/ui";import { METAKEY } from "metabase/utils/browser";-export const SearchButton = (props: ButtonProps) => {+import S from "./SearchButton.module.css";++type SearchButtonProps = ButtonProps & {+ location: SearchAwareLocation;+};++const SearchButtonView = ({ location, ...props }: SearchButtonProps) => {const kbar = useKBar();const { setVisualState } = kbar.query;+ const searchText = getSearchTextFromLocation(location);const handleClick = useCallback(() => {setVisualState(VisualState.showing);@@ -34,7 +43,7 @@ export const SearchButton = (props: ButtonProps) => {<Buttonh="36px"w="240px"- c="text-tertiary"+ c={searchText ? "text-primary" : "text-tertiary"}leftSection={<Icon name="search" c="text-primary" />}onClick={handleClick}styles={{@@ -51,7 +60,7 @@ export const SearchButton = (props: ButtonProps) => {aria-label="Search"{...props}>- <span>{t`Search...`}</span>+ <span>{searchText || t`Search...`}</span><Flex gap="xs"><span className={S.shortcutText}>{METAKEY}</span><span className={S.shortcutText}>{t`K`}</span>@@ -59,3 +68,5 @@ export const SearchButton = (props: ButtonProps) => {</Button>);};++export const SearchButton = withRouter(SearchButtonView);diff --git a/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.unit.spec.tsx b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.unit.spec.tsxnew file mode 100644index 00000000000..478c1b3a251--- /dev/null+++ b/frontend/src/metabase/nav/components/search/SearchButton/SearchButton.unit.spec.tsx@@ -0,0 +1,19 @@+import { Route } from "react-router";++import { renderWithProviders, screen } from "__support__/ui";++import { SearchButton } from "./SearchButton";++describe("SearchButton", () => {+ it("should show the current search query on the search page (UXW-3370)", () => {+ renderWithProviders(<Route path="*" component={() => <SearchButton />} />, {+ withKBar: true,+ withRouter: true,+ initialRoute: "/search?q=products",+ });++ expect(screen.getByRole("button", { name: /Search/ })).toHaveTextContent(+ "products",+ );+ });+});diff --git a/frontend/src/metabase/palette/components/HydratedKBarSearch.module.css b/frontend/src/metabase/palette/components/HydratedKBarSearch.module.cssnew file mode 100644index 00000000000..e78c3982dae--- /dev/null+++ b/frontend/src/metabase/palette/components/HydratedKBarSearch.module.css@@ -0,0 +1,14 @@+.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-primary);+ line-height: 1rem;+ outline: none;+ background-color: transparent;+}diff --git a/frontend/src/metabase/palette/components/HydratedKBarSearch.tsx b/frontend/src/metabase/palette/components/HydratedKBarSearch.tsxnew file mode 100644index 00000000000..42456990b6e--- /dev/null+++ b/frontend/src/metabase/palette/components/HydratedKBarSearch.tsx@@ -0,0 +1,51 @@+import { KBarSearch, useKBar } from "kbar";+import { useEffect, useState } from "react";+import { t } from "ttag";++import S from "./HydratedKBarSearch.module.css";++/**+ * KBarSearch component wrapper, that initializes the input state based on+ * existing `searchText` value before rendering the component.+ */+export const HydratedKBarSearch = ({ searchText }: { searchText: string }) => {+ const { query, searchQuery } = useKBar((state) => ({+ searchQuery: state.searchQuery,+ }));+ const [isHydrated, setIsHydrated] = useState(searchText === "");++ useEffect(() => {+ setIsHydrated(searchText === "");++ if (searchText) {+ query.setSearch(searchText);+ }+ }, [query, searchText]);++ useEffect(() => {+ if (searchQuery === searchText) {+ setIsHydrated(true);+ }+ }, [searchQuery, searchText]);++ /**+ * KBarSearch clears kbar's query in its mount effect.+ * Re-apply the URL query after it mounts so results hydrate too.+ */+ useEffect(() => {+ if (isHydrated && searchText) {+ query.setSearch(searchText);+ }+ }, [isHydrated, query, searchText]);++ if (!isHydrated) {+ return null;+ }++ return (+ <KBarSearch+ className={S.input}+ defaultPlaceholder={t`Search for anything…`}+ />+ );+};diff --git a/frontend/src/metabase/palette/components/Palette.module.css b/frontend/src/metabase/palette/components/Palette.module.cssindex f27c307c8c5..65a802970f7 100644--- a/frontend/src/metabase/palette/components/Palette.module.css+++ b/frontend/src/metabase/palette/components/Palette.module.css@@ -1,18 +1,3 @@-.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-primary);- line-height: 1rem;- outline: none;- background-color: transparent;-}-.iconContainer {pointer-events: none;}diff --git a/frontend/src/metabase/palette/components/Palette.tsx b/frontend/src/metabase/palette/components/Palette.tsxindex c8cfcf46171..82810c793ff 100644--- a/frontend/src/metabase/palette/components/Palette.tsx+++ b/frontend/src/metabase/palette/components/Palette.tsx@@ -1,8 +1,7 @@import type { Query } from "history";-import { KBarPortal, KBarSearch, VisualState, useKBar } from "kbar";+import { KBarPortal, VisualState, useKBar } from "kbar";import { useEffect, useRef } from "react";import { type PlainRoute, withRouter } from "react-router";-import { t } from "ttag";import { useOnClickOutside } from "metabase/common/hooks/use-on-click-outside";import { useSelector } from "metabase/redux";@@ -13,6 +12,7 @@ import { isWithinIframe } from "metabase/utils/iframe";import { useCommandPalette } from "../hooks/useCommandPalette";import { useCommandPaletteBasicActions } from "../hooks/useCommandPaletteBasicActions";+import { HydratedKBarSearch } from "./HydratedKBarSearch";import S from "./Palette.module.css";import { PaletteResults } from "./PaletteResults";@@ -58,6 +58,8 @@ export const PaletteContainer = withRouter(}) => {const { query } = useKBar();const ref = useRef(null);+ const searchText =+ typeof locationQuery.q === "string" ? locationQuery.q : "";const {searchRequestId,@@ -83,10 +85,7 @@ export const PaletteContainer = withRouter(><Stack gap={rem(4)} pb="lg"><Box pos="relative">- <KBarSearch- className={S.input}- defaultPlaceholder={t`Search for anything…`}- />+ <HydratedKBarSearch searchText={searchText} /><StackclassName={S.iconContainer}diff --git a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx b/frontend/src/metabase/palette/components/Palette.unit.spec.tsxindex 6dd32d50631..1d8ae0bd7f0 100644--- a/frontend/src/metabase/palette/components/Palette.unit.spec.tsx+++ b/frontend/src/metabase/palette/components/Palette.unit.spec.tsx@@ -8,7 +8,7 @@ import {setupRecentViewsEndpoints,setupSearchEndpoints,} from "__support__/server-mocks";-import { renderWithProviders, screen } from "__support__/ui";+import { renderWithProviders, screen, waitFor } from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks";import type { SearchResult } from "metabase-types/api";import {@@ -21,10 +21,12 @@ import { Palette } from "./Palette";const setup = ({routeProps,+ initialRoute,searchResults = [],searchResultsDelay,}: {routeProps?: { disableCommandPalette?: boolean };+ initialRoute?: string;searchResults?: SearchResult[];searchResultsDelay?: number;} = {}) => {@@ -34,15 +36,23 @@ const setup = ({setupCollectionByIdEndpoint({collections: [createMockCollection({ id: "root", can_write: true })],});- renderWithProviders(<Route path="/" component={Palette} {...routeProps} />, {- withKBar: true,- withRouter: true,- storeInitialState: createMockState({- currentUser: createMockUser({- permissions: { can_create_queries: true },+ renderWithProviders(+ <Route+ path={initialRoute ? "*" : "/"}+ component={Palette}+ {...routeProps}+ />,+ {+ withKBar: true,+ withRouter: true,+ initialRoute,+ storeInitialState: createMockState({+ currentUser: createMockUser({+ permissions: { can_create_queries: true },+ }),}),- }),- });+ },+ );};describe("command palette", () => {@@ -153,4 +163,21 @@ describe("command palette", () => {await screen.findByText("Metric search result");expect(getSelectedOption()?.textContent).toBe("Browse metrics");});++ it("should initialize the search input from the search URL query (#71248)", async () => {+ setup({+ initialRoute: "/search?q=products",+ searchResults: [createMockSearchResult({ name: "Products" })],+ });++ await userEvent.keyboard("[ControlLeft>]k");+ await screen.findByTestId("command-palette");++ await waitFor(() => {+ expect(screen.getByPlaceholderText(/search for anything/i)).toHaveValue(+ "products",+ );+ });+ expect(await screen.findByText("Products")).toBeInTheDocument();+ });});