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
Include headers when copying table rows (#65439)
Andersone8d760345b68
diff --git a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.jsindex f02e3c3d129..261c93182be 100644--- a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js@@ -126,13 +126,17 @@ describe("scenarios > visualizations > table", () => {// Copy formatted content with Cmd+Ccy.realPress(["Meta", "c"]);- H.readClipboard().should("equal", "39.72 February 11, 2025, 9:40 PM");+ H.readClipboard().should(+ "equal",+ "Total Discount ($) Created At\n39.72 February 11, 2025, 9:40 PM",+ );// Copy unformatted content with Shift+Cmd+Ccy.realPress(["Shift", "Meta", "c"]);H.readClipboard().should("equal",- "39.718145389078366 null 2025-02-11T21:40:27.892-08:00",+ "Total Discount ($) Created At\n" ++ "39.718145389078366 null 2025-02-11T21:40:27.892-08:00",);// Escape to clear selectiondiff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsxindex 4931ed426d2..afca50f59c1 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx@@ -241,7 +241,11 @@ export const DataGrid = function DataGrid<TData>({);return (- <div key={header.id} style={style}>+ <div+ key={header.id}+ style={style}+ data-header-id={header.id}+ >{headerContent}</div>);diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsxindex e6aec192188..300dda53c30 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx@@ -53,6 +53,7 @@ interface TestDataGridProps {enableRowId?: boolean;sortableColumns?: boolean;wrapableColumns?: string[];+ enableSelection?: boolean;}const TestDataGrid = ({@@ -66,6 +67,7 @@ const TestDataGrid = ({enableRowId = false,sortableColumns = false,wrapableColumns = [],+ enableSelection = false,}: TestDataGridProps) => {const columns: ColumnOptions<SampleDataType>[] = useMemo(() => [@@ -135,6 +137,7 @@ const TestDataGrid = ({onColumnReorder,onColumnResize,rowId,+ enableSelection,});return (@@ -263,4 +266,52 @@ describe("DataGrid", () => {expect(idSortIcon).toBeDefined();expect(nameSortIcon).toBeDefined();});++ it("can copy selected cells with headers included", async () => {+ const writeTextMock = jest.fn().mockResolvedValue(undefined);+ Object.assign(navigator, {+ clipboard: {+ writeText: writeTextMock,+ },+ });++ renderWithProviders(+ <TestDataGrid sortableColumns={true} enableSelection={true} />,+ );++ act(() => {+ jest.runAllTimers();+ });++ const bodyCells = screen+ .getByTestId("table-body")+ .querySelectorAll("[data-selectable-cell]");++ // Find cells by their content+ const cellsArray = Array.from(bodyCells);+ const firstCell = cellsArray.find((cell) => cell.textContent === "Item 1");+ const lastCell = cellsArray.find((cell) => cell.textContent === "Clothing");++ // Select first cell and extend to last desired cell+ fireEvent.mouseDown(firstCell!);+ fireEvent.mouseUp(firstCell!);+ fireEvent.mouseDown(lastCell!, { shiftKey: true });+ fireEvent.mouseUp(lastCell!);++ // Trigger copy+ fireEvent.keyDown(window, { key: "c", metaKey: true });++ // Assert clipboard was called and data copied+ expect(writeTextMock).toHaveBeenCalledTimes(1);+ const copiedText = writeTextMock.mock.calls[0][0];++ const lines = copiedText.split("\n");+ expect(lines.length).toBe(3);++ // Should have headers+ expect(lines[0]).toBe("Name\tCategory");+ // And selected data rows+ expect(lines[1]).toBe("Item 1\tElectronics");+ expect(lines[2]).toBe("Item 2\tClothing");+ });});diff --git a/frontend/src/metabase/data-grid/hooks/use-cell-selection.tsx b/frontend/src/metabase/data-grid/hooks/use-cell-selection.tsxindex 2b97b71013a..75c68e6002f 100644--- a/frontend/src/metabase/data-grid/hooks/use-cell-selection.tsx+++ b/frontend/src/metabase/data-grid/hooks/use-cell-selection.tsx@@ -1,5 +1,11 @@import type { Cell, Row, Table } from "@tanstack/react-table";-import { useCallback, useEffect, useMemo, useState } from "react";+import {+ type RefObject,+ useCallback,+ useEffect,+ useMemo,+ useState,+} from "react";import _ from "underscore";import type { CellId, DataGridSelection } from "../types";@@ -12,7 +18,7 @@ const noopHandlers: DataGridSelection["handlers"] = {handleCellDoubleClick: _.noop,};-export type SelectedCellRowMap = Record<string, CellId[]>;+type CellsMap = Record<string, CellId[]>;/*** Configuration options for the cell selection hook.@@ -20,6 +26,8 @@ export type SelectedCellRowMap = Record<string, CellId[]>;interface UseCellSelectionProps {/** Table instance from TanStack Table */table: Table<any>;+ /** Ref to the grid element */+ gridRef: RefObject<HTMLDivElement>;/** Whether cell selection is enabled */isEnabled?: boolean;/** Optional function to scroll to a specific cell */@@ -47,10 +55,11 @@ interface UseCellSelectionProps {* @returns Object with selection state and event handlers*/export const useCellSelection = ({- table,+ gridRef,isEnabled = false,- scrollTo,onChangeSelection,+ scrollTo,+ table,}: UseCellSelectionProps): DataGridSelection => {const [selectedCells, setSelectedCells] = useState<CellId[]>([]);const [focusedCell, setFocusedCell] = useState<CellId | null>(null);@@ -61,10 +70,15 @@ export const useCellSelection = ({const handleCopy = useCallback(async (useRawValues = false) => {- const formattedText = getCellValues(table, selectedCells, useRawValues);+ const formattedText = getCellValues(+ gridRef,+ table,+ selectedCells,+ useRawValues,+ );await navigator.clipboard.writeText(formattedText);},- [table, selectedCells],+ [gridRef, table, selectedCells],);const handleClickOutside = useCallback(@@ -231,17 +245,7 @@ export const useCellSelection = ({getCellSelectionData(cell),) as CellId[];- setSelectedCells((prev) => {- const startIndex = prev.findIndex(- (c) => c.cellId === selectedStartCell.cellId,- );- const prevSelectedCells = prev.slice(0, startIndex);- const newCellSelection = selectedCellsInRange.filter(- (c) => c.cellId !== selectedStartCell.cellId,- );-- return [...prevSelectedCells, selectedStartCell, ...newCellSelection];- });+ setSelectedCells(selectedCellsInRange);},[selectedStartCell, table],);@@ -445,8 +449,8 @@ export const useCellSelection = ({);};-const groupCellsByRow = (cells: CellId[]): SelectedCellRowMap => {- return cells.reduce<SelectedCellRowMap>((acc, cellData) => {+const groupCellsByRow = (cells: CellId[]) => {+ return cells.reduce<CellsMap>((acc, cellData) => {const cellsForRow = acc[cellData.rowId] ?? [];return {...acc,@@ -455,6 +459,16 @@ const groupCellsByRow = (cells: CellId[]): SelectedCellRowMap => {}, {});};+const groupCellsByColumn = (cells: CellId[]) => {+ return cells.reduce<CellsMap>((acc, cellData) => {+ const cellsForColumn = acc[cellData.columnId] ?? [];+ return {+ ...acc,+ [cellData.columnId]: [...cellsForColumn, cellData],+ };+ }, {});+};+/*** Extracts values from cells in a single row, applying formatting as needed.*/@@ -468,33 +482,41 @@ const extractRowCellValues = (for (const cell of row.getAllCells()) {if (selectedCellIds.has(cell.id)) {- const rawValue = cell.getValue();- const clipboardFormatter = useRawValues- ? undefined- : cell.column.columnDef.meta?.clipboardFormatter;- const formattedValue = formatCellValueForCopy(- rawValue,- clipboardFormatter,- row.index,- cell.column.id,- );-- cellValues.push(formattedValue);+ cellValues.push(extractCellValue(row.index, cell, useRawValues));}}return cellValues;};+const extractCellValue = (+ rowIndex: number,+ cell: Cell<unknown, unknown>,+ useRawValues: boolean,+) => {+ const rawValue = cell.getValue();+ const clipboardFormatter = useRawValues+ ? undefined+ : cell.column.columnDef.meta?.clipboardFormatter;+ return formatCellValueForCopy(+ rawValue,+ clipboardFormatter,+ rowIndex,+ cell.column.id,+ );+};+/*** Converts selected cells to clipboard-ready text format.*+ * @param gridRef - Ref to the grid html element* @param table - The table instance* @param cells - Array of selected cells* @param useRawValues - Whether to use raw values instead of formatted ones* @returns Tab-separated values with newlines between rows*/const getCellValues = (+ gridRef: RefObject<HTMLDivElement>,table: Table<unknown>,cells: CellId[],useRawValues = false,@@ -504,25 +526,71 @@ const getCellValues = (}const rowGroups = groupCellsByRow(cells);+ const columnGroups = groupCellsByColumn(cells);++ const columnIds = Object.keys(columnGroups);- return Object.keys(rowGroups)+ const headerRow = columnIds+ .map((columnId) => {+ return columnId+ ? gridRef.current?.querySelector(`[data-header-id="${columnId}"]`)+ ?.textContent+ : undefined;+ })+ .filter(Boolean) as string[];++ if (columnIds.length !== headerRow.length) {+ // Couldn't retrieve all headers: copy the data only+ return Object.keys(rowGroups)+ .map((rowId) => {+ try {+ const row = table.getRow(rowId);+ const selectedCells = rowGroups[rowId]!;+ const cellValues = extractRowCellValues(+ row,+ selectedCells,+ useRawValues,+ );+ return cellValues.join("\t");+ } catch (error) {+ console.warn(`Error processing row ${rowId}:`, error);+ return "";+ }+ })+ .filter((rowText) => rowText.length > 0)+ .join("\n");+ }++ const dataRows = Object.keys(rowGroups).map((rowId) => {try {const row = table.getRow(rowId);- const selectedCells = rowGroups[rowId]!;- const cellValues = extractRowCellValues(- row,- selectedCells,- useRawValues,- );- return cellValues.join("\t");+ const cellByColumnId = row._getAllCellsByColumnId();+ return columnIds+ .map((columnId) => {+ if (+ cellByColumnId[columnId] &&+ rowGroups[rowId].some((cellId) => cellId.columnId === columnId)+ ) {+ return extractCellValue(+ row.index,+ cellByColumnId[columnId],+ useRawValues,+ );+ }++ return "";+ })+ .join("\t");} catch (error) {console.warn(`Error processing row ${rowId}:`, error);return "";}})- .filter((rowText) => rowText.length > 0)- .join("\n");+ .filter((rowText) => rowText.length > 0);++ // Combine headers and data+ return [headerRow.join("\t"), ...dataRows].join("\n");};const canSelectCell = (cell: Cell<any, any>) => {diff --git a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsxindex 96fc19d4a4f..598aeedbeef 100644--- a/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx+++ b/frontend/src/metabase/data-grid/hooks/use-data-grid-instance.tsx@@ -432,6 +432,7 @@ export const useDataGridInstance = <TData, TValue>({// Setup cell selection functionalityconst selection = useCellSelection({+ gridRef,table,isEnabled: enableSelection,scrollTo,