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: data editor plugin v2 (#5514)
Shahmir Varqhab5fc4b8ae5e1
diff --git a/frontend/index.html b/frontend/index.htmlindex 6fda22668d..2a602ea1af 100644--- a/frontend/index.html+++ b/frontend/index.html@@ -62,6 +62,8 @@</head><body><div id="root"></div>+ <!-- This is a portal for the data editor to render in -->+ <div id="portal" data-testid="glide-portal" style="position: fixed; left: 0; top: 0; z-index: 9999"></div><script data-marimo="true">window.__MARIMO_MOUNT_CONFIG__ = '{{ mount_config }}';</script>diff --git a/frontend/package.json b/frontend/package.jsonindex 903ce6ccb7..ae0ad7a359 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -36,6 +36,7 @@"@dnd-kit/utilities": "^3.2.2","@emotion/cache": "^11.14.0","@emotion/react": "^11.14.0",+ "@glideapps/glide-data-grid": "6.0.4-alpha16","@hookform/resolvers": "^3.10.0","@img-comparison-slider/react": "^8.0.2","@internationalized/date": "^3.8.2",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 53c63e531a..01a1dd75e7 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -84,6 +84,9 @@ importers:'@emotion/react':specifier: ^11.14.0version: 11.14.0(@types/[email protected])([email protected])+ '@glideapps/glide-data-grid':+ specifier: 6.0.4-alpha16+ version: 6.0.4-alpha16([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])'@hookform/resolvers':specifier: ^3.10.0version: 3.10.0([email protected]([email protected]))@@ -1391,6 +1394,15 @@ packages:'@formatjs/[email protected]':resolution: {integrity: sha512-zTwEpWOzZ2CiKcB93BLngUX59hQkuZjT2+SAQEscSm52peDW/getsawMcWF1rGRpMCX6D7nSJA3CzJ8gn13N/g==}+ '@glideapps/[email protected]':+ resolution: {integrity: sha512-sdxnb7jFdEycj+VZVbZ011javugovH3lzdqstt2JLYMBKz0C9ahGvgRf4Rmz5+uaj0xEcvkL9cb+l5hodKJUJw==}+ peerDependencies:+ lodash: ^4.17.19+ marked: ^4.0.10+ react: ^16.12.0 || 17.x || 18.x || 19.x+ react-dom: ^16.12.0 || 17.x || 18.x || 19.x+ react-responsive-carousel: ^3.2.7+'@hookform/[email protected]':resolution: {integrity: sha512-79Dv+3mDF7i+2ajj7SkypSKHhl1cbln1OGavqrsF7p6mbUv11xpqpacPsGDCTRvCSjEEIez2ef1NveSVL3b0Ag==}peerDependencies:@@ -1550,6 +1562,16 @@ packages:'@lezer/[email protected]':resolution: {integrity: sha512-XCkwuxe+eumJ28nA9e1S6XKsXz9W7V/AG+WBiWOtiIuUpKcZ/bHuvN8bLxSDREIcybSRpEd/jvphh4vgm6Ed2g==}+ '@linaria/[email protected]':+ resolution: {integrity: sha512-fs1aQyX4DmJpeGMyobuSznAo/Y02+Q8vhm+c/jr2WHDmqKHEJpCqH2Mhu1End+SdiUvZIUgb4MNiZryWtZLD5g==}+ engines: {node: '>=16.0.0'}++ '@linaria/[email protected]':+ resolution: {integrity: sha512-CjdEPwQCIRB3BRecnwK0g9mEWow3M1zAJTKI7h/B6j3yRLQRelitcoLd19MxZNz89pc0NNPALqy2I+eBGH0lJA==}+ engines: {node: '>=16.0.0'}+ peerDependencies:+ react: '>=16'+'@mapbox/[email protected]':resolution: {integrity: sha512-tJaT+RbYGJYStt7wI3cq4Nl4SXxG8W7JDG5DMJu97V25RnbNg3QtQtf+KD+VLjNpWKYsRvXDNmNrBgEETr1ifA==}hasBin: true@@ -3895,6 +3917,14 @@ packages:'@webassemblyjs/[email protected]':resolution: {integrity: sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==}+ '@wyw-in-js/[email protected]':+ resolution: {integrity: sha512-5YAZMUmF+S2HaqheKfew6ybbYBMnF10PjIgI7ieyuFxCohyqJNF4xdo6oHftv2z5Z4vCQ0OZHtDOQyDImBYwmg==}+ engines: {node: '>=16.0.0'}++ '@wyw-in-js/[email protected]':+ resolution: {integrity: sha512-BozBos29AuMWOvjjKf+bYYN+Vku0Nar6+y5oxrJXIZzUEKiWTVnIxO256vi8cUBGfo/DH44o+qZTkkdSN2pPXw==}+ engines: {node: '>=16.0.0'}+'@xterm/[email protected]':resolution: {integrity: sha512-JboCN0QAY6ZLY/SSB/Zl2cQ5zW1Eh4X3fH7BnuR1NB7xGRhzbqU2Npmpiw/3zFlxDaU88vtKzok44JKi2L2V2Q==}peerDependencies:@@ -4272,6 +4302,9 @@ packages:resolution: {integrity: sha512-onIcjRpz69/Hx5bB5HGbYKUF2uC6QT6Gp+pfpGm3A7mPfcluSLV5v4Zu+oflDUwLdUw0rLIBhUbi0v8hM4FJQQ==}+ resolution: {integrity: sha512-+VsMpRr64jYgKq2IeFUNel3vCZH/IzS+iXSHxmUV3IUH5dXlC9xHz4AwtPZisDxZ5MWcuK0V+TXgPKFPiZnxzg==}+resolution: {integrity: sha512-ODLXH644w9C2fMPAm7bMDQ3GRvipZWZfKc+8As6hIadRIelE0n0xZuN38NS6kiK3KPEVrpymmQD8bvncAHWQkQ==}@@ -4342,6 +4375,9 @@ packages:resolution: {integrity: sha512-sbpkOw6z413p+HDGcBENe498WM9woqWHiJxCq7nvmxe9WmrUmqfAcxpIwAiMtM5Q3AhYkzXcNQHqsWq0mND51g==}+ resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}+resolution: {integrity: sha512-GfisEZEJvzKrmGWkvfhgzcz/BllN1USeqD2V6tg14OAOgaCD2Z/PUEuxnAZ/nPvmaHRG7a8y77p1T/IRQ4D1Hw==}engines: {node: '>=4'}@@ -5709,6 +5745,9 @@ packages:resolution: {integrity: sha512-+o4Y4Z0CLuyemeccvGN4bAO20aauB2N9tFEAep5x4OW34kV4PTarBHm6RL02afYt2BMKcr0D2Agep8S3nJPIBg==}+ resolution: {integrity: sha512-UrRKgp5sQmRnDy4TEwAUsu14XBUlzKB8U3hjIYDjcZ3Hbp86Jtftzxfgrv6E/ii/h78tsaZwAnAE8HwnHr0dPA==}+resolution: {integrity: sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==}engines: {node: '>=18'}@@ -7372,6 +7411,10 @@ packages:peerDependencies:react: '>= 16.8 || 18.0.0'+ resolution: {integrity: sha512-OeR2jAxdoqUMHIn/nS9fgreI5hSpgGoL5ezdal4+oO7YSSgJR8ga+PkYGJrSrJ9MKlPcQjMQXnketrD7WNmNsg==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-tnjAxG+IkpLephNcePNA7v6F/QpWLH8He65+DmedchDwg162JZqx4NmbXj0mlAYVVEd81OW7aFhmbsScYfiAFQ==}peerDependencies:@@ -7389,6 +7432,9 @@ packages:peerDependencies:react: ^16.8.0 || ^17 || ^18 || ^19+ resolution: {integrity: sha512-uS3MmThNKFH2EZUQQw4k5pIcU7XIr208UE5dktrj/GOH1CMagqxDl4DCLpt3o2l9x+IB5nVYBeN3Cr4IutBXAg==}+resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}@@ -7404,6 +7450,12 @@ packages:'@types/react': '>=18'react: '>=18'+ resolution: {integrity: sha512-wOmoNZoOpvMminhifQYiYSTCLUDOiUbBunrMrMjA+dV52sY+vck1S4UhR6PkgnoCquvvMSeJjErXZ4qSaWCliA==}+ peerDependencies:+ react: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^0.14 || ^15.0.0 || ^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+resolution: {integrity: sha512-g93xcyhAVCSt9kV1svqG1clAEdL6k3U+jjuSzfTV7owaSU9Go6Ph8bl25J+jKfKvIGAEYpe4qj++WHJuc9IaeA==}peerDependencies:@@ -7448,6 +7500,9 @@ packages:peerDependencies:react: '>= 16.3'+ resolution: {integrity: sha512-pqJLsBaKHWJhw/ItODgbVoziR2z4lpcJg+YwmRlSk4rKH32VE633mAtZZ9kDXjy4wFO+pgUZmDKPsPe1fPmHCg==}+resolution: {integrity: sha512-fm2LRM3XN5lJD48+WQKWvESx54kAIHw0JztCRHMsFmTDgYWX/VASuXKON7LECv227stSEadrxGa8LhPkcelljw==}peerDependencies:@@ -8226,6 +8281,10 @@ packages:resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==}+ resolution: {integrity: sha512-uivwYcQaxAucv1CzRp2n/QdYPo4ILf9VXgH19zEIjFx2EJufV16P0JtJVpYHy89DItG6Kwj2oIUjrcK5au+4tQ==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-CLDfGgUp7XPswWnezWwsCRxNmgQjhYq3VXHM0/XIRxhVrKw0M1if9agzryh1QS3nxjCROvV+xWxoJO1YctzzWg==}engines: {node: ^18 || >=20}@@ -9981,6 +10040,19 @@ snapshots:dependencies:tslib: 2.8.1+ '@glideapps/[email protected]([email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])':+ dependencies:+ '@linaria/react': 6.3.0([email protected])+ canvas-hypertxt: 1.0.3+ lodash: 4.17.21+ marked: 15.0.12+ react: 19.1.0+ react-dom: 19.1.0([email protected])+ react-responsive-carousel: 3.2.23+ transitivePeerDependencies:+ - supports-color+dependencies:react-hook-form: 7.54.2([email protected])@@ -10191,6 +10263,26 @@ snapshots:'@lezer/highlight': 1.2.1'@lezer/lr': 1.4.2+ '@linaria/[email protected]':+ dependencies:+ '@wyw-in-js/processor-utils': 0.6.0+ transitivePeerDependencies:+ - supports-color++ '@linaria/[email protected]([email protected])':+ dependencies:+ '@emotion/is-prop-valid': 1.3.1+ '@linaria/core': 6.3.0+ '@wyw-in-js/processor-utils': 0.6.0+ '@wyw-in-js/shared': 0.6.0+ minimatch: 9.0.4+ react: 19.1.0+ react-html-attributes: 1.4.6+ resolve: 1.22.10+ ts-invariant: 0.10.3+ transitivePeerDependencies:+ - supports-color+'@mapbox/[email protected]':dependencies:get-stream: 6.0.1@@ -13247,6 +13339,21 @@ snapshots:'@webassemblyjs/ast': 1.14.1'@xtuc/long': 4.2.2+ '@wyw-in-js/[email protected]':+ dependencies:+ '@babel/generator': 7.27.5+ '@wyw-in-js/shared': 0.6.0+ transitivePeerDependencies:+ - supports-color++ '@wyw-in-js/[email protected]':+ dependencies:+ debug: 4.4.1+ find-up: 5.0.0+ minimatch: 9.0.4+ transitivePeerDependencies:+ - supports-color+'@xterm/[email protected](@xterm/[email protected])':dependencies:'@xterm/xterm': 5.5.0@@ -13620,6 +13727,8 @@ snapshots:dependencies:element-size: 1.1.1+ [email protected]: {}+@@ -13694,6 +13803,8 @@ snapshots:+ [email protected]: {}+dependencies:escape-string-regexp: 1.0.5@@ -15367,6 +15478,8 @@ snapshots:domhandler: 5.0.3htmlparser2: 10.0.0+ [email protected]: {}+dependencies:whatwg-encoding: 3.1.1@@ -17291,6 +17404,10 @@ snapshots:prop-types: 15.8.1react: 19.1.0+ dependencies:+ prop-types: 15.8.1+dependencies:'@babel/runtime': 7.27.6@@ -17311,6 +17428,10 @@ snapshots:dependencies:react: 19.1.0+ dependencies:+ html-element-attributes: 1.3.1+@@ -17335,6 +17456,11 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ react: 19.1.0+ react-dom: 19.1.0([email protected])+[email protected](patch_hash=e65888c226f3ef8f42923cbb3b026d2f4811da3e96fa0d7dee3cb62df02c6189)([email protected]([email protected])([email protected]([email protected])))([email protected]):dependencies:@@ -17377,6 +17503,12 @@ snapshots:transitivePeerDependencies:- react-dom+ dependencies:+ classnames: 2.5.1+ prop-types: 15.8.1+ react-easy-swipe: 0.0.21+dependencies:'@react-stately/calendar': 3.8.2([email protected])@@ -18414,6 +18546,10 @@ snapshots:+ dependencies:+ tslib: 2.8.1+optionalDependencies:typescript: 5.8.3diff --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 2a51eb362c..745bbfaee7 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,6 +2,7 @@import type { Cell, Table } from "@tanstack/react-table";import useEvent from "react-use-event-hook";+import { Events } from "@/utils/events";import { type SelectedCell, useCellSelectionReducerActions } from "./atoms";export interface UseCellRangeSelectionProps<TData> {@@ -47,7 +48,7 @@ export const useCellRangeSelection = <TData>({const handleCellsKeyDown = useEvent((e: React.KeyboardEvent<HTMLElement>) => {switch (e.key) {case "c":- if (e.metaKey || e.ctrlKey) {+ if (Events.isMetaOrCtrl(e)) {handleCopy();}break;diff --git a/frontend/src/components/data-table/range-focus/utils.ts b/frontend/src/components/data-table/range-focus/utils.tsindex 61d4105ee7..e9871e88e9 100644--- a/frontend/src/components/data-table/range-focus/utils.ts+++ b/frontend/src/components/data-table/range-focus/utils.ts@@ -36,7 +36,11 @@ export function getCellValues<TData>(rowValues.set(rowId, values);}- return [...rowValues.values()].map((values) => values.join("\t")).join("\n");+ return getTabSeparatedValues([...rowValues.values()]);+}++export function getTabSeparatedValues(values: string[][]) {+ return values.map((row) => row.join("\t")).join("\n");}/**diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsxindex 09ee69e977..8ee4139d0b 100644--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx@@ -1,39 +1,36 @@/* Copyright 2024 Marimo. All rights reserved. */+import glideCss from "@glideapps/glide-data-grid/dist/index.css?inline";import { TooltipProvider } from "@radix-ui/react-tooltip";-import agGridCss from "ag-grid-community/styles/ag-grid.css?inline";-import agThemeCss from "ag-grid-community/styles/ag-theme-quartz.css?inline";-import React from "react";+import React, { useState } from "react";import { z } from "zod";+import { inferFieldTypes } from "@/components/data-table/columns";import { LoadingTable } from "@/components/data-table/loading-table";-import { toFieldTypes } from "@/components/data-table/types";+import { type FieldTypes, toFieldTypes } from "@/components/data-table/types";import { Alert, AlertTitle } from "@/components/ui/alert";import { DelayMount } from "@/components/utils/delay-mount";import { DATA_TYPES } from "@/core/kernel/messages";import { useAsyncData } from "@/hooks/useAsyncData";import { createPlugin } from "../core/builder";import type { Setter } from "../types";-import type { DataEditorProps } from "./data-editor/data-editor";-import gridCss from "./data-editor/grid.css?inline";+import {+ BulkEdit,+ type DataEditorProps,+ type Edits,+} from "./data-editor/types";import { vegaLoadData } from "./vega/loader";import { getVegaFieldTypes } from "./vega/utils";type CsvURL = string;type TableData<T> = T[] | CsvURL;-interface Edits {- edits: Array<{- rowIdx: number;- columnId: string;- value: unknown;- }>;-}--// Lazy load the data editor since it brings in ag-grid-const LazyDataEditor = React.lazy(() => import("./data-editor/data-editor"));+// Lazy load the data editor since it brings in glide-data-grid+const LazyDataEditor = React.lazy(+ () => import("./data-editor/glide-data-editor"),+);export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {- cssStyles: [gridCss, agGridCss, agThemeCss],+ cssStyles: [glideCss],}).withData(z.object({@@ -48,8 +45,6 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {}),label: z.string().nullable(),data: z.union([z.string(), z.array(z.object({}).passthrough())]),- pagination: z.boolean().default(false),- pageSize: z.number().default(10),fieldTypes: z.array(z.tuple([@@ -58,7 +53,7 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {]),).nullish(),- columnSizingMode: z.enum(["auto", "fit"]).default("auto"),+ columnSizingMode: z.enum(["auto", "fit"]).default("auto"), // TODO: Remove this}),).withFunctions({})@@ -67,12 +62,11 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {<TooltipProvider><LoadingDataEditordata={props.data.data}- pagination={props.data.pagination}- pageSize={props.data.pageSize}fieldTypes={props.data.fieldTypes}- edits={props.value.edits}+ edits={props.value}onEdits={props.setValue}columnSizingMode={props.data.columnSizingMode}+ host={props.host}/></TooltipProvider>);@@ -81,25 +75,32 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor", {interface Propsextends Omit<DataEditorProps<object>, "data" | "onAddEdits" | "onAddRows"> {data: TableData<object>;- edits: Edits["edits"];+ edits: Edits;onEdits: Setter<Edits>;+ host: HTMLElement;}const LoadingDataEditor = (props: Props) => {- // Load the data- const { data, error } = useAsyncData(async () => {- // If we already have the data, return it- if (Array.isArray(props.data)) {- return props.data;- }+ const [data, setData] = useState<unknown[]>([]);+ const [columnFields, setColumnFields] = useState<FieldTypes>({});+ // Load the data+ const { error } = useAsyncData(async () => {const withoutExternalTypes = toFieldTypes(props.fieldTypes ?? []);+ // If we already have the data, return it// Otherwise, load the data from the URL- return await vegaLoadData(- props.data,- { type: "csv", parse: getVegaFieldTypes(withoutExternalTypes) },- { handleBigIntAndNumberLike: true },+ const localData = Array.isArray(props.data)+ ? props.data+ : await vegaLoadData(+ props.data,+ { type: "csv", parse: getVegaFieldTypes(withoutExternalTypes) },+ { handleBigIntAndNumberLike: true },+ );++ setData(localData);+ setColumnFields(+ toFieldTypes(props.fieldTypes ?? inferFieldTypes(localData)),);}, [props.fieldTypes, props.data]);@@ -125,10 +126,10 @@ const LoadingDataEditor = (props: Props) => {return (<LazyDataEditordata={data}- pagination={props.pagination}- pageSize={props.pageSize}- fieldTypes={props.fieldTypes}- edits={props.edits}+ setData={setData}+ columnFields={columnFields}+ setColumnFields={setColumnFields}+ edits={props.edits.edits} // TODO: This is returning old edits upon refreshonAddEdits={(edits) => {props.onEdits((v) => ({ ...v, edits: [...v.edits, ...edits] }));}}@@ -142,7 +143,36 @@ const LoadingDataEditor = (props: Props) => {);props.onEdits((v) => ({ ...v, edits: [...v.edits, ...newEdits] }));}}- columnSizingMode={props.columnSizingMode}+ onDeleteRows={(rowIndexes) => {+ props.onEdits((v) => {+ const newEdits = rowIndexes.map((rowIdx, index) => ({+ rowIdx: rowIdx - index,+ type: BulkEdit.Remove,+ }));+ return {+ ...v,+ edits: [...v.edits, ...newEdits],+ };+ });+ }}+ onRenameColumn={(columnIdx: number, newName: string) => {+ props.onEdits((v) => ({+ ...v,+ edits: [...v.edits, { columnIdx, newName, type: BulkEdit.Rename }],+ }));+ }}+ onDeleteColumn={(columnIdx: number) => {+ props.onEdits((v) => ({+ ...v,+ edits: [...v.edits, { columnIdx, type: BulkEdit.Remove }],+ }));+ }}+ onAddColumn={(columnIdx: number, newName: string) => {+ props.onEdits((v) => ({+ ...v,+ edits: [...v.edits, { columnIdx, newName, type: BulkEdit.Insert }],+ }));+ }}/>);};diff --git a/frontend/src/plugins/impl/data-editor/__tests__/data-utils.test.ts b/frontend/src/plugins/impl/data-editor/__tests__/data-utils.test.tsnew file mode 100644index 0000000000..55d01b1f7a--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/__tests__/data-utils.test.ts@@ -0,0 +1,876 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import type { FieldTypes } from "@/components/data-table/types";+import {+ insertColumn,+ modifyColumnFields,+ removeColumn,+ renameColumn,+} from "../data-utils";++describe("removeColumn", () => {+ const testData = [+ { int: 1, string: "a", bool: "True", datetime: "2025-07-12 00:07:13" },+ { int: 2, string: "b", bool: "False", datetime: null },+ { int: 3, string: "c", bool: null, datetime: "2025-07-12 00:07:13" },+ { int: 0, string: "", bool: "", datetime: "" },+ ];++ it("should remove column at index 0", () => {+ const result = removeColumn(testData, 0);++ expect(result).toEqual([+ { string: "a", bool: "True", datetime: "2025-07-12 00:07:13" },+ { string: "b", bool: "False", datetime: null },+ { string: "c", bool: null, datetime: "2025-07-12 00:07:13" },+ { string: "", bool: "", datetime: "" },+ ]);+ });++ it("should remove column at index 1", () => {+ const result = removeColumn(testData, 1);++ expect(result).toEqual([+ { int: 1, bool: "True", datetime: "2025-07-12 00:07:13" },+ { int: 2, bool: "False", datetime: null },+ { int: 3, bool: null, datetime: "2025-07-12 00:07:13" },+ { int: 0, bool: "", datetime: "" },+ ]);+ });++ it("should remove column at index 2", () => {+ const result = removeColumn(testData, 2);++ expect(result).toEqual([+ { int: 1, string: "a", datetime: "2025-07-12 00:07:13" },+ { int: 2, string: "b", datetime: null },+ { int: 3, string: "c", datetime: "2025-07-12 00:07:13" },+ { int: 0, string: "", datetime: "" },+ ]);+ });++ it("should remove column at index 3", () => {+ const result = removeColumn(testData, 3);++ expect(result).toEqual([+ { int: 1, string: "a", bool: "True" },+ { int: 2, string: "b", bool: "False" },+ { int: 3, string: "c", bool: null },+ { int: 0, string: "", bool: "" },+ ]);+ });++ it("should handle removing non-existent column index", () => {+ const result = removeColumn(testData, 999);+ // Should return the original data since the index doesn't exist+ expect(result).toEqual(testData);+ });++ it("should handle negative index", () => {+ const result = removeColumn(testData, -1);+ // Should return the original data since negative index is invalid+ expect(result).toEqual(testData);+ });++ it("should preserve original data structure", () => {+ const originalData = [...testData];+ removeColumn(testData, 1);+ // Original data should remain unchanged+ expect(testData).toEqual(originalData);+ });++ it("should handle objects with different property counts", () => {+ const mixedData = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }];++ const result = removeColumn(mixedData, 1);++ expect(result).toEqual([{ a: 1 }, { a: 3, c: 5 }, { a: 6 }]);+ });++ it("should handle null and undefined values in data", () => {+ const dataWithNulls = [+ { a: 1, b: null, c: undefined },+ { a: null, b: 2, c: 3 },+ ];++ const result = removeColumn(dataWithNulls, 1);++ expect(result).toEqual([+ { a: 1, c: undefined },+ { a: null, c: 3 },+ ]);+ });+});++describe("insertColumn", () => {+ const testData = [+ { int: 1, string: "a", bool: "True", datetime: "2025-07-12 00:07:13" },+ { int: 2, string: "b", bool: "False", datetime: null },+ { int: 3, string: "c", bool: null, datetime: "2025-07-12 00:07:13" },+ { int: 0, string: "", bool: "", datetime: "" },+ ];++ it("should insert column at index 0", () => {+ const result = insertColumn(testData, "newColumn");++ const expected = [+ {+ newColumn: "",+ int: 1,+ string: "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ },+ { newColumn: "", int: 2, string: "b", bool: "False", datetime: null },+ {+ newColumn: "",+ int: 3,+ string: "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ },+ { newColumn: "", int: 0, string: "", bool: "", datetime: "" },+ ];+ expect(result).toEqual(expected);+ });++ it("should insert column at index 1", () => {+ const result = insertColumn(testData, "newColumn");++ expect(result).toEqual([+ {+ int: 1,+ newColumn: "",+ string: "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ },+ { int: 2, newColumn: "", string: "b", bool: "False", datetime: null },+ {+ int: 3,+ newColumn: "",+ string: "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ },+ { int: 0, newColumn: "", string: "", bool: "", datetime: "" },+ ]);+ });++ it("should insert column at index 2", () => {+ const result = insertColumn(testData, "newColumn");++ expect(result).toEqual([+ {+ int: 1,+ string: "a",+ newColumn: "",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ },+ { int: 2, string: "b", newColumn: "", bool: "False", datetime: null },+ {+ int: 3,+ string: "c",+ newColumn: "",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ },+ { int: 0, string: "", newColumn: "", bool: "", datetime: "" },+ ]);+ });++ it("should insert column at index 3", () => {+ const result = insertColumn(testData, "newColumn");++ expect(result).toEqual([+ {+ int: 1,+ string: "a",+ bool: "True",+ newColumn: "",+ datetime: "2025-07-12 00:07:13",+ },+ { int: 2, string: "b", bool: "False", newColumn: "", datetime: null },+ {+ int: 3,+ string: "c",+ bool: null,+ newColumn: "",+ datetime: "2025-07-12 00:07:13",+ },+ { int: 0, string: "", bool: "", newColumn: "", datetime: "" },+ ]);+ });++ it("should insert column at the end when index equals length", () => {+ const result = insertColumn(testData, "newColumn");++ expect(result).toEqual([+ {+ int: 1,+ string: "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ newColumn: "",+ },+ { int: 2, string: "b", bool: "False", datetime: null, newColumn: "" },+ {+ int: 3,+ string: "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ newColumn: "",+ },+ { int: 0, string: "", bool: "", datetime: "", newColumn: "" },+ ]);+ });++ it("should handle inserting at index beyond array length", () => {+ const result = insertColumn(testData, "newColumn");+ // Should add the column at the end+ expect(result).toEqual([+ {+ int: 1,+ string: "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ newColumn: "",+ },+ { int: 2, string: "b", bool: "False", datetime: null, newColumn: "" },+ {+ int: 3,+ string: "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ newColumn: "",+ },+ { int: 0, string: "", bool: "", datetime: "", newColumn: "" },+ ]);+ });++ it("should preserve original data structure", () => {+ const originalData = [...testData];+ insertColumn(testData, "newColumn");+ // Original data should remain unchanged+ expect(testData).toEqual(originalData);+ });++ it("should handle empty array", () => {+ const result = insertColumn([], "newColumn");+ expect(result).toEqual([]);+ });++ it("should handle array with single object", () => {+ const singleRowData = [{ a: 1, b: 2, c: 3 }];+ const result = insertColumn(singleRowData, "newColumn");+ expect(result).toEqual([{ a: 1, newColumn: "", b: 2, c: 3 }]);+ });++ it("should handle objects with different property counts", () => {+ const mixedData = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }];++ const result = insertColumn(mixedData, "newColumn");++ expect(result).toEqual([+ { a: 1, newColumn: "", b: 2 },+ { a: 3, newColumn: "", b: 4, c: 5 },+ { a: 6, newColumn: "" },+ ]);+ });++ it("should handle null and undefined values in data", () => {+ const dataWithNulls = [+ { a: 1, b: null, c: undefined },+ { a: null, b: 2, c: 3 },+ ];++ const result = insertColumn(dataWithNulls, "newColumn");++ expect(result).toEqual([+ { a: 1, newColumn: "", b: null, c: undefined },+ { a: null, newColumn: "", b: 2, c: 3 },+ ]);+ });++ it("should handle special characters in column name", () => {+ const result = insertColumn(testData, "new-column_with_123");++ expect(result).toEqual([+ {+ int: 1,+ "new-column_with_123": "",+ string: "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ },+ {+ int: 2,+ "new-column_with_123": "",+ string: "b",+ bool: "False",+ datetime: null,+ },+ {+ int: 3,+ "new-column_with_123": "",+ string: "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ },+ { int: 0, "new-column_with_123": "", string: "", bool: "", datetime: "" },+ ]);+ });+});++describe("renameColumn", () => {+ const testData = [+ { int: 1, string: "a", bool: "True", datetime: "2025-07-12 00:07:13" },+ { int: 2, string: "b", bool: "False", datetime: null },+ { int: 3, string: "c", bool: null, datetime: "2025-07-12 00:07:13" },+ { int: 0, string: "", bool: "", datetime: "" },+ ];++ it("should rename a column successfully", () => {+ const result = renameColumn(testData, "int", "number");++ expect(result).toEqual([+ { number: 1, string: "a", bool: "True", datetime: "2025-07-12 00:07:13" },+ { number: 2, string: "b", bool: "False", datetime: null },+ { number: 3, string: "c", bool: null, datetime: "2025-07-12 00:07:13" },+ { number: 0, string: "", bool: "", datetime: "" },+ ]);+ });++ it("should rename a column with special characters", () => {+ const result = renameColumn(testData, "string", "text-field");++ expect(result).toEqual([+ {+ int: 1,+ "text-field": "a",+ bool: "True",+ datetime: "2025-07-12 00:07:13",+ },+ { int: 2, "text-field": "b", bool: "False", datetime: null },+ {+ int: 3,+ "text-field": "c",+ bool: null,+ datetime: "2025-07-12 00:07:13",+ },+ { int: 0, "text-field": "", bool: "", datetime: "" },+ ]);+ });++ it("should handle renaming to an existing column name", () => {+ const result = renameColumn(testData, "int", "string");++ expect(result).toEqual([+ { string: 1, bool: "True", datetime: "2025-07-12 00:07:13" },+ { string: 2, bool: "False", datetime: null },+ { string: 3, bool: null, datetime: "2025-07-12 00:07:13" },+ { string: 0, bool: "", datetime: "" },+ ]);+ });++ it("should handle non-existent column name gracefully", () => {+ const result = renameColumn(testData, "nonexistent", "newName");++ // Should return the original data unchanged since the column doesn't exist+ expect(result).toEqual(testData);+ });++ it("should handle empty string column names", () => {+ const result = renameColumn(testData, "", "emptyColumn");++ // Should return the original data unchanged since empty string is not a valid column name+ expect(result).toEqual(testData);+ });++ it("should handle renaming to empty string", () => {+ const result = renameColumn(testData, "int", "");++ // Should return the original data unchanged since empty string is not a valid column name+ expect(result).toEqual(testData);+ });++ it("should preserve original data structure", () => {+ const originalData = [...testData];+ renameColumn(testData, "int", "number");+ // Original data should remain unchanged+ expect(testData).toEqual(originalData);+ });++ it("should handle empty array", () => {+ const result = renameColumn([], "oldName", "newName");+ expect(result).toEqual([]);+ });++ it("should handle array with single object", () => {+ const singleRowData = [{ a: 1, b: 2, c: 3 }];+ const result = renameColumn(singleRowData, "a", "x");+ expect(result).toEqual([{ x: 1, b: 2, c: 3 }]);+ });++ it("should handle objects with different property counts", () => {+ const mixedData = [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }];++ const result = renameColumn(mixedData, "a", "alpha");++ expect(result).toEqual([+ { alpha: 1, b: 2 },+ { alpha: 3, b: 4, c: 5 },+ { alpha: 6 },+ ]);+ });++ it("should handle null and undefined values in data", () => {+ const dataWithNulls = [+ { a: 1, b: null, c: undefined },+ { a: null, b: 2, c: 3 },+ ];++ const result = renameColumn(dataWithNulls, "b", "beta");++ expect(result).toEqual([+ { a: 1, beta: null, c: undefined },+ { a: null, beta: 2, c: 3 },+ ]);+ });++ it("should handle case-sensitive column names", () => {+ const caseSensitiveData = [{ Name: "John", name: "Jane" }];+ const result = renameColumn(caseSensitiveData, "Name", "FullName");++ expect(result).toEqual([{ FullName: "John", name: "Jane" }]);+ });++ it("should handle renaming multiple columns in sequence", () => {+ let result = renameColumn(testData, "int", "number");+ result = renameColumn(result, "string", "text");+ result = renameColumn(result, "bool", "boolean");++ expect(result).toEqual([+ {+ number: 1,+ text: "a",+ boolean: "True",+ datetime: "2025-07-12 00:07:13",+ },+ { number: 2, text: "b", boolean: "False", datetime: null },+ { number: 3, text: "c", boolean: null, datetime: "2025-07-12 00:07:13" },+ { number: 0, text: "", boolean: "", datetime: "" },+ ]);+ });++ it("should handle renaming to the same name", () => {+ const result = renameColumn(testData, "int", "int");++ // Should return the original data unchanged+ expect(result).toEqual(testData);+ });++ it("should handle numeric column names", () => {+ const numericData = [{ "1": "value1", "2": "value2" }];+ const result = renameColumn(numericData, "1", "one");++ expect(result).toEqual([{ one: "value1", "2": "value2" }]);+ });+});++describe("modifyColumnFields", () => {+ const testFieldTypes: FieldTypes = {+ int: "integer",+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ it("should insert a new column at index 0", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 0,+ type: "insert",+ newColumnName: "newColumn",+ });++ const expected = {+ newColumn: "string",+ int: "integer",+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should insert a new column at index 1", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 1,+ type: "insert",+ newColumnName: "newColumn",+ });++ const expected = {+ int: "integer",+ newColumn: "string",+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should insert a new column at index 2", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 2,+ type: "insert",+ newColumnName: "newColumn",+ });++ const expected = {+ int: "integer",+ string: "string",+ newColumn: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should insert a new column at the end", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 4,+ type: "insert",+ newColumnName: "newColumn",+ dataType: "datetime",+ });++ const expected = {+ int: "integer",+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ newColumn: "datetime", // Set to the same type as the data type+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should insert a new column beyond the array length", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 10,+ type: "insert",+ newColumnName: "newColumn",+ });++ const expected = {+ int: "integer",+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ newColumn: "string",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should remove column at index 0", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 0,+ type: "remove",+ });++ const expected = {+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should remove column at index 1", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 1,+ type: "remove",+ });++ const expected = {+ int: "integer",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should remove column at index 2", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 2,+ type: "remove",+ });++ const expected = {+ int: "integer",+ string: "string",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should remove column at index 3", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 3,+ type: "remove",+ });++ const expected = {+ int: "integer",+ string: "string",+ bool: "boolean",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should handle removing non-existent column index", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 999,+ type: "remove",+ });+ // Should return the original field types since the index doesn't exist+ expect(result).toEqual(testFieldTypes);+ });++ it("should handle negative index for remove", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: -1,+ type: "remove",+ });+ // Should return the original field types since negative index is invalid+ expect(result).toEqual(testFieldTypes);+ });++ it("should rename column at index 0", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 0,+ type: "rename",+ newColumnName: "number",+ });++ const expected = {+ number: "string", // Defaults to string type for renamed columns+ string: "string",+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should rename column at index 1", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 1,+ type: "rename",+ newColumnName: "text",+ });++ const expected = {+ int: "integer",+ text: "string", // Defaults to string type for renamed columns+ bool: "boolean",+ datetime: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should rename column at index 3", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 3,+ type: "rename",+ dataType: "datetime",+ newColumnName: "timestamp",+ });++ const expected = {+ int: "integer",+ string: "string",+ bool: "boolean",+ timestamp: "datetime",+ };++ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });++ it("should handle renaming non-existent column index", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 999,+ type: "rename",+ newColumnName: "newName",+ });+ // Should return the original field types since the index doesn't exist+ expect(result).toEqual(testFieldTypes);+ });++ it("should handle negative index for rename", () => {+ const result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: -1,+ type: "rename",+ newColumnName: "newName",+ });+ // Should return the original field types since negative index is invalid+ expect(result).toEqual(testFieldTypes);+ });++ it("should preserve original field types structure", () => {+ const originalFieldTypes = { ...testFieldTypes };+ modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 1,+ type: "remove",+ });+ // Original field types should remain unchanged+ expect(testFieldTypes).toEqual(originalFieldTypes);+ });++ it("should handle empty field types object", () => {+ const emptyFieldTypes: FieldTypes = {};++ // Insert+ const insertResult = modifyColumnFields({+ columnFields: emptyFieldTypes,+ columnIdx: 0,+ type: "insert",+ newColumnName: "newColumn",+ });+ expect(insertResult).toEqual({ newColumn: "string" });++ // Remove+ const removeResult = modifyColumnFields({+ columnFields: emptyFieldTypes,+ columnIdx: 0,+ type: "remove",+ });+ expect(removeResult).toEqual({});+ });++ it("should handle field types with special characters in column names", () => {+ const specialFieldTypes: FieldTypes = {+ "column-with-dash": "integer",+ column_with_underscore: "string",+ "column.with.dot": "boolean",+ "column with space": "datetime",+ };++ // Insert+ const insertResult = modifyColumnFields({+ columnFields: specialFieldTypes,+ columnIdx: 1,+ type: "insert",+ newColumnName: "new-column",+ });+ const insertExpected = {+ "column-with-dash": "integer",+ "new-column": "string",+ column_with_underscore: "string",+ "column.with.dot": "boolean",+ "column with space": "datetime",+ };+ expect(Object.keys(insertResult)).toEqual(Object.keys(insertExpected));+ expect(insertResult).toEqual(insertExpected);++ // Remove+ const removeResult = modifyColumnFields({+ columnFields: specialFieldTypes,+ columnIdx: 1,+ type: "remove",+ });+ const removeExpected = {+ "column-with-dash": "integer",+ "column.with.dot": "boolean",+ "column with space": "datetime",+ };+ expect(Object.keys(removeResult)).toEqual(Object.keys(removeExpected));+ expect(removeResult).toEqual(removeExpected);++ // Rename+ const renameResult = modifyColumnFields({+ columnFields: specialFieldTypes,+ columnIdx: 1,+ type: "rename",+ newColumnName: "renamed-column",+ });+ const renameExpected = {+ "column-with-dash": "integer",+ "renamed-column": "string",+ "column.with.dot": "boolean",+ "column with space": "datetime",+ };+ expect(Object.keys(renameResult)).toEqual(Object.keys(renameExpected));+ expect(renameResult).toEqual(renameExpected);+ });++ it("should handle multiple operations in sequence", () => {+ let result = modifyColumnFields({+ columnFields: testFieldTypes,+ columnIdx: 1,+ type: "insert",+ newColumnName: "newColumn",+ });+ result = modifyColumnFields({+ columnFields: result,+ columnIdx: 2,+ type: "remove",+ });+ result = modifyColumnFields({+ columnFields: result,+ columnIdx: 0,+ type: "rename",+ newColumnName: "renamed",+ });++ const expected = {+ renamed: "string",+ newColumn: "string",+ bool: "boolean",+ datetime: "datetime",+ };+ expect(Object.keys(result)).toEqual(Object.keys(expected));+ expect(result).toEqual(expected);+ });+});diff --git a/frontend/src/plugins/impl/data-editor/__tests__/glide-utils.test.ts b/frontend/src/plugins/impl/data-editor/__tests__/glide-utils.test.tsnew file mode 100644index 0000000000..b115fee15c--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/__tests__/glide-utils.test.ts@@ -0,0 +1,413 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { GridSelection } from "@glideapps/glide-data-grid";+import { CompactSelection, GridCellKind } from "@glideapps/glide-data-grid";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { pasteCells } from "../glide-utils";+import type { ModifiedGridColumn } from "../types";++// Mock navigator.clipboard+const mockClipboard = {+ readText: vi.fn(),+};++Object.defineProperty(navigator, "clipboard", {+ value: mockClipboard,+ writable: true,+});++describe("pasteCells", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ // GridSelection expects { current?: { range: { x, y } }, rows, columns }+ const createMockSelection = (x: number, y: number): GridSelection => ({+ current: {+ cell: [x, y],+ range: { x, y, width: 1, height: 1 },+ rangeStack: [],+ },+ rows: CompactSelection.empty(),+ columns: CompactSelection.empty(),+ });++ /**+ * Name Age Active+ * ------- ------- -------+ * Alice 25 true+ * Bob 30 false+ * Charlie 35 true+ */+ const createMockColumns = (): ModifiedGridColumn[] => [+ {+ title: "name",+ dataType: "string",+ kind: GridCellKind.Text,+ width: 100,+ id: "name",+ },+ {+ title: "age",+ dataType: "integer",+ kind: GridCellKind.Number,+ width: 100,+ id: "age",+ },+ {+ title: "active",+ dataType: "boolean",+ kind: GridCellKind.Boolean,+ width: 100,+ id: "active",+ },+ ];++ const createMockData = () => [+ { name: "Alice", age: 25, active: true },+ { name: "Bob", age: 30, active: false },+ { name: "Charlie", age: 35, active: true },+ ];++ it("should handle empty clipboard text", async () => {+ mockClipboard.readText.mockResolvedValue("");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ // Wait for the async operation+ await vi.waitFor(() => {+ expect(mockOnAddEdits).not.toHaveBeenCalled();+ expect(mockSetLocalData).not.toHaveBeenCalled();+ });+ });++ it("should handle whitespace-only clipboard text", async () => {+ mockClipboard.readText.mockResolvedValue(" \n\t ");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).not.toHaveBeenCalled();+ expect(mockSetLocalData).not.toHaveBeenCalled();+ });+ });++ it("should paste string data correctly", async () => {+ mockClipboard.readText.mockResolvedValue("David\t40\ttrue");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "David" },+ { rowIdx: 0, columnId: "age", value: 40 },+ { rowIdx: 0, columnId: "active", value: true },+ ]);+ });+ });++ it("should convert number values correctly", async () => {+ mockClipboard.readText.mockResolvedValue("Eve\t25.5\tfalse");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Eve" },+ { rowIdx: 0, columnId: "age", value: 25.5 },+ { rowIdx: 0, columnId: "active", value: false },+ ]);+ });+ });++ it("should handle boolean conversion with different values", async () => {+ mockClipboard.readText.mockResolvedValue("Frank\t30\t1");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Frank" },+ { rowIdx: 0, columnId: "age", value: 30 },+ { rowIdx: 0, columnId: "active", value: true },+ ]);+ });+ });++ it("should skip invalid number values", async () => {+ mockClipboard.readText.mockResolvedValue("Grace\tinvalid\tfalse");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Grace" },+ { rowIdx: 0, columnId: "active", value: false },+ ]);+ });+ });++ it("should handle multiple rows", async () => {+ mockClipboard.readText.mockResolvedValue("Hank\t40\ttrue\nIvy\t35\tfalse");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Hank" },+ { rowIdx: 0, columnId: "age", value: 40 },+ { rowIdx: 0, columnId: "active", value: true },+ { rowIdx: 1, columnId: "name", value: "Ivy" },+ { rowIdx: 1, columnId: "age", value: 35 },+ { rowIdx: 1, columnId: "active", value: false },+ ]);+ });+ });++ it("should respect data bounds - not exceed row count", async () => {+ mockClipboard.readText.mockResolvedValue(+ "Jack\t45\ttrue\nKate\t50\tfalse\nLiam\t55\ttrue",+ );++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(), // Only 3 rows+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Jack" },+ { rowIdx: 0, columnId: "age", value: 45 },+ { rowIdx: 0, columnId: "active", value: true },+ { rowIdx: 1, columnId: "name", value: "Kate" },+ { rowIdx: 1, columnId: "age", value: 50 },+ { rowIdx: 1, columnId: "active", value: false },+ { rowIdx: 2, columnId: "name", value: "Liam" },+ { rowIdx: 2, columnId: "age", value: 55 },+ { rowIdx: 2, columnId: "active", value: true },+ ]);+ });+ });++ it("should respect column bounds - not exceed column count", async () => {+ mockClipboard.readText.mockResolvedValue("Mia\t30\ttrue\textra");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(), // Only 3 columns+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Mia" },+ { rowIdx: 0, columnId: "age", value: 30 },+ { rowIdx: 0, columnId: "active", value: true },+ ]);+ });+ });++ it("should handle starting position offset", async () => {+ mockClipboard.readText.mockResolvedValue("Noah\t25\ttrue");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(1, 1), // Start at column 1, row 1+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 1, columnId: "active", value: false },+ ]);+ });+ });++ it("should handle no selection", async () => {+ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: {+ current: undefined,+ rows: CompactSelection.empty(),+ columns: CompactSelection.empty(),+ },+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).not.toHaveBeenCalled();+ expect(mockSetLocalData).not.toHaveBeenCalled();+ });+ });++ it("should handle clipboard read error", async () => {+ mockClipboard.readText.mockRejectedValue(+ new Error("Clipboard access denied"),+ );++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();+ const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {+ // Do nothing+ });++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).not.toHaveBeenCalled();+ expect(mockSetLocalData).not.toHaveBeenCalled();+ });++ consoleSpy.mockRestore();+ });++ it("should update local data when edits are applied", async () => {+ mockClipboard.readText.mockResolvedValue("Olivia\t28\ttrue");++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockSetLocalData).toHaveBeenCalled();++ // Verify the updater function is called+ const updater = mockSetLocalData.mock.calls[0][0];+ const originalData = createMockData();+ const updatedData = updater(originalData);++ expect(updatedData[0].name).toBe("Olivia");+ expect(updatedData[0].age).toBe(28);+ expect(updatedData[0].active).toBe(true);+ });+ });++ it("should handle empty rows in clipboard data", async () => {+ mockClipboard.readText.mockResolvedValue(+ "Paul\t30\ttrue\n\nRachel\t25\tfalse",+ );++ const mockSetLocalData = vi.fn();+ const mockOnAddEdits = vi.fn();++ pasteCells({+ selection: createMockSelection(0, 0),+ data: createMockData(),+ setData: mockSetLocalData,+ columns: createMockColumns(),+ onAddEdits: mockOnAddEdits,+ });++ await vi.waitFor(() => {+ expect(mockOnAddEdits).toHaveBeenCalledWith([+ { rowIdx: 0, columnId: "name", value: "Paul" },+ { rowIdx: 0, columnId: "age", value: 30 },+ { rowIdx: 0, columnId: "active", value: true },+ { rowIdx: 1, columnId: "name", value: "Rachel" },+ { rowIdx: 1, columnId: "age", value: 25 },+ { rowIdx: 1, columnId: "active", value: false },+ ]);+ });+ });+});diff --git a/frontend/src/plugins/impl/data-editor/components.tsx b/frontend/src/plugins/impl/data-editor/components.tsxnew file mode 100644index 0000000000..224ae9da41--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/components.tsx@@ -0,0 +1,179 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { capitalize } from "lodash-es";+import { PencilIcon, PlusIcon } from "lucide-react";+import { useState } from "react";+import { Button } from "@/components/ui/button";+import {+ DropdownMenuPortal,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import type { DataType } from "@/core/kernel/messages";++interface RenameColumnSubProps {+ currentColumnName: string;+ onRename: (newName: string) => void;+ onCancel: () => void;+}++export const RenameColumnSub: React.FC<RenameColumnSubProps> = ({+ currentColumnName,+ onRename,+ onCancel,+}) => {+ const [inputValue, setInputValue] = useState("");++ const handleRename = () => {+ if (inputValue.trim()) {+ onRename(inputValue.trim());+ setInputValue(currentColumnName);+ }+ };++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ handleRename();+ } else if (e.key === "Escape") {+ onCancel();+ }+ };++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <PencilIcon className="mr-2 h-3.5 w-3.5" />+ Rename column+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="w-64 p-4">+ <div className="space-y-3">+ <div>+ <Label htmlFor="rename-input">Column name</Label>+ <Input+ value={inputValue}+ onChange={(e) => setInputValue(e.target.value)}+ placeholder="Enter new column name"+ className="mt-1"+ onKeyDown={handleKeyDown}+ />+ </div>+ <Button+ onClick={handleRename}+ disabled={!inputValue.trim()}+ size="sm"+ className="w-full"+ >+ Rename+ </Button>+ </div>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ );+};++interface AddColumnSubProps {+ direction: "left" | "right";+ onAdd: (columnName: string, dataType: DataType) => void;+ onCancel: () => void;+}++export const AddColumnSub: React.FC<AddColumnSubProps> = ({+ direction,+ onAdd,+ onCancel,+}) => {+ const [columnName, setColumnName] = useState("");+ const [dataType, setDataType] = useState<DataType>("string");++ const supportedDataTypes: DataType[] = [+ "string",+ "number",+ "boolean",+ "datetime",+ ];++ const handleAdd = () => {+ if (columnName.trim()) {+ onAdd(columnName.trim(), dataType);+ setColumnName("");+ setDataType("string"); // reset+ }+ };++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Enter") {+ handleAdd();+ } else if (e.key === "Escape") {+ onCancel();+ }+ };++ return (+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>+ <PlusIcon className="mr-2 h-3.5 w-3.5" />+ Add column to the {direction}+ </DropdownMenuSubTrigger>+ <DropdownMenuPortal>+ <DropdownMenuSubContent className="w-64 p-4">+ <div className="space-y-3">+ <div>+ <Label htmlFor={`add-column-input-${direction}`}>+ Column name+ </Label>+ <Input+ id={`add-column-input-${direction}`}+ value={columnName}+ onChange={(e) => setColumnName(e.target.value)}+ placeholder="Enter column name"+ className="mt-1"+ onKeyDown={handleKeyDown}+ />+ </div>+ <div>+ <Label htmlFor={`add-column-type-${direction}`}>Data type</Label>+ <Select+ value={dataType}+ onValueChange={(value) => setDataType(value as DataType)}+ >+ <SelectTrigger+ id={`add-column-type-${direction}`}+ className="mt-1"+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {supportedDataTypes.map((type) => (+ <SelectItem key={type} value={type}>+ {capitalize(type)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <Button+ onClick={handleAdd}+ disabled={!columnName.trim()}+ size="sm"+ className="w-full"+ >+ Add+ </Button>+ </div>+ </DropdownMenuSubContent>+ </DropdownMenuPortal>+ </DropdownMenuSub>+ );+};diff --git a/frontend/src/plugins/impl/data-editor/data-utils.ts b/frontend/src/plugins/impl/data-editor/data-utils.tsnew file mode 100644index 0000000000..c29e31e1a9--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/data-utils.ts@@ -0,0 +1,123 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { FieldTypes } from "@/components/data-table/types";+import type { DataType } from "@/core/kernel/messages";+import { Logger } from "@/utils/Logger";++/**+ * For modifying data, we do not worry about the order of the columns.+ * Because we define getCellContent based on columnTitle, the order does not matter.+ *+ * For column fields, we do care about the order+ */++export function removeColumn<T>(data: T[], columnIdx: number): T[] {+ return data.map((row) => {+ const rowData = row as Record<string, unknown>;+ const keys = Object.keys(rowData);++ // If the column index is out of bounds, return the original row+ if (columnIdx < 0 || columnIdx >= keys.length) {+ return rowData as T;+ }++ const keyToRemove = keys[columnIdx];++ // Create new object without the specified key+ const { [keyToRemove]: _, ...rest } = rowData;+ return rest as T;+ });+}++/**+ * Insert a new column at the end of the data.+ * @param data - The data to insert the column into+ * @param newName - The name of the new column+ * @returns The data with the new column inserted at the end+ */+export function insertColumn<T>(data: T[], newName?: string): T[] {+ if (!newName) {+ return data;+ }++ return data.map((row) => ({+ ...(row as Record<string, unknown>),+ [newName]: "",+ })) as T[];+}++export function renameColumn<T>(+ data: T[],+ oldName: string,+ newName: string,+): T[] {+ if (!oldName || !newName || oldName === newName) {+ return data;+ }++ return data.map((row) => {+ const rowData = row as Record<string, unknown>;+ const { [oldName]: _, ...rest } = rowData;+ return { ...rest, [newName]: rowData[oldName] } as T;+ });+}++// Order of columns is important+export function modifyColumnFields(opts: {+ columnFields: FieldTypes;+ columnIdx: number;+ type: "insert" | "remove" | "rename";+ dataType?: DataType;+ newColumnName?: string;+}): FieldTypes {+ const { columnFields, columnIdx, type, dataType, newColumnName } = opts;++ switch (type) {+ case "insert": {+ if (!newColumnName) {+ Logger.error("newName is required for insert");+ return columnFields;+ }++ const entries = Object.entries(columnFields);+ const newEntries = [+ ...entries.slice(0, columnIdx),+ [newColumnName, dataType || "string"],+ ...entries.slice(columnIdx),+ ];+ return Object.fromEntries(newEntries);+ }+ case "remove": {+ if (columnIdx < 0 || columnIdx >= Object.keys(columnFields).length) {+ return columnFields;+ }++ const entries = Object.entries(columnFields);+ const columnName = entries[columnIdx]?.[0];+ if (columnName) {+ const { [columnName]: _, ...rest } = columnFields;+ return rest;+ }+ return columnFields;+ }+ case "rename": {+ if (!newColumnName) {+ Logger.error("newName is required for rename");+ return columnFields;+ }++ if (columnIdx < 0 || columnIdx >= Object.keys(columnFields).length) {+ return columnFields;+ }++ // Rename at the right index+ const entries = Object.entries(columnFields);+ const newEntries = [+ ...entries.slice(0, columnIdx),+ [newColumnName, dataType || "string"],+ ...entries.slice(columnIdx + 1),+ ];+ return Object.fromEntries(newEntries);+ }+ }+}diff --git a/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx b/frontend/src/plugins/impl/data-editor/glide-data-editor.tsxnew file mode 100644index 0000000000..83f92f5df5--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/glide-data-editor.tsx@@ -0,0 +1,628 @@+/* Copyright 2024 Marimo. All rights reserved. */++import DataEditor, {+ CompactSelection,+ type DataEditorRef,+ type EditableGridCell,+ type GridCell,+ GridCellKind,+ type GridColumn,+ type GridKeyEventArgs,+ type GridSelection,+ type Item,+ type Rectangle,+} from "@glideapps/glide-data-grid";+import { CopyIcon, TrashIcon } from "lucide-react";+import React, { useCallback, useMemo, useRef, useState } from "react";+import useEvent from "react-use-event-hook";+import type { FieldTypes } from "@/components/data-table/types";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "@/components/ui/dropdown-menu";+import { useTheme } from "@/theme/useTheme";+import { copyToClipboard } from "@/utils/copy";+import {+ getColumnHeaderIcon,+ getColumnKind,+ isColumnEdit,+ isPositionalEdit,+ isRowEdit,+ pasteCells,+} from "./glide-utils";+import { getGlideTheme } from "./themes";+import { BulkEdit, type Edits, type ModifiedGridColumn } from "./types";+import "@glideapps/glide-data-grid/dist/index.css"; // TODO: We are reimporting this+import { ErrorBoundary } from "@/components/editor/boundary/ErrorBoundary";+import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/use-toast";+import type { DataType } from "@/core/kernel/messages";+import { useOnMount } from "@/hooks/useLifecycle";+import { useNonce } from "@/hooks/useNonce";+import { logNever } from "@/utils/assertNever";+import { Events } from "@/utils/events";+import { AddColumnSub, RenameColumnSub } from "./components";+import {+ insertColumn,+ modifyColumnFields,+ removeColumn,+ renameColumn,+} from "./data-utils";++interface GlideDataEditorProps<T> {+ data: T[];+ setData: (data: T[] | ((prev: T[]) => T[])) => void;+ columnFields: FieldTypes;+ setColumnFields: React.Dispatch<React.SetStateAction<FieldTypes>>;+ edits: Edits["edits"];+ onAddEdits: (edits: Edits["edits"]) => void;+ onAddRows: (newRows: object[]) => void;+ onDeleteRows: (rows: number[]) => void;+ onRenameColumn: (columnIdx: number, newName: string) => void;+ onDeleteColumn: (columnIdx: number) => void;+ onAddColumn: (columnIdx: number, newName: string) => void;+}++export const GlideDataEditor = <T,>({+ data,+ setData,+ columnFields,+ setColumnFields,+ edits,+ onAddEdits,+ onAddRows,+ onDeleteRows,+ onRenameColumn,+ onDeleteColumn,+ onAddColumn,+}: GlideDataEditorProps<T>) => {+ const { theme } = useTheme();+ const dataEditorRef = useRef<DataEditorRef>(null);++ const [menu, setMenu] = useState<{ col: number; bounds: Rectangle }>();+ const [showSearch, setShowSearch] = useState<boolean>(false);+ const [selection, setSelection] = React.useState<GridSelection>({+ columns: CompactSelection.empty(),+ rows: CompactSelection.empty(),+ });++ const [columnWidths, setColumnWidths] = useState<Record<string, number>>({});+ const rerender = useNonce();++ // Handle initial edits passed in+ useOnMount(() => {+ if (edits.length === 0) {+ return;+ }++ // Group edits by row index to build new rows+ const newRows = new Map<number, Record<string, unknown>>();++ for (const edit of edits) {+ if (isPositionalEdit(edit)) {+ if (edit.rowIdx >= data.length) {+ // This is a new row+ if (!newRows.has(edit.rowIdx)) {+ newRows.set(edit.rowIdx, {});+ }+ const row = newRows.get(edit.rowIdx);+ if (row) {+ row[edit.columnId] = edit.value;+ }+ } else {+ // This is an existing row, update the data+ setData((prev) => {+ const newData = [...prev];+ newData[edit.rowIdx][edit.columnId as keyof T] =+ edit.value as T[keyof T];+ return newData;+ });+ }+ } else if (isRowEdit(edit) && edit.type === BulkEdit.Remove) {+ // Add rows is currently handled under positional edits, so we only cover deletes here+ setData((prev) => prev.filter((_, i) => i !== edit.rowIdx));+ } else if (isColumnEdit(edit)) {+ switch (edit.type) {+ case BulkEdit.Remove:+ // Remove the column from the data+ setData((prev) => removeColumn(prev, edit.columnIdx));+ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: edit.columnIdx,+ type: "remove",+ }),+ );+ break;+ case BulkEdit.Insert:+ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: edit.columnIdx,+ type: "insert",+ newColumnName: edit.newName,+ }),+ );+ setData((prev) => insertColumn(prev, edit.newName));+ break;+ case BulkEdit.Rename: {+ const oldName = columns[edit.columnIdx].title;+ const newName = edit.newName;+ if (!oldName || !newName) {+ return;+ }++ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: edit.columnIdx,+ type: "rename",+ newColumnName: newName,+ }),+ );++ setData((prev) => renameColumn(prev, oldName, newName));+ break;+ }+ }+ }+ }++ // Add new rows in order+ const sortedNewRows = [...newRows.entries()]+ .sort(([a], [b]) => a - b)+ .map(([, row]) => row);++ if (sortedNewRows.length > 0) {+ setData((prev) => [...prev, ...(sortedNewRows as T[])]);+ }++ // Force re-render to update the total rows+ rerender();+ });++ const columns: ModifiedGridColumn[] = useMemo(() => {+ const columns: ModifiedGridColumn[] = [];+ for (const [columnName, fieldType] of Object.entries(columnFields)) {+ columns.push({+ id: columnName,+ title: columnName,+ width: columnWidths[columnName], // Enables resizing+ icon: getColumnHeaderIcon(fieldType),+ kind: getColumnKind(fieldType),+ dataType: fieldType,+ hasMenu: true,+ });+ }++ return columns;+ }, [columnFields, columnWidths]);++ const getCellContent = useCallback(+ (cell: Item): GridCell => {+ const [col, row] = cell;+ const dataRow = data[row];++ const dataItem = dataRow[columns[col].title as keyof T];+ const columnKind = columns[col].kind;++ if (columnKind === GridCellKind.Boolean) {+ const value = Boolean(dataItem);+ return {+ kind: GridCellKind.Boolean,+ allowOverlay: false,+ readonly: false,+ data: value,+ };+ }++ if (columnKind === GridCellKind.Number && typeof dataItem === "number") {+ return {+ kind: GridCellKind.Number,+ allowOverlay: true,+ readonly: false,+ displayData: String(dataItem),+ data: dataItem,+ };+ }++ return {+ kind: GridCellKind.Text,+ allowOverlay: true,+ readonly: false,+ displayData: String(dataItem),+ data: String(dataItem),+ };+ },+ [columns, data],+ );++ const onCellEdited = useCallback(+ (cell: Item, newValue: EditableGridCell) => {+ const [col, row] = cell;+ const column = columns[col];+ const key = column.title;++ // Deletes are not handled by validateCell, so we need to handle them here+ let newData = newValue.data;+ if (+ (column.dataType === "number" || column.dataType === "integer") &&+ (newValue.data === undefined || newValue.data === "")+ ) {+ newData = null;+ }++ setData((prev) => {+ const data = [...prev];+ data[row][key as keyof T] = newData as T[keyof T];+ return data;+ });++ onAddEdits([{ rowIdx: row, columnId: key, value: newData }]);+ },+ [columns, onAddEdits, setData],+ );++ const onColumnResize = useCallback((column: GridColumn, newSize: number) => {+ setColumnWidths((prev) => ({+ ...prev,+ [column.title]: newSize,+ }));+ }, []);++ // Only called when user edits a cell, not deletes+ const validateCell = useCallback(+ (cell: Item, newValue: EditableGridCell, _prevValue: GridCell): boolean => {+ const [col, _row] = cell;+ const key = columns[col].title;++ const columnType = columnFields[key];+ // Verify the new value is of the correct type+ switch (columnType) {+ case "number":+ case "integer":+ if (Number.isNaN(Number(newValue.data))) {+ return false;+ }+ break;+ case "boolean":+ if (typeof newValue.data !== "boolean") {+ return false;+ }+ break;+ }++ return true;+ },+ [columnFields, columns],+ );++ // Hack to emit copy event as these events aren't triggered automatically in shadow DOM+ // Paste event does not work so we manually handle it+ const onKeyDown = useCallback(+ (e: GridKeyEventArgs) => {+ if (!dataEditorRef.current) {+ return;+ }++ if (Events.isMetaOrCtrl(e) && e.key === "c") {+ dataEditorRef.current.emit("copy");+ return;+ }++ if (Events.isMetaOrCtrl(e) && e.key === "v") {+ pasteCells({+ selection,+ data,+ setData,+ columns,+ onAddEdits,+ });+ return;+ }++ if (Events.isMetaOrCtrl(e) && e.key === "f") {+ setShowSearch((prev) => !prev);+ e.stopPropagation();+ e.preventDefault();+ return;+ }++ if (e.key === "Escape") {+ setShowSearch(false);+ return;+ }+ },+ [columns, data, onAddEdits, selection, setData],+ );++ const onRowAppend = useCallback(() => {+ const newRow: Record<string, unknown> = Object.fromEntries(+ columns.map((column) => {+ const dataType = column.dataType;+ switch (dataType) {+ case "boolean":+ return [column.title, false];+ case "number":+ case "integer":+ return [column.title, null];+ case "date":+ case "datetime":+ case "time":+ // TODO: Handle specific types+ return [column.title, new Date()];+ case "string":+ case "unknown":+ return [column.title, ""];+ default:+ logNever(dataType);+ return [column.title, ""];+ }+ }),+ );+ onAddRows([newRow]);++ // Update data+ setData((prev) => [...prev, newRow as T]);+ }, [columns, onAddRows, setData]);++ const handleDeleteRows = () => {+ const rows = selection.rows.toArray();+ onDeleteRows(rows);++ let index = 0;+ for (const row of rows) {+ const adjustedRow = row - index; // Adjust for previously deleted rows+ setData((prev) => prev.filter((_, i) => i !== adjustedRow));+ index++;+ }++ // Clear selection+ setSelection({+ columns: CompactSelection.empty(),+ rows: CompactSelection.empty(),+ });+ };++ const onHeaderMenuClick = useEvent((col: number, bounds: Rectangle) => {+ setMenu({ col, bounds });+ });++ const handleCopyColumnName = async () => {+ if (menu) {+ const columnName = columns[menu.col].title;+ await copyToClipboard(columnName);+ setMenu(undefined);+ }+ };++ function toastColumnExists(name: string) {+ toast({+ title: `Column '${name}' already exists`,+ description: "Please enter a different column name",+ variant: "danger",+ });+ }++ const handleRenameColumn = (newName: string) => {+ if (menu) {+ const oldColumnName = columns[menu.col].title;++ // Validate the new column name+ if (columnFields[newName]) {+ toastColumnExists(newName);+ return;+ }++ const dataType = columns[menu.col].dataType;++ onRenameColumn(menu.col, newName);+ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: menu.col,+ type: "rename",+ dataType,+ newColumnName: newName,+ }),+ );++ // Update the data+ setData((prev) => renameColumn(prev, oldColumnName, newName));+ setMenu(undefined);+ }+ };++ const handleDeleteColumn = () => {+ if (menu) {+ onDeleteColumn(menu.col);+ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: menu.col,+ type: "remove",+ }),+ );++ setData((prev) => removeColumn(prev, menu.col));+ setMenu(undefined);+ }+ };++ const handleAddColumn = (options: {+ direction: "left" | "right";+ columnName: string;+ dataType: DataType;+ }) => {+ const { direction, columnName, dataType } = options;++ if (menu) {+ const columnIdx = menu.col + (direction === "left" ? 0 : 1);+ // Clamp to 0 and length of columns+ const clampedColumnIdx = Math.max(0, Math.min(columnIdx, columns.length));++ // Validate the new column name+ if (columnFields[columnName]) {+ toastColumnExists(columnName);+ return;+ }++ onAddColumn(clampedColumnIdx, columnName);++ setColumnFields((prev) =>+ modifyColumnFields({+ columnFields: prev,+ columnIdx: clampedColumnIdx,+ type: "insert",+ dataType,+ newColumnName: columnName,+ }),+ );++ // Update the data - add the new column to all rows,+ // ordering does not matter as we call getCellContent based on columnTitle+ setData((prev) => insertColumn(prev, columnName));+ setMenu(undefined);+ }+ };++ const isLastColumn = menu?.col === columns.length - 1;++ // There is a guarantee that only one column's menu is open (as interaction is disabled outside of the menu)+ const isMenuOpen = menu !== undefined;+ const iconClassName = "mr-2 h-3.5 w-3.5";++ const trailingRowOptions = {+ hint: "New row",+ sticky: true,+ tint: true,+ };++ const isLargeDataset = data.length > 100_000;++ const renderDropdownMenu = () => {+ if (!isMenuOpen) {+ return;+ }++ const bulkEditItems = (+ <>+ <RenameColumnSub+ currentColumnName={columns[menu.col].title}+ onRename={handleRenameColumn}+ onCancel={() => setMenu(undefined)}+ />++ <DropdownMenuSeparator />++ <AddColumnSub+ direction="left"+ onAdd={(columnName, dataType) =>+ handleAddColumn({ direction: "left", columnName, dataType })+ }+ onCancel={() => setMenu(undefined)}+ />++ <AddColumnSub+ direction="right"+ onAdd={(columnName, dataType) =>+ handleAddColumn({ direction: "right", columnName, dataType })+ }+ onCancel={() => setMenu(undefined)}+ />++ <DropdownMenuSeparator />++ {/* There is a bug `undefined (reading 'headerRowMarkerDisabled')` when deleting the last column. So we temporarily disable it. */}+ {!isLastColumn && (+ <DropdownMenuItem+ onClick={handleDeleteColumn}+ className="text-destructive focus:text-destructive"+ >+ <TrashIcon className={iconClassName} />+ Delete column+ </DropdownMenuItem>+ )}+ </>+ );++ return (+ <DropdownMenu+ open={isMenuOpen}+ onOpenChange={(open) => !open && setMenu(undefined)}+ >+ <DropdownMenuContent+ style={{+ left: menu?.bounds.x ?? 0,+ top: (menu?.bounds.y ?? 0) + (menu?.bounds.height ?? 0),+ }}+ className="fixed w-52"+ >+ <DropdownMenuItem onClick={handleCopyColumnName}>+ <CopyIcon className={iconClassName} />+ Copy column name+ </DropdownMenuItem>++ {!isLargeDataset && bulkEditItems}+ </DropdownMenuContent>+ </DropdownMenu>+ );+ };++ return (+ <>+ <ErrorBoundary>+ <DataEditor+ ref={dataEditorRef}+ getCellContent={getCellContent}+ columns={columns}+ gridSelection={selection}+ onGridSelectionChange={setSelection}+ rows={data.length}+ overscrollX={50} // Adds padding at the end for resizing the last column+ smoothScrollX={!isLargeDataset} // Disable smooth scrolling to improve performance+ smoothScrollY={!isLargeDataset}+ validateCell={validateCell}+ getCellsForSelection={true}+ onPaste={true}+ showSearch={showSearch}+ fillHandle={true}+ allowedFillDirections="vertical" // We can support all directions, but we need to handle datatype logic+ onKeyDown={onKeyDown}+ height={data.length > 10 ? 450 : undefined}+ width={"100%"}+ rowMarkers={{+ kind: "both",+ headerDisabled: true,+ }}+ rowSelectionMode={"multi"}+ onCellEdited={onCellEdited}+ onColumnResize={onColumnResize}+ onHeaderMenuClick={onHeaderMenuClick}+ theme={getGlideTheme(theme)}+ trailingRowOptions={trailingRowOptions}+ onRowAppended={onRowAppend}+ maxColumnAutoWidth={600}+ maxColumnWidth={600}+ />+ </ErrorBoundary>+ {renderDropdownMenu()}++ <div className="absolute bottom-1 right-2 w-26">+ <Button+ variant="destructive"+ size="sm"+ disabled={selection.rows.length === 0}+ className="bottom-1 right-2 h-7"+ onClick={handleDeleteRows}+ >+ {selection.rows.length <= 1 ? "Delete row" : "Delete rows"}+ </Button>+ </div>+ </>+ );+};++export default GlideDataEditor;diff --git a/frontend/src/plugins/impl/data-editor/glide-utils.ts b/frontend/src/plugins/impl/data-editor/glide-utils.tsnew file mode 100644index 0000000000..6851fc35fd--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/glide-utils.ts@@ -0,0 +1,191 @@+/* Copyright 2024 Marimo. All rights reserved. */++import {+ GridCellKind,+ GridColumnIcon,+ type GridSelection,+} from "@glideapps/glide-data-grid";+import type { DataType } from "@/core/kernel/messages";+import { logNever } from "@/utils/assertNever";+import { Logger } from "@/utils/Logger";+import type {+ ColumnEdit,+ Edits,+ ModifiedGridColumn,+ PositionalEdit,+ RowEdit,+} from "./types";++export function getColumnKind(fieldType: DataType): GridCellKind {+ switch (fieldType) {+ case "string":+ return GridCellKind.Text;+ case "number":+ return GridCellKind.Number;+ case "boolean":+ return GridCellKind.Boolean;+ default:+ return GridCellKind.Text;+ }+}++export function getColumnHeaderIcon(fieldType: DataType): GridColumnIcon {+ switch (fieldType) {+ case "string":+ return GridColumnIcon.HeaderString;+ case "number":+ case "integer":+ return GridColumnIcon.HeaderNumber;+ case "boolean":+ return GridColumnIcon.HeaderBoolean;+ case "date":+ case "datetime":+ return GridColumnIcon.HeaderDate;+ case "time":+ return GridColumnIcon.HeaderTime;+ case "unknown":+ return GridColumnIcon.HeaderString;+ default:+ logNever(fieldType);+ return GridColumnIcon.HeaderString;+ }+}++export function isPositionalEdit(+ edit: Edits["edits"][number],+): edit is PositionalEdit {+ return "rowIdx" in edit && "columnId" in edit && "value" in edit;+}++export function isRowEdit(edit: Edits["edits"][number]): edit is RowEdit {+ return "rowIdx" in edit && "type" in edit;+}++export function isColumnEdit(edit: Edits["edits"][number]): edit is ColumnEdit {+ return "columnIdx" in edit && "type" in edit;+}++export function pasteCells<T>(options: {+ selection: GridSelection;+ data: T[];+ setData: (updater: (prev: T[]) => T[]) => void;+ columns: ModifiedGridColumn[];+ onAddEdits: (edits: Edits["edits"]) => void;+}) {+ const { selection, data, setData, onAddEdits, columns } = options;+ if (!selection.current) {+ return;+ }++ const { range } = selection.current;+ const { x: startCol, y: startRow } = range;++ // Read clipboard data+ navigator.clipboard+ .readText()+ .then((clipboardText) => {+ if (!clipboardText.trim()) {+ return;+ }++ // Parse tab-separated values+ const rows = clipboardText.split("\n").filter((row) => row.trim());+ const parsedData: string[][] = [];++ for (const row of rows) {+ const cells = row.split("\t");+ parsedData.push(cells);+ }++ if (parsedData.length === 0) {+ return;+ }++ const edits: Edits["edits"] = [];++ for (const [rowIndex, dataRow] of parsedData.entries()) {+ if (!dataRow) {+ continue;+ }++ const targetRowIdx = startRow + rowIndex;++ // Check if we've exceeded the data bounds+ if (targetRowIdx >= data.length) {+ break;+ }++ for (const [colIndex, cellValue] of dataRow.entries()) {+ if (cellValue === undefined) {+ continue;+ }++ const targetColIdx = startCol + colIndex;++ // Check if we've exceeded the column bounds+ if (!columns || targetColIdx >= columns.length) {+ break;+ }++ const columnType = columns[targetColIdx].dataType;++ // Convert the value based on the cell type+ let convertedValue: unknown = cellValue;++ switch (columnType) {+ case "integer":+ case "number": {+ const numValue = Number(cellValue);+ if (Number.isNaN(numValue)) {+ continue;+ }+ convertedValue = numValue;+ break;+ }+ case "boolean": {+ const boolValue = cellValue.toLowerCase();+ convertedValue = boolValue === "true" || boolValue === "1";+ break;+ }+ }++ // Get the column ID from the columns array using the title+ const columnId = columns[targetColIdx].title;++ edits.push({+ rowIdx: targetRowIdx,+ columnId,+ value: convertedValue,+ });+ }+ }++ if (edits.length > 0) {+ onAddEdits(edits);++ setData((prev: T[]) => {+ const newData = [...prev];++ // Apply all edits to the data+ for (const edit of edits) {+ if (isPositionalEdit(edit)) {+ const rowIdx = edit.rowIdx;+ const columnId = edit.columnId;++ if (rowIdx < newData.length) {+ const row = newData[rowIdx] as Record<string, unknown>;+ if (columnId in row) {+ row[columnId] = edit.value;+ }+ }+ }+ }++ return newData;+ });+ }+ })+ .catch((error) => {+ Logger.error("Failed to read clipboard data", error);+ });+}diff --git a/frontend/src/plugins/impl/data-editor/grid.css b/frontend/src/plugins/impl/data-editor/grid.cssdeleted file mode 100644index c151c420ce..0000000000--- a/frontend/src/plugins/impl/data-editor/grid.css+++ /dev/null@@ -1,51 +0,0 @@-.ag-theme-marimo {- --ag-foreground-color: var(--foreground);- --ag-background-color: var(--background);- --ag-secondary-foreground-color: var(--secondary-foreground);- --ag-data-color: var(--foreground);- --ag-header-foreground-color: var(--muted-foreground);- --ag-header-background-color: var(--background);- --ag-tooltip-background-color: var(--muted);- --ag-disabled-foreground-color: var(--muted-foreground);- --ag-border-color: var(--border);- --ag-selected-row-background-color: var(--accent);- --ag-menu-background-color: var(--accent);- --ag-panel-background-color: var(--accent);- --ag-row-hover-color: var(--accent);- --ag-header-height: 2.5rem;-}--.ag-theme-marimo .ag-paging-panel {- height: 2.5rem;-- @apply text-sm font-prose text-muted-foreground;-}--.ag-row .ag-cell {- align-content: center !important;-- @apply font-prose;-}--.ag-header-cell-text {- font-weight: bold;-- @apply text-sm font-prose;-}--.ag-cell {- line-height: 1.25rem;-}--.ag-cell-wrapper {- align-items: normal !important;-}--.ag-body-horizontal-scroll-viewport,-.ag-body-vertical-scroll-viewport {- cursor: auto;-}--.ag-paging-page-size {- display: none;-}diff --git a/frontend/src/plugins/impl/data-editor/themes.ts b/frontend/src/plugins/impl/data-editor/themes.tsnew file mode 100644index 0000000000..faeec8cade--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/themes.ts@@ -0,0 +1,49 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { Theme } from "@glideapps/glide-data-grid";+import type { ResolvedTheme } from "@/theme/useTheme";++export function getGlideTheme(+ theme: ResolvedTheme,+): Partial<Theme> | undefined {+ if (theme === "light") {+ return {+ lineHeight: 1.25,+ };+ }++ return {+ lineHeight: 1.25,+ accentColor: "#7c3aed",+ accentLight: "rgba(124, 58, 237, 0.15)",++ textDark: "#f4f4f5",+ textMedium: "#a1a1aa",+ textLight: "#71717a",+ textBubble: "#f4f4f5",++ bgIconHeader: "#a1a1aa",+ fgIconHeader: "#18181b",+ textHeader: "#d4d4d8",+ textHeaderSelected: "#18181b",++ bgCell: "#18181b",+ bgCellMedium: "#27272a",+ bgHeader: "#27272a",+ bgHeaderHasFocus: "#3f3f46",+ bgHeaderHovered: "#3f3f46",++ bgBubble: "#27272a",+ bgBubbleSelected: "#7c3aed",++ bgSearchResult: "#312e81",++ borderColor: "#27272a",+ drilldownBorder: "#7c3aed",++ linkColor: "#818cf8",++ headerFontStyle: "bold 14px",+ baseFontStyle: "13px",+ };+}diff --git a/frontend/src/plugins/impl/data-editor/types.ts b/frontend/src/plugins/impl/data-editor/types.tsnew file mode 100644index 0000000000..0c2c8e476e--- /dev/null+++ b/frontend/src/plugins/impl/data-editor/types.ts@@ -0,0 +1,45 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { GridCellKind, GridColumn } from "@glideapps/glide-data-grid";+import type { FieldTypesWithExternalType } from "@/components/data-table/types";+import type { DataType } from "@/core/kernel/messages";++export interface PositionalEdit {+ rowIdx: number;+ columnId: string;+ value: unknown;+}++export enum BulkEdit {+ Insert = "insert",+ Remove = "remove",+ Rename = "rename",+}++export interface RowEdit {+ rowIdx: number;+ type: BulkEdit;+}++export interface ColumnEdit {+ columnIdx: number;+ newName?: string;+ type: BulkEdit;+}++export interface Edits {+ edits: Array<PositionalEdit | RowEdit | ColumnEdit>;+}++export type ModifiedGridColumn = GridColumn & {+ kind: GridCellKind;+ dataType: DataType;+};++export interface DataEditorProps<T> {+ data: T[];+ fieldTypes: FieldTypesWithExternalType | null | undefined;+ onAddEdits: (edits: Edits["edits"]) => void;+ onAddRows: (newRows: object[]) => void;+ columnSizingMode: "fit" | "auto";+}diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.pyindex eb3200c3db..d474028cc0 100644--- a/marimo/_plugins/ui/_impl/data_editor.py+++ b/marimo/_plugins/ui/_impl/data_editor.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport astimport datetime+from copy import deepcopyfrom dataclasses import dataclassfrom typing import (TYPE_CHECKING,@@ -24,13 +25,13 @@ from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._plugins.ui._impl.tables.utils import get_table_manager-from marimo._plugins.validators import validate_page_sizefrom marimo._utils.deprecated import deprecatedLOGGER = _loggers.marimo_logger()if TYPE_CHECKING:from narwhals.dtypes import DType+ from typing_extensions import TypeIs@dataclass@@ -58,14 +59,43 @@ class PositionalEdit(TypedDict):value: Any+class ColumnEdit(TypedDict):+ """A typed dictionary representing a bulk edit of a column.++ Attributes:+ columnIdx (int): The index of the column being edited.+ If insert/remove, this is the index of the column to be edited. If rename, this is the index of the column to be renamed.+ newName (Optional[str]): The new name of the column.+ type (Literal["insert", "remove", "rename"]): The type of edit.+ """++ columnIdx: int+ newName: Optional[str]+ type: Literal["insert", "remove", "rename"]+++class RowEdit(TypedDict):+ """A typed dictionary representing a bulk edit of a row.++ Attributes:+ rowIdx (int): The index of the row being edited.+ type (Literal["insert", "remove"]): The type of edit.++ Note: Insert is already handled with positional edits, so we can focus on 'remove' here+ """++ rowIdx: int+ type: Literal["insert", "remove"]++class DataEdits(TypedDict):- """A typed dictionary containing a list of positional edits.+ """A typed dictionary containing a list of edits.Attributes:- edits (List[PositionalEdit]): List of individual cell edits.+ edits (List[PositionalEdit | RowEdit | ColumnEdit]): List of individual cell edits, row edits, or column edits."""- edits: list[PositionalEdit]+ edits: list[Union[PositionalEdit, RowEdit, ColumnEdit]]RowOrientedData = list[dict[str, Any]]@@ -135,20 +165,20 @@ class data_editor(on_change (Optional[Callable]): Optional callback to run when this element's value changes.column_sizing_mode (Literal["auto", "fit"]): The column sizing mode for the table.`auto` will size columns based on the content, `fit` will size columns to fit the view.- pagination (Optional[bool]): Whether to use pagination, enabled by default.- page_size (Optional[int]): Page size if pagination is in use, 50 by default.++ Deprecated:+ pagination (bool): Whether to enable pagination.+ page_size (int): The number of rows to display per page."""_name: Final[str] = "marimo-data-editor"- LIMIT: Final[int] = 1000-def __init__(self,data: Union[RowOrientedData, ColumnOrientedData, IntoDataFrame],*,- pagination: bool = True,- page_size: int = 50,+ pagination: bool = True, # Deprecated, TODO: Remove+ page_size: int = 50, # Deprecatedlabel: str = "",on_change: Optional[Callable[@@ -158,15 +188,9 @@ class data_editor(] = None,column_sizing_mode: Literal["auto", "fit"] = "auto",) -> None:- validate_page_size(page_size)+ del pagination, page_sizetable_manager = get_table_manager(data)- size = table_manager.get_num_rows()- if size is None or size > self.LIMIT:- raise ValueError(- f"Data editor supports a maximum of {self.LIMIT} rows."- )-self._data = dataself._edits: DataEdits | None = Nonefield_types = table_manager.get_field_types()@@ -178,8 +202,6 @@ class data_editor(args={"data": mo_data.csv(table_manager.to_csv()).url,"field-types": field_types or None,- "pagination": pagination,- "page-size": page_size,"column-sizing-mode": column_sizing_mode,},on_change=on_change,@@ -195,7 +217,7 @@ class data_editor(self, value: DataEdits) -> Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]:self._edits = value- return apply_edits(self._data, value)+ return apply_edits(deepcopy(self._data), value)def __hash__(self) -> int:return id(self)@@ -229,14 +251,12 @@ def _apply_edits_column_oriented(schema: Optional[nw.Schema] = None,) -> ColumnOrientedData:for edit in edits["edits"]:- column = data[edit["columnId"]]- if edit["rowIdx"] >= len(column):- # Extend the column with None values up to the new row index- column.extend([None] * (edit["rowIdx"] - len(column) + 1))- dtype = schema.get(edit["columnId"]) if schema else None- column[edit["rowIdx"]] = _convert_value(- edit["value"], column[0] if column else None, dtype- )+ if is_positional_edit(edit):+ _apply_positional_edit_column_oriented(data, edit, schema)+ elif is_row_edit(edit):+ _apply_row_edit_column_oriented(data, edit)+ elif is_column_edit(edit):+ _apply_column_edit_column_oriented(data, edit)return data@@ -247,15 +267,12 @@ def _apply_edits_row_oriented(schema: Optional[nw.Schema] = None,) -> RowOrientedData:for edit in edits["edits"]:- if edit["rowIdx"] >= len(data):- # Create a new row with None values for all columns- new_row = {col: None for col in data[0].keys()}- data.append(new_row)- original_value = data[0][edit["columnId"]] if data else None- dtype = schema.get(edit["columnId"]) if schema else None- data[edit["rowIdx"]][edit["columnId"]] = _convert_value(- edit["value"], original_value, dtype- )+ if is_positional_edit(edit):+ _apply_positional_edit_row_oriented(data, edit, schema)+ elif is_row_edit(edit):+ _apply_row_edit_row_oriented(data, edit)+ elif is_column_edit(edit):+ _apply_column_edit_row_oriented(data, edit)return data@@ -266,6 +283,8 @@ def _apply_edits_dataframe(df = nw.from_native(native_df, eager_or_interchange_only=True)column_oriented = df.to_dict(as_series=False)schema = schema or cast(nw.Schema, df.schema)++ # TODO: We should try to find more performant methods of bulk edits for dataframesnew_data = _apply_edits_column_oriented(column_oriented, edits, schema)new_native_df = nw.from_dict(new_data, backend=nw.get_native_namespace(df)@@ -279,6 +298,10 @@ def _convert_value(dtype: Optional[DType] = None,) -> Any:try:+ # None is a valid value for all dtypes+ if value is None:+ return None+if dtype is not None:if dtype == nw.Datetime:return datetime.datetime.fromisoformat(value)@@ -338,12 +361,13 @@ def _convert_value(return original_type(value)elif isinstance(original_value, str):return str(value)- elif isinstance(original_value, (datetime.date)):- return datetime.date.fromisoformat(value)- elif isinstance(original_value, (datetime.datetime)):- return datetime.datetime.fromisoformat(value)+ # The more specific time checks are handled first to avoid parent classes matchingelif isinstance(original_value, (datetime.timedelta)):return datetime.timedelta(microseconds=float(value))+ elif isinstance(original_value, (datetime.datetime)):+ return datetime.datetime.fromisoformat(value)+ elif isinstance(original_value, (datetime.date)):+ return datetime.date.fromisoformat(value)elif isinstance(original_value, list):# Handle list conversionif isinstance(value, str):@@ -364,3 +388,227 @@ def _convert_value(LOGGER.error(str(e))# If conversion fails, return the original valuereturn original_value # type: ignore[return-value]+++def is_positional_edit(+ edit: Union[PositionalEdit, RowEdit, ColumnEdit],+) -> TypeIs[PositionalEdit]:+ """Check if edit is a PositionalEdit and return it typed."""+ return "rowIdx" in edit and "columnId" in edit and "value" in edit+++def is_row_edit(+ edit: Union[PositionalEdit, RowEdit, ColumnEdit],+) -> TypeIs[RowEdit]:+ """Check if edit is a RowEdit and return it typed."""+ return "rowIdx" in edit and "type" in edit+++def is_column_edit(+ edit: Union[PositionalEdit, RowEdit, ColumnEdit],+) -> TypeIs[ColumnEdit]:+ """Check if edit is a ColumnEdit and return it typed."""+ return "columnIdx" in edit and "type" in edit+++def _apply_positional_edit_column_oriented(+ data: ColumnOrientedData,+ edit: PositionalEdit,+ schema: Optional[nw.Schema] = None,+) -> None:+ """Apply a positional edit to column-oriented data."""+ column = data[edit["columnId"]]+ if edit["rowIdx"] >= len(column):+ # Extend the column with None values up to the new row index+ column.extend([None] * (edit["rowIdx"] - len(column) + 1))+ dtype = schema.get(edit["columnId"]) if schema else None+ column[edit["rowIdx"]] = _convert_value(+ edit["value"], column[0] if column else None, dtype+ )+++def _apply_positional_edit_row_oriented(+ data: RowOrientedData,+ edit: PositionalEdit,+ schema: Optional[nw.Schema] = None,+) -> None:+ """Apply a positional edit to row-oriented data."""+ if edit["rowIdx"] >= len(data):+ # Create a new row with None values for all columns+ new_row = {col: None for col in data[0].keys()}+ data.append(new_row)+ original_value = data[0][edit["columnId"]] if data else None+ dtype = schema.get(edit["columnId"]) if schema else None+ data[edit["rowIdx"]][edit["columnId"]] = _convert_value(+ edit["value"], original_value, dtype+ )+++def _apply_row_edit_column_oriented(+ data: ColumnOrientedData,+ edit: RowEdit,+) -> None:+ """Apply a row edit to column-oriented data."""+ if edit["type"] == "remove":+ rowIdx = edit["rowIdx"]+ for column in data.values():+ if not _is_valid_index(rowIdx, len(column)):+ continue+ del column[rowIdx]+++def _apply_row_edit_row_oriented(+ data: RowOrientedData,+ edit: RowEdit,+) -> None:+ """Apply a row edit to row-oriented data."""+ rowIdx = edit["rowIdx"]+ if not _is_valid_index(rowIdx, len(data)):+ return+ if edit["type"] == "remove":+ data.pop(rowIdx)+++def _validate_column_edit(+ edit: ColumnEdit,+ data_length: int,+ new_column_name: Optional[str],+) -> None:+ """Validate column edit parameters."""+ column_idx = edit["columnIdx"]+ edit_type = edit["type"]++ if column_idx < 0 or column_idx > data_length:+ raise ValueError(f"Column index {column_idx} is out of bounds")++ if edit_type in ("insert", "rename") and new_column_name is None:+ raise ValueError(+ "New column name is required for insert/rename operations"+ )+++def _apply_column_edit_column_oriented(+ data: ColumnOrientedData,+ edit: ColumnEdit,+) -> None:+ """Apply a column edit to column-oriented data."""+ column_order = list(data.keys())+ new_column_name = edit.get("newName")++ column_idx = edit["columnIdx"]+ edit_type = edit["type"]++ _validate_column_edit(edit, len(data), new_column_name)++ column_idx = edit["columnIdx"]+ edit_type = edit["type"]++ if edit_type == "insert":+ assert new_column_name is not None++ data_length = len(data[column_order[0]]) if column_order else 0++ if column_idx == len(column_order):+ # Add new column at the end+ data[new_column_name] = [None] * data_length+ else:+ # Insert new column at specific index+ column_data = data.copy()+ data.clear()+ for idx, key in enumerate(column_order):+ if idx == column_idx:+ data[new_column_name] = [None] * data_length+ data[key] = column_data[key]+ return++ # Find column by index+ column_id = None+ for idx, key in enumerate(column_order):+ if idx == column_idx:+ column_id = key+ break++ if column_id is None:+ raise ValueError(f"Column index {column_idx} not found")++ if edit_type == "rename":+ assert new_column_name is not None++ column_data = data.copy()+ data.clear()+ for key in column_order:+ if key == column_id:+ data[new_column_name] = column_data[key]+ else:+ data[key] = column_data[key]+ elif edit_type == "remove":+ del data[column_id]+++def _apply_column_edit_row_oriented(+ data: RowOrientedData,+ edit: ColumnEdit,+) -> None:+ """Apply a column edit to row-oriented data."""+ if not data:+ return++ column_order = list(data[0].keys())+ new_column_name = edit.get("newName")++ _validate_column_edit(edit, len(data[0]) + 1, new_column_name)++ column_idx = edit["columnIdx"]+ edit_type = edit["type"]++ if edit_type == "insert":+ assert new_column_name is not None++ if column_idx < len(column_order):+ new_column_order = (+ column_order[:column_idx]+ + [new_column_name]+ + column_order[column_idx:]+ )+ else:+ new_column_order = column_order + [new_column_name]++ for row_idx, row in enumerate(data):+ new_row = {+ column: row.get(column, None) for column in new_column_order+ }+ data[row_idx] = new_row+ return++ # Find column by index+ column_id = None+ for idx, column in enumerate(data[0]):+ if idx == column_idx:+ column_id = column+ break++ if column_id is None:+ raise ValueError(f"Column index {column_idx} not found")++ if edit_type == "remove":+ for d in data:+ del d[column_id]+ elif edit_type == "rename":+ assert new_column_name is not None++ # Get the column name at the specified index+ column_name = list(data[0].keys())[column_idx]++ for row in data:+ new_row = {}+ for key in row.keys():+ if key == column_name:+ new_row[new_column_name] = row[key]+ else:+ new_row[key] = row[key]+ row.clear()+ row.update(new_row)+++def _is_valid_index(index: int, length: int) -> bool:+ return index >= 0 and index < lengthdiff --git a/marimo/_smoke_tests/tables/complex_types.py b/marimo/_smoke_tests/tables/complex_types.pyindex e991c034fa..978d6b5a10 100644--- a/marimo/_smoke_tests/tables/complex_types.py+++ b/marimo/_smoke_tests/tables/complex_types.py@@ -150,6 +150,13 @@ def _(mo):return (pd,)+def _(df, mo):+ subset = df.drop(["nested_lists", "list_with_structs", "nested_arrays"])+ mo.ui.data_editor(subset)+ return++@app.celldef _(mo):mo.md(diff --git a/tests/_plugins/ui/_impl/test_data_editor.py b/tests/_plugins/ui/_impl/test_data_editor.pyindex 3fe55e0a99..f041c42088 100644--- a/tests/_plugins/ui/_impl/test_data_editor.py+++ b/tests/_plugins/ui/_impl/test_data_editor.py@@ -2,6 +2,7 @@from __future__ import annotationsimport datetime+from copy import deepcopyfrom typing import Anyimport narwhals.stable.v1 as nw@@ -11,6 +12,7 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins import uifrom marimo._plugins.ui._impl.data_editor import (DataEdits,+ _convert_value,apply_edits,)@@ -20,6 +22,28 @@ HAS_PANDAS = DependencyManager.pandas.has()HAS_POLARS = DependencyManager.polars.has()+def assert_data_equals_with_order(actual, expected):+ """Helper function to test both values and column ordering."""+ # Test that the data has the same values+ assert actual == expected++ # Test that the column order is preserved+ if isinstance(actual, list) and actual and isinstance(actual[0], dict):+ # Row-oriented data+ actual_keys = list(actual[0].keys())+ expected_keys = list(expected[0].keys())+ assert actual_keys == expected_keys, (+ f"Column order mismatch: {actual_keys} != {expected_keys}"+ )+ elif isinstance(actual, dict) and actual:+ # Column-oriented data+ actual_keys = list(actual.keys())+ expected_keys = list(expected.keys())+ assert actual_keys == expected_keys, (+ f"Column order mismatch: {actual_keys} != {expected_keys}"+ )++@pytest.mark.skipif(not DependencyManager.polars.has(), reason="Polars not installed")@@ -28,8 +52,6 @@ def test_data_editor_initialization():editor = data_editor(data=data, label="Test Editor")assert editor._data == dataassert editor._edits == {"edits": []}- assert editor._component_args["pagination"] is True- assert editor._component_args["page-size"] == 50assert editor._component_args["column-sizing-mode"] == "auto"@@ -42,16 +64,6 @@ def test_data_editor_with_column_oriented_data():assert editor._data == data- not DependencyManager.polars.has(), reason="Polars not installed"-)-def test_data_editor_with_too_many_rows():- data = [{"A": i} for i in range(1001)]- with pytest.raises(ValueError) as excinfo:- data_editor(data=data)- assert "Data editor supports a maximum of 1000 rows" in str(excinfo.value)--@pytest.mark.skipif(not DependencyManager.polars.has(), reason="Polars not installed")@@ -242,7 +254,7 @@ def test_apply_edits_various_datatypes():"float": 3.14,"str": "updated","bool": False,- "datetime": datetime.datetime(2023, 1, 1, 12, 0),+ "datetime": datetime.datetime(2023, 3, 15, 15, 30),"date": datetime.date(2023, 3, 15),"duration": datetime.timedelta(days=2, seconds=13500),"list": [7, 8, 9],@@ -252,7 +264,7 @@ def test_apply_edits_various_datatypes():"float": 4.5,"str": "updated2","bool": True,- "datetime": datetime.datetime(2023, 1, 1, 12, 0),+ "datetime": datetime.datetime(2023, 4, 20, 10, 0),"date": datetime.date(2023, 4, 20),"duration": datetime.timedelta(days=2, seconds=13500),"list": [10, 11, 12],@@ -385,25 +397,6 @@ def test_data_editor_with_polars_dataframe():assert df.equals(editor.data)- not DependencyManager.polars.has(), reason="Polars not installed"-)-def test_data_editor_with_custom_pagination():- data = [{"A": i} for i in range(100)]- editor = data_editor(data=data, pagination=False, page_size=25)- assert editor._component_args["pagination"] is False- assert editor._component_args["page-size"] == 25--- not DependencyManager.polars.has(), reason="Polars not installed"-)-def test_data_editor_with_too_large_pagesize():- data = [{"A": i} for i in range(300)]- with pytest.raises(ValueError):- _ = data_editor(data=data, page_size=201)--@pytest.mark.skipif(not DependencyManager.polars.has(), reason="Polars not installed")@@ -423,3 +416,692 @@ def test_data_editor_on_change_callback():editor = data_editor(data=data, on_change=on_change)editor._update({"edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]})assert callback_called+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+class TestBulkEditsRowOrientedData:+ """Test bulk edits for row-oriented data."""++ def test_remove_start_row(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"rowIdx": 0, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [{"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_middle_row(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"rowIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [{"A": 1, "B": "a"}, {"A": 3, "B": "c"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_end_row(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"rowIdx": 2, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_invalid_row(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"rowIdx": 3, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert result == [+ {"A": 1, "B": "a"},+ {"A": 2, "B": "b"},+ {"A": 3, "B": "c"},+ ]++ def test_remove_multiple_rows(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {+ "edits": [+ {"rowIdx": 0, "type": "remove"},+ {"rowIdx": 1, "type": "remove"},+ ]+ }+ result = apply_edits(data, edits)+ expected = [{"A": 2, "B": "b"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_then_edit(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {+ "edits": [+ {"rowIdx": 0, "type": "remove"},+ {"rowIdx": 0, "columnId": "B", "value": "x"},+ ]+ }+ result = apply_edits(data, edits)+ expected = [{"A": 2, "B": "x"}, {"A": 3, "B": "c"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_first_column(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 0, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [{"B": "a"}, {"B": "b"}, {"B": "c"}]+ assert_data_equals_with_order(result, expected)++ def test_remove_middle_column(self):+ data = [+ {"A": 1, "B": "a", "C": "x"},+ {"A": 2, "B": "b", "C": "y"},+ {"A": 3, "B": "c", "C": "z"},+ ]+ edits = {"edits": [{"columnIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [+ {"A": 1, "C": "x"},+ {"A": 2, "C": "y"},+ {"A": 3, "C": "z"},+ ]+ assert_data_equals_with_order(result, expected)++ def test_remove_last_column(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = [{"A": 1}, {"A": 2}, {"A": 3}]+ assert_data_equals_with_order(result, expected)++ def test_add_column_start(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 0, "type": "insert", "newName": "C"}]}+ result = apply_edits(data, edits)+ expected = [+ {"C": None, "A": 1, "B": "a"},+ {"C": None, "A": 2, "B": "b"},+ {"C": None, "A": 3, "B": "c"},+ ]+ assert_data_equals_with_order(result, expected)++ def test_add_column_middle(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 1, "type": "insert", "newName": "C"}]}+ result = apply_edits(data, edits)+ expected = [+ {"A": 1, "C": None, "B": "a"},+ {"A": 2, "C": None, "B": "b"},+ {"A": 3, "C": None, "B": "c"},+ ]+ assert_data_equals_with_order(result, expected)++ def test_add_column_end(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 2, "type": "insert", "newName": "C"}]}+ result = apply_edits(data, edits)+ expected = [+ {"A": 1, "B": "a", "C": None},+ {"A": 2, "B": "b", "C": None},+ {"A": 3, "B": "c", "C": None},+ ]+ assert_data_equals_with_order(result, expected)++ def test_add_column_fails(self):+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]+ edits = {"edits": [{"columnIdx": 3, "type": "insert"}]}++ with pytest.raises(+ ValueError, match="New column name is required for insert"+ ):+ apply_edits(data, edits)++ def test_rename_column_start(self):+ data = [+ {"A": 1, "B": "a", "C": "x", "D": "w"},+ {"A": 2, "B": "b", "C": "y", "D": "v"},+ {"A": 3, "B": "c", "C": "z", "D": "u"},+ ]+ edits = {"edits": [{"columnIdx": 0, "type": "rename", "newName": "X"}]}+ result = apply_edits(data, edits)+ expected = [+ {"X": 1, "B": "a", "C": "x", "D": "w"},+ {"X": 2, "B": "b", "C": "y", "D": "v"},+ {"X": 3, "B": "c", "C": "z", "D": "u"},+ ]+ assert_data_equals_with_order(result, expected)++ def test_rename_column_middle(self):+ data = [+ {"A": 1, "B": "a", "C": "x", "D": "w"},+ {"A": 2, "B": "b", "C": "y", "D": "v"},+ {"A": 3, "B": "c", "C": "z", "D": "u"},+ ]+ edits = {"edits": [{"columnIdx": 1, "type": "rename", "newName": "X"}]}+ result = apply_edits(data, edits)+ expected = [+ {"A": 1, "X": "a", "C": "x", "D": "w"},+ {"A": 2, "X": "b", "C": "y", "D": "v"},+ {"A": 3, "X": "c", "C": "z", "D": "u"},+ ]+ assert_data_equals_with_order(result, expected)++ def test_rename_column_end(self):+ data = [+ {"A": 1, "B": "a", "C": "x", "D": "w"},+ {"A": 2, "B": "b", "C": "y", "D": "v"},+ {"A": 3, "B": "c", "C": "z", "D": "u"},+ ]+ edits = {"edits": [{"columnIdx": 3, "type": "rename", "newName": "X"}]}+ result = apply_edits(data, edits)+ expected = [+ {"A": 1, "B": "a", "C": "x", "X": "w"},+ {"A": 2, "B": "b", "C": "y", "X": "v"},+ {"A": 3, "B": "c", "C": "z", "X": "u"},+ ]+ assert_data_equals_with_order(result, expected)+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+class TestBulkEditsColumnOrientedData:+ """Test bulk edits for column-oriented data."""++ def test_remove_start_row(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {"edits": [{"rowIdx": 0, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = {"A": [2, 3], "B": ["b", "c"], "C": [5, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_middle_row(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {"edits": [{"rowIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = {"A": [1, 3], "B": ["a", "c"], "C": [4, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_end_row(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {"edits": [{"rowIdx": 2, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = {"A": [1, 2], "B": ["a", "b"], "C": [4, 5]}+ assert_data_equals_with_order(result, expected)++ def test_remove_invalid_row(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [+ {"rowIdx": 3, "type": "remove"},+ {"rowIdx": -1, "type": "remove"},+ ]+ }+ result = apply_edits(data, edits)+ expected = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_then_edit(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [+ {"rowIdx": 0, "type": "remove"},+ {"rowIdx": 0, "columnId": "B", "value": "x"},+ ]+ }+ result = apply_edits(data, edits)+ expected = {"A": [2, 3], "B": ["x", "c"], "C": [5, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_multiple_rows(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [+ {"rowIdx": 0, "type": "remove"},+ {"rowIdx": 1, "type": "remove"},+ ]+ }+ result = apply_edits(data, edits)+ expected = {"A": [2], "B": ["b"], "C": [5]}+ assert_data_equals_with_order(result, expected)++ def test_rename_column(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [{"columnIdx": 0, "type": "rename", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ expected = {"D": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_column_middle(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {"edits": [{"columnIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = {"A": [1, 2, 3], "C": [4, 5, 6]}+ assert_data_equals_with_order(result, expected)++ def test_remove_column_end(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {"edits": [{"columnIdx": 2, "type": "remove"}]}+ result = apply_edits(data, edits)+ expected = {"A": [1, 2, 3], "B": ["a", "b", "c"]}+ assert_data_equals_with_order(result, expected)++ def test_insert_column_start(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [{"columnIdx": 0, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ expected = {+ "D": [None, None, None],+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [4, 5, 6],+ }+ assert_data_equals_with_order(result, expected)++ def test_insert_column_middle(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [{"columnIdx": 1, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(deepcopy(data), edits)+ expected = {+ "A": [1, 2, 3],+ "D": [None, None, None],+ "B": ["a", "b", "c"],+ "C": [4, 5, 6],+ }+ assert_data_equals_with_order(result, expected)++ edits = {"edits": [{"columnIdx": 2, "type": "insert", "newName": "D"}]}+ result = apply_edits(deepcopy(data), edits)+ expected = {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "D": [None, None, None],+ "C": [4, 5, 6],+ }+ assert_data_equals_with_order(result, expected)++ def test_insert_column_end(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [{"columnIdx": 3, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ expected = {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [4, 5, 6],+ "D": [None, None, None],+ }+ assert_data_equals_with_order(result, expected)++ def test_mixed_edits(self):+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ edits: DataEdits = {+ "edits": [+ {"columnIdx": 1, "type": "insert", "newName": "D"},+ {"rowIdx": 0, "type": "remove"},+ ]+ }+ result = apply_edits(data, edits)+ expected = {+ "A": [2, 3],+ "D": [None, None],+ "B": ["b", "c"],+ "C": [5, 6],+ }+ assert_data_equals_with_order(result, expected)+++ not DependencyManager.pandas.has() and not DependencyManager.polars.has(),+ reason="Pandas or Polars not installed",+)+class TestBulkEditsDataframe:+ """Test bulk edits for dataframe data."""++ def test_remove_start_row(self):+ import pandas as pd+ import polars as pl++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 0, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pd.DataFrame({"A": [2, 3], "B": ["b", "c"]}).equals(result)++ data = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 0, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pl.DataFrame({"A": [2, 3], "B": ["b", "c"]}).equals(result)++ def test_remove_middle_row(self):+ import pandas as pd+ import polars as pl++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pd.DataFrame({"A": [1, 3], "B": ["a", "c"]}).equals(result)++ data = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pl.DataFrame({"A": [1, 3], "B": ["a", "c"]}).equals(result)++ def test_remove_end_row(self):+ import pandas as pd+ import polars as pl++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 2, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pd.DataFrame({"A": [1, 2], "B": ["a", "b"]}).equals(result)++ data = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"rowIdx": 2, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pl.DataFrame({"A": [1, 2], "B": ["a", "b"]}).equals(result)++ def test_insert_column_start(self):+ import pandas as pd++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {+ "edits": [{"columnIdx": 0, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ assert pd.DataFrame(+ {"D": [None, None, None], "A": [1, 2, 3], "B": ["a", "b", "c"]}+ ).equals(result)++ def test_insert_column_middle(self):+ import pandas as pd++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {+ "edits": [{"columnIdx": 1, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ assert pd.DataFrame(+ {"A": [1, 2, 3], "D": [None, None, None], "B": ["a", "b", "c"]}+ ).equals(result)++ def test_insert_column_end(self):+ import pandas as pd++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {+ "edits": [{"columnIdx": 2, "type": "insert", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ assert pd.DataFrame(+ {"A": [1, 2, 3], "B": ["a", "b", "c"], "D": [None, None, None]}+ ).equals(result)++ def test_rename_column(self):+ import pandas as pd++ data = pd.DataFrame(+ {"A": [1, 2, 3], "B": ["a", "b", "c"], "C": [4, 5, 6]}+ )+ edits: DataEdits = {+ "edits": [{"columnIdx": 1, "type": "rename", "newName": "D"}]+ }+ result = apply_edits(data, edits)+ assert pd.DataFrame(+ {"A": [1, 2, 3], "D": ["a", "b", "c"], "C": [4, 5, 6]}+ ).equals(result)++ def test_remove_column(self):+ import pandas as pd++ data = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})+ edits: DataEdits = {"edits": [{"columnIdx": 1, "type": "remove"}]}+ result = apply_edits(data, edits)+ assert pd.DataFrame({"A": [1, 2, 3]}).equals(result)+++class TestConvertValue:+ """Test the _convert_value function directly."""++ def test_convert_value_with_dtype_datetime(self):+ """Test datetime conversion with dtype."""+ result = _convert_value("2023-03-15T10:30:00", None, nw.Datetime)+ assert result == datetime.datetime(2023, 3, 15, 10, 30, 0)++ def test_convert_value_with_dtype_date(self):+ """Test date conversion with dtype."""+ result = _convert_value("2023-03-15", None, nw.Date)+ assert result == datetime.date(2023, 3, 15)++ def test_convert_value_with_dtype_duration(self):+ """Test duration conversion with dtype."""+ result = _convert_value("186300000000", None, nw.Duration)+ assert result == datetime.timedelta(days=2, seconds=13500)++ def test_convert_value_with_dtype_float32(self):+ """Test Float32 conversion with dtype."""+ result = _convert_value("3.14", None, nw.Float32)+ assert result == 3.14+ assert isinstance(result, float)++ def test_convert_value_with_dtype_float64(self):+ """Test Float64 conversion with dtype."""+ result = _convert_value("3.14", None, nw.Float64)+ assert result == 3.14+ assert isinstance(result, float)++ def test_convert_value_with_dtype_int16(self):+ """Test Int16 conversion with dtype."""+ result = _convert_value("42", None, nw.Int16)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_int32(self):+ """Test Int32 conversion with dtype."""+ result = _convert_value("42", None, nw.Int32)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_int64(self):+ """Test Int64 conversion with dtype."""+ result = _convert_value("42", None, nw.Int64)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_uint16(self):+ """Test UInt16 conversion with dtype."""+ result = _convert_value("42", None, nw.UInt16)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_uint32(self):+ """Test UInt32 conversion with dtype."""+ result = _convert_value("42", None, nw.UInt32)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_uint64(self):+ """Test UInt64 conversion with dtype."""+ result = _convert_value("42", None, nw.UInt64)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_with_dtype_string(self):+ """Test String conversion with dtype."""+ result = _convert_value(42, None, nw.String)+ assert result == "42"+ assert isinstance(result, str)++ def test_convert_value_with_dtype_enum(self):+ """Test Enum conversion with dtype."""+ result = _convert_value(42, None, nw.Enum)+ assert result == "42"+ assert isinstance(result, str)++ def test_convert_value_with_dtype_categorical(self):+ """Test Categorical conversion with dtype."""+ result = _convert_value(42, None, nw.Categorical)+ assert result == "42"+ assert isinstance(result, str)++ def test_convert_value_with_dtype_boolean(self):+ """Test Boolean conversion with dtype."""+ result = _convert_value(True, None, nw.Boolean)+ assert result is True+ assert isinstance(result, bool)++ result = _convert_value(False, None, nw.Boolean)+ assert result is False+ assert isinstance(result, bool)++ result = _convert_value(1, None, nw.Boolean)+ assert result is True++ result = _convert_value(0, None, nw.Boolean)+ assert result is False++ def test_convert_value_with_dtype_list_string_parsable(self):+ """Test List conversion with dtype - string that can be parsed as list."""+ result = _convert_value("[1, 2, 3]", None, nw.List)+ assert result == [1, 2, 3]+ assert isinstance(result, list)++ def test_convert_value_with_dtype_list_string_comma_separated(self):+ """Test List conversion with dtype - comma-separated string."""+ result = _convert_value("1,2,3", None, nw.List)+ assert result == [1, 2, 3]+ assert isinstance(result, list)++ def test_convert_value_with_dtype_list_already_list(self):+ """Test List conversion with dtype - value is already a list."""+ result = _convert_value([1, 2, 3], None, nw.List)+ assert result == [1, 2, 3]+ assert isinstance(result, list)++ def test_convert_value_with_dtype_list_wrap_single_value(self):+ """Test List conversion with dtype - wrap single value in list."""+ result = _convert_value(42, None, nw.List)+ assert result == [42]+ assert isinstance(result, list)++ def test_convert_value_with_dtype_none_value(self):+ """Test conversion with dtype when value is None."""+ result = _convert_value(None, None, nw.String)+ assert result is None++ def test_convert_value_with_unsupported_dtype(self):+ """Test conversion with unsupported dtype."""+ result = _convert_value("test", None, "unsupported_dtype")+ assert result == "test"+ assert isinstance(result, str)++ def test_convert_value_without_dtype_original_none(self):+ """Test conversion without dtype when original_value is None."""+ result = _convert_value("test", None, None)+ assert result == "test"++ def test_convert_value_without_dtype_value_none(self):+ """Test conversion without dtype when value is None."""+ result = _convert_value(None, "original", None)+ assert result is None++ def test_convert_value_without_dtype_int_conversion(self):+ """Test conversion without dtype - int type conversion."""+ result = _convert_value("42", 10, None)+ assert result == 42+ assert isinstance(result, int)++ def test_convert_value_without_dtype_float_conversion(self):+ """Test conversion without dtype - float type conversion."""+ result = _convert_value("3.14", 1.0, None)+ assert result == 3.14+ assert isinstance(result, float)++ def test_convert_value_without_dtype_string_conversion(self):+ """Test conversion without dtype - string type conversion."""+ result = _convert_value(42, "original", None)+ assert result == "42"+ assert isinstance(result, str)++ def test_convert_value_without_dtype_date_conversion(self):+ """Test conversion without dtype - date type conversion."""+ original = datetime.date(2023, 1, 1)+ result = _convert_value("2023-03-15", original, None)+ assert result == datetime.date(2023, 3, 15)+ assert isinstance(result, datetime.date)++ def test_convert_value_without_dtype_datetime_conversion(self):+ """Test conversion without dtype - datetime type conversion."""+ original = datetime.datetime(2023, 1, 1, 12, 0)+ result = _convert_value("2023-03-15T10:30:00", original, None)+ assert result == datetime.datetime(2023, 3, 15, 10, 30, 0)+ assert isinstance(result, datetime.datetime)++ def test_convert_value_without_dtype_timedelta_conversion(self):+ """Test conversion without dtype - timedelta type conversion."""+ original = datetime.timedelta(days=1)+ result = _convert_value("186300000000", original, None)+ assert result == datetime.timedelta(days=2, seconds=13500)+ assert isinstance(result, datetime.timedelta)++ def test_convert_value_without_dtype_list_string_parsable(self):+ """Test conversion without dtype - list from parsable string."""+ original = [1, 2, 3]+ result = _convert_value("[4, 5, 6]", original, None)+ assert result == [4, 5, 6]+ assert isinstance(result, list)++ def test_convert_value_without_dtype_list_string_comma_separated(self):+ """Test conversion without dtype - list from comma-separated string."""+ original = [1, 2, 3]+ result = _convert_value("4,5,6", original, None)+ assert result == [4, 5, 6]+ assert isinstance(result, list)++ def test_convert_value_without_dtype_list_already_list(self):+ """Test conversion without dtype - list when value is already list."""+ original = [1, 2, 3]+ result = _convert_value([4, 5, 6], original, None)+ assert result == [4, 5, 6]+ assert isinstance(result, list)++ def test_convert_value_without_dtype_list_wrap_single_value(self):+ """Test conversion without dtype - wrap single value in list."""+ original = [1, 2, 3]+ result = _convert_value(42, original, None)+ assert result == [42]+ assert isinstance(result, list)++ def test_convert_value_without_dtype_other_types(self):+ """Test conversion without dtype - other types return value as-is."""+ original = {"key": "value"}+ result = _convert_value("new_value", original, None)+ assert result == "new_value"++ def test_convert_value_value_error_handling(self):+ """Test error handling when conversion fails."""+ # This should fail to convert "invalid" to int+ result = _convert_value("invalid", 42, None)+ # Should return original value when conversion fails+ assert result == 42++ def test_convert_value_value_error_handling_with_dtype(self):+ """Test error handling when conversion fails with dtype."""+ # This should fail to convert "invalid" to int+ result = _convert_value("invalid", 42, nw.Int64)+ # Should return original value when conversion fails+ assert result == 42++ def test_convert_value_list_parsing_error(self):+ """Test list parsing error handling."""+ # This should fail to parse as a list+ result = _convert_value("invalid[list", [1, 2, 3], nw.List)+ # Should split by comma as fallback+ assert result == ["invalid[list"]++ def test_convert_value_list_parsing_error_without_dtype(self):+ """Test list parsing error handling without dtype."""+ # This should fail to parse as a list+ result = _convert_value("invalid[list", [1, 2, 3], None)+ # Should split by comma as fallback+ assert result == ["invalid[list"]