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
Fix middle-click on search results (#76123)
Andrei Chernykh0c9ca2b55d0d
diff --git a/frontend/src/metabase/common/components/SearchResult/SearchResult.module.css b/frontend/src/metabase/common/components/SearchResult/SearchResult.module.cssnew file mode 100644index 00000000000..1c6600a7aef--- /dev/null+++ b/frontend/src/metabase/common/components/SearchResult/SearchResult.module.css@@ -0,0 +1,87 @@+.root {+ position: relative;+ display: grid;+ grid-template-columns: auto 1fr auto auto;+ justify-content: center;+ align-items: start;+ gap: var(--mantine-spacing-sm) 0.75rem;+}++.active {+ border-radius: var(--mantine-radius-md);++ &:hover {+ background-color: var(--mb-color-background-hover);+ cursor: pointer;+ }++ &:focus-within {+ background-color: var(--mb-color-background-hover);+ }+}++.selected {+ color: var(--mb-color-core-brand);+ background-color: var(--mb-color-background-hover);+}++.title {+ line-height: unset;++ /* When the title is a real link, stretch its hit area over the whole row+ (positioned by .root) so middle/ctrl-click opens the result in a new tab+ from anywhere on the row. Interactive children sit above this overlay via+ position: relative. */+ &[href]::after {+ content: "";+ position: absolute;+ inset: 0;+ }+}++/* Title colors are scoped under .root so they outrank Mantine Anchor's own+ .root color (a bare .title only ties on specificity and would lose by+ non-deterministic CSS-module emission order). The brand states all carry a+ higher specificity than the base, so the cascade stays order-independent. */+.root .title {+ color: var(--mb-color-text-primary);+}++.root .title:hover,+.root .title:focus,+.root .title:focus-visible {+ color: var(--mb-color-core-brand);+ text-decoration: none;+ outline: 0;+}++/* parent state drives the title color; the title can't know it on its own */+.root.selected .title,+.root.active:hover .title {+ color: var(--mb-color-core-brand);+}++.nameSection {+ overflow: hidden;+}++.loadingSection {+ grid-row: 1 / span 1;+ grid-column: 3;+}++.xraySection {+ grid-row: 1 / span 1;+ grid-column: 4;+}++.description {+ display: -webkit-box;+ line-clamp: 2;+ -webkit-line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+ overflow-wrap: break-word;+ white-space: pre-line;+ font-size: var(--mantine-font-size-sm);+}diff --git a/frontend/src/metabase/common/components/SearchResult/SearchResult.styled.tsx b/frontend/src/metabase/common/components/SearchResult/SearchResult.styled.tsxdeleted file mode 100644index 5a5e65b362e..00000000000--- a/frontend/src/metabase/common/components/SearchResult/SearchResult.styled.tsx+++ /dev/null@@ -1,123 +0,0 @@-import isPropValid from "@emotion/is-prop-valid";-// eslint-disable-next-line no-restricted-imports-import { css } from "@emotion/react";-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";-import type {- AnchorHTMLAttributes,- HTMLAttributes,- PropsWithChildren,- RefObject,-} from "react";--import { Markdown } from "metabase/common/components/Markdown";-import type { AnchorProps, BoxProps, ButtonProps } from "metabase/ui";-import { Anchor, Box, Button, Divider, Stack } from "metabase/ui";--const isBoxPropValid = (propName: string) => {- return (- propName !== "isActive" &&- propName !== "isSelected" &&- isPropValid(propName)- );-};--export const ResultTitle = styled(Anchor)<- AnchorProps & AnchorHTMLAttributes<HTMLAnchorElement>->`- line-height: unset;- font-weight: 700;- font-size: ${({ theme }) => theme.fontSizes.md};- color: var(--mb-color-text-primary);-- &:hover,- &:focus-visible,- &:focus {- text-decoration: none;- color: var(--mb-color-core-brand);- outline: 0;- }-`;--export const SearchResultContainer = styled(Box, {- shouldForwardProp: isBoxPropValid,-})<- BoxProps &- HTMLAttributes<HTMLButtonElement> & {- isActive?: boolean;- isSelected?: boolean;- component?: string;- ref?: RefObject<HTMLButtonElement> | null;- }->`- display: grid;- grid-template-columns: auto 1fr auto auto;- justify-content: center;- align-items: start;- gap: 0.5rem 0.75rem;- padding: ${({ theme }) => theme.spacing.sm};-- ${({ theme, isActive, isSelected }) =>- isActive &&- css`- border-radius: ${theme.radius.md};- color: ${isSelected && "var(--mb-color-core-brand)"};- background-color: ${isSelected && "var(--mb-color-background-hover)"};-- ${ResultTitle} {- color: ${isSelected && "var(--mb-color-core-brand)"};- }-- &:hover {- background-color: var(--mb-color-background-hover);- cursor: pointer;-- ${ResultTitle} {- color: var(--mb-color-core-brand);- }- }-- &:focus-within {- background-color: var(--mb-color-background-hover);- }- `}-`;--export const ResultNameSection = styled(Stack)`- overflow: hidden;-`;--export const LoadingSection = styled(Box)<BoxProps>`- grid-row: 1 / span 1;- grid-column: 3;-` as unknown as typeof Box;--export const XRaySection = styled(Box)<BoxProps>`- grid-row: 1 / span 1;- grid-column: 4;-` as unknown as typeof Box;--export const XRayButton = styled(Button)<- ButtonProps & HTMLAttributes<HTMLButtonElement>->`- width: 2rem;- height: 2rem;-`;--export const DescriptionSection = styled(Box)<PropsWithChildren>`- margin-top: 0.5rem;-` as unknown as typeof Box;--export const DescriptionDivider = styled(Divider)`- border-radius: ${({ theme }) => theme.radius.xs};-`;--export const SearchResultDescription = styled(Markdown)`- display: -webkit-box;- -webkit-line-clamp: 2;- -webkit-box-orient: vertical;- overflow: hidden;- overflow-wrap: break-word;- white-space: pre-line;- font-size: 0.75rem;-`;diff --git a/frontend/src/metabase/common/components/SearchResult/SearchResult.tsx b/frontend/src/metabase/common/components/SearchResult/SearchResult.tsxindex c0681c0796c..dd27b56cb89 100644--- a/frontend/src/metabase/common/components/SearchResult/SearchResult.tsx+++ b/frontend/src/metabase/common/components/SearchResult/SearchResult.tsx@@ -1,31 +1,84 @@+import cx from "classnames";import type { LocationDescriptorObject } from "history";-import type { MouseEvent } from "react";-import { useCallback } from "react";+import type { AnchorHTMLAttributes, HTMLAttributes, MouseEvent } from "react";+import { forwardRef, useCallback } from "react";import { push } from "react-router-redux";+import { Markdown } from "metabase/common/components/Markdown";import { trackSearchClick } from "metabase/common/search/analytics";import { PLUGIN_MODERATION } from "metabase/plugins";import { useDispatch } from "metabase/redux";-import { Group, Icon, Loader } from "metabase/ui";+import type { AnchorProps, BoxProps, StackProps } from "metabase/ui";+import {+ Anchor,+ Box,+ Button,+ Divider,+ Group,+ Icon,+ Loader,+ Stack,+ rem,+} from "metabase/ui";import { modelToUrl } from "metabase/urls";import { isSyncCompleted } from "metabase/utils/syncing";import type { SearchContext, SearchResult } from "metabase-types/api";import { InfoText } from "../InfoText";-import {- DescriptionDivider,- DescriptionSection,- LoadingSection,- ResultNameSection,- ResultTitle,- SearchResultContainer,- SearchResultDescription,- XRayButton,- XRaySection,-} from "./SearchResult.styled";+import S from "./SearchResult.module.css";import { ItemIcon } from "./components";+// Always a div: the title's stretched link handles navigation, so the row must+// not become an interactive element wrapping other interactive elements.+export const SearchResultContainer = forwardRef<+ HTMLDivElement,+ BoxProps &+ HTMLAttributes<HTMLDivElement> & {+ isActive?: boolean;+ isSelected?: boolean;+ }+>(function SearchResultContainer(+ { className, isActive, isSelected, ...props },+ ref,+) {+ return (+ <Box+ ref={ref}+ p="sm"+ className={cx(+ S.root,+ { [S.active]: isActive, [S.selected]: isActive && isSelected },+ className,+ )}+ {...props}+ />+ );+});++// base color lives in .title so .title:hover, .active:hover .title, and+// .selected .title can override it (a c prop would render an inline style)+export const ResultTitle = ({+ className,+ ...props+}: AnchorProps & AnchorHTMLAttributes<HTMLAnchorElement>) => (+ <Anchor fw={700} fz="md" className={cx(S.title, className)} {...props} />+);++export const ResultNameSection = ({+ className,+ ...props+}: StackProps & HTMLAttributes<HTMLDivElement>) => (+ <Stack className={cx(S.nameSection, className)} {...props} />+);++export const LoadingSection = ({+ className,+ ...props+}: BoxProps & HTMLAttributes<HTMLDivElement>) => (+ <Box className={cx(S.loadingSection, className)} {...props} />+);+export function SearchResult({result,compact = false,@@ -78,7 +131,33 @@ export function SearchResult({);};+ // the row navigates via the title's stretched link; gate it on isActive so an+ // item that isn't ready yet (e.g. a still-syncing table) isn't a link at all,+ // which keeps plain, modified, and middle clicks all inert+ const url = isActive && !onClick ? modelToUrl(result) : undefined;++ const trackClick = () => {+ trackSearchClick({+ itemType: "item",+ position: index,+ context,+ searchEngine: searchEngine || "unknown",+ requestId: searchRequestId,+ entityModel: result.model,+ entityId: typeof result.id === "number" ? result.id : null,+ searchTerm,+ });+ };+const handleClick = (e: MouseEvent) => {+ // let the browser open the result in a new tab/window on a modified click+ // instead of doing an in-app navigation, but still record the open+ if (url && (e.metaKey || e.ctrlKey || e.shiftKey)) {+ e.stopPropagation();+ trackClick();+ return;+ }+e.stopPropagation();e.preventDefault();@@ -90,24 +169,23 @@ export function SearchResult({onClick(result);return;}- trackSearchClick({- itemType: "item",- position: index,- context,- searchEngine: searchEngine || "unknown",- requestId: searchRequestId,- entityModel: result.model,- entityId: typeof result.id === "number" ? result.id : null,- searchTerm,- });+ trackClick();onChangeLocation(modelToUrl(result));};+ // attached to the title link (not the row) so a middle-click on a lifted+ // child such as a breadcrumb or the x-ray button doesn't record a result+ // open; onClick never fires for a middle-click, so record the open here+ const handleAuxClick = (e: MouseEvent) => {+ if (e.button === 1 && url) {+ trackClick();+ }+ };+return (<SearchResultContainerclassName={className}data-testid="search-result-item"- component="button"onClick={handleClick}isActive={isActive}isSelected={isSelected}@@ -128,7 +206,8 @@ export function SearchResult({role="heading"data-testid="search-result-item-name"truncate- href={!onClick ? modelToUrl(result) : undefined}+ href={url}+ onAuxClick={handleAuxClick}>{name}</ResultTitle>@@ -138,25 +217,29 @@ export function SearchResult({size={14}/></Group>- <InfoText showLinks={!onClick} result={result} isCompact={compact} />+ <Box pos="relative" w="fit-content" maw="100%">+ <InfoText showLinks={!onClick} result={result} isCompact={compact} />+ </Box>{description && showDescription && (- <DescriptionSection>+ <Box mt="sm"><Group wrap="nowrap" gap="sm" data-testid="result-description">- <DescriptionDivider+ <Dividersize="md"color="focus"orientation="vertical"+ bdrs="xs"/>- <SearchResultDescription+ <MarkdowndarkunwrapDisallowedunstyleLinksallowedElements={[]}+ className={S.description}>{description}- </SearchResultDescription>+ </Markdown></Group>- </DescriptionSection>+ </Box>)}</ResultNameSection>{isLoading && (@@ -165,12 +248,14 @@ export function SearchResult({</LoadingSection>)}{showXRayButton && (- <XRaySection>- <XRayButton+ <Box className={S.xraySection} pos="relative">+ <Button+ w={rem(32)}+ h={rem(32)}leftSection={<Icon name="bolt" />}onClick={onXRayClick}/>- </XRaySection>+ </Box>)}</SearchResultContainer>);diff --git a/frontend/src/metabase/common/components/SearchResult/index.ts b/frontend/src/metabase/common/components/SearchResult/index.tsindex 330f1efd5db..d8eeaf06b0e 100644--- a/frontend/src/metabase/common/components/SearchResult/index.ts+++ b/frontend/src/metabase/common/components/SearchResult/index.ts@@ -1,3 +1,8 @@-export { SearchResult } from "./SearchResult";+export {+ LoadingSection,+ ResultNameSection,+ ResultTitle,+ SearchResult,+ SearchResultContainer,+} from "./SearchResult";export * from "./components";-export * from "./SearchResult.styled";diff --git a/frontend/src/metabase/common/components/SearchResult/tests/SearchResult-Tables.unit.spec.tsx b/frontend/src/metabase/common/components/SearchResult/tests/SearchResult-Tables.unit.spec.tsxindex 1f606dc4564..558fe1da74d 100644--- a/frontend/src/metabase/common/components/SearchResult/tests/SearchResult-Tables.unit.spec.tsx+++ b/frontend/src/metabase/common/components/SearchResult/tests/SearchResult-Tables.unit.spec.tsx@@ -72,4 +72,29 @@ describe("SearchResult > Tables", () => {await userEvent.click(link);expect(onClick).not.toHaveBeenCalled();});++ it("does not turn a still-syncing table into a link (no middle/ctrl-click navigation)", () => {+ const TEST_TABLE = createMockTable({+ name: "Syncing Table",+ initial_sync_status: "incomplete",+ });+ const TEST_DATABASE = createMockDatabase();+ setupTableEndpoints(TEST_TABLE);+ setupDatabaseEndpoints(TEST_DATABASE);+ setupUsersEndpoints([USER]);+ setupUserRecipientsEndpoint({ users: [USER] });+ const result = createWrappedSearchResult({+ model: "table",+ table_id: TEST_TABLE.id,+ database_id: TEST_DATABASE.id,+ name: "Syncing Table",+ initial_sync_status: "incomplete",+ });++ renderWithProviders(<SearchResult result={result} index={0} />);++ expect(screen.getByTestId("search-result-item-name")).not.toHaveAttribute(+ "href",+ );+ });});diff --git a/frontend/src/metabase/common/components/SearchResult/tests/SearchResult.unit.spec.tsx b/frontend/src/metabase/common/components/SearchResult/tests/SearchResult.unit.spec.tsxindex 36862b1b6d3..21895f6b609 100644--- a/frontend/src/metabase/common/components/SearchResult/tests/SearchResult.unit.spec.tsx+++ b/frontend/src/metabase/common/components/SearchResult/tests/SearchResult.unit.spec.tsx@@ -6,13 +6,24 @@ import {setupUserRecipientsEndpoint,setupUsersEndpoints,} from "__support__/server-mocks";-import { getIcon, renderWithProviders, screen } from "__support__/ui";+import {+ fireEvent,+ getIcon,+ renderWithProviders,+ screen,+} from "__support__/ui";import { SearchResult } from "metabase/common/components/SearchResult/SearchResult";import { createWrappedSearchResult } from "metabase/common/components/SearchResult/tests/util";+import { trackSearchClick } from "metabase/common/search/analytics";import { modelToUrl } from "metabase/urls";import type { SearchResult as ApiSearchResult } from "metabase-types/api";import { createMockCollection, createMockUser } from "metabase-types/api/mocks";+jest.mock("metabase/common/search/analytics", () => ({+ ...jest.requireActual("metabase/common/search/analytics"),+ trackSearchClick: jest.fn(),+}));+const TEST_REGULAR_COLLECTION = createMockCollection({id: 1,name: "Regular Collection",@@ -92,6 +103,71 @@ describe("SearchResult", () => {expect(history?.getCurrentLocation().pathname).toEqual(expectedPath);});+ it("renders the result as a link and lets the browser open a modified click in a new tab", () => {+ const { history } = setup({ result: TEST_RESULT_QUESTION });++ const title = screen.getByTestId("search-result-item-name");+ expect(title).toHaveAttribute("href", modelToUrl(TEST_RESULT_QUESTION));++ fireEvent.click(title, { metaKey: true });++ // a ⌘/ctrl-click must not navigate in-app; the browser opens the new tab+ // via the href instead+ expect(history?.getCurrentLocation().pathname).toBe("/");+ });++ it("tracks a search click when a result is opened via a ⌘/ctrl-click", () => {+ const trackSearchClickMock = jest.mocked(trackSearchClick);+ trackSearchClickMock.mockClear();++ setup({ result: TEST_RESULT_QUESTION });+ fireEvent.click(screen.getByTestId("search-result-item-name"), {+ metaKey: true,+ });++ expect(trackSearchClickMock).toHaveBeenCalledWith(+ expect.objectContaining({ itemType: "item", position: 0 }),+ );+ });++ it("tracks a search click when a result is opened via a middle-click", () => {+ const trackSearchClickMock = jest.mocked(trackSearchClick);+ trackSearchClickMock.mockClear();++ setup({ result: TEST_RESULT_QUESTION });+ fireEvent(+ screen.getByTestId("search-result-item-name"),+ new MouseEvent("auxclick", {+ button: 1,+ bubbles: true,+ cancelable: true,+ }),+ );++ expect(trackSearchClickMock).toHaveBeenCalledWith(+ expect.objectContaining({ itemType: "item", position: 0 }),+ );+ });++ it("does not track a result open when a child control is middle-clicked", () => {+ const trackSearchClickMock = jest.mocked(trackSearchClick);+ trackSearchClickMock.mockClear();++ setup({ result: TEST_RESULT_INDEXED_ENTITY });+ // middle-clicking the x-ray button opens nothing for the result itself, so+ // the bubbled auxclick must not record a result-open+ fireEvent(+ getIcon("bolt"),+ new MouseEvent("auxclick", {+ button: 1,+ bubbles: true,+ cancelable: true,+ }),+ );++ expect(trackSearchClickMock).not.toHaveBeenCalled();+ });+describe("indexed entities", () => {it("renders x-ray button for indexed entity search result", () => {setup({ result: TEST_RESULT_INDEXED_ENTITY });diff --git a/frontend/src/metabase/nav/components/search/RecentsList/RecentsListContent.tsx b/frontend/src/metabase/nav/components/search/RecentsList/RecentsListContent.tsxindex f7e425a979a..7203b168479 100644--- a/frontend/src/metabase/nav/components/search/RecentsList/RecentsListContent.tsx+++ b/frontend/src/metabase/nav/components/search/RecentsList/RecentsListContent.tsx@@ -36,7 +36,7 @@ export const RecentsListContent = ({}: RecentsListContentProps) => {const { getRef, cursorIndex } = useListKeyboardNavigation<RecentItem,- HTMLButtonElement+ HTMLDivElement>({list: results,onEnter: (item: RecentItem) => onClick?.(item),@@ -75,11 +75,9 @@ export const RecentsListContent = ({data-testid="recently-viewed-item"ref={getRef(item)}key={getItemKey(item)}- component="button"onClick={() => onClick?.(item)}isActive={isActive}isSelected={cursorIndex === index}- p="sm"><ItemIcon active={isActive} item={item} type={item.model} /><ResultNameSection justify="center" gap="xs">