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
add context menu for copy, copy selected and filter for table cells (#7351)
Shahmir Varqha4f51e62e1367
diff --git a/frontend/src/components/data-table/cell-utils.ts b/frontend/src/components/data-table/cell-utils.tsnew file mode 100644index 0000000000..8da5fd696c--- /dev/null+++ b/frontend/src/components/data-table/cell-utils.ts@@ -0,0 +1,9 @@+/* Copyright 2024 Marimo. All rights reserved. */++export const DATA_CELL_ID = "data-cell-id";++export function getCellDomProps(cellId: string) {+ return {+ [DATA_CELL_ID]: cellId,+ };+}diff --git a/frontend/src/components/data-table/charts/__tests__/renderer.test.ts b/frontend/src/components/data-table/charts/__tests__/renderer.test.tsindex d1b5ed8080..cc2617cfff 100644--- a/frontend/src/components/data-table/charts/__tests__/renderer.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/renderer.test.ts@@ -1,20 +1,20 @@/* Copyright 2024 Marimo. All rights reserved. */import { describe, expect, it } from "vitest";-import { renderUnknownValue } from "@/components/data-table/renderers";+import { stringifyUnknownValue } from "@/components/data-table/utils";describe("renderUnknownValue", () => {it("should render an object as a JSON string", () => {- expect(renderUnknownValue({ value: { a: 1 } })).toBe('{"a":1}');+ expect(stringifyUnknownValue({ value: { a: 1 } })).toBe('{"a":1}');});it("should render a null value as raw string when", () => {- expect(renderUnknownValue({ value: null })).toBe("null");+ expect(stringifyUnknownValue({ value: null })).toBe("null");});it("should render a null value as an empty string when specified", () => {- expect(renderUnknownValue({ value: null, nullAsEmptyString: true })).toBe(- "",- );+ expect(+ stringifyUnknownValue({ value: null, nullAsEmptyString: true }),+ ).toBe("");});});diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsxindex 20224fd281..018a6efaa1 100644--- a/frontend/src/components/data-table/column-header.tsx+++ b/frontend/src/components/data-table/column-header.tsx@@ -59,7 +59,7 @@ import {renderSortFilterIcon,renderSorts,} from "./header-items";-import { renderUnknownValue } from "./renderers";+import { stringifyUnknownValue } from "./utils";const TOP_K_ROWS = 30;@@ -616,7 +616,7 @@ const PopoverFilterByValues = <TData, TValue>({)}{filteredData.map(([value, count], rowIndex) => {const isSelected = chosenValues.has(value);- const valueString = renderUnknownValue({ value });+ const valueString = stringifyUnknownValue({ value });return (<CommandItemdiff --git a/frontend/src/components/data-table/context-menu.tsx b/frontend/src/components/data-table/context-menu.tsxnew file mode 100644index 0000000000..070dd73317--- /dev/null+++ b/frontend/src/components/data-table/context-menu.tsx@@ -0,0 +1,130 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { Cell } from "@tanstack/react-table";+import { useAtomValue } from "jotai";+import { CopyIcon, FilterIcon, SquareStack } from "lucide-react";+import type { RefObject } from "react";+import useEvent from "react-use-event-hook";+import { copyToClipboard } from "@/utils/copy";+import { Logger } from "@/utils/Logger";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuPortal,+ ContextMenuSeparator,+ ContextMenuTrigger,+} from "../ui/context-menu";+import { DATA_CELL_ID } from "./cell-utils";+import { Filter } from "./filters";+import { selectedCellsAtom } from "./range-focus/atoms";+import { stringifyUnknownValue } from "./utils";++export const DataTableContextMenu = <TData,>({+ contextMenuRef,+ tableBody,+ tableRef,+ copyAllCells,+}: {+ contextMenuRef: RefObject<Cell<TData, unknown> | null>;+ tableBody: React.ReactNode;+ tableRef: RefObject<HTMLTableSectionElement | null>;+ copyAllCells: () => void;+}) => {+ const handleContextMenuChange = useEvent((open: boolean) => {+ const cell = contextMenuRef.current;+ if (!cell) {+ return;+ }++ // Add a background color to the cell when the context menu is open+ const cellElement = tableRef.current?.querySelector(+ `[${DATA_CELL_ID}="${cell.id}"]`,+ );+ if (!cellElement) {+ Logger.error("Context menu cell not found in table");+ return;+ }++ if (open) {+ cellElement.classList.add("bg-(--green-4)");+ } else {+ cellElement.classList.remove("bg-(--green-4)");+ }+ });++ return (+ <ContextMenu onOpenChange={handleContextMenuChange}>+ <ContextMenuTrigger asChild={true}>{tableBody}</ContextMenuTrigger>+ <ContextMenuPortal>+ <CellContextMenu+ cellRef={contextMenuRef}+ copySelectedCells={copyAllCells}+ />+ </ContextMenuPortal>+ </ContextMenu>+ );+};++export const CellContextMenu = <TData,>({+ cellRef,+ copySelectedCells,+}: {+ cellRef: RefObject<Cell<TData, unknown> | null>;+ copySelectedCells: () => void;+}) => {+ const selectedCells = useAtomValue(selectedCellsAtom);+ const multipleSelectedCells = selectedCells.size > 1;++ const cell = cellRef.current;+ if (!cell) {+ Logger.error("No cell found in context menu");+ return;+ }++ const handleCopyCell = () => {+ try {+ const value = cell.getValue();+ const stringValue = stringifyUnknownValue({ value });+ copyToClipboard(stringValue);+ } catch (error) {+ Logger.error("Failed to copy context menu cell", error);+ }+ };++ const column = cell.column;+ const canFilter = column.getCanFilter() && column.columnDef.meta?.filterType;++ const handleFilterCell = () => {+ column.setFilterValue(+ Filter.select({+ options: [cell.getValue()],+ operator: "in",+ }),+ );+ };++ return (+ <ContextMenuContent>+ <ContextMenuItem onClick={handleCopyCell}>+ <CopyIcon className="mo-dropdown-icon h-3 w-3" />+ Copy cell+ </ContextMenuItem>+ {multipleSelectedCells && (+ <ContextMenuItem onClick={copySelectedCells}>+ <SquareStack className="mo-dropdown-icon h-3 w-3" />+ Copy selected cells+ </ContextMenuItem>+ )}+ {canFilter && (+ <>+ <ContextMenuSeparator />+ <ContextMenuItem onClick={handleFilterCell}>+ <FilterIcon className="mo-dropdown-icon h-3 w-3" />+ Filter by this value+ </ContextMenuItem>+ </>+ )}+ </ContextMenuContent>+ );+};diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsxindex 6680c97898..163f988a8b 100644--- a/frontend/src/components/data-table/filter-pills.tsx+++ b/frontend/src/components/data-table/filter-pills.tsx@@ -11,7 +11,7 @@ import { type DateFormatter, useDateFormatter } from "react-aria";import { logNever } from "@/utils/assertNever";import { Badge } from "../ui/badge";import type { ColumnFilterValue } from "./filters";-import { renderUnknownValue } from "./renderers";+import { stringifyUnknownValue } from "./utils";interface Props<TData> {filters: ColumnFiltersState | undefined;@@ -94,7 +94,7 @@ function formatValue(value: ColumnFilterValue, timeFormatter: DateFormatter) {}if (value.type === "select") {const stringifiedOptions = value.options.map((o) =>- renderUnknownValue({ value: o }),+ stringifyUnknownValue({ value: o }),);return `is in [${stringifiedOptions.join(", ")}]`;}diff --git a/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts b/frontend/src/components/data-table/range-focus/use-cell-range-selection.tsindex 745bbfaee7..6039827006 100644--- a/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts+++ b/frontend/src/components/data-table/range-focus/use-cell-range-selection.ts@@ -86,6 +86,11 @@ export const useCellRangeSelection = <TData>({const handleCellMouseDown = useEvent((e: React.MouseEvent, cell: Cell<TData, unknown>) => {+ // Right-clicks will trigger context menu, so avoid updating selected cells+ if (e.buttons === 2) {+ return;+ }+actions.handleCellMouseDown({cell,isShiftKey: e.shiftKey,diff --git a/frontend/src/components/data-table/range-focus/utils.ts b/frontend/src/components/data-table/range-focus/utils.tsindex e9871e88e9..a8a54cbc34 100644--- a/frontend/src/components/data-table/range-focus/utils.ts+++ b/frontend/src/components/data-table/range-focus/utils.ts@@ -1,8 +1,8 @@/* Copyright 2024 Marimo. All rights reserved. */import type { Table } from "@tanstack/react-table";-import { renderUnknownValue } from "../renderers";import { SELECT_COLUMN_ID } from "../types";+import { stringifyUnknownValue } from "../utils";import type { SelectedCell } from "./atoms";/**@@ -32,7 +32,7 @@ export function getCellValues<TData>(}const values = rowValues.get(rowId) ?? [];- values.push(renderUnknownValue({ value: tableCell.getValue() }));+ values.push(stringifyUnknownValue({ value: tableCell.getValue() }));rowValues.set(rowId, values);}diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex 4276e71773..9457b6a8db 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -12,6 +12,7 @@ import {type Table as TanStackTable,} from "@tanstack/react-table";import { type JSX, useRef } from "react";+import useEvent from "react-use-event-hook";import {TableBody,TableCell,@@ -20,10 +21,13 @@ import {TableRow,} from "@/components/ui/table";import { cn } from "@/utils/cn";+import { getCellDomProps } from "./cell-utils";import { COLUMN_WRAPPING_STYLES } from "./column-wrapping/feature";+import { DataTableContextMenu } from "./context-menu";import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";import { useScrollIntoViewOnFocus } from "./range-focus/use-scroll-into-view";+import { stringifyUnknownValue } from "./utils";export function renderTableHeader<TData>(table: Table<TData>,@@ -93,8 +97,14 @@ export const DataTableBody = <TData,>({handleCellMouseUp,handleCellMouseOver,handleCellsKeyDown,+ handleCopy: handleCopyAllCells,} = useCellRangeSelection({ table });+ const contextMenuCell = useRef<Cell<TData, unknown> | null>(null);+ const handleContextMenu = useEvent((cell: Cell<TData, unknown>) => {+ contextMenuCell.current = cell;+ });+function applyHoverTemplate(template: string,cells: Cell<TData, unknown>[],@@ -105,7 +115,7 @@ export const DataTableBody = <TData,>({for (const c of cells) {const v = c.getValue();// Prefer empty string for nulls to keep tooltip clean- const s = renderUnknownValue({ value: v, nullAsEmptyString: true });+ const s = stringifyUnknownValue({ value: v, nullAsEmptyString: true });idToValue.set(c.column.id, s);}return template.replaceAll(variableRegex, (_substr, varName: string) => {@@ -127,6 +137,7 @@ export const DataTableBody = <TData,>({return (<TableCelltabIndex={0}+ {...getCellDomProps(cell.id)}key={cell.id}className={cn("whitespace-pre truncate max-w-[300px] outline-hidden",@@ -141,6 +152,7 @@ export const DataTableBody = <TData,>({onMouseDown={(e) => handleCellMouseDown(e, cell)}onMouseUp={handleCellMouseUp}onMouseOver={(e) => handleCellMouseOver(e, cell)}+ onContextMenu={() => handleContextMenu(cell)}><CellRangeSelectionIndicator cellId={cell.id} /><div className="relative">@@ -160,7 +172,7 @@ export const DataTableBody = <TData,>({const hoverTemplate = table.getState().cellHoverTemplate || null;- return (+ const tableBody = (<TableBody onKeyDown={handleCellsKeyDown} ref={tableRef}>{table.getRowModel().rows?.length ? (table.getRowModel().rows.map((row) => {@@ -213,6 +225,15 @@ export const DataTableBody = <TData,>({)}</TableBody>);++ return (+ <DataTableContextMenu+ tableBody={tableBody}+ contextMenuRef={contextMenuCell}+ tableRef={tableRef}+ copyAllCells={handleCopyAllCells}+ />+ );};function getPinningStyles<TData>(@@ -265,23 +286,3 @@ function columnSizingHandler<TData>([column.id]: thead.getBoundingClientRect().width,}));}--/**- * Render an unknown value as a string. Converts objects to JSON strings.- * @param opts.value - The value to render.- * @param opts.nullAsEmptyString - If true, null values will be "". Else, stringify.- */-export function renderUnknownValue(opts: {- value: unknown;- nullAsEmptyString?: boolean;-}): string {- const { value, nullAsEmptyString = false } = opts;-- if (typeof value === "object" && value !== null) {- return JSON.stringify(value);- }- if (value === null && nullAsEmptyString) {- return "";- }- return String(value);-}diff --git a/frontend/src/components/data-table/utils.ts b/frontend/src/components/data-table/utils.tsindex 6e2b259f53..c1741755ac 100644--- a/frontend/src/components/data-table/utils.ts+++ b/frontend/src/components/data-table/utils.ts@@ -67,3 +67,23 @@ export function getPageIndexForRow(return null;}++/**+ * Stringify an unknown value. Converts objects to JSON strings.+ * @param opts.value - The value to stringify.+ * @param opts.nullAsEmptyString - If true, null values will be "". Else, stringify.+ */+export function stringifyUnknownValue(opts: {+ value: unknown;+ nullAsEmptyString?: boolean;+}): string {+ const { value, nullAsEmptyString = false } = opts;++ if (typeof value === "object" && value !== null) {+ return JSON.stringify(value);+ }+ if (value === null && nullAsEmptyString) {+ return "";+ }+ return String(value);+}