A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Pass raw data for tables during search and copy text/html to clipboard (#8622)
Shahmir Varqha536c5f224051
diff --git a/frontend/src/components/data-table/__tests__/utils.test.ts b/frontend/src/components/data-table/__tests__/utils.test.tsindex a1bcf52fde..55f6bcdd88 100644--- a/frontend/src/components/data-table/__tests__/utils.test.ts+++ b/frontend/src/components/data-table/__tests__/utils.test.ts@@ -1,7 +1,13 @@/* Copyright 2026 Marimo. All rights reserved. */+import type { Table } from "@tanstack/react-table";import { describe, expect, it } from "vitest";-import { getPageIndexForRow } from "../utils";+import {+ getClipboardContent,+ getPageIndexForRow,+ getRawValue,+ stringifyUnknownValue,+} from "../utils";describe("getPageIndexForRow", () => {it("should return null when row is on current page", () => {@@ -77,3 +83,134 @@ describe("getPageIndexForRow", () => {expect(getPageIndexForRow(999, 100, 10)).toBe(99);});});++describe("stringifyUnknownValue", () => {+ it("should stringify primitives", () => {+ expect(stringifyUnknownValue({ value: "hello" })).toBe("hello");+ expect(stringifyUnknownValue({ value: 42 })).toBe("42");+ expect(stringifyUnknownValue({ value: true })).toBe("true");+ expect(stringifyUnknownValue({ value: null })).toBe("null");+ expect(stringifyUnknownValue({ value: undefined })).toBe("undefined");+ });++ it("should stringify null as empty string when flag is set", () => {+ expect(+ stringifyUnknownValue({ value: null, nullAsEmptyString: true }),+ ).toBe("");+ });++ it("should JSON-stringify plain objects", () => {+ expect(stringifyUnknownValue({ value: { x: 1 } })).toBe('{"x":1}');+ });+});++describe("getClipboardContent", () => {+ it("should use rawValue for text when it differs from displayedValue", () => {+ const displayed = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: '<a href="https://example.com">42</a>',+ },+ };+ const result = getClipboardContent(42, displayed);+ expect(result.text).toBe("42");+ expect(result.html).toBe('<a href="https://example.com">42</a>');+ });++ it("should strip html for text when rawValue equals displayedValue", () => {+ const mimeBundle = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: "<b>bold</b>",+ },+ };+ const result = getClipboardContent(mimeBundle, mimeBundle);+ expect(result.text).toBe("bold");+ expect(result.html).toBe("<b>bold</b>");+ });++ it("should handle undefined rawValue", () => {+ const displayed = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: "<b>hello</b>",+ },+ };+ const result = getClipboardContent(undefined, displayed);+ expect(result.text).toBe("hello");+ expect(result.html).toBe("<b>hello</b>");+ });++ it("should return no html for plain values", () => {+ const result = getClipboardContent(undefined, "plain text");+ expect(result.text).toBe("plain text");+ expect(result.html).toBeUndefined();+ });++ it("should treat text/markdown as html since mo.md() data is rendered html", () => {+ const displayed = {+ _serialized_mime_bundle: {+ mimetype: "text/markdown",+ data: '<span class="markdown"><strong>Hello</strong></span>',+ },+ };+ const result = getClipboardContent(undefined, displayed);+ expect(result.text).toBe("Hello");+ expect(result.html).toBe(+ '<span class="markdown"><strong>Hello</strong></span>',+ );+ });++ it("should return no html for non-html mime bundles", () => {+ const displayed = {+ _serialized_mime_bundle: {+ mimetype: "text/plain",+ data: "just text",+ },+ };+ const result = getClipboardContent(undefined, displayed);+ expect(result.text).toBe("just text");+ expect(result.html).toBeUndefined();+ });++ it("should handle null rawValue as a real value", () => {+ const displayed = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: "<i>N/A</i>",+ },+ };+ const result = getClipboardContent(null, displayed);+ expect(result.text).toBe("null");+ expect(result.html).toBe("<i>N/A</i>");+ });+});++function createMockTableWithMeta<TData>(rawData?: TData[]): Table<TData> {+ return {+ options: {+ meta: { rawData },+ },+ } as unknown as Table<TData>;+}++describe("getRawValue", () => {+ it("should return raw value when rawData is available", () => {+ const table = createMockTableWithMeta([+ { a: 10, b: 20 },+ { a: 30, b: 40 },+ ]);+ expect(getRawValue(table, 0, "a")).toBe(10);+ expect(getRawValue(table, 1, "b")).toBe(40);+ });++ it("should return undefined when rawData is not set", () => {+ const table = createMockTableWithMeta(undefined);+ expect(getRawValue(table, 0, "a")).toBeUndefined();+ });++ it("should return undefined when row index is out of bounds", () => {+ const table = createMockTableWithMeta([{ a: 1 }]);+ expect(getRawValue(table, 5, "a")).toBeUndefined();+ });+});diff --git a/frontend/src/components/data-table/context-menu.tsx b/frontend/src/components/data-table/context-menu.tsxindex 09c88beb92..89dbd24f2f 100644--- a/frontend/src/components/data-table/context-menu.tsx+++ b/frontend/src/components/data-table/context-menu.tsx@@ -18,7 +18,7 @@ import {import { DATA_CELL_ID } from "./cell-utils";import { Filter } from "./filters";import { selectedCellsAtom } from "./range-focus/atoms";-import { stringifyUnknownValue } from "./utils";+import { getClipboardContent, getRawValue } from "./utils";export const DataTableContextMenu = <TData,>({contextMenuRef,@@ -82,11 +82,15 @@ export const CellContextMenu = <TData,>({return;}+ const table = cell.getContext().table;+ const displayedValue = cell.getValue();+ const rawValue =+ getRawValue(table, cell.row.index, cell.column.id) ?? displayedValue;+const handleCopyCell = () => {try {- const value = cell.getValue();- const stringValue = stringifyUnknownValue({ value });- copyToClipboard(stringValue);+ const { text, html } = getClipboardContent(rawValue, displayedValue);+ copyToClipboard(text, html);} catch (error) {Logger.error("Failed to copy context menu cell", error);}@@ -98,7 +102,7 @@ export const CellContextMenu = <TData,>({const handleFilterCell = (operator: "in" | "not_in") => {column.setFilterValue(Filter.select({- options: [cell.getValue()],+ options: [rawValue],operator,}),);diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex b4856d88e6..28d04ab306 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -52,6 +52,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {maxHeight?: number;columns: ColumnDef<TData>[];data: TData[];+ rawData?: TData[]; // raw data for filtering/copying (present only if format_mapping is provided)// SortingmanualSorting?: boolean; // server-side sortingsorting?: SortingState; // controlled sorting@@ -103,6 +104,7 @@ const DataTableInternal = <TData,>({maxHeight,columns,data,+ rawData,selection,totalColumns,totalRows,@@ -197,6 +199,7 @@ const DataTableInternal = <TData,>({],data,columns,+ meta: { rawData },getCoreRowModel: getCoreRowModel(),// paginationrowCount: totalRows === "too_many" ? undefined : totalRows,diff --git a/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts b/frontend/src/components/data-table/range-focus/__tests__/atoms.test.tsindex 7cd1448fc7..568460f4ce 100644--- a/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts+++ b/frontend/src/components/data-table/range-focus/__tests__/atoms.test.ts@@ -403,7 +403,10 @@ describe("cell selection atoms", () => {beforeEach(() => {// Reset mocks before each testvi.mocked(getCellValues).mockClear();- vi.mocked(getCellValues).mockReturnValue("mocked cell values");+ vi.mocked(getCellValues).mockReturnValue({+ text: "mocked cell values",+ html: undefined,+ });});afterEach(() => {@@ -424,7 +427,10 @@ describe("cell selection atoms", () => {});expect(getCellValues).toHaveBeenCalledWith(mockTable, selectedCells);- expect(copyToClipboard).toHaveBeenCalledWith("mocked cell values");+ expect(copyToClipboard).toHaveBeenCalledWith(+ "mocked cell values",+ undefined,+ );expect(onCopyComplete).toHaveBeenCalledWith();expect(state.copiedCells).toEqual(selectedCells);});diff --git a/frontend/src/components/data-table/range-focus/__tests__/test-utils.ts b/frontend/src/components/data-table/range-focus/__tests__/test-utils.tsindex 6e7fe8d8e4..a1f7bafda4 100644--- a/frontend/src/components/data-table/range-focus/__tests__/test-utils.ts+++ b/frontend/src/components/data-table/range-focus/__tests__/test-utils.ts@@ -56,12 +56,14 @@ export function createMockRow(export function createMockTable(rows: Row<unknown>[],columns: Column<unknown>[],+ opts?: { rawData?: unknown[] },): Table<unknown> {return {getRow: (id: string) => rows.find((row) => row.id === id),getRowModel: () => ({ rows }),getColumn: (columnId: string) => columns.find((col) => col.id === columnId),getAllColumns: () => columns,+ options: { meta: { rawData: opts?.rawData } },} as unknown as Table<unknown>;}diff --git a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts b/frontend/src/components/data-table/range-focus/__tests__/utils.test.tsindex 9a9a50e05b..02c52b1312 100644--- a/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts+++ b/frontend/src/components/data-table/range-focus/__tests__/utils.test.ts@@ -20,7 +20,8 @@ describe("getCellValues", () => {it("should return empty string for empty selection", () => {const mockTable = createMockTable([], []);const result = getCellValues(mockTable, new Set());- expect(result).toBe("");+ expect(result.text).toBe("");+ expect(result.html).toBeUndefined();});it("should ignore select checkbox in tables", () => {@@ -29,7 +30,8 @@ describe("getCellValues", () => {const table = createMockTable([row], []);const result = getCellValues(table, new Set());- expect(result).toBe("");+ expect(result.text).toBe("");+ expect(result.html).toBeUndefined();});it("should return single cell value", () => {@@ -38,7 +40,8 @@ describe("getCellValues", () => {const table = createMockTable([row], []);const result = getCellValues(table, new Set(["0_0"]));- expect(result).toBe("test");+ expect(result.text).toBe("test");+ expect(result.html).toBeUndefined();});it("should return multiple cells from same row separated by tabs", () => {@@ -48,7 +51,8 @@ describe("getCellValues", () => {const table = createMockTable([row], []);const result = getCellValues(table, new Set(["0_0", "0_1"]));- expect(result).toBe("value1\tvalue2");+ expect(result.text).toBe("value1\tvalue2");+ expect(result.html).toBeUndefined();});it("should return multiple rows separated by newlines", () => {@@ -59,7 +63,8 @@ describe("getCellValues", () => {const table = createMockTable([row1, row2], []);const result = getCellValues(table, new Set(["0_0", "1_0"]));- expect(result).toBe("row1\nrow2");+ expect(result.text).toBe("row1\nrow2");+ expect(result.html).toBeUndefined();});it("should handle missing rows gracefully", () => {@@ -69,7 +74,7 @@ describe("getCellValues", () => {// Row "999" doesn't exist and is skippedconst result = getCellValues(table, new Set(["0_0", "999_0"]));- expect(result).toBe("test");+ expect(result.text).toBe("test");});it("should include undefined for missing columns on existing rows", () => {@@ -80,7 +85,7 @@ describe("getCellValues", () => {// Column "999" doesn't exist but row.getValue() returns undefinedconst result = getCellValues(table, new Set(["0_0", "0_1", "0_999"]));- expect(result).toBe("test1\ttest2\tundefined");+ expect(result.text).toBe("test1\ttest2\tundefined");});it("should handle complex data types", () => {@@ -91,7 +96,76 @@ describe("getCellValues", () => {const table = createMockTable([row], []);const result = getCellValues(table, new Set(["0_0", "0_1", "0_2"]));- expect(result).toBe('{"name":"test"}\tnull\tundefined');+ expect(result.text).toBe('{"name":"test"}\tnull\tundefined');+ expect(result.html).toBeUndefined();+ });++ it("should use raw values when rawData is available", () => {+ const mimeBundle = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: "<b>formatted_42</b>",+ },+ };+ const cell1 = createMockCell("0_a", mimeBundle);+ const cell2 = createMockCell("0_b", "displayed_b");+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], [], {+ rawData: [{ a: 42, b: "raw_b" }],+ });++ const result = getCellValues(table, new Set(["0_a", "0_b"]));+ expect(result.text).toBe("42\traw_b");+ expect(result.html).toBe(+ "<table><tr><td><b>formatted_42</b></td><td>raw_b</td></tr></table>",+ );+ });++ it("should fall back to displayed value when rawData is not set", () => {+ const cell = createMockCell("0_name", "displayed");+ const row = createMockRow("0", [cell]);+ const table = createMockTable([row], []);++ const result = getCellValues(table, new Set(["0_name"]));+ expect(result.text).toBe("displayed");+ expect(result.html).toBeUndefined();+ });++ it("should return html table when cells contain mime bundles", () => {+ const mimeBundle = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: '<a href="https://example.com">link</a>',+ },+ };+ const cell1 = createMockCell("0_url", mimeBundle);+ const cell2 = createMockCell("0_name", "plain text");+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);++ const result = getCellValues(table, new Set(["0_url", "0_name"]));+ expect(result.text).toBe("link\tplain text");+ expect(result.html).toBe(+ '<table><tr><td><a href="https://example.com">link</a></td><td>plain text</td></tr></table>',+ );+ });++ it("should escape html entities in non-mime cells within html table", () => {+ const mimeBundle = {+ _serialized_mime_bundle: {+ mimetype: "text/html",+ data: "<b>bold</b>",+ },+ };+ const cell1 = createMockCell("0_html", mimeBundle);+ const cell2 = createMockCell("0_text", "a < b & c > d");+ const row = createMockRow("0", [cell1, cell2]);+ const table = createMockTable([row], []);++ const result = getCellValues(table, new Set(["0_html", "0_text"]));+ expect(result.html).toBe(+ "<table><tr><td><b>bold</b></td><td>a < b & c > d</td></tr></table>",+ );});});diff --git a/frontend/src/components/data-table/range-focus/atoms.ts b/frontend/src/components/data-table/range-focus/atoms.tsindex f9035b6c3b..b2dcb7dafa 100644--- a/frontend/src/components/data-table/range-focus/atoms.ts+++ b/frontend/src/components/data-table/range-focus/atoms.ts@@ -167,8 +167,8 @@ const {return state;}- const text = getCellValues(table, state.selectedCells);- copyToClipboard(text);+ const { text, html } = getCellValues(table, state.selectedCells);+ copyToClipboard(text, html);onCopyComplete();return {diff --git a/frontend/src/components/data-table/range-focus/utils.ts b/frontend/src/components/data-table/range-focus/utils.tsindex 70d9c505b3..ecfcfd0b2d 100644--- a/frontend/src/components/data-table/range-focus/utils.ts+++ b/frontend/src/components/data-table/range-focus/utils.ts@@ -2,17 +2,25 @@import type { Table } from "@tanstack/react-table";import { SELECT_COLUMN_ID } from "../types";-import { stringifyUnknownValue } from "../utils";+import { getClipboardContent, getRawValue } from "../utils";import type { SelectedCell } from "./atoms";+export interface CellValuesResult {+ text: string;+ html: string | undefined;+}+/**- * Get the values of the selected cells.+ * Get the values of the selected cells, preferring raw (unformatted) values+ * for plain text. If any cell contains HTML (e.g. a hyperlink), also builds+ * an HTML table so rich content can be preserved on paste.*/export function getCellValues<TData>(table: Table<TData>,selectedCellIds: Set<string>,-): string {- const rowValues = new Map<string, string[]>();+): CellValuesResult {+ const rows = new Map<string, { text: string; html?: string }[]>();+ let hasHtml = false;for (const cellId of selectedCellIds) {if (cellId.includes(SELECT_COLUMN_ID)) {@@ -26,17 +34,46 @@ export function getCellValues<TData>(continue;}- const cellValue = row.getValue(columnId);- const values = rowValues.get(rowId) ?? [];- values.push(stringifyUnknownValue({ value: cellValue }));- rowValues.set(rowId, values);+ const rawValue = getRawValue(table, row.index, columnId);+ const { text, html } = getClipboardContent(+ rawValue,+ row.getValue(columnId),+ );++ if (html) {+ hasHtml = true;+ }+ const cells = rows.get(rowId) ?? [];+ cells.push({ text, html });+ rows.set(rowId, cells);+ }++ const rowValues = [...rows.values()];+ const tabSeparatedText = rowValues+ .map((cells) => cells.map((c) => c.text).join("\t"))+ .join("\n");++ let htmlTable: string | undefined;+ if (hasHtml) {+ const htmlTableRows = rowValues+ .map(+ (cells) =>+ `<tr>${cells.map((c) => `<td>${c.html ?? escapeHtml(c.text)}</td>`).join("")}</tr>`,+ )+ .join("");+ htmlTable = `<table>${htmlTableRows}</table>`;}- return getTabSeparatedValues([...rowValues.values()]);+ return {+ text: tabSeparatedText,+ html: htmlTable,+ };}-export function getTabSeparatedValues(values: string[][]) {- return values.map((row) => row.join("\t")).join("\n");+function escapeHtml(str: string): string {+ const div = document.createElement("div");+ div.textContent = str;+ return div.innerHTML;}/**@@ -74,7 +111,8 @@ export function getNumericValuesFromSelectedCells<TData>(continue;}- const value = row.getValue(columnId);+ const value =+ getRawValue(table, row.index, columnId) ?? row.getValue(columnId);// Only accept numbers and strings// Skip booleans, null, etc.diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.tsindex a3354fd5f4..118e7283fe 100644--- a/frontend/src/components/data-table/types.ts+++ b/frontend/src/components/data-table/types.ts@@ -1,8 +1,15 @@/* Copyright 2026 Marimo. All rights reserved. */+import type { RowData } from "@tanstack/react-table";import type { DataType } from "@/core/kernel/messages";import { Objects } from "@/utils/objects";+declare module "@tanstack/react-table" {+ interface TableMeta<TData extends RowData> {+ rawData?: TData[]; // raw data for filtering/copying (present only if format_mapping is provided)+ }+}+export type ColumnName = string;export const ColumnHeaderStatsKeys = [diff --git a/frontend/src/components/data-table/utils.ts b/frontend/src/components/data-table/utils.tsindex a52cd74113..c79cdfe92a 100644--- a/frontend/src/components/data-table/utils.ts+++ b/frontend/src/components/data-table/utils.ts@@ -1,8 +1,10 @@/* Copyright 2026 Marimo. All rights reserved. */+import type { Table } from "@tanstack/react-table";import type { TableData } from "@/plugins/impl/DataTablePlugin";import { vegaLoadData } from "@/plugins/impl/vega/loader";import { jsonParseWithSpecialChar } from "@/utils/json/json-parser";+import { getMimeValues } from "./mime-cell";import { INDEX_COLUMN_NAME } from "./types";/**@@ -32,6 +34,21 @@ export async function loadTableData<T = object>(return tableData;}+/**+ * Load both table and raw table data. Raw table data is typically when+ * there is formatting applied to the table data.+ */+export async function loadTableAndRawData<T>(+ tableData: TableData<T>,+ rawTableData?: TableData<T> | null,+): Promise<[T[], T[] | undefined]> {+ if (rawTableData) {+ return Promise.all([loadTableData(tableData), loadTableData(rawTableData)]);+ }++ return [await loadTableData(tableData), undefined];+}+/*** Get the stable row ID for a row.*@@ -87,3 +104,73 @@ export function stringifyUnknownValue(opts: {}return String(value);}++function stripHtml(html: string): string {+ const div = document.createElement("div");+ div.innerHTML = html;+ const text = (div.textContent || div.innerText || "").trim();+ return text || html;+}++const HTML_MIMETYPES = new Set(["text/html", "text/markdown"]);++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++/**+ * Get clipboard-ready text and optional HTML for a cell.+ *+ * @param rawValue - The raw (unformatted) value, or undefined if not available.+ * @param displayedValue - The displayed value (may be a mime bundle).+ */+export function getClipboardContent(+ rawValue: unknown,+ displayedValue: unknown,+): { text: string; html?: string } {+ const mimeValues =+ typeof displayedValue === "object" && displayedValue !== null+ ? getMimeValues(displayedValue)+ : undefined;++ let html: string | undefined;+ if (mimeValues) {+ // text/markdown from mo.md() contains rendered HTML+ const htmlParts = mimeValues+ .filter((v) => HTML_MIMETYPES.has(v.mimetype))+ .map((v) => v.data);+ html = htmlParts.length > 0 ? htmlParts.join("") : undefined;+ }++ let text: string;+ if (rawValue !== undefined && rawValue !== displayedValue) {+ text = stringifyUnknownValue({ value: rawValue });+ } else if (mimeValues) {+ text = mimeValues+ .map((v) => (HTML_MIMETYPES.has(v.mimetype) ? stripHtml(v.data) : v.data))+ .join(", ");+ } else {+ text = stringifyUnknownValue({ value: displayedValue });+ }++ return { text, html };+}++/**+ * Get the raw (unformatted) value for a row/column from the table,+ * or undefined if raw data is not available.+ */+export function getRawValue<TData>(+ table: Table<TData>,+ rowIndex: number,+ columnId: string,+): unknown {+ const rawData = table.options.meta?.rawData;+ if (rawData) {+ const rawRow = rawData[rowIndex];+ if (isRecord(rawRow)) {+ return rawRow[columnId];+ }+ }+ return undefined;+}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex e46281d01e..ee67f9359b 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -53,6 +53,7 @@ import {} from "@/components/data-table/types";import {getPageIndexForRow,+ loadTableAndRawData,loadTableData,} from "@/components/data-table/utils";import { ErrorBoundary } from "@/components/editor/boundary/ErrorBoundary";@@ -174,6 +175,7 @@ const valueCounts: z.ZodType<ValueCounts> = z.array(interface Data<T> {label: string | null;data: TableData<T>;+ rawData?: TableData<T> | null;totalRows: number | TooManyRows;pagination: boolean;pageSize: number;@@ -221,6 +223,7 @@ type DataTableFunctions = {total_rows: number | TooManyRows;cell_styles?: CellStyleState | null;cell_hover_texts?: Record<string, Record<string, string | null>> | null;+ raw_data?: TableData<T> | null;}>;get_data_url?: GetDataUrl;get_row_ids?: GetRowIds;@@ -243,6 +246,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")]),label: z.string().nullable(),data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ rawData: z.union([z.string(), z.array(z.looseObject({}))]).nullish(),totalRows: z.union([z.number(), z.literal(TOO_MANY_ROWS)]),pagination: z.boolean().default(false),pageSize: z.number().default(10),@@ -327,6 +331,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")).nullable(),cell_hover_texts: cellHoverTextSchema.nullable(),+ raw_data: z.union([z.string(), z.array(z.looseObject({}))]).nullish(),}),),get_row_ids: rpc.input(z.object({}).passthrough()).output(@@ -529,17 +534,23 @@ export const LoadingDataTableComponent = memo(// Data loadingconst { data, error, isPending, isFetching } = useAsyncData<{rows: T[];+ rawRows?: T[];totalRows: number | TooManyRows;cellStyles: CellStyleState | undefined | null;cellHoverTexts?: Record<string, Record<string, string | null>> | null;}>(async () => {// If there is no data, return an empty arrayif (props.totalRows === 0) {- return { rows: Arrays.EMPTY, totalRows: 0, cellStyles: {} };+ return {+ rows: Arrays.EMPTY,+ totalRows: 0,+ cellStyles: {},+ };}// Table data is a url string or an array of objectslet tableData = props.data;+ let rawTableData: TableData<T> | undefined | null = props.rawData;let totalRows = props.totalRows;let cellStyles = props.cellStyles;let cellHoverTexts = props.cellHoverTexts;@@ -587,13 +598,19 @@ export const LoadingDataTableComponent = memo(} else {const searchResults = await searchResultsPromise;tableData = searchResults.data;+ rawTableData = searchResults.raw_data;totalRows = searchResults.total_rows;cellStyles = searchResults.cell_styles || {};cellHoverTexts = searchResults.cell_hover_texts || {};}- tableData = await loadTableData(tableData);+ const [data, rawData] = await loadTableAndRawData(+ tableData,+ rawTableData,+ );+ tableData = data;return {rows: tableData,+ rawRows: rawData,totalRows: totalRows,cellStyles,cellHoverTexts,@@ -715,6 +732,7 @@ export const LoadingDataTableComponent = memo(<DataTableComponent{...props}data={data?.rows ?? Arrays.EMPTY}+ rawData={data?.rawRows}columnSummaries={columnSummaries}sorting={sorting}setSorting={setSorting}@@ -766,6 +784,7 @@ LoadingDataTableComponent.displayName = "LoadingDataTableComponent";const DataTableComponent = ({label,data,+ rawData,totalRows,maxColumns,pagination,@@ -814,6 +833,7 @@ const DataTableComponent = ({}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];+ rawData?: unknown[];columnSummaries?: ColumnSummaries;getRow: (rowIdx: number) => Promise<GetRowResult>;}): JSX.Element => {@@ -1015,6 +1035,7 @@ const DataTableComponent = ({<Labeled label={label} align="top" fullWidth={true}><DataTabledata={data}+ rawData={rawData}columns={columns}className={className}maxHeight={maxHeight}diff --git a/frontend/src/utils/copy.ts b/frontend/src/utils/copy.tsindex f30c08a6c6..fb55772d2b 100644--- a/frontend/src/utils/copy.ts+++ b/frontend/src/utils/copy.ts@@ -2,21 +2,34 @@import { Logger } from "./Logger";/**- * Tries to copy text to the clipboard using the navigator.clipboard API.- * If that fails, it falls back to prompting the user to copy.+ * Copy text to the clipboard. When `html` is provided, writes both+ * text/html and text/plain so rich content (e.g. hyperlinks) is+ * preserved when pasting into apps like Excel or Google Sheets.** As of 2024-10-29, Safari does not support navigator.clipboard.writeText* when running localhost http.*/-export async function copyToClipboard(text: string) {+export async function copyToClipboard(text: string, html?: string) {if (navigator.clipboard === undefined) {Logger.warn("navigator.clipboard is not supported");window.prompt("Copy to clipboard: Ctrl+C, Enter", text);return;}- await navigator.clipboard.writeText(text).catch(async () => {- // Fallback to prompt+ if (html && navigator.clipboard.write) {+ try {+ const item = new ClipboardItem({+ "text/html": new Blob([html], { type: "text/html" }),+ "text/plain": new Blob([text], { type: "text/plain" }),+ });+ await navigator.clipboard.write([item]);+ return;+ } catch {+ Logger.warn("Failed to write rich text, falling back to plain text");+ }+ }++ await navigator.clipboard.writeText(text).catch(() => {Logger.warn("Failed to copy to clipboard using navigator.clipboard");window.prompt("Copy to clipboard: Ctrl+C, Enter", text);});diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex a62ce49c57..3bc4293762 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -151,6 +151,9 @@ class SearchTableResponse:cell_hover_texts: Optional[dict[RowId, dict[ColumnName, Optional[str]]]] = None+ # Unformatted data mirroring the same shape/page as `data`,+ # provided when format_mapping is applied.+ raw_data: str | None = None@dataclass@@ -666,6 +669,7 @@ class table(dict[RowId, dict[ColumnName, Optional[str]]]] = Nonesearch_result_data: JSONType = []+ search_result_raw_data: str | None = Nonefield_types: Optional[FieldTypes] = Nonenum_columns = 0@@ -682,6 +686,7 @@ class table()search_result_styles = search_result.cell_stylessearch_result_data = search_result.data+ search_result_raw_data = search_result.raw_datasearch_result_hover_texts = search_result.cell_hover_texts# Validate column configurations@@ -703,6 +708,7 @@ class table(initial_value=initial_value,args={"data": search_result_data,+ "raw-data": search_result_raw_data,"total-rows": total_rows,"total-columns": num_columns,"max-columns": max_columns_arg,@@ -1353,7 +1359,9 @@ class table(if max_columns == MAX_COLUMNS_NOT_PROVIDED:max_columns = self._max_columns- def clamp_rows_and_columns(manager: TableManager[Any]) -> str:+ def clamp_rows_and_columns(+ manager: TableManager[Any],+ ) -> tuple[str, str | None]:# Limit to page and column clamping for the frontenddata = manager.take(args.page_size, offset)column_names = data.get_column_names()@@ -1369,7 +1377,9 @@ class table(data = data.select_columns(columns_to_select)try:- return data.to_json_str(self._format_mapping)+ formatted = data.to_json_str(self._format_mapping)+ raw = data.to_json_str() if self._format_mapping else None+ return formatted, rawexcept BaseException as e:# Catch and re-raise the error as a non-BaseException# to avoid crashing the kernel@@ -1385,8 +1395,9 @@ class table(else:total_rows = self._manager.get_num_rows(force=True) or 0+ formatted_data, raw_data = clamp_rows_and_columns(self._manager)return SearchTableResponse(- data=clamp_rows_and_columns(self._manager),+ data=formatted_data,total_rows=total_rows,cell_styles=self._style_cells(offset, args.page_size, total_rows@@ -1394,6 +1405,7 @@ class table(cell_hover_texts=self._hover_cells(offset, args.page_size, total_rows),+ raw_data=raw_data,)filter_function = (@@ -1422,8 +1434,9 @@ class table(if element.descending:descending = True+ formatted_data, raw_data = clamp_rows_and_columns(result)return SearchTableResponse(- data=clamp_rows_and_columns(result),+ data=formatted_data,total_rows=total_rows,cell_styles=self._style_cells(offset, args.page_size, total_rows, descending@@ -1431,6 +1444,7 @@ class table(cell_hover_texts=self._hover_cells(offset, args.page_size, total_rows, descending),+ raw_data=raw_data,)def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:diff --git a/marimo/_smoke_tests/tables/copy_rich_content.py b/marimo/_smoke_tests/tables/copy_rich_content.pynew file mode 100644index 0000000000..7196befb70--- /dev/null+++ b/marimo/_smoke_tests/tables/copy_rich_content.py@@ -0,0 +1,165 @@+import marimo++__generated_with = "0.21.0"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import random+ import polars as pl++ return mo, pl, random++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # Copy Rich Content from Tables++ Test copying and filtering cells with rich HTML content.++ - **Right-click → Copy cell** should preserve hyperlinks (text/html clipboard)+ - **Ctrl+C multi-cell** should produce an HTML table alongside tab-separated text+ - **Right-click → Filter by this value** should use the raw value, not the HTML+ """)+ return++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ ## Table with `format_mapping` (hyperlinks)+ """)+ return+++def _(mo):+ data = {+ "id": [1, 2, 3, 4, 5],+ "name": ["Alice", "Bob", "Charlie", "Diana", "Eve"],+ "score": [95, 87, 72, 91, 88],+ "website": [+ "https://example.com/alice",+ "https://example.com/bob",+ "https://example.com/charlie",+ "https://example.com/diana",+ "https://example.com/eve",+ ],+ }++ mo.ui.table(+ data,+ format_mapping={+ "name": lambda name: mo.md(f"**{name}**"),+ "score": lambda score: mo.md(+ f'<span style="color: {"green" if score >= 90 else "orange"}">{score}</span>'+ ),+ "website": lambda url: mo.md(f"[Visit site]({url})"),+ },+ label="Hyperlinks via format_mapping",+ )+ return+++def _(mo):+ mo.md("""+ ## Table with mixed content (UI elements + plain values)+ """)+ return+++def _(mo):+ mo.ui.table(+ {+ "label": ["Enable feature", "Dark mode", "Notifications"],+ "toggle": [+ mo.ui.checkbox(label="On"),+ mo.ui.checkbox(label="Off"),+ mo.ui.checkbox(label="On", value=True),+ ],+ "priority": [1, 2, 3],+ },+ label="Mixed: UI elements + plain values",+ )+ return+++def _(mo):+ mo.md("""+ ## Table with `mo.Html()` (text/html mime)+ """)+ return+++def _(mo):+ mo.ui.table(+ {+ "link": [+ mo.Html('<a href="https://marimo.io">marimo</a>'),+ mo.Html('<a href="https://github.com">GitHub</a>'),+ mo.Html('<a href="https://python.org">Python</a>'),+ ],+ "badge": [+ mo.Html(+ '<span style="background: green; color: white; padding: 2px 6px; border-radius: 4px">Active</span>'+ ),+ mo.Html(+ '<span style="background: red; color: white; padding: 2px 6px; border-radius: 4px">Inactive</span>'+ ),+ mo.Html(+ '<span style="background: orange; color: white; padding: 2px 6px; border-radius: 4px">Pending</span>'+ ),+ ],+ "plain": ["alpha", "beta", "gamma"],+ },+ label="Raw HTML via mo.Html()",+ )+ return+++def _(mo):+ mo.md("""+ ## Table with inline markdown (no format_mapping)+ """)+ return+++def _(mo):+ mo.ui.table(+ {+ "description": [+ mo.md("Contains **bold** text"),+ mo.md("Contains `inline code`"),+ mo.md("[A hyperlink](https://marimo.io)"),+ ],+ "plain": ["alpha", "beta", "gamma"],+ },+ label="Inline markdown as values (text/markdown mime)",+ )+ return+++def _(mo, pl, random):+ def url(k):+ return mo.md(f"[{k}](https://www.google.com/search?q={k})")+++ _random_numbers = [random.randint(1, 100) for _ in range(10)]+ df = pl.DataFrame({"filter_by_this": _random_numbers})++ mo.ui.table(df, format_mapping={"filter_by_this": url})+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex ccd1ceeb84..db4cc56294 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -2610,3 +2610,84 @@ def test_polars_enums_in_list():response_next_page.data== '[{"value":["C"]},{"value":["D"]},{"value":["A"]},{"value":["B"]},{"value":["C"]}]')+++def test_search_returns_raw_data_with_format_mapping() -> None:+ data = {"a": [1, 2, 3], "b": [4, 5, 6]}+ table = ui.table(+ data, # pyright: ignore[reportArgumentType]+ format_mapping={"a": lambda x: f"formatted_{x}"},+ )++ result = table._search(SearchTableArgs(page_size=10, page_number=0))++ assert json.loads(result.data) == [+ {"a": "formatted_1", "b": 4},+ {"a": "formatted_2", "b": 5},+ {"a": "formatted_3", "b": 6},+ ]++ assert result.raw_data is not None+ assert json.loads(result.raw_data) == [+ {"a": 1, "b": 4},+ {"a": 2, "b": 5},+ {"a": 3, "b": 6},+ ]+++def test_search_returns_no_raw_data_without_format_mapping() -> None:+ data = {"a": [1, 2, 3]}+ table = ui.table(data) # pyright: ignore[reportArgumentType]++ result = table._search(SearchTableArgs(page_size=10, page_number=0))++ assert result.raw_data is None+++def test_initial_args_include_raw_data_with_format_mapping() -> None:+ data = {"a": [10, 20], "b": ["x", "y"]}+ table = ui.table(+ data,+ format_mapping={"a": lambda x: x * 10},+ )++ raw_data = table._component_args["raw-data"]+ assert isinstance(raw_data, str)+ assert json.loads(raw_data) == [+ {"a": 10, "b": "x"},+ {"a": 20, "b": "y"},+ ]+ formatted_data = table._component_args["data"]+ assert isinstance(formatted_data, str)+ assert json.loads(formatted_data) == [+ {"a": 100, "b": "x"},+ {"a": 200, "b": "y"},+ ]+++def test_initial_args_no_raw_data_without_format_mapping() -> None:+ data = {"a": [1, 2]}+ table = ui.table(data) # pyright: ignore[reportArgumentType]++ assert table._component_args["raw-data"] is None+++def test_search_raw_data_with_query_and_format_mapping() -> None:+ data = {"name": ["alice", "bob", "charlie"], "score": [10, 20, 30]}+ table = ui.table(+ data,+ format_mapping={"score": lambda x: f"{x}%"},+ )++ result = table._search(+ SearchTableArgs(query="bob", page_size=10, page_number=0)+ )++ assert json.loads(result.data) == [+ {"name": "bob", "score": "20%"},+ ]++ assert result.raw_data is not None+ assert json.loads(result.raw_data) == [+ {"name": "bob", "score": 20},+ ]