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
PRO-180: Add copy to clipboard for query results (#79341)
Andrei Simionescu537b24220274
diff --git a/frontend/src/metabase/data-grid/utils/formatting.ts b/frontend/src/metabase/data-grid/utils/formatting.tsindex 35f4c31443d..ed19596fbd0 100644--- a/frontend/src/metabase/data-grid/utils/formatting.ts+++ b/frontend/src/metabase/data-grid/utils/formatting.ts@@ -39,3 +39,18 @@ export const formatCellValueForCopy = (return formatter(rawValue, rowIndex, columnId);};++const NEEDS_QUOTING_PATTERN = /[\t\n\r]/;++const needsQuoting = (text: string) => NEEDS_QUOTING_PATTERN.test(text);++export const serializeTsv = (lines: string[][]): string =>+ lines+ .map((cells) =>+ cells+ .map((cell) =>+ needsQuoting(cell) ? `"${cell.replaceAll('"', '""')}"` : cell,+ )+ .join("\t"),+ )+ .join("\n");diff --git a/frontend/src/metabase/data-grid/utils/formatting.unit.spec.ts b/frontend/src/metabase/data-grid/utils/formatting.unit.spec.tsnew file mode 100644index 00000000000..5dbed332552--- /dev/null+++ b/frontend/src/metabase/data-grid/utils/formatting.unit.spec.ts@@ -0,0 +1,38 @@+import { parse } from "csv-parse/browser/esm/sync";++import { serializeTsv } from "./formatting";++const roundTrip = (lines: string[][]): string[][] =>+ parse(serializeTsv(lines), { delimiter: "\t" });++describe("serializeTsv", () => {+ it("joins cells with tabs and lines with newlines", () => {+ expect(+ serializeTsv([+ ["a", "b"],+ ["c", "d"],+ ]),+ ).toBe("a\tb\nc\td");+ });++ it("quotes cells containing tabs, newlines, or carriage returns", () => {+ expect(serializeTsv([["tab\there", "line\nbreak", "cr\rhere"]])).toBe(+ '"tab\there"\t"line\nbreak"\t"cr\rhere"',+ );+ });++ it("round-trips quoted cells, doubling their embedded quotes", () => {+ const lines = [['say "hi"\twith tab', 'multi\n"quoted"']];+ expect(roundTrip(lines)).toEqual(lines);+ });++ it("leaves cells without delimiters unquoted, even when they contain quotes", () => {+ expect(serializeTsv([['say "hi"', '{"tags":["a","b"]}']])).toBe(+ 'say "hi"\t{"tags":["a","b"]}',+ );+ });++ it("keeps empty cells so the pasted shape survives", () => {+ expect(serializeTsv([["a", "", "c"]])).toBe("a\t\tc");+ });+});diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/RightViewFooterButtonGroup.tsx b/frontend/src/metabase/query_builder/components/view/ViewFooter/RightViewFooterButtonGroup.tsxindex de1119d53d7..917565d7074 100644--- a/frontend/src/metabase/query_builder/components/view/ViewFooter/RightViewFooterButtonGroup.tsx+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/RightViewFooterButtonGroup.tsx@@ -1,6 +1,7 @@import cx from "classnames";import CS from "metabase/css/core/index.css";+import { ViewFooterCopyWidget } from "metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget";import { ViewFooterDownloadWidget } from "metabase/query_builder/components/view/ViewFooter/ViewFooterDownloadWidget";import {getFirstQueryResult,@@ -38,6 +39,9 @@ export const RightViewFooterButtonGroup = () => {result={result}/>)}+ {ViewFooterCopyWidget.shouldRender({ result }) && (+ <ViewFooterCopyWidget />+ )}<ViewFooterDownloadWidget />{QuestionTimelineWidget.shouldRender({ isTimeseries }) && (<QuestionTimelineWidget className={cx(CS.hide, CS.smShow)} />diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.tsx b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.tsxnew file mode 100644index 00000000000..8204b2e71b1--- /dev/null+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.tsx@@ -0,0 +1,91 @@+import { useMemo } from "react";+import { t } from "ttag";++import { canDownloadResults } from "metabase/common/utils/dataset";+import { getFirstQueryResult } from "metabase/query_builder/selectors";+import { useSelector } from "metabase/redux";+import { useSetting } from "metabase/settings";+import { ActionIcon, Flex, Icon, Tooltip } from "metabase/ui";+import type Question from "metabase-lib/v1/Question";+import type { Dataset } from "metabase-types/api";++import {+ getCopyIneligibleReason,+ getCopyMode,+ useCopyResults,+} from "./use-copy-results";+import { useRenderedQuestion } from "./use-rendered-question";++export const ViewFooterCopyWidget = () => {+ const { question, isPivotResult, staleReason } = useRenderedQuestion();+ const result = useSelector(getFirstQueryResult);++ return (+ question &&+ result && (+ <CopyResultsButton+ question={question}+ result={result}+ isPivotResult={isPivotResult}+ staleReason={staleReason}+ />+ )+ );+};++interface CopyResultsButtonProps {+ question: Question;+ result: Dataset;+ isPivotResult: boolean;+ staleReason: string | null;+}++const CopyResultsButton = ({+ question,+ result,+ isPivotResult,+ staleReason,+}: CopyResultsButtonProps) => {+ const pivotedCopyEnabled = useSetting("enable-pivoted-exports") ?? true;+ const ineligibleReason = useMemo(+ () =>+ staleReason ??+ getCopyIneligibleReason(+ question,+ result,+ isPivotResult,+ pivotedCopyEnabled,+ ),+ [staleReason, question, result, isPivotResult, pivotedCopyEnabled],+ );+ const copyResults = useCopyResults({+ question,+ result,+ isPivotResult,+ pivotedCopyEnabled,+ });++ const label =+ getCopyMode(question) === "results"+ ? t`Copy these results to clipboard`+ : t`Copy this chart to clipboard`;++ return (+ <Flex visibleFrom="sm">+ <Tooltip label={ineligibleReason ?? label}>+ <ActionIcon+ data-testid="question-results-copy-button"+ onClick={copyResults}+ aria-label={label}+ disabled={ineligibleReason !== null}+ variant="viewFooter"+ >+ <Icon name="clipboard" />+ </ActionIcon>+ </Tooltip>+ </Flex>+ );+};++ViewFooterCopyWidget.shouldRender = ({ result }: { result?: Dataset | null }) =>+ result != null && canDownloadResults(result);diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsxnew file mode 100644index 00000000000..22ffb085e78--- /dev/null+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/ViewFooterCopyWidget.unit.spec.tsx@@ -0,0 +1,685 @@+import userEvent from "@testing-library/user-event";++import { act, renderWithProviders, screen, waitFor } from "__support__/ui";+import { queryErrored } from "metabase/query_builder/actions/querying";+import * as SaveChartImage from "metabase/visualizations/lib/save-chart-image";+import { registerVisualizations } from "metabase/visualizations/register";+import type { Card, Dataset } from "metabase-types/api";+import { createMockColumn, createMockDataset } from "metabase-types/api/mocks";++import { ViewFooterCopyWidget } from "./ViewFooterCopyWidget";+import {+ ALL_HIDDEN_OBJECT_CARD,+ ALL_HIDDEN_TABLE_CARD,+ CLASSIC_PIVOT_CARD,+ CLASSIC_PIVOT_RESULT,+ DETAILS_TABLE_RESULT,+ LINE_CARD,+ OBJECT_CARD,+ OBJECT_CARD_WITH_HIDDEN_COLUMN,+ PIVOT_CARD,+ PIVOT_RESULT,+ SCALAR_CARD,+ TABLE_CARD,+ TABLE_RESULT,+ createSparseAggregateResult,+ createSparseClassicPivotResult,+ createSparsePivotResult,+ createViewFooterState,+} from "./test-utils";++jest.mock("metabase/visualizations/lib/save-chart-image", () => ({+ ...jest.requireActual<typeof SaveChartImage>(+ "metabase/visualizations/lib/save-chart-image",+ ),+ getChartImageBlob: jest.fn(),+}));++registerVisualizations();++// One shared row instance keeps the over-limit fixture cheap to build+const WIDE_ROW = Array.from({ length: 501 }, () => 1);++const ORIGINAL_CLIPBOARD = navigator.clipboard;+const ORIGINAL_CLIPBOARD_ITEM = window.ClipboardItem;++afterEach(() => {+ jest.mocked(SaveChartImage.getChartImageBlob).mockReset();+ Object.assign(navigator, { clipboard: ORIGINAL_CLIPBOARD });+ Object.assign(window, { ClipboardItem: ORIGINAL_CLIPBOARD_ITEM });+});++// jsdom has no ClipboardItem; a stub that keeps its input is enough+class FakeClipboardItem {+ constructor(readonly parts: Record<string, Blob | Promise<Blob>>) {}+}++// jsdom's Blob has no .text()+const readBlob = (blob: Blob) =>+ new Promise<string>((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(String(reader.result));+ reader.onerror = () => reject(reader.error);+ reader.readAsText(blob);+ });++const mockClipboardWrite = () => {+ Object.assign(window, { ClipboardItem: FakeClipboardItem });+ const write = jest.fn().mockResolvedValue(undefined);+ Object.assign(navigator, { clipboard: { write } });+ return write;+};++const mockClipboardWriteText = () => {+ Reflect.deleteProperty(window, "ClipboardItem");+ const writeText = jest.fn().mockResolvedValue(undefined);+ Object.assign(navigator, { clipboard: { writeText } });+ return writeText;+};++interface SetupOpts {+ card: Card;+ result: Dataset;+ lastRunCard?: Card;+ isRunning?: boolean;+ isShowingRawTable?: boolean;+ pivotedExportsEnabled?: boolean;+ whitelabeled?: boolean;+}++const setup = (opts: SetupOpts) =>+ renderWithProviders(<ViewFooterCopyWidget />, {+ storeInitialState: createViewFooterState(opts),+ });++describe("ViewFooterCopyWidget", () => {+ it("copies text and html table flavors so spreadsheets paste a grid", async () => {+ const write = mockClipboardWrite();+ setup({ card: TABLE_CARD, result: TABLE_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => expect(write).toHaveBeenCalledTimes(1));+ const item: FakeClipboardItem = write.mock.calls[0][0][0];+ expect(await readBlob(await item.parts["text/plain"])).toBe(+ "Name\tTotal\nWidget\t10.5",+ );+ expect(await readBlob(await item.parts["text/html"])).toBe(+ "<table><tbody><tr><td>Name</td><td>Total</td></tr><tr><td>Widget</td><td>10.5</td></tr></tbody></table>",+ );+ });++ it("copies the rendered grid for pivot tables", async () => {+ const writeText = mockClipboardWriteText();+ setup({ card: PIVOT_CARD, result: PIVOT_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith(+ ["Category\tAlpha\tBeta", "Doohickey\t10\t20"].join("\n"),+ ),+ );+ });++ it("copies the flat table when the raw data view is shown", async () => {+ const writeText = mockClipboardWriteText();+ setup({ card: PIVOT_CARD, result: PIVOT_RESULT, isShowingRawTable: true });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith(+ [+ "Category\tVendor\tCount",+ "Doohickey\tAlpha\t10",+ "Doohickey\tBeta\t20",+ ].join("\n"),+ ),+ );+ });++ it("copies results, not a chart, when a chart is toggled to the raw data view", async () => {+ const writeText = mockClipboardWriteText();+ setup({ card: LINE_CARD, result: TABLE_RESULT, isShowingRawTable: true });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith("Name\tTotal\nWidget\t10.5"),+ );+ });++ it("copies a png of the chart for chart views", async () => {+ const write = mockClipboardWrite();+ jest+ .mocked(SaveChartImage.getChartImageBlob)+ .mockResolvedValue(new Blob(["png-bytes"], { type: "image/png" }));+ setup({ card: LINE_CARD, result: TABLE_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy this chart to clipboard"),+ );++ await waitFor(() => expect(write).toHaveBeenCalledTimes(1));+ const item: FakeClipboardItem = write.mock.calls[0][0][0];+ expect(await readBlob(await item.parts["image/png"])).toBe("png-bytes");+ expect(SaveChartImage.getChartImageBlob).toHaveBeenCalledWith(+ expect.objectContaining({ includeBranding: true }),+ );+ });++ it("suppresses the chart branding when the instance is whitelabeled", async () => {+ const write = mockClipboardWrite();+ jest+ .mocked(SaveChartImage.getChartImageBlob)+ .mockResolvedValue(new Blob(["png-bytes"], { type: "image/png" }));+ setup({ card: LINE_CARD, result: TABLE_RESULT, whitelabeled: true });++ await userEvent.click(+ screen.getByLabelText("Copy this chart to clipboard"),+ );++ await waitFor(() => expect(write).toHaveBeenCalledTimes(1));+ const item: FakeClipboardItem = write.mock.calls[0][0][0];+ expect(await readBlob(await item.parts["image/png"])).toBe("png-bytes");+ expect(SaveChartImage.getChartImageBlob).toHaveBeenCalledWith(+ expect.objectContaining({ includeBranding: false }),+ );+ });++ it("copies a pivot flat when pivoted exports are disabled", async () => {+ const writeText = mockClipboardWriteText();+ setup({+ card: PIVOT_CARD,+ result: PIVOT_RESULT,+ pivotedExportsEnabled: false,+ });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith(+ [+ "Category\tVendor\tCount",+ "Doohickey\tAlpha\t10",+ "Doohickey\tBeta\t20",+ ].join("\n"),+ ),+ );+ });++ it.each([+ ["table", TABLE_CARD, "Name\tTotal\nWidget\t10.5"],+ ["scalar", SCALAR_CARD, "Name\tTotal\nWidget\t10.5"],+ ["object", OBJECT_CARD, "Name\tTotal\tRaw JSON\nWidget\t10.5\t{}"],+ ])(+ "copies details-only fields only for the %s views that render them",+ async (_display, card, expected) => {+ const writeText = mockClipboardWriteText();+ setup({ card, result: DETAILS_TABLE_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => expect(writeText).toHaveBeenCalledWith(expected));+ },+ );++ it("skips columns hidden in the object detail view", async () => {+ const writeText = mockClipboardWriteText();++ setup({+ card: OBJECT_CARD_WITH_HIDDEN_COLUMN,+ result: DETAILS_TABLE_RESULT,+ });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith("Total\tRaw JSON\n10.5\t{}"),+ );+ });++ it("disables copy when every object detail column is hidden", async () => {+ const writeText = mockClipboardWriteText();++ setup({ card: ALL_HIDDEN_OBJECT_CARD, result: DETAILS_TABLE_RESULT });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText(+ "All columns are hidden, so there's nothing to copy",+ ),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it("disables copy for a pivot the renderer rejected as truncated", async () => {+ const writeText = mockClipboardWriteText();+ const truncated = createMockDataset({+ data: { ...PIVOT_RESULT.data, pivot_rows_truncated: 1000 },+ });++ setup({ card: PIVOT_CARD, result: truncated });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText(+ "This pivot table is truncated and can't be copied",+ ),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it("disables copy for a truncated pivot even when pivoted exports are off", async () => {+ const writeText = mockClipboardWriteText();+ const truncated = createMockDataset({+ data: { ...PIVOT_RESULT.data, pivot_rows_truncated: 1000 },+ });++ setup({+ card: PIVOT_CARD,+ result: truncated,+ pivotedExportsEnabled: false,+ });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText(+ "This pivot table is truncated and can't be copied",+ ),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it.each([[false], [true]])(+ "disables copy for a pivot result with only total rows (raw view: %s)",+ async (isShowingRawTable) => {+ const writeText = mockClipboardWriteText();+ const totalsOnly = createMockDataset({+ data: {+ ...PIVOT_RESULT.data,+ rows: [[null, null, 0, 3]],+ },+ });++ setup({ card: PIVOT_CARD, result: totalsOnly, isShowingRawTable });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("There are no results to copy"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ },+ );++ it.each([+ ["pivot", PIVOT_CARD, createSparsePivotResult(2000)],+ ["classic pivot", CLASSIC_PIVOT_CARD, createSparseClassicPivotResult(2000)],+ ])(+ "disables copy for a sparse %s whose grid would be too large",+ async (_desc, card, result) => {+ const writeText = mockClipboardWriteText();++ setup({ card, result });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("These results are too large to copy"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ },+ );++ it("keeps copy enabled for an ordinary table with a column named pivot-grouping", async () => {+ const writeText = mockClipboardWriteText();+ const result = createMockDataset({+ data: {+ cols: [+ createMockColumn({+ name: "pivot-grouping",+ display_name: "pivot-grouping",+ base_type: "type/Integer",+ }),+ ],+ rows: [[1], [2]],+ },+ });++ setup({ card: TABLE_CARD, result });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).not.toHaveAttribute("data-disabled");+ await userEvent.click(button);++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith("pivot-grouping\n1\n2"),+ );+ });++ it("keeps copy enabled for a high-cardinality aggregate that renders flat", async () => {+ const writeText = mockClipboardWriteText();++ setup({ card: TABLE_CARD, result: createSparseAggregateResult(2000) });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).not.toHaveAttribute("data-disabled");+ await userEvent.click(button);++ await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));+ expect(writeText.mock.calls[0][0].split("\n")).toHaveLength(2001);+ });++ it("disables copy for a flat table with more cells than the copy limit", async () => {+ const writeText = mockClipboardWriteText();+ const wide = createMockDataset({+ data: {+ cols: Array.from({ length: 501 }, (_, index) =>+ createMockColumn({+ name: `WIDE_${index}`,+ display_name: `Wide ${index}`,+ base_type: "type/Integer",+ }),+ ),+ rows: Array.from({ length: 2000 }, () => WIDE_ROW),+ },+ });++ setup({ card: TABLE_CARD, result: wide });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("These results are too large to copy"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it("shows the too-large toast when serialized text passes the size limit", async () => {+ const writeText = mockClipboardWriteText();+ const huge = createMockDataset({+ data: {+ ...TABLE_RESULT.data,+ rows: [["x".repeat(21_000_000), 1]],+ },+ });++ const { store } = setup({ card: TABLE_CARD, result: huge });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => {+ expect(store.getState().undo).toContainEqual(+ expect.objectContaining({+ message: "These results are too large to copy",+ }),+ );+ });+ expect(writeText).not.toHaveBeenCalled();+ });++ it("disables chart copy when there are no results to render", async () => {+ mockClipboardWrite();+ const empty = createMockDataset({+ data: { ...TABLE_RESULT.data, rows: [] },+ });++ setup({ card: LINE_CARD, result: empty });++ const button = screen.getByLabelText("Copy this chart to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("There are no results to copy"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(SaveChartImage.getChartImageBlob).not.toHaveBeenCalled();+ });++ it("disables chart copy when the browser cannot write image clipboard items", async () => {+ mockClipboardWriteText();++ setup({ card: LINE_CARD, result: TABLE_RESULT });++ const button = screen.getByLabelText("Copy this chart to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("Copying isn't supported in this browser"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(SaveChartImage.getChartImageBlob).not.toHaveBeenCalled();+ });++ it("disables results copy when the browser exposes no clipboard API", async () => {+ Reflect.deleteProperty(window, "ClipboardItem");+ Object.assign(navigator, { clipboard: undefined });++ setup({ card: TABLE_CARD, result: TABLE_RESULT });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("Copying isn't supported in this browser"),+ ).toBeInTheDocument();+ });++ it("disables copy for a table with every column hidden", async () => {+ const writeText = mockClipboardWriteText();++ setup({ card: ALL_HIDDEN_TABLE_CARD, result: TABLE_RESULT });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText(+ "All columns are hidden, so there's nothing to copy",+ ),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it("disables copy while a rerun is pending", async () => {+ const writeText = mockClipboardWriteText();++ setup({ card: TABLE_CARD, result: TABLE_RESULT, isRunning: true });++ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("Results are still loading"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ });++ it.each([+ [+ "a pivot result behind a table view",+ TABLE_CARD,+ PIVOT_CARD,+ PIVOT_RESULT,+ ],+ [+ "a table result behind a pivot view",+ PIVOT_CARD,+ TABLE_CARD,+ TABLE_RESULT,+ ],+ ])(+ "disables copy when a cancelled rerun leaves %s",+ async (_desc, card, lastRunCard, result) => {+ const writeText = mockClipboardWriteText();++ const { store } = setup({ card, result, lastRunCard, isRunning: true });+ await act(async () => {+ await store.dispatch(+ queryErrored(+ Date.now(),+ new DOMException("The operation was aborted.", "AbortError"),+ ),+ );+ });++ expect(store.getState().qb.lastRunCard).toEqual(lastRunCard);+ expect(store.getState().qb.queryResults).toEqual([result]);+ const button = screen.getByLabelText("Copy these results to clipboard");+ expect(button).toHaveAttribute("data-disabled", "true");+ await userEvent.hover(button);+ expect(+ await screen.findByText("Rerun the query to copy its results"),+ ).toBeInTheDocument();+ await userEvent.click(button);+ expect(writeText).not.toHaveBeenCalled();+ },+ );++ it("says the raw view of a truncated pivot copied only the first rows", async () => {+ const writeText = mockClipboardWriteText();+ const truncated = createMockDataset({+ data: { ...PIVOT_RESULT.data, pivot_rows_truncated: 1000 },+ });++ const { store } = setup({+ card: PIVOT_CARD,+ result: truncated,+ isShowingRawTable: true,+ });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() =>+ expect(writeText).toHaveBeenCalledWith(+ [+ "Category\tVendor\tCount",+ "Doohickey\tAlpha\t10",+ "Doohickey\tBeta\t20",+ ].join("\n"),+ ),+ );+ await waitFor(() => {+ expect(store.getState().undo).toContainEqual(+ expect.objectContaining({+ message: "First 2 rows copied to clipboard",+ }),+ );+ });+ });++ it("starts the chart clipboard write before the image is rendered", async () => {+ const write = mockClipboardWrite();+ jest+ .mocked(SaveChartImage.getChartImageBlob)+ .mockReturnValue(new Promise(() => {}));++ setup({ card: LINE_CARD, result: TABLE_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy this chart to clipboard"),+ );++ expect(write).toHaveBeenCalledTimes(1);+ });++ it("shows an error toast when the clipboard write fails", async () => {+ Reflect.deleteProperty(window, "ClipboardItem");+ const writeText = jest.fn().mockRejectedValue(new Error("denied"));+ Object.assign(navigator, { clipboard: { writeText } });++ const { store } = setup({ card: TABLE_CARD, result: TABLE_RESULT });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => {+ expect(store.getState().undo).toContainEqual(+ expect.objectContaining({+ message: "Couldn't copy to clipboard",+ }),+ );+ });+ });++ it("says when only the first rows were copied", async () => {+ mockClipboardWriteText();+ const truncated = createMockDataset({+ data: { ...TABLE_RESULT.data, rows_truncated: 2000 },+ });++ const { store } = setup({ card: TABLE_CARD, result: truncated });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => {+ expect(store.getState().undo).toContainEqual(+ expect.objectContaining({+ message: "First 1 row copied to clipboard",+ }),+ );+ });+ });++ it("says the pivot was computed from a truncated result", async () => {+ mockClipboardWriteText();+ const truncated = createMockDataset({+ data: { ...CLASSIC_PIVOT_RESULT.data, rows_truncated: 2000 },+ });++ const { store } = setup({ card: CLASSIC_PIVOT_CARD, result: truncated });++ await userEvent.click(+ screen.getByLabelText("Copy these results to clipboard"),+ );++ await waitFor(() => {+ expect(store.getState().undo).toContainEqual(+ expect.objectContaining({+ message:+ "Pivot table copied to clipboard, based on the first 2,000 rows of the result",+ }),+ );+ });+ });+});diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/test-utils.ts b/frontend/src/metabase/query_builder/components/view/ViewFooter/test-utils.tsnew file mode 100644index 00000000000..49b0b1cad65--- /dev/null+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/test-utils.ts@@ -0,0 +1,294 @@+import { mockSettings } from "__support__/settings";+import { createMockEntitiesState } from "__support__/store";+import {+ createMockQueryBuilderState,+ createMockQueryBuilderUIControlsState,+ createMockState,+} from "metabase/redux/store/mocks";+import type { Card, Dataset } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDataset,+ createMockStructuredDatasetQuery,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";+import { ORDERS_ID, SAMPLE_DB_ID } from "metabase-types/api/mocks/presets";++const testDatasetQuery = () =>+ createMockStructuredDatasetQuery({+ database: SAMPLE_DB_ID,+ query: { "source-table": ORDERS_ID },+ });++export const TABLE_CARD = createMockCard({+ display: "table",+ dataset_query: testDatasetQuery(),+});++export const TABLE_RESULT = createMockDataset({+ data: {+ cols: [+ createMockColumn({+ name: "NAME",+ display_name: "Name",+ base_type: "type/Text",+ }),+ createMockColumn({+ name: "TOTAL",+ display_name: "Total",+ base_type: "type/Float",+ }),+ ],+ rows: [["Widget", 10.5]],+ },+});++export const PIVOT_CARD = createMockCard({+ display: "pivot",+ dataset_query: testDatasetQuery(),+ visualization_settings: {+ "pivot_table.column_split": {+ rows: ["CATEGORY"],+ columns: ["VENDOR"],+ values: ["COUNT"],+ },+ "pivot.show_row_totals": false,+ "pivot.show_column_totals": false,+ },+});++export const PIVOT_RESULT = createMockDataset({+ data: {+ cols: [+ createMockColumn({+ name: "CATEGORY",+ display_name: "Category",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "VENDOR",+ display_name: "Vendor",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "COUNT",+ display_name: "Count",+ base_type: "type/Integer",+ source: "aggregation",+ }),+ createMockColumn({+ name: "pivot-grouping",+ display_name: "pivot-grouping",+ base_type: "type/Integer",+ }),+ ],+ rows: [+ ["Doohickey", "Alpha", 10, 0],+ ["Doohickey", "Beta", 20, 0],+ [null, "Alpha", 30, 1],+ ],+ },+});++export const CLASSIC_PIVOT_CARD = createMockCard({+ display: "table",+ dataset_query: testDatasetQuery(),+ visualization_settings: {+ "table.pivot": true,+ "table.pivot_column": "VENDOR",+ "table.cell_column": "COUNT",+ },+});++export const CLASSIC_PIVOT_RESULT = createMockDataset({+ data: {+ cols: [+ createMockColumn({+ name: "CATEGORY",+ display_name: "Category",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "VENDOR",+ display_name: "Vendor",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "COUNT",+ display_name: "Count",+ base_type: "type/Integer",+ source: "aggregation",+ }),+ ],+ rows: [+ ["Doohickey", "Alpha", 10],+ ["Doohickey", "Beta", 20],+ ["Gizmo", "Alpha", 30],+ ],+ },+});++export const DETAILS_TABLE_RESULT = createMockDataset({+ data: {+ cols: [+ ...TABLE_RESULT.data.cols,+ createMockColumn({+ name: "RAW_JSON",+ display_name: "Raw JSON",+ base_type: "type/Text",+ visibility_type: "details-only",+ }),+ ],+ rows: [["Widget", 10.5, "{}"]],+ },+});++// One observation per distinct row/column key pair, so the logical pivot grid+// is size × size while the source stays at size rows+export const createSparsePivotResult = (size: number) =>+ createMockDataset({+ data: {+ ...PIVOT_RESULT.data,+ rows: Array.from({ length: size }, (_, index) => [+ `row-${index}`,+ `column-${index}`,+ 1,+ 0,+ ]),+ },+ });++export const createSparseClassicPivotResult = (size: number) =>+ createMockDataset({+ data: {+ ...CLASSIC_PIVOT_RESULT.data,+ rows: Array.from({ length: size }, (_, index) => [+ `row-${index}`,+ `column-${index}`,+ 1,+ ]),+ },+ });++// Cardinality high enough that the table renders flat instead of auto-pivoting.+// Unique column names: the column-cardinality cache is module-global, name-keyed+export const createSparseAggregateResult = (size: number) =>+ createMockDataset({+ data: {+ cols: [+ createMockColumn({+ name: "AUTOPIVOT_DIM_A",+ display_name: "Dim A",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "AUTOPIVOT_DIM_B",+ display_name: "Dim B",+ base_type: "type/Text",+ source: "breakout",+ }),+ createMockColumn({+ name: "AUTOPIVOT_COUNT",+ display_name: "Count",+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "aggregation",+ }),+ ],+ rows: Array.from({ length: size }, (_, index) => [+ `a-${index}`,+ `b-${index}`,+ 1,+ ]),+ },+ });++export const ALL_HIDDEN_TABLE_CARD = createMockCard({+ display: "table",+ dataset_query: testDatasetQuery(),+ visualization_settings: {+ "table.columns": [+ { name: "NAME", enabled: false },+ { name: "TOTAL", enabled: false },+ ],+ },+});++export const LINE_CARD = createMockCard({+ display: "line",+ dataset_query: testDatasetQuery(),+});++export const SCALAR_CARD = createMockCard({+ display: "scalar",+ dataset_query: testDatasetQuery(),+});++export const OBJECT_CARD = createMockCard({+ display: "object",+ dataset_query: testDatasetQuery(),+});++export const OBJECT_CARD_WITH_HIDDEN_COLUMN = createMockCard({+ display: "object",+ dataset_query: testDatasetQuery(),+ visualization_settings: {+ "table.columns": [+ { name: "NAME", enabled: false },+ { name: "TOTAL", enabled: true },+ { name: "RAW_JSON", enabled: true },+ ],+ },+});++export const ALL_HIDDEN_OBJECT_CARD = createMockCard({+ display: "object",+ dataset_query: testDatasetQuery(),+ visualization_settings: {+ "table.columns": [+ { name: "NAME", enabled: false },+ { name: "TOTAL", enabled: false },+ { name: "RAW_JSON", enabled: false },+ ],+ },+});++export const createViewFooterState = ({+ card,+ result,+ lastRunCard = card,+ isRunning = false,+ isShowingRawTable = false,+ pivotedExportsEnabled = true,+ whitelabeled = false,+}: {+ card: Card;+ result: Dataset;+ lastRunCard?: Card;+ isRunning?: boolean;+ isShowingRawTable?: boolean;+ pivotedExportsEnabled?: boolean;+ whitelabeled?: boolean;+}) =>+ createMockState({+ entities: createMockEntitiesState({ questions: [card] }),+ settings: mockSettings({+ "enable-pivoted-exports": pivotedExportsEnabled,+ "token-features": createMockTokenFeatures({ whitelabel: whitelabeled }),+ }),+ qb: createMockQueryBuilderState({+ card,+ lastRunCard,+ queryResults: [result],+ uiControls: createMockQueryBuilderUIControlsState({+ isRunning,+ isShowingRawTable,+ }),+ }),+ });diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/use-copy-results.ts b/frontend/src/metabase/query_builder/components/view/ViewFooter/use-copy-results.tsnew file mode 100644index 00000000000..1d486353fa4--- /dev/null+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/use-copy-results.ts@@ -0,0 +1,308 @@+import { useCallback } from "react";+import { t } from "ttag";++import {+ type NumberFormatter,+ useNumberFormatter,+} from "metabase/common/hooks/use-number-formatter";+import { formatRowCount } from "metabase/common/utils/format-row-count";+import { useTranslateContent } from "metabase/content-translation/hooks";+import { useDispatch, useSelector } from "metabase/redux";+import { addUndo } from "metabase/redux/undo";+import { getTokenFeature } from "metabase/settings";+import { canSavePng, extractRemappedColumns } from "metabase/visualizations";+import { multiLevelPivot } from "metabase/visualizations/lib/data_grid";+import { getChartSelector } from "metabase/visualizations/lib/image-exports";+import { hasNoResults } from "metabase/visualizations/lib/no-results";+import {+ MAX_COPY_CELLS,+ ResultsTooLargeError,+ flattenPivotGroupedData,+ getResultsClipboardContent,+} from "metabase/visualizations/lib/results-clipboard";+import { getChartImageBlob } from "metabase/visualizations/lib/save-chart-image";+import { isPivoted } from "metabase/visualizations/lib/settings/column";+import { getComputedSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";+import {+ getClassicPivotColumnIndexes,+ getVisibleTableData,+} from "metabase/visualizations/lib/visible-table-data";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type Question from "metabase-lib/v1/Question";+import { datasetContainsNoResults } from "metabase-lib/v1/queries/utils/dataset";+import type {+ Card,+ Dataset,+ DatasetData,+ RawSeries,+ RowValues,+} from "metabase-types/api";++type CopyMode = "results" | "chart";++const isGridDisplay = (question: Question) =>+ question.display() === "table" || question.display() === "pivot";++export const getCopyMode = (question: Question): CopyMode =>+ isGridDisplay(question) || !canSavePng(question.display())+ ? "results"+ : "chart";++const canWriteRichClipboard = () =>+ typeof ClipboardItem !== "undefined" &&+ typeof navigator.clipboard?.write === "function";++const canWriteTextClipboard = () =>+ typeof navigator.clipboard?.writeText === "function";++const getTooLargeReason = () => t`These results are too large to copy`;++const countDistinctValues = (rows: RowValues[], columnIndex: number) =>+ new Set(rows.map((row) => row[columnIndex])).size;++// multiLevelPivot returns the grid's dimensions plus a getRowSection accessor,+// so its size can be measured without fetching any cells+const getPivotGridSizeReason = (+ card: Card,+ data: DatasetData,+): string | null => {+ const series: RawSeries = [{ card, data: extractRemappedColumns(data) }];+ const settings = getComputedSettingsForSeries(series);+ const pivotData = multiLevelPivot(series[0].data, settings);+ if (!pivotData) {+ return null;+ }+ const cellCount =+ pivotData.rowCount * pivotData.columnCount * pivotData.valueIndexes.length;+ return cellCount > MAX_COPY_CELLS ? getTooLargeReason() : null;+};++const getClassicPivotSizeReason = (+ data: DatasetData,+ settings: ComputedVisualizationSettings,+): string | null => {+ const { pivotIndex, normalIndex } = getClassicPivotColumnIndexes(+ data,+ settings,+ );+ if (pivotIndex < 0 || normalIndex < 0) {+ return null;+ }+ const cellCount =+ countDistinctValues(data.rows, normalIndex) *+ (countDistinctValues(data.rows, pivotIndex) + 1);+ return cellCount > MAX_COPY_CELLS ? getTooLargeReason() : null;+};++export const getCopyIneligibleReason = (+ question: Question,+ result: Dataset,+ isPivotResult: boolean,+ pivotedCopyEnabled: boolean,+): string | null => {+ // hasNoResults spots a pivot by column name alone, so an ordinary table with+ // a real column named pivot-grouping would read as an empty pivot+ const noResults = isPivotResult+ ? hasNoResults(result.data)+ : datasetContainsNoResults(result.data);+ if (noResults) {+ return t`There are no results to copy`;+ }++ if (getCopyMode(question) === "chart") {+ return canWriteRichClipboard()+ ? null+ : t`Copying isn't supported in this browser`;+ }++ if (!canWriteRichClipboard() && !canWriteTextClipboard()) {+ return t`Copying isn't supported in this browser`;+ }++ // The pivot renderer rejects a truncated result whatever the pivoted-export+ // format setting says, so nothing coherent is on screen to copy+ if (+ question.display() === "pivot" &&+ result.data.pivot_rows_truncated != null+ ) {+ return t`This pivot table is truncated and can't be copied`;+ }++ // The pivot grid comes from multiLevelPivot, not table.columns, so the+ // hidden-columns check below doesn't apply to it+ if (question.display() === "pivot" && pivotedCopyEnabled) {+ return getPivotGridSizeReason(question.card(), result.data);+ }++ // Anything but a table display (a chart, or a pivot copied flat because pivoted+ // copy is off) has no table.columns settings, so it copies through a table card+ const card =+ question.display() === "table"+ ? question.card()+ : question.setDisplay("table").card();+ const series: RawSeries = [+ { card, data: extractRemappedColumns(result.data) },+ ];+ const settings = getComputedSettingsForSeries(series);++ if (isPivoted(series, settings)) {+ return getClassicPivotSizeReason(result.data, settings);+ }++ const flatSeries: RawSeries = [+ {+ card,+ data: isPivotResult+ ? flattenPivotGroupedData(series[0].data)+ : series[0].data,+ },+ ];+ const { cols } = getVisibleTableData({+ series: flatSeries,+ settings,+ isShowingDetailsOnlyColumns: question.display() === "object",+ isShowingDisabledColumns: false,+ });++ if (cols.length === 0) {+ return t`All columns are hidden, so there's nothing to copy`;+ }+ return result.data.rows.length * cols.length > MAX_COPY_CELLS+ ? getTooLargeReason()+ : null;+};++interface UseCopyResultsParams {+ question: Question;+ result: Dataset;+ isPivotResult: boolean;+ pivotedCopyEnabled: boolean;+}++export const useCopyResults = ({+ question,+ result,+ isPivotResult,+ pivotedCopyEnabled,+}: UseCopyResultsParams) => {+ const dispatch = useDispatch();+ const translate = useTranslateContent();+ const formatNumber = useNumberFormatter();+ const isWhitelabeled = useSelector((state) =>+ getTokenFeature(state, "whitelabel"),+ );++ return useCallback(async (): Promise<void> => {+ try {+ if (getCopyMode(question) === "chart") {+ await copyChartImage(question, !isWhitelabeled);+ dispatch(addUndo({ message: t`Chart copied to clipboard` }));+ return;+ }++ const copiesPivotGrid =+ question.display() === "pivot" && pivotedCopyEnabled;+ const card =+ question.display() === "table" || copiesPivotGrid+ ? question.card()+ : question.setDisplay("table").card();++ const { text, html, rowCount, isPivotGrid } = getResultsClipboardContent({+ card,+ data: result.data,+ pivoted: copiesPivotGrid,+ isPivotResult,+ isShowingDetailsOnlyColumns: question.display() === "object",+ translate,+ });+ await writeResultsToClipboard(text, html);++ const message = getRowsCopiedMessage({+ rowCount,+ truncatedRowCount:+ result.data.rows_truncated || result.data.pivot_rows_truncated,+ isPivotGrid,+ formatNumber,+ });+ dispatch(addUndo({ message }));+ } catch (error) {+ dispatch(+ addUndo({+ icon: "warning",+ message:+ error instanceof ResultsTooLargeError+ ? getTooLargeReason()+ : t`Couldn't copy to clipboard`,+ }),+ );+ }+ }, [+ dispatch,+ question,+ result,+ translate,+ isWhitelabeled,+ isPivotResult,+ pivotedCopyEnabled,+ formatNumber,+ ]);+};++function getRowsCopiedMessage({+ rowCount,+ truncatedRowCount,+ isPivotGrid,+ formatNumber,+}: {+ rowCount: number;+ truncatedRowCount: number | undefined;+ isPivotGrid: boolean;+ formatNumber: NumberFormatter;+}): string {+ if (!truncatedRowCount) {+ return t`${formatRowCount(rowCount, formatNumber)} copied to clipboard`;+ }+ if (isPivotGrid) {+ const rows = formatRowCount(truncatedRowCount, formatNumber);+ return t`Pivot table copied to clipboard, based on the first ${rows} of the result`;+ }+ const rows = formatRowCount(rowCount, formatNumber);+ return t`First ${rows} copied to clipboard`;+}++function copyChartImage(question: Question, includeBranding: boolean) {+ if (!canWriteRichClipboard()) {+ return Promise.reject(+ new Error("Clipboard images are not supported in this browser"),+ );+ }++ // Safari only accepts a clipboard write started inside the click, so the+ // image goes in as a promise+ const blob = getChartImageBlob({+ selector: getChartSelector({ cardId: question.id() }),+ includeBranding,+ }).then((blob) => {+ if (!blob) {+ throw new Error("No chart to copy");+ }+ return blob;+ });+ void blob.catch(() => {});++ return navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);+}++// Spreadsheets paste the html flavor as a grid+async function writeResultsToClipboard(text: string, html: string) {+ if (canWriteRichClipboard()) {+ await navigator.clipboard.write([+ new ClipboardItem({+ "text/plain": new Blob([text], { type: "text/plain" }),+ "text/html": new Blob([html], { type: "text/html" }),+ }),+ ]);+ } else {+ await navigator.clipboard.writeText(text);+ }+}diff --git a/frontend/src/metabase/query_builder/components/view/ViewFooter/use-rendered-question.ts b/frontend/src/metabase/query_builder/components/view/ViewFooter/use-rendered-question.tsnew file mode 100644index 00000000000..a94280b068b--- /dev/null+++ b/frontend/src/metabase/query_builder/components/view/ViewFooter/use-rendered-question.ts@@ -0,0 +1,49 @@+import { useMemo } from "react";+import { t } from "ttag";++import {+ getIsRunning,+ getLastRunQuestion,+ getQuestion,+ getRawSeries,+} from "metabase/query_builder/selectors";+import { useSelector } from "metabase/redux";+import type Question from "metabase-lib/v1/Question";++// The current question can be ahead of the retained result while a forced rerun is+// pending or was cancelled, so whether the result is pivoted has to come from the card+// that produced it, and copy has to wait out the mismatch+const getStaleReason = (+ question: Question | undefined,+ isPivotResult: boolean,+ isRunning: boolean,+): string | null => {+ if (isRunning) {+ return t`Results are still loading`;+ }+ if (question != null && isPivotResult !== (question.display() === "pivot")) {+ return t`Rerun the query to copy its results`;+ }+ return null;+};++export const useRenderedQuestion = () => {+ const question = useSelector(getQuestion);+ const lastRunQuestion = useSelector(getLastRunQuestion);+ const isRunning = useSelector(getIsRunning);+ const rawSeries = useSelector(getRawSeries);++ return useMemo(() => {+ const renderedCard = rawSeries?.[0]?.card;+ const renderedQuestion =+ question != null && renderedCard != null+ ? question.setCard(renderedCard)+ : question;+ const isPivotResult = lastRunQuestion?.display() === "pivot";+ return {+ question: renderedQuestion,+ isPivotResult,+ staleReason: getStaleReason(question, isPivotResult, isRunning),+ };+ }, [question, lastRunQuestion, rawSeries, isRunning]);+};diff --git a/frontend/src/metabase/query_builder/reducers.ts b/frontend/src/metabase/query_builder/reducers.tsindex ccd4700654d..1db709a816a 100644--- a/frontend/src/metabase/query_builder/reducers.ts+++ b/frontend/src/metabase/query_builder/reducers.ts@@ -451,7 +451,12 @@ export const lastRunCard = createReducer<Card | null>(null, (builder) => {QUERY_COMPLETED,(_state, action) => action.payload.card,)- .addCase(QUERY_ERRORED, () => null);+ // A null payload means the run was cancelled and the rendered result is+ // still valid, so keep the card; a real error clears it+ .addCase<string, { type: string; payload: unknown }>(+ QUERY_ERRORED,+ (_state, action) => (action.payload ? null : undefined),+ );});// The results of a query execution. optionally an error if the query fails to complete successfully.diff --git a/frontend/src/metabase/value-formatting/url.ts b/frontend/src/metabase/value-formatting/url.tsindex fcb823f4446..9f1a20f472c 100644--- a/frontend/src/metabase/value-formatting/url.ts+++ b/frontend/src/metabase/value-formatting/url.ts@@ -5,7 +5,11 @@ import type { ColumnSettings } from "metabase-types/api";import { getDataFromClicked } from "./click-data";import { renderLinkTextForClick, renderLinkURLForClick } from "./link";import { getJsxLinkRenderer } from "./registry";-import { formatValue, getRemappedValue } from "./value";+import {+ type FormatValueOptions,+ formatValue,+ getRemappedValue,+} from "./value";function isSafeProtocol(protocol: string) {return (@@ -28,8 +32,8 @@ export function getUrlProtocol(url: string) {}}-export function formatUrl(value: string, options: ColumnSettings = {}) {- const { jsx, rich, column, collapseNewlines } = options;+export function formatUrl(value: string, options: FormatValueOptions = {}) {+ const { jsx, rich, column, collapseNewlines, copyLinkUrl } = options;const url = getLinkUrl(value, options);@@ -37,6 +41,8 @@ export function formatUrl(value: string, options: ColumnSettings = {}) {if (jsx && rich && url && jsxLinkRenderer) {const text = getLinkText(value, options);return jsxLinkRenderer(url, text);+ } else if (url && copyLinkUrl) {+ return url;} else if (!url && !isURL(column)) {// Even when no URL is found, return a formatted valuereturn formatValue(value, { ...options, view_as: null });diff --git a/frontend/src/metabase/value-formatting/url.unit.spec.tsx b/frontend/src/metabase/value-formatting/url.unit.spec.tsxindex bfb107ee753..cd33a43f14a 100644--- a/frontend/src/metabase/value-formatting/url.unit.spec.tsx+++ b/frontend/src/metabase/value-formatting/url.unit.spec.tsx@@ -7,4 +7,27 @@ describe("formatUrl", () => {it("should return a string when not in jsx mode", () => {expect(formatUrl("http://metabase.com/")).toEqual("http://metabase.com/");});++ it("should return the value, not the link_text, for plain text output", () => {+ const formatted = formatUrl("http://not.metabase.com", {+ link_text: "metabase link",+ link_url: "http://metabase.com",+ view_as: "link",+ clicked: {},+ });++ expect(formatted).toEqual("http://not.metabase.com");+ });++ it("should return the link_url instead of the value when copyLinkUrl is set", () => {+ const formatted = formatUrl("http://not.metabase.com", {+ link_text: "metabase link",+ link_url: "http://metabase.com",+ view_as: "link",+ clicked: {},+ copyLinkUrl: true,+ });++ expect(formatted).toEqual("http://metabase.com");+ });});diff --git a/frontend/src/metabase/value-formatting/value.tsx b/frontend/src/metabase/value-formatting/value.tsxindex 08e8b396965..49d258c475f 100644--- a/frontend/src/metabase/value-formatting/value.tsx+++ b/frontend/src/metabase/value-formatting/value.tsx@@ -27,7 +27,11 @@ import { getJsxMarkdownRenderer } from "./registry";import { formatTime } from "./time";import { formatUrl } from "./url";-export function formatValue(value: unknown, _options: ColumnSettings = {}) {+export type FormatValueOptions = ColumnSettings & {+ copyLinkUrl?: boolean;+};++export function formatValue(value: unknown, _options: FormatValueOptions = {}) {let { prefix, suffix, ...options } = _options;// avoid rendering <ExternalLink> if we have click_behavior setif (diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsxindex be7ee0b3411..1ae4a511f27 100644--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx@@ -49,6 +49,7 @@ import { Flex, type MantineTheme } from "metabase/ui";import { getScrollBarSize } from "metabase/utils/dom";import { memoize } from "metabase/utils/memoize";import { formatValue } from "metabase/value-formatting";+import { createPlainCellFormatter } from "metabase/visualizations/lib/plain-cell-formatter";import {getTableCellClickedObject,getTableClickedObjectRowData,@@ -300,18 +301,11 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner();const plain: PlainCellFormatter<RowValue> = memoize(- (untranslatedValue, rowIndex) => {- const clicked = getCellClickedObject(columnIndex, rowIndex);- const value = tc(untranslatedValue);-- return String(- formatValue(value, {- ...columnSettings,- type: "cell",- clicked,- }),- );- },+ createPlainCellFormatter({+ columnSettings,+ translate: tc,+ getClicked: (rowIndex) => getCellClickedObject(columnIndex, rowIndex),+ }),);return {diff --git a/frontend/src/metabase/visualizations/lib/data_grid.ts b/frontend/src/metabase/visualizations/lib/data_grid.tsindex bb5d9ab1bec..7c547361a06 100644--- a/frontend/src/metabase/visualizations/lib/data_grid.ts+++ b/frontend/src/metabase/visualizations/lib/data_grid.ts@@ -27,6 +27,12 @@ export function isPivotGroupColumn(return col?.name === "pivot-grouping";}+// Detail rows (real data, not subtotals/totals) have a pivot-grouping of 0;+// Number() so a string-typed value from some drivers still compares.+export function isPivotDetailRow(row: RowValues, pivotGroupingIndex: number) {+ return Number(row[pivotGroupingIndex]) === 0;+}+export const COLUMN_FORMATTING_SETTING = "table.column_formatting";export const COLLAPSED_ROWS_SETTING = "pivot_table.collapsed_rows";export const COLUMN_SPLIT_SETTING = "pivot_table.column_split";diff --git a/frontend/src/metabase/visualizations/lib/no-results.ts b/frontend/src/metabase/visualizations/lib/no-results.tsindex bb0e11538f2..6f17679a1e1 100644--- a/frontend/src/metabase/visualizations/lib/no-results.ts+++ b/frontend/src/metabase/visualizations/lib/no-results.ts@@ -1,4 +1,7 @@-import { isPivotGroupColumn } from "metabase/visualizations/lib/data_grid";+import {+ isPivotDetailRow,+ isPivotGroupColumn,+} from "metabase/visualizations/lib/data_grid";import { datasetContainsNoResults } from "metabase-lib/v1/queries/utils/dataset";import type { DatasetData } from "metabase-types/api";@@ -18,7 +21,5 @@ export function hasNoResults(return false;}- // Detail rows (real data, not subtotals/totals) have a pivot-grouping of 0;- // Number() so a string-typed value from some drivers still compares.- return !data.rows.some((row) => Number(row[pivotGroupingIndex]) === 0);+ return !data.rows.some((row) => isPivotDetailRow(row, pivotGroupingIndex));}diff --git a/frontend/src/metabase/visualizations/lib/plain-cell-formatter.ts b/frontend/src/metabase/visualizations/lib/plain-cell-formatter.tsnew file mode 100644index 00000000000..eb4e125982a--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/plain-cell-formatter.ts@@ -0,0 +1,27 @@+import type { ContentTranslationFunction } from "metabase/content-translation/types";+import type { PlainCellFormatter } from "metabase/data-grid/types";+import { formatValue } from "metabase/value-formatting";+import type { ClickObject } from "metabase/visualizations/types";+import type { ColumnSettings } from "metabase-types/api";++export function createPlainCellFormatter<TValue = unknown>({+ columnSettings,+ translate,+ getClicked,+ copyLinkUrl,+}: {+ columnSettings?: ColumnSettings;+ translate: ContentTranslationFunction;+ getClicked?: (rowIndex: number, columnId: string) => ClickObject | undefined;+ copyLinkUrl?: boolean;+}): PlainCellFormatter<TValue> {+ return (untranslatedValue, rowIndex, columnId) =>+ String(+ formatValue(translate(untranslatedValue), {+ ...columnSettings,+ type: "cell",+ copyLinkUrl,+ clicked: getClicked?.(rowIndex, columnId),+ }),+ );+}diff --git a/frontend/src/metabase/visualizations/lib/results-clipboard.ts b/frontend/src/metabase/visualizations/lib/results-clipboard.tsnew file mode 100644index 00000000000..81e0d9e2d9d--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/results-clipboard.ts@@ -0,0 +1,341 @@+import type { ContentTranslationFunction } from "metabase/content-translation/types";+import {+ formatCellValueForCopy,+ serializeTsv,+} from "metabase/data-grid/utils/formatting";+import { extractRemappedColumns } from "metabase/visualizations";+import * as DataGrid from "metabase/visualizations/lib/data_grid";+import { createPlainCellFormatter } from "metabase/visualizations/lib/plain-cell-formatter";+import {+ getTitleForColumn,+ isPivoted,+} from "metabase/visualizations/lib/settings/column";+import { getComputedSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";+import {+ getTableCellClickedObject,+ getTableClickedObjectRowData,+} from "metabase/visualizations/lib/table";+import { getVisibleTableData } from "metabase/visualizations/lib/visible-table-data";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import { getTitleForColumn as getPivotTitleForColumn } from "metabase/visualizations/visualizations/PivotTable/settings";+import type { HeaderItem } from "metabase/visualizations/visualizations/PivotTable/types";+import {+ getTopHeaderRowIndex,+ getTopHeaderRowsCount,+} from "metabase/visualizations/visualizations/PivotTable/utils";+import type {+ Card,+ ColumnSettings,+ DatasetData,+ RawSeries,+ RowValue,+} from "metabase-types/api";++interface ResultsClipboardParams {+ card: Card;+ data: DatasetData;+ pivoted?: boolean;+ // Whether this result came from a pivot query, independent of whether it's+ // currently displayed pivoted (the raw-table toggle keeps this data shape)+ isPivotResult?: boolean;+ isShowingDetailsOnlyColumns?: boolean;+ translate: ContentTranslationFunction;+}++interface ResultsClipboardContent {+ text: string;+ html: string;+ rowCount: number;+ isPivotGrid: boolean;+}++export function getResultsClipboardContent({+ card,+ data,+ pivoted = false,+ isPivotResult = pivoted,+ isShowingDetailsOnlyColumns = false,+ translate,+}: ResultsClipboardParams): ResultsClipboardContent {+ const series: RawSeries = [{ card, data: extractRemappedColumns(data) }];+ const settings = getComputedSettingsForSeries(series);++ if (pivoted && card.display === "pivot") {+ const grid = getPivotGrid(series, settings, translate);+ if (!grid) {+ throw new Error("Could not lay out the pivot table");+ }+ return {+ ...serializeLines(grid.lines),+ rowCount: grid.bodyRowCount,+ isPivotGrid: true,+ };+ }++ const [{ data: remappedData }] = series;+ const flatSeries: RawSeries = [+ {+ card,+ data: isPivotResult+ ? flattenPivotGroupedData(remappedData)+ : remappedData,+ },+ ];+ const visibleData = getVisibleTableData({+ series: flatSeries,+ settings,+ isShowingDetailsOnlyColumns,+ isShowingDisabledColumns: false,+ });+ const { cols, rows } = visibleData;++ // The renderer shows the all-columns-hidden message instead of a grid here+ if (cols.length === 0) {+ throw new Error("All columns are hidden");+ }++ const isClassicPivot = isPivoted(flatSeries, settings);++ const headers = cols.map((col) =>+ String(translate(getTitleForColumn(col, series, settings))),+ );++ // Click row data varies per cell only in classic pivots, so cache it per row+ const rowClickedData = new Map<+ number,+ ReturnType<typeof getTableClickedObjectRowData>+ >();+ const getRowClickedData = (rowIndex: number, columnIndex: number) => {+ if (isClassicPivot) {+ return getTableClickedObjectRowData(+ flatSeries,+ rowIndex,+ columnIndex,+ isClassicPivot,+ visibleData,+ );+ }+ if (!rowClickedData.has(rowIndex)) {+ rowClickedData.set(+ rowIndex,+ getTableClickedObjectRowData(+ flatSeries,+ rowIndex,+ 0,+ false,+ visibleData,+ ),+ );+ }+ return rowClickedData.get(rowIndex) ?? null;+ };++ const formatters = cols.map((col, columnIndex) => {+ const columnSettings = settings.column?.(col);+ return createPlainCellFormatter({+ columnSettings,+ translate,+ copyLinkUrl: true,+ getClicked: cellTextNeedsClicked(columnSettings)+ ? (rowIndex) =>+ getTableCellClickedObject(+ visibleData,+ settings,+ rowIndex,+ columnIndex,+ isClassicPivot,+ getRowClickedData(rowIndex, columnIndex),+ )+ : undefined,+ });+ });+ const getCellText = (+ value: RowValue,+ rowIndex: number,+ columnIndex: number,+ ) =>+ formatCellValueForCopy(+ value,+ formatters[columnIndex],+ rowIndex,+ cols[columnIndex].name,+ );++ const lines = [+ headers,+ ...rows.map((row, rowIndex) =>+ row.map((value, columnIndex) =>+ getCellText(value, rowIndex, columnIndex),+ ),+ ),+ ];+ return {+ ...serializeLines(lines),+ rowCount: rows.length,+ isPivotGrid: isClassicPivot,+ };+}++// Only the link branches of formatValue read `clicked` for plain text+function cellTextNeedsClicked(columnSettings?: ColumnSettings): boolean {+ const clickBehavior = columnSettings?.click_behavior;+ const hasClickBehaviorLinkText =+ clickBehavior != null &&+ "linkTextTemplate" in clickBehavior &&+ Boolean(clickBehavior.linkTextTemplate);+ const hasLegacyLink =+ columnSettings?.view_as === "link" &&+ Boolean(columnSettings.link_text || columnSettings.link_url);+ return hasClickBehaviorLinkText || hasLegacyLink;+}++// Spreadsheets evaluate pasted cells that start like formulas; the leading+// quote is their own text-literal marker. Formatted numbers ("-5", "-$1,234.5",+// "-1.5e-11") paste as numbers, never as formulas, so they keep pasting+// unquoted. The trigger set follows OWASP's CSV-injection list, including the+// full-width forms some locales produce.+const FORMULA_TRIGGER_PATTERN = /^[=+\-@\t\r\n\0=+-@]/;+const NUMERIC_LITERAL_PATTERN =+ /^[+-]?[\p{Sc}\d.,\s]*\d(?:\s*[eE][+-]?\d+)?\s*%?$/u;++function escapeSpreadsheetFormula(text: string): string {+ const isFormulaLike =+ FORMULA_TRIGGER_PATTERN.test(text) && !NUMERIC_LITERAL_PATTERN.test(text);+ return isFormulaLike ? `'${text}` : text;+}++export class ResultsTooLargeError extends Error {+ constructor() {+ super("The serialized results exceed the clipboard size limit");+ }+}++// Enforced by callers before anything materializes: a sparse pivot with 2,000+// unique row and column keys expands to a 2,000×2,000 grid, which costs >2s of+// synchronous work, 36MB of HTML and 900MB of memory.+export const MAX_COPY_CELLS = 1_000_000;++// Raw cell characters, checked after formatting; guards a small grid of huge+// text cells that stays under the cell cap.+const MAX_COPY_TEXT_LENGTH = 20_000_000;++function serializeLines(lines: string[][]) {+ const escapedLines = lines.map((cells) =>+ cells.map(escapeSpreadsheetFormula),+ );+ const textLength = escapedLines.reduce(+ (total, cells) =>+ cells.reduce((lineTotal, cell) => lineTotal + cell.length, total),+ 0,+ );+ if (textLength > MAX_COPY_TEXT_LENGTH) {+ throw new ResultsTooLargeError();+ }+ return {+ text: serializeTsv(escapedLines),+ html: serializeHtmlTable(escapedLines),+ };+}++function serializeHtmlTable(lines: string[][]): string {+ const rows = lines+ .map(+ (cells) =>+ `<tr>${cells.map((cell) => `<td>${escapeHtmlCell(cell)}</td>`).join("")}</tr>`,+ )+ .join("");+ return `<table><tbody>${rows}</tbody></table>`;+}++function escapeHtmlCell(text: string): string {+ return text+ .replaceAll("&", "&")+ .replaceAll("<", "<")+ .replaceAll(">", ">")+ .replace(/\r\n|\r|\n/g, "<br>");+}++// Only top headers and dimension titles are content-translated, as in the rendered grid+function getPivotGrid(+ series: RawSeries,+ settings: ComputedVisualizationSettings,+ translate: ContentTranslationFunction,+): { lines: string[][]; bodyRowCount: number } | null {+ const [{ data }] = series;+ const pivotData = DataGrid.multiLevelPivot(data, settings);+ if (!pivotData) {+ return null;+ }++ const getItemText = (item: Pick<HeaderItem, "value">) => item.value ?? "";++ const {+ topHeaderItems,+ leftHeaderItems,+ rowCount,+ columnCount,+ rowIndexes,+ columnIndexes,+ valueIndexes,+ columnsWithoutPivotGroup,+ getRowSection,+ } = pivotData;++ const topRowCount = getTopHeaderRowsCount(columnIndexes, valueIndexes);+ const leftColumnCount = rowIndexes.length;+ const bodyColumnCount = columnCount * valueIndexes.length;++ const headerLines = Array.from({ length: topRowCount }, () =>+ new Array<string>(leftColumnCount + bodyColumnCount).fill(""),+ );+ for (const item of topHeaderItems) {+ const lineIndex = getTopHeaderRowIndex(item, topRowCount);+ if (headerLines[lineIndex]) {+ headerLines[lineIndex][leftColumnCount + item.offset] = String(+ translate(getItemText(item)),+ );+ }+ }+ // The renderer titles these dimension cells with the pivot-local helper, which+ // never appends the currency unit the generic one does+ rowIndexes.forEach((columnIndex, position) => {+ headerLines[topRowCount - 1][position] = String(+ translate(+ getPivotTitleForColumn(columnsWithoutPivotGroup[columnIndex], settings),+ ),+ );+ });++ const bodyLines: string[][] = [];+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {+ const line = new Array<string>(leftColumnCount).fill("");+ for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {+ for (const cell of getRowSection(columnIndex, rowIndex)) {+ line.push(getItemText(cell));+ }+ }+ bodyLines.push(line);+ }+ for (const item of leftHeaderItems) {+ if (bodyLines[item.offset]) {+ bodyLines[item.offset][item.depth] = getItemText(item);+ }+ }++ return { lines: [...headerLines, ...bodyLines], bodyRowCount: rowCount };+}++// Pivot results interleave subtotal rows and carry the grouping column+export function flattenPivotGroupedData(data: DatasetData): DatasetData {+ const groupIndex = data.cols.findIndex(DataGrid.isPivotGroupColumn);+ if (groupIndex < 0) {+ return data;+ }+ return {+ ...data,+ cols: data.cols.filter((col) => !DataGrid.isPivotGroupColumn(col)),+ rows: data.rows+ .filter((row) => DataGrid.isPivotDetailRow(row, groupIndex))+ .map((row) => row.filter((_value, index) => index !== groupIndex)),+ };+}diff --git a/frontend/src/metabase/visualizations/lib/results-clipboard.unit.spec.ts b/frontend/src/metabase/visualizations/lib/results-clipboard.unit.spec.tsnew file mode 100644index 00000000000..af66a1e90c0--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/results-clipboard.unit.spec.ts@@ -0,0 +1,712 @@+import type { ContentTranslationFunction } from "metabase/content-translation/types";+import type * as VisualizationsTable from "metabase/visualizations/lib/table";+import { getTableClickedObjectRowData } from "metabase/visualizations/lib/table";+import { registerVisualizations } from "metabase/visualizations/register";+import type {+ Card,+ DatasetData,+ VisualizationSettings,+} from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++import {+ ResultsTooLargeError,+ getResultsClipboardContent,+} from "./results-clipboard";++jest.mock("metabase/visualizations/lib/table", () => {+ const actual = jest.requireActual<typeof VisualizationsTable>(+ "metabase/visualizations/lib/table",+ );+ return {+ ...actual,+ getTableClickedObjectRowData: jest.fn(actual.getTableClickedObjectRowData),+ };+});++registerVisualizations();++const identity: ContentTranslationFunction = (value) => value;++const NAME = createMockColumn({+ name: "NAME",+ display_name: "Name",+ base_type: "type/Text",+});++const TOTAL = createMockColumn({+ name: "TOTAL",+ display_name: "Total",+ base_type: "type/Float",+});++const CATEGORY = createMockColumn({+ name: "CATEGORY",+ display_name: "Category",+ base_type: "type/Text",+ source: "breakout",+});++const VENDOR = createMockColumn({+ name: "VENDOR",+ display_name: "Vendor",+ base_type: "type/Text",+ source: "breakout",+});++const COUNT = createMockColumn({+ name: "COUNT",+ display_name: "Count",+ base_type: "type/Integer",+ source: "aggregation",+});++const TOTAL_AGG = createMockColumn({+ name: "TOTAL",+ display_name: "Total",+ base_type: "type/Float",+ source: "aggregation",+});++const PIVOT_GROUPING = createMockColumn({+ name: "pivot-grouping",+ display_name: "pivot-grouping",+ base_type: "type/Integer",+});++const tableCard = (visualization_settings: VisualizationSettings = {}) =>+ createMockCard({ display: "table", visualization_settings });++const TEST_DATA = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [+ ["Widget", 1234.5],+ ["Gadget", 3],+ ],+});++interface CopyOpts {+ card?: Card;+ data?: DatasetData;+ pivoted?: boolean;+ isPivotResult?: boolean;+ isShowingDetailsOnlyColumns?: boolean;+ translate?: ContentTranslationFunction;+}++const copy = ({+ card = tableCard(),+ data = TEST_DATA,+ pivoted = false,+ isPivotResult = pivoted,+ isShowingDetailsOnlyColumns = false,+ translate = identity,+}: CopyOpts = {}) =>+ getResultsClipboardContent({+ card,+ data,+ pivoted,+ isPivotResult,+ isShowingDetailsOnlyColumns,+ translate,+ });++describe("getResultsClipboardContent", () => {+ it("serializes headers and rows as TSV plus an html grid flavor", () => {+ const { text, html, rowCount, isPivotGrid } = copy();++ expect(isPivotGrid).toBe(false);+ expect(text).toBe("Name\tTotal\nWidget\t1,234.5\nGadget\t3");+ expect(html).toBe(+ "<table><tbody>" ++ "<tr><td>Name</td><td>Total</td></tr>" ++ "<tr><td>Widget</td><td>1,234.5</td></tr>" ++ "<tr><td>Gadget</td><td>3</td></tr>" ++ "</tbody></table>",+ );+ expect(rowCount).toBe(2);+ });++ it("quotes formula-like cells into literals in both flavors, leaving numbers alone", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [+ ["=1+2", -1234.5],+ ["@cmd", -3],+ ["-2+3", 5],+ ["\n=1+2", 1],+ ["\0=1+2", 2],+ ["=1+2", 3],+ ["-2+3", 4],+ [`+1${" ".repeat(64)}x`, 6],+ ],+ });++ const { text, html } = copy({ data });++ expect(text).toBe(+ [+ "Name\tTotal",+ "'=1+2\t-1,234.5",+ "'@cmd\t-3",+ "'-2+3\t5",+ `"'\n=1+2"\t1`,+ "'\0=1+2\t2",+ "'=1+2\t3",+ "'-2+3\t4",+ `'+1${" ".repeat(64)}x\t6`,+ ].join("\n"),+ );+ expect(html).toContain("<td>'=1+2</td><td>-1,234.5</td>");+ });++ it("keeps scientific-notation numbers unquoted whatever their sign", () => {+ const card = tableCard({+ column_settings: { '["name","TOTAL"]': { number_style: "scientific" } },+ });+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [+ ["negative", -0.000000000015],+ ["positive", 0.000000000015],+ ],+ });++ expect(copy({ card, data }).text).toBe(+ ["Name\tTotal", "negative\t-1.5e-11", "positive\t1.5e-11"].join("\n"),+ );+ });++ it("escapes html in the html flavor", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [["<b>bold & brash</b>", 1]],+ });++ expect(copy({ data }).html).toContain(+ "<td><b>bold & brash</b></td>",+ );+ });++ it("serializes only the header row when there are no rows", () => {+ const { text, rowCount } = copy({+ data: createMockDatasetData({ cols: [NAME, TOTAL], rows: [] }),+ });++ expect(text).toBe("Name\tTotal");+ expect(rowCount).toBe(0);+ });++ it("serializes null cells as empty strings", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [["Widget", null]],+ });++ expect(copy({ data }).text).toBe("Name\tTotal\nWidget\t");+ });++ it("applies column formatting settings", () => {+ const card = tableCard({+ column_settings: { '["name","TOTAL"]': { number_style: "percent" } },+ });+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [["Widget", 0.5]],+ });++ expect(copy({ card, data }).text).toBe("Name\tTotal\nWidget\t50%");+ });++ it("uses renamed column titles in the header row", () => {+ const card = tableCard({+ column_settings: { '["name","TOTAL"]': { column_title: "Revenue" } },+ });++ expect(copy({ card }).text).toBe(+ "Name\tRevenue\nWidget\t1,234.5\nGadget\t3",+ );+ });++ it("does not copy the row-index pseudo-column", () => {+ const card = tableCard({ "table.row_index": true });++ expect(copy({ card }).text).toBe("Name\tTotal\nWidget\t1,234.5\nGadget\t3");+ });++ it("respects column visibility and order from table.columns settings", () => {+ const card = tableCard({+ "table.columns": [+ { name: "TOTAL", enabled: true },+ { name: "NAME", enabled: false },+ ],+ });++ expect(copy({ card }).text).toBe("Total\n1,234.5\n3");+ });++ it("refuses to copy when every column is hidden", () => {+ const card = tableCard({+ "table.columns": [+ { name: "TOTAL", enabled: false },+ { name: "NAME", enabled: false },+ ],+ });++ expect(() => copy({ card })).toThrow("All columns are hidden");+ });++ it("keeps a real column literally named pivot-grouping on an ordinary table", () => {+ const data = createMockDatasetData({+ cols: [NAME, PIVOT_GROUPING],+ rows: [+ ["a", 1],+ ["b", 0],+ ["c", "text"],+ ],+ });++ expect(copy({ data }).text).toBe(+ ["Name\tpivot-grouping", "a\t1", "b\t0", "c\ttext"].join("\n"),+ );+ });++ it("keeps details-only fields when isShowingDetailsOnlyColumns matches the display", () => {+ const detailsOnlyCol = createMockColumn({+ name: "RAW_JSON",+ display_name: "Raw json",+ base_type: "type/Text",+ visibility_type: "details-only",+ });+ const data = createMockDatasetData({+ cols: [NAME, detailsOnlyCol],+ rows: [["Widget", "{}"]],+ });++ expect(copy({ data, isShowingDetailsOnlyColumns: true }).text).toBe(+ "Name\tRaw json\nWidget\t{}",+ );+ expect(() =>+ copy({+ data: createMockDatasetData({ cols: [detailsOnlyCol], rows: [["{}"]] }),+ isShowingDetailsOnlyColumns: false,+ }),+ ).toThrow("All columns are hidden");+ });++ it("serializes JSON cells as single-line JSON", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [[{ tags: ["a", "b"] }, 1]],+ });++ expect(copy({ data }).text).toBe('Name\tTotal\n{"tags":["a","b"]}\t1');+ });++ it("preserves newlines like csv exports, quoting the text flavor", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [["multi\nline", 1]],+ });++ expect(copy({ data }).text).toBe('Name\tTotal\n"multi\nline"\t1');+ expect(copy({ data }).html).toContain("<td>multi<br>line</td>");+ });++ it("renders every line-ending form as a single break in the html flavor", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [+ ["a\nb", 1],+ ["c\rd", 2],+ ["e\r\nf", 3],+ ],+ });++ const { html } = copy({ data });++ expect(html).toContain("<td>a<br>b</td>");+ expect(html).toContain("<td>c<br>d</td>");+ expect(html).toContain("<td>e<br>f</td>");+ });++ it("refuses to serialize past the clipboard size limit", () => {+ const data = createMockDatasetData({+ cols: [NAME, TOTAL],+ rows: [["x".repeat(21_000_000), 1]],+ });++ expect(() => copy({ data })).toThrow(ResultsTooLargeError);+ });++ it("serializes the pivoted layout when table.pivot is enabled", () => {+ const card = tableCard({+ "table.pivot": true,+ "table.pivot_column": "VENDOR",+ "table.cell_column": "COUNT",+ });+ const data = createMockDatasetData({+ cols: [CATEGORY, VENDOR, COUNT],+ rows: [+ ["Doohickey", "Alpha", 10],+ ["Doohickey", "Beta", 20],+ ["Gizmo", "Alpha", 30],+ ],+ });++ const { text, rowCount, isPivotGrid } = copy({ card, data });++ expect(isPivotGrid).toBe(true);+ expect(text).toBe(+ ["Category\tAlpha\tBeta", "Doohickey\t10\t20", "Gizmo\t30\t"].join("\n"),+ );+ expect(rowCount).toBe(2);+ });++ it("copies remapped columns as displayed, without the helper column", () => {+ const data = createMockDatasetData({+ cols: [+ createMockColumn({+ name: "PRODUCT_ID",+ display_name: "Product ID",+ base_type: "type/Integer",+ remapped_to: "PRODUCT_NAME",+ }),+ createMockColumn({+ name: "PRODUCT_NAME",+ display_name: "Product Name",+ base_type: "type/Text",+ remapped_from: "PRODUCT_ID",+ }),+ TOTAL,+ ],+ rows: [+ [1, "Awesome Bronze Plate", 99.5],+ [2, "Mediocre Wool Toucan", 42],+ ],+ });++ expect(copy({ data }).text).toBe(+ [+ "Product Name\tTotal",+ "Awesome Bronze Plate\t99.5",+ "Mediocre Wool Toucan\t42",+ ].join("\n"),+ );+ });++ it("follows the auto-pivot default for aggregated questions", () => {+ const data = createMockDatasetData({+ cols: [+ CATEGORY,+ createMockColumn({+ name: "QUARTER",+ display_name: "Quarter",+ base_type: "type/Date",+ source: "breakout",+ }),+ createMockColumn({+ name: "COUNT",+ display_name: "Count",+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "aggregation",+ }),+ ],+ rows: [+ ["Doohickey", "2025-04-01", 15],+ ["Doohickey", "2025-07-01", 51],+ ["Doohickey", "2025-10-01", 111],+ ["Gadget", "2025-04-01", 15],+ ["Gadget", "2025-07-01", 57],+ ],+ });++ expect(copy({ data }).text).toBe(+ [+ "Quarter\tDoohickey\tGadget",+ "April 1, 2025\t15\t15",+ "July 1, 2025\t51\t57",+ "October 1, 2025\t111\t",+ ].join("\n"),+ );+ });++ it("renders custom click-behavior link text like the table does", () => {+ const card = tableCard({+ column_settings: {+ '["name","NAME"]': {+ click_behavior: {+ type: "link",+ linkType: "url",+ linkTemplate: "https://example.com/{{NAME}}",+ linkTextTemplate: "open {{NAME}}",+ },+ },+ },+ });++ expect(copy({ card }).text).toBe(+ "Name\tTotal\nopen Widget\t1,234.5\nopen Gadget\t3",+ );+ });++ it("copies link columns as the resolved url, not the label", () => {+ const card = tableCard({+ column_settings: {+ '["name","NAME"]': {+ view_as: "link",+ link_text: "Click",+ link_url: "https://example.com/{{NAME}}",+ },+ },+ });++ expect(copy({ card }).text).toBe(+ [+ "Name\tTotal",+ "https://example.com/Widget\t1,234.5",+ "https://example.com/Gadget\t3",+ ].join("\n"),+ );+ });++ it("builds click metadata only for columns whose text needs it", () => {+ const rowDataCalls = jest.mocked(getTableClickedObjectRowData);++ rowDataCalls.mockClear();+ copy();+ expect(rowDataCalls).not.toHaveBeenCalled();++ const card = tableCard({+ column_settings: {+ '["name","NAME"]': {+ click_behavior: {+ type: "link",+ linkType: "url",+ linkTemplate: "https://example.com/{{NAME}}",+ linkTextTemplate: "open {{NAME}}",+ },+ },+ },+ });++ rowDataCalls.mockClear();+ copy({ card });+ expect(rowDataCalls).toHaveBeenCalledTimes(TEST_DATA.rows.length);+ });++ describe("pivot table display", () => {+ const PIVOT_CARD = createMockCard({+ display: "pivot",+ visualization_settings: {+ "pivot_table.column_split": {+ rows: ["CATEGORY"],+ columns: ["VENDOR"],+ values: ["COUNT"],+ },+ "pivot.show_row_totals": false,+ "pivot.show_column_totals": false,+ },+ });++ const PIVOT_DATA = createMockDatasetData({+ cols: [CATEGORY, VENDOR, COUNT, PIVOT_GROUPING],+ rows: [+ ["Doohickey", "Alpha", 10, 0],+ ["Doohickey", "Beta", 20, 0],+ ["Gizmo", "Alpha", 30, 0],+ [null, "Alpha", 40, 1],+ ],+ });++ const RAW_VIEW_CARD: Card = { ...PIVOT_CARD, display: "table" };++ const copyPivot = (opts: CopyOpts = {}) =>+ copy({ card: PIVOT_CARD, data: PIVOT_DATA, pivoted: true, ...opts });++ it("serializes the rendered grid when copying pivoted", () => {+ const { text, rowCount, isPivotGrid } = copyPivot();++ expect(isPivotGrid).toBe(true);+ expect(text).toBe(+ ["Category\tAlpha\tBeta", "Doohickey\t10\t20", "Gizmo\t30\t"].join(+ "\n",+ ),+ );+ expect(rowCount).toBe(2);+ });++ it("titles row dimensions like the renderer, without the currency header unit", () => {+ const price = createMockColumn({+ name: "PRICE",+ display_name: "Price",+ base_type: "type/Float",+ semantic_type: "type/Currency",+ source: "breakout",+ });+ const card = createMockCard({+ display: "pivot",+ visualization_settings: {+ "pivot_table.column_split": {+ rows: ["PRICE"],+ columns: ["VENDOR"],+ values: ["COUNT"],+ },+ "pivot.show_row_totals": false,+ "pivot.show_column_totals": false,+ column_settings: {+ '["name","PRICE"]': {+ number_style: "currency",+ currency: "USD",+ currency_in_header: true,+ },+ },+ },+ });+ const data = createMockDatasetData({+ cols: [price, VENDOR, COUNT, PIVOT_GROUPING],+ rows: [[10, "Alpha", 1, 0]],+ });++ const { text } = copy({ card, data, pivoted: true });++ expect(text.split("\n")[0]).toBe("Price\tAlpha");+ });++ it("throws when the grid cannot be laid out instead of copying nothing", () => {+ const flatDataWithoutGroupColumn = createMockDatasetData({+ cols: [CATEGORY, VENDOR, COUNT],+ rows: [["Doohickey", "Alpha", 10]],+ });+ const consoleError = jest+ .spyOn(console, "error")+ .mockImplementation(() => {});++ try {+ expect(() => copyPivot({ data: flatDataWithoutGroupColumn })).toThrow(+ "Could not lay out the pivot table",+ );+ } finally {+ consoleError.mockRestore();+ }+ });++ it("content-translates top headers and dimension titles like the renderer", () => {+ const shout: ContentTranslationFunction = (value) =>+ typeof value === "string" ? value.toUpperCase() : value;++ expect(copyPivot({ translate: shout }).text).toBe(+ ["CATEGORY\tALPHA\tBETA", "Doohickey\t10\t20", "Gizmo\t30\t"].join(+ "\n",+ ),+ );+ });++ it("serializes flat base rows without the pivot-grouping column when not pivoted", () => {+ const { text, rowCount } = copyPivot({+ card: RAW_VIEW_CARD,+ pivoted: false,+ isPivotResult: true,+ });++ expect(text).toBe(+ [+ "Category\tVendor\tCount",+ "Doohickey\tAlpha\t10",+ "Doohickey\tBeta\t20",+ "Gizmo\tAlpha\t30",+ ].join("\n"),+ );+ expect(rowCount).toBe(3);+ });++ it("filters subtotal rows even when the grouping values are string-typed", () => {+ const data = createMockDatasetData({+ cols: [CATEGORY, VENDOR, COUNT, PIVOT_GROUPING],+ rows: [+ ["Doohickey", "Alpha", 10, "0"],+ [null, "Alpha", 40, "1"],+ ],+ });++ expect(+ copyPivot({+ card: RAW_VIEW_CARD,+ data,+ pivoted: false,+ isPivotResult: true,+ }).text,+ ).toBe(["Category\tVendor\tCount", "Doohickey\tAlpha\t10"].join("\n"));+ });++ it("serializes formatted values in the grid", () => {+ const card = createMockCard({+ display: "pivot",+ visualization_settings: {+ "pivot_table.column_split": {+ rows: ["CATEGORY"],+ columns: ["VENDOR"],+ values: ["TOTAL"],+ },+ "pivot.show_row_totals": false,+ "pivot.show_column_totals": false,+ },+ });+ const data = createMockDatasetData({+ cols: [CATEGORY, VENDOR, TOTAL_AGG, PIVOT_GROUPING],+ rows: [+ ["Doohickey", "Alpha", 1234.5, 0],+ ["Gizmo", "Alpha", 6789.1, 0],+ ],+ });++ expect(copy({ card, data, pivoted: true }).text).toBe(+ ["Category\tAlpha", "Doohickey\t1,234.5", "Gizmo\t6,789.1"].join("\n"),+ );+ });++ it("serializes multi-measure grids with subtotal and grand-total rows", () => {+ const card = createMockCard({+ display: "pivot",+ visualization_settings: {+ "pivot_table.column_split": {+ rows: ["CATEGORY"],+ columns: ["VENDOR"],+ values: ["COUNT", "TOTAL"],+ },+ },+ });+ const data = createMockDatasetData({+ cols: [CATEGORY, VENDOR, COUNT, TOTAL_AGG, PIVOT_GROUPING],+ rows: [+ ["Doohickey", "Alpha", 10, 100.5, 0],+ ["Doohickey", "Beta", 20, 200.5, 0],+ ["Gizmo", "Alpha", 30, 300.5, 0],+ ["Doohickey", null, 30, 301, 2],+ ["Gizmo", null, 30, 300.5, 2],+ [null, "Alpha", 40, 401, 1],+ [null, "Beta", 20, 200.5, 1],+ [null, null, 60, 601.5, 3],+ ],+ });++ const { text, rowCount } = copy({ card, data, pivoted: true });++ expect(text).toBe(+ [+ "\tAlpha\t\tBeta\t\tRow totals\t",+ "Category\tCount\tTotal\tCount\tTotal\tCount\tTotal",+ "Doohickey\t10\t100.5\t20\t200.5\t30\t301",+ "Gizmo\t30\t300.5\t\t\t30\t300.5",+ "Grand totals\t40\t401\t20\t200.5\t60\t601.5",+ ].join("\n"),+ );+ expect(rowCount).toBe(3);+ });+ });+});diff --git a/frontend/src/metabase/visualizations/lib/save-chart-image.ts b/frontend/src/metabase/visualizations/lib/save-chart-image.tsindex 6611e9740b7..c0c718a9526 100644--- a/frontend/src/metabase/visualizations/lib/save-chart-image.ts+++ b/frontend/src/metabase/visualizations/lib/save-chart-image.ts@@ -8,27 +8,32 @@ import {getBrandingConfig,getBrandingSize,} from "./exports-branding-utils";-import { resolveSvgVarPaint, restoreNestedSvgOverflow } from "./image-exports";+import {+ canvasToBlob,+ resolveSvgVarPaint,+ restoreNestedSvgOverflow,+} from "./image-exports";export const SAVING_DOM_IMAGE_CLASS = "saving-dom-image";export const SAVING_DOM_IMAGE_HIDDEN_CLASS = "saving-dom-image-hidden";-interface Opts {+interface RenderOpts {selector: string;- fileName: string;includeBranding: boolean;}-export const saveChartImage = async ({+type Opts = RenderOpts & {+ fileName: string;+};++const renderChartCanvas = async ({selector,- fileName,includeBranding,-}: Opts) => {+}: RenderOpts): Promise<HTMLCanvasElement | null> => {const node = document.querySelector(selector);if (!node || !(node instanceof HTMLElement)) {- console.warn("No node found for selector", selector);- return;+ return null;}const contentHeight = node.getBoundingClientRect().height;@@ -81,6 +86,26 @@ export const saveChartImage = async ({}),);+ return canvas;+};++export const getChartImageBlob = async (+ opts: RenderOpts,+): Promise<Blob | null> => {+ const canvas = await renderChartCanvas(opts);+ if (!canvas) {+ return null;+ }+ return canvasToBlob(canvas);+};++export const saveChartImage = async ({ fileName, ...renderOpts }: Opts) => {+ const canvas = await renderChartCanvas(renderOpts);+ if (!canvas) {+ console.warn("No node found for selector", renderOpts.selector);+ return;+ }+if (isStorybookActive) {// In storybook/loki we must wait for the blob and image to be ready// before the play function returns, otherwise the async callback maydiff --git a/frontend/src/metabase/visualizations/lib/save-chart-image.unit.spec.ts b/frontend/src/metabase/visualizations/lib/save-chart-image.unit.spec.tsnew file mode 100644index 00000000000..c7ddf2ce22a--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/save-chart-image.unit.spec.ts@@ -0,0 +1,12 @@+import { getChartImageBlob } from "./save-chart-image";++describe("getChartImageBlob", () => {+ it("returns null when the chart is not in the DOM", async () => {+ const blob = await getChartImageBlob({+ selector: "#missing-chart",+ includeBranding: false,+ });++ expect(blob).toBeNull();+ });+});diff --git a/frontend/src/metabase/visualizations/lib/table.ts b/frontend/src/metabase/visualizations/lib/table.tsindex ab1bdacb454..6a8eed602c0 100644--- a/frontend/src/metabase/visualizations/lib/table.ts+++ b/frontend/src/metabase/visualizations/lib/table.ts@@ -23,7 +23,7 @@ export function getTableClickedObjectRowData(rowIndex: number,columnIndex: number,isPivoted: boolean,- data: DatasetData,+ data: Pick<DatasetData, "sourceRows">,): Dimension[] | null {const { rows, cols } = series.data;@@ -45,7 +45,7 @@ export function getTableClickedObjectRowData(}export function getTableCellClickedObject(- data: DatasetData,+ data: Pick<DatasetData, "rows" | "cols">,settings: VisualizationSettings,rowIndex: number,columnIndex: number,diff --git a/frontend/src/metabase/visualizations/lib/visible-table-data.ts b/frontend/src/metabase/visualizations/lib/visible-table-data.tsnew file mode 100644index 00000000000..98afc61c038--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/visible-table-data.ts@@ -0,0 +1,78 @@+import * as DataGrid from "metabase/visualizations/lib/data_grid";+import { isPivoted } from "metabase/visualizations/lib/settings/column";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import { findColumnIndexesForColumnSettings } from "metabase-lib/v1/queries/utils/dataset";+import type { DatasetData, RawSeries } from "metabase-types/api";++export type VisibleTableData = Pick<+ DatasetData,+ "cols" | "rows" | "results_timezone" | "rows_truncated" | "sourceRows"+>;++export function getClassicPivotColumnIndexes(+ data: Pick<DatasetData, "cols">,+ settings: ComputedVisualizationSettings,+) {+ const pivotIndex = data.cols.findIndex(+ (col) => col.name === settings["table.pivot_column"],+ );+ const cellIndex = data.cols.findIndex(+ (col) => col.name === settings["table.cell_column"],+ );+ const normalIndex = data.cols.findIndex(+ (_col, index) => index !== pivotIndex && index !== cellIndex,+ );+ return { pivotIndex, cellIndex, normalIndex };+}++export function getVisibleTableData({+ series,+ settings,+ isShowingDetailsOnlyColumns = false,+ isShowingDisabledColumns = isShowingDetailsOnlyColumns,+}: {+ series: RawSeries;+ settings: ComputedVisualizationSettings;+ isShowingDetailsOnlyColumns?: boolean;+ isShowingDisabledColumns?: boolean;+}): VisibleTableData {+ const [{ data }] = series;++ if (isPivoted(series, settings)) {+ const { pivotIndex, cellIndex, normalIndex } = getClassicPivotColumnIndexes(+ data,+ settings,+ );+ return {+ ...DataGrid.pivot(data, normalIndex, pivotIndex, cellIndex, settings),+ results_timezone: data.results_timezone,+ };+ }++ const { cols, rows, results_timezone, rows_truncated } = data;+ const columnSettings = settings["table.columns"] ?? [];++ const isColumnVisible = (columnIndex: number, settingIndex: number) => {+ if (columnIndex < 0) {+ return false;+ }+ const isDetailsOnlyColumn =+ cols[columnIndex].visibility_type === "details-only";+ if (isDetailsOnlyColumn && !isShowingDetailsOnlyColumns) {+ return false;+ }+ return isShowingDisabledColumns || columnSettings[settingIndex].enabled;+ };++ const columnIndexes = findColumnIndexesForColumnSettings(+ cols,+ columnSettings,+ ).filter(isColumnVisible);++ return {+ cols: columnIndexes.map((i) => cols[i]),+ rows: rows.map((row) => columnIndexes.map((i) => row[i])),+ results_timezone,+ rows_truncated,+ };+}diff --git a/frontend/src/metabase/visualizations/lib/visible-table-data.unit.spec.ts b/frontend/src/metabase/visualizations/lib/visible-table-data.unit.spec.tsnew file mode 100644index 00000000000..cba38d3d5f7--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/visible-table-data.unit.spec.ts@@ -0,0 +1,101 @@+import type { RawSeries } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDatasetData,+} from "metabase-types/api/mocks";++import { getVisibleTableData } from "./visible-table-data";++const TEST_SERIES: RawSeries = [+ {+ card: createMockCard({ display: "table" }),+ data: createMockDatasetData({+ cols: [+ createMockColumn({ name: "NAME", display_name: "Name" }),+ createMockColumn({ name: "TOTAL", display_name: "Total" }),+ ],+ rows: [["Widget", 10.5]],+ }),+ },+];++describe("getVisibleTableData", () => {+ it("hides every column when the table.columns setting is missing", () => {+ const { cols, rows } = getVisibleTableData({+ series: TEST_SERIES,+ settings: {},+ });++ expect(cols).toEqual([]);+ expect(rows).toEqual([[]]);+ });++ it("keeps details-only columns while honoring hidden ones when the flags split", () => {+ const series: RawSeries = [+ {+ card: createMockCard({ display: "table" }),+ data: createMockDatasetData({+ cols: [+ createMockColumn({ name: "NAME", display_name: "Name" }),+ createMockColumn({+ name: "DETAIL",+ display_name: "Detail",+ visibility_type: "details-only",+ }),+ ],+ rows: [["Widget", "d"]],+ }),+ },+ ];+ const settings = {+ "table.columns": [+ { name: "NAME", enabled: false },+ { name: "DETAIL", enabled: true },+ ],+ };++ const split = getVisibleTableData({+ series,+ settings,+ isShowingDetailsOnlyColumns: true,+ isShowingDisabledColumns: false,+ });+ expect(split.cols.map((col) => col.name)).toEqual(["DETAIL"]);++ const tied = getVisibleTableData({+ series,+ settings,+ isShowingDetailsOnlyColumns: true,+ });+ expect(tied.cols.map((col) => col.name)).toEqual(["NAME", "DETAIL"]);+ });++ it("keeps the results timezone when pivoting", () => {+ const series: RawSeries = [+ {+ card: createMockCard({ display: "table" }),+ data: createMockDatasetData({+ cols: [+ createMockColumn({ name: "CATEGORY", display_name: "Category" }),+ createMockColumn({ name: "VENDOR", display_name: "Vendor" }),+ createMockColumn({ name: "COUNT", display_name: "Count" }),+ ],+ rows: [["Doohickey", "Alpha", 10]],+ results_timezone: "Europe/Bucharest",+ }),+ },+ ];++ const { results_timezone } = getVisibleTableData({+ series,+ settings: {+ "table.pivot": true,+ "table.pivot_column": "VENDOR",+ "table.cell_column": "COUNT",+ },+ });++ expect(results_timezone).toBe("Europe/Bucharest");+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableInner.tsx b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableInner.tsxindex fa054cd924f..8cfd2537c18 100644--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableInner.tsx+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/PivotTableInner.tsx@@ -52,6 +52,7 @@ import type { HeaderWidthType, PivotTableClicked } from "./types";import {getCellWidthsForSection,getLeftHeaderWidths,+ getTopHeaderRowsCount,leftHeaderCellSizeAndPositionGetter,topHeaderCellSizeAndPositionGetter,} from "./utils";@@ -332,8 +333,7 @@ const PivotTableInner = forwardRef<HTMLDivElement, VisualizationProps>(columnsWithoutPivotGroup,} = pivoted;- const topHeaderRows =- columnIndexes.length + (valueIndexes.length > 1 ? 1 : 0) || 1;+ const topHeaderRows = getTopHeaderRowsCount(columnIndexes, valueIndexes);const topHeaderHeight = topHeaderRows * CELL_HEIGHT;const bodyHeight = height - topHeaderHeight;diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.tsindex 62820bcb363..b15edc7ac2f 100644--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.ts@@ -272,12 +272,22 @@ export const leftHeaderCellSizeAndPositionGetter = (};};+export const getTopHeaderRowsCount = (+ columnIndexes: number[],+ valueIndexes: number[],+) => columnIndexes.length + (valueIndexes.length > 1 ? 1 : 0) || 1;++export const getTopHeaderRowIndex = (+ item: Pick<HeaderItem, "maxDepthBelow">,+ topHeaderRows: number,+) => topHeaderRows - item.maxDepthBelow - 1;+export const topHeaderCellSizeAndPositionGetter = (item: HeaderItem,topHeaderRows: number,valueHeaderWidths: CustomColumnWidth,) => {- const { offset, span, maxDepthBelow } = item;+ const { offset, span } = item;const leftOffset = getWidthForRange(valueHeaderWidths, 0, offset);const width = getWidthForRange(valueHeaderWidths, offset, offset + span);@@ -286,7 +296,7 @@ export const topHeaderCellSizeAndPositionGetter = (height: CELL_HEIGHT,width,x: leftOffset,- y: (topHeaderRows - maxDepthBelow - 1) * CELL_HEIGHT,+ y: getTopHeaderRowIndex(item, topHeaderRows) * CELL_HEIGHT,};};diff --git a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.tsindex 83baa7eed4f..be418f28cbc 100644--- a/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts+++ b/frontend/src/metabase/visualizations/visualizations/PivotTable/utils.unit.spec.ts@@ -13,6 +13,8 @@ import {checkRenderable,getColumnValues,getLeftHeaderWidths,+ getTopHeaderRowIndex,+ getTopHeaderRowsCount,isColumnValid,isFormattablePivotColumn,leftHeaderCellSizeAndPositionGetter,@@ -423,4 +425,23 @@ describe("Visualizations > Visualizations > PivotTable > utils", () => {expect(result.width).toBe(100);});});++ describe("getTopHeaderRowsCount", () => {+ it("adds a measure-name row only when there are multiple measures", () => {+ expect(getTopHeaderRowsCount([0, 1], [2])).toBe(2);+ expect(getTopHeaderRowsCount([0, 1], [2, 3])).toBe(3);+ });++ it("keeps a single header row when there are no column breakouts", () => {+ expect(getTopHeaderRowsCount([], [0])).toBe(1);+ expect(getTopHeaderRowsCount([], [0, 1])).toBe(1);+ });+ });++ describe("getTopHeaderRowIndex", () => {+ it("places items by their depth below, deepest at the last row", () => {+ expect(getTopHeaderRowIndex({ maxDepthBelow: 0 }, 3)).toBe(2);+ expect(getTopHeaderRowIndex({ maxDepthBelow: 2 }, 3)).toBe(0);+ });+ });});diff --git a/frontend/src/metabase/visualizations/visualizations/Table/Table.tsx b/frontend/src/metabase/visualizations/visualizations/Table/Table.tsxindex afeba369ccc..b3e739d1dde 100644--- a/frontend/src/metabase/visualizations/visualizations/Table/Table.tsx+++ b/frontend/src/metabase/visualizations/visualizations/Table/Table.tsx@@ -5,15 +5,16 @@ import { t } from "ttag";import CS from "metabase/css/core/index.css";import { getSubpathSafeUrl } from "metabase/urls";-import * as DataGrid from "metabase/visualizations/lib/data_grid";import {isPivoted as _isPivoted,getTitleForColumn,} from "metabase/visualizations/lib/settings/column";+import {+ type VisibleTableData,+ getVisibleTableData,+} from "metabase/visualizations/lib/visible-table-data";import * as Lib from "metabase-lib";import Question from "metabase-lib/v1/Question";-import { findColumnIndexesForColumnSettings } from "metabase-lib/v1/queries/utils/dataset";-import type { DatasetData } from "metabase-types/api";import { TableInteractive } from "../../components/TableInteractive";import type { VisualizationProps } from "../../types";@@ -24,11 +25,6 @@ interface TableProps extends VisualizationProps {isShowingDetailsOnlyColumns?: boolean;}-type TableData = Pick<- DatasetData,- "cols" | "rows" | "results_timezone" | "rows_truncated"->;-function TableComponent(props: TableProps) {const {series,@@ -40,42 +36,11 @@ function TableComponent(props: TableProps) {const question = useSyncedQuestion(series, metadata);- const data = useMemo<TableData>(() => {- const [{ data }] = series;-- if (_isPivoted(series, settings)) {- const pivotIndex = data.cols.findIndex(- (col) => col.name === settings["table.pivot_column"],- );- const cellIndex = data.cols.findIndex(- (col) => col.name === settings["table.cell_column"],- );- const normalIndex = data.cols.findIndex(- (col, index) => index !== pivotIndex && index !== cellIndex,- );- return DataGrid.pivot(data, normalIndex, pivotIndex, cellIndex, settings);- }-- const { cols, rows, results_timezone, rows_truncated } = data;- const columnSettings = settings["table.columns"] ?? [];- const columnIndexes = findColumnIndexesForColumnSettings(- cols,- columnSettings,- ).filter(- (columnIndex, settingIndex) =>- columnIndex >= 0 &&- (isShowingDetailsOnlyColumns ||- (cols[columnIndex].visibility_type !== "details-only" &&- columnSettings[settingIndex].enabled)),- );-- return {- cols: columnIndexes.map((i) => cols[i]),- rows: rows.map((row) => columnIndexes.map((i) => row[i])),- results_timezone,- rows_truncated,- };- }, [series, settings, isShowingDetailsOnlyColumns]);+ const data = useMemo<VisibleTableData>(+ () =>+ getVisibleTableData({ series, settings, isShowingDetailsOnlyColumns }),+ [series, settings, isShowingDetailsOnlyColumns],+ );const getColumnTitle = useCallback((columnIndex: number) =>