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
feat: add back cell range selection & table json viewer improvements (#5450)
Shahmir Varqhaf657c7d74d84
diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex f0d2a0aeaf..25bf401a10 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -73,7 +73,7 @@ export function inferFieldTypes<T>(items: T[]): FieldTypesWithExternalType {}// We will be a bit defensive and assume values are not homogeneous.// If any is a mimetype, then we will treat it as a mimetype (i.e. not sortable)- Object.entries(item).forEach(([key, value], idx) => {+ Object.entries(item).forEach(([key, value]) => {const currentValue = fieldTypes[key];if (!currentValue) {// Set for the first time@@ -313,7 +313,11 @@ const PopoutColumn = ({{rawStringValue}</span></PopoverTrigger>- <PopoverContent className={contentClassName}>+ <PopoverContent+ className={contentClassName}+ align="start"+ alignOffset={10}+ ><PopoverClose className="absolute top-2 right-2"><Button variant="link" size="xs">{buttonText ?? "Close"}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 b6626e6a46..2a51eb362c 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@@ -2,7 +2,6 @@import type { Cell, Table } from "@tanstack/react-table";import useEvent from "react-use-event-hook";-import { Functions } from "@/utils/functions";import { type SelectedCell, useCellSelectionReducerActions } from "./atoms";export interface UseCellRangeSelectionProps<TData> {@@ -107,18 +106,6 @@ export const useCellRangeSelection = <TData>({},);- if (DISABLED) {- return {- handleCellMouseDown: Functions.NOOP,- handleCellMouseUp: Functions.NOOP,- handleCellMouseOver: Functions.NOOP,- handleCellsKeyDown: Functions.NOOP,- updateSelection: Functions.NOOP,- clearSelection: Functions.NOOP,- handleCopy: Functions.NOOP,- };- }-return {handleCellMouseDown,handleCellMouseUp,@@ -129,5 +116,3 @@ export const useCellRangeSelection = <TData>({clearSelection: actions.clearSelection,};};--const DISABLED = true;diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex 63f50969ca..ce82e7d956 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -20,6 +20,8 @@ import {TableRow,} from "@/components/ui/table";import { cn } from "@/utils/cn";+import { CellRangeSelectionIndicator } from "./range-focus/cell-selection-indicator";+import { useCellRangeSelection } from "./range-focus/use-cell-range-selection";export function renderTableHeader<TData>(table: Table<TData>,@@ -79,6 +81,13 @@ export const DataTableBody = <TData,>({getRowIndex,viewedRowIdx,}: DataTableBodyProps<TData>) => {+ const {+ handleCellMouseDown,+ handleCellMouseUp,+ handleCellMouseOver,+ handleCellsKeyDown,+ } = useCellRangeSelection({ table });+const renderCells = (cells: Array<Cell<TData, unknown>>) => {return cells.map((cell) => {const { className, style: pinningstyle } = getPinningStyles(cell.column);@@ -92,7 +101,7 @@ export const DataTableBody = <TData,>({tabIndex={0}key={cell.id}className={cn(- "whitespace-pre truncate max-w-[300px]",+ "whitespace-pre truncate max-w-[300px] select-none outline-none",cell.column.getColumnWrapping &&cell.column.getColumnWrapping() === "wrap" &&"whitespace-pre-wrap min-w-[200px]",@@ -101,8 +110,14 @@ export const DataTableBody = <TData,>({)}style={style}title={String(cell.getValue())}+ onMouseDown={(e) => handleCellMouseDown(e, cell)}+ onMouseUp={handleCellMouseUp}+ onMouseOver={(e) => handleCellMouseOver(e, cell)}>- {flexRender(cell.column.columnDef.cell, cell.getContext())}+ <CellRangeSelectionIndicator cellId={cell.id} />+ <div className="relative">+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </div></TableCell>);});@@ -116,7 +131,7 @@ export const DataTableBody = <TData,>({};return (- <TableBody>+ <TableBody onKeyDown={handleCellsKeyDown}>{table.getRowModel().rows?.length ? (table.getRowModel().rows.map((row) => {// Only find the row index if the row viewer panel is opendiff --git a/frontend/src/components/editor/output/JsonOutput.tsx b/frontend/src/components/editor/output/JsonOutput.tsxindex dc6a050f6d..fc35db6564 100644--- a/frontend/src/components/editor/output/JsonOutput.tsx+++ b/frontend/src/components/editor/output/JsonOutput.tsx@@ -128,12 +128,13 @@ export const JsonOutput: React.FC<Props> = memo(collapseStringsAfterLength={COLLAPSED_TEXT_LENGTH}// leave the default valueTypes as it was - 'python', only 'json' is changedvalueTypes={valueTypesMap[valueTypes]}- // When the number of elements exceed 50, we group them in sizes of 50- // This improves perf but may look like there are nested arrays- groupArraysAfterLength={50}+ // Don't group arrays, it will make the tree view look like there are nested arrays+ groupArraysAfterLength={Number.MAX_SAFE_INTEGER}// Built-in clipboard shifts content on hover// so we provide our own copy buttonenableClipboard={false}+ // Improve perf for large arrays+ maxDisplayLength={determineMaxDisplayLength(data)}/>);@@ -343,7 +344,7 @@ const REPLACE_SUFFIX = "</marimo-replace>";* - maps booleans to True and False* - maps null/undefined to None*/-function pythonJsonReplacer(key: string, value: unknown): unknown {+function pythonJsonReplacer(_key: string, value: unknown): unknown {if (value == null) {return `${REPLACE_PREFIX}None${REPLACE_SUFFIX}`;}@@ -385,3 +386,39 @@ export function getCopyValue(value: unknown): string {.replaceAll(`"${REPLACE_PREFIX}`, "").replaceAll(`${REPLACE_SUFFIX}"`, "");}++/**+ * Determine the max display length for a given data.+ * - For 3D arrays, we return 5+ * - For 2D arrays, return undefined <= 20 items, 10 >= 20 items, 5 >= 50 items+ * - For 1D arrays and other types, we return undefined+ *+ * @param data - The data to determine the max display length for.+ * @returns The max display length, or undefined to use the default.+ */+export function determineMaxDisplayLength(data: unknown): number | undefined {+ if (Array.isArray(data)) {+ const sampleElements = data.slice(0, 15);++ let maxLength = 0;+ for (const element of sampleElements) {+ if (Array.isArray(element)) {+ // Check for 3D arrays and return early+ const nextSample = element.slice(0, 5);+ for (const nextElement of nextSample) {+ if (Array.isArray(nextElement)) {+ return 5;+ }+ }++ maxLength = Math.max(maxLength, element.length);+ }+ }++ if (maxLength <= 20) {+ return undefined;+ }++ return maxLength >= 50 ? 5 : 10;+ }+}diff --git a/frontend/src/components/editor/output/__tests__/json-output.test.ts b/frontend/src/components/editor/output/__tests__/json-output.test.tsindex 2b04a165d8..2ff76ba494 100644--- a/frontend/src/components/editor/output/__tests__/json-output.test.ts+++ b/frontend/src/components/editor/output/__tests__/json-output.test.ts@@ -1,6 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */import { describe, expect, it } from "vitest";-import { getCopyValue } from "../JsonOutput";+import { determineMaxDisplayLength, getCopyValue } from "../JsonOutput";describe("getCopyValue", () => {it("should handle strings without MIME prefixes", () => {@@ -219,3 +219,51 @@ describe("getCopyValue", () => {);});});++describe("determineMaxDisplayLength", () => {+ const sample2DArray = [+ [1, 2, 3],+ [4, 5, 6],+ [7, 8, 9],+ [10, 11, 12],+ [13, 14, 15],+ [16, 17, 18],+ [19, 20, 21],+ [22, 23, 24],+ [25, 26, 27],+ [28, 29, 30],+ ];++ it("should return undefined for 1 level arrays", () => {+ const value = [1, 2, 3];+ const result = determineMaxDisplayLength(value);+ expect(result).toBeUndefined();+ });++ it("should return undefined for 2 level arrays with less than 20 items", () => {+ const value = sample2DArray;+ const result = determineMaxDisplayLength(value);+ expect(result).toBeUndefined();+ });++ it("should return 10 for 2 level arrays with more than 20 items", () => {+ const longArray = Array.from({ length: 21 }, (_, i) => i);+ const value = [...sample2DArray, longArray];+ const result = determineMaxDisplayLength(value);+ expect(result).toBe(10);+ });++ it("should return 5 for 2 level arrays with more than 50 items", () => {+ const longArray = Array.from({ length: 51 }, (_, i) => i);+ const value = [...sample2DArray, longArray];+ const result = determineMaxDisplayLength(value);+ expect(result).toBe(5);+ });++ it("should return 5 for 3 level arrays with more than 20 items", () => {+ const longArray = Array.from({ length: 21 }, (_, i) => i);+ const value = [[...sample2DArray], [...sample2DArray, longArray]];+ const result = determineMaxDisplayLength(value);+ expect(result).toBe(5);+ });+});