Skip to content

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.

experimental: mo.ui.data_editor (#2567)

Myles Scolnickc461eb592df5
diff --git a/frontend/package.json b/frontend/package.json
index bfbd411b9c..c5970e1403 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -84,6 +84,8 @@
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
+ "ag-grid-community": "^32.2.2",
+ "ag-grid-react": "^32.2.2",
"ai": "^3.3.12",
"ansi_up": "^6.0.2",
"class-variance-authority": "^0.7.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index c49145838e..f37fd04fe2 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -228,6 +228,12 @@ importers:
'@xterm/xterm':
specifier: ^5.5.0
version: 5.5.0
+ ag-grid-community:
+ specifier: ^32.2.2
+ version: 32.2.2
+ ag-grid-react:
+ specifier: ^32.2.2
ai:
specifier: ^3.3.12
@@ -4536,6 +4542,18 @@ packages:
resolution: {integrity: sha512-OXwN5b9pCUXNQHJpwwD2qP40byEmSgzj8B4ydSN0uMNYWiFmJ6x6KwUllMmfk8Rwu/HJDFR7U8ubsWBoN0Xp0A==}
engines: {node: '>=8.9'}
+ resolution: {integrity: sha512-PUqH1QtugpYLnlbMdeSZVf5PpT1XZVsP69qN1JXhetLtQpVC28zaj7ikwu9CMA9N9b+dBboA9QcjUQUJZVUokQ==}
+
+ resolution: {integrity: sha512-RQluoEXbTCkYHHwmOUzG4wGBX3yQffFH+52aWJUAFqFKNNHYKYGhjvH2iuAa2xw3CWva1hupUaDpP+Rol32Arg==}
+
+ resolution: {integrity: sha512-YNj6ssjcaE5R2xnxH21YvseKatsTN59Tb8EoafjT/zWQvOAvSWofdbKwYVz8YfPOwNzw+FB+qiQfP1j8rJtVdA==}
+ peerDependencies:
+ react: ^16.3.0 || ^17.0.0 || ^18.0.0
+ react-dom: ^16.3.0 || ^17.0.0 || ^18.0.0
+
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
@@ -15153,6 +15171,19 @@ snapshots:
loader-utils: 2.0.4
regex-parser: 2.2.11
+
+ dependencies:
+ ag-charts-types: 10.2.0
+
+ dependencies:
+ ag-grid-community: 32.2.2
+ prop-types: 15.8.1
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+
dependencies:
debug: 4.3.6
diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsx
new file mode 100644
index 0000000000..438e3ad16b
--- /dev/null
+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx
@@ -0,0 +1,151 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { z } from "zod";
+import { createPlugin } from "../core/builder";
+import { TooltipProvider } from "@radix-ui/react-tooltip";
+import type { DataEditorProps } from "./data-editor/data-editor";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { Objects } from "@/utils/objects";
+import { vegaLoadData } from "./vega/loader";
+import { getVegaFieldTypes } from "./vega/utils";
+import type { Setter } from "../types";
+import { LoadingTable } from "@/components/data-table/loading-table";
+import { Alert, AlertTitle } from "@/components/ui/alert";
+import { DelayMount } from "@/components/utils/delay-mount";
+import React from "react";
+import "./data-editor/grid.css";
+import "ag-grid-community/styles/ag-grid.css";
+import "ag-grid-community/styles/ag-theme-quartz.css";
+
+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"));
+
+export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor")
+ .withData(
+ z.object({
+ initialValue: z.object({
+ edits: z.array(
+ z.object({
+ rowIdx: z.number(),
+ columnId: z.string(),
+ value: z.unknown(),
+ }),
+ ),
+ }),
+ 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
+ .record(
+ z.tuple([
+ z.enum([
+ "boolean",
+ "integer",
+ "number",
+ "date",
+ "string",
+ "unknown",
+ ]),
+ z.string(),
+ ]),
+ )
+ .nullish(),
+ }),
+ )
+ .withFunctions({})
+ .renderer((props) => {
+ return (
+ <TooltipProvider>
+ <LoadingDataEditor
+ data={props.data.data}
+ pagination={props.data.pagination}
+ pageSize={props.data.pageSize}
+ fieldTypes={props.data.fieldTypes}
+ edits={props.value.edits}
+ onEdits={props.setValue}
+ />
+ </TooltipProvider>
+ );
+ });
+
+interface Props
+ extends Omit<DataEditorProps<object>, "data" | "onAddEdits" | "onAddRows"> {
+ data: TableData<object>;
+ edits: Edits["edits"];
+ onEdits: Setter<Edits>;
+}
+
+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 withoutExternalTypes = Objects.mapValues(
+ props.fieldTypes ?? {},
+ ([type]) => type,
+ );
+
+ // Otherwise, load the data from the URL
+ return await vegaLoadData(
+ props.data,
+ { type: "csv", parse: getVegaFieldTypes(withoutExternalTypes) },
+ { handleBigInt: true },
+ );
+ }, [props.fieldTypes, props.data]);
+
+ if (error) {
+ return (
+ <Alert variant="destructive" className="mb-2">
+ <AlertTitle>Error</AlertTitle>
+ <div className="text-md">
+ {error.message || "An unknown error occurred"}
+ </div>
+ </Alert>
+ );
+ }
+
+ if (!data) {
+ return (
+ <DelayMount milliseconds={200}>
+ <LoadingTable pageSize={10} />
+ </DelayMount>
+ );
+ }
+
+ return (
+ <LazyDataEditor
+ data={data}
+ pagination={props.pagination}
+ pageSize={props.pageSize}
+ fieldTypes={props.fieldTypes}
+ edits={props.edits}
+ onAddEdits={(edits) => {
+ props.onEdits((v) => ({ ...v, edits: [...v.edits, ...edits] }));
+ }}
+ onAddRows={(rows) => {
+ const newEdits = rows.flatMap((row, rowIndex) =>
+ Object.entries(row).map(([columnId, value]) => ({
+ rowIdx: data.length + rowIndex,
+ columnId,
+ value,
+ })),
+ );
+ props.onEdits((v) => ({ ...v, edits: [...v.edits, ...newEdits] }));
+ }}
+ />
+ );
+};
diff --git a/frontend/src/plugins/impl/data-editor/data-editor.tsx b/frontend/src/plugins/impl/data-editor/data-editor.tsx
new file mode 100644
index 0000000000..eb81e509b3
--- /dev/null
+++ b/frontend/src/plugins/impl/data-editor/data-editor.tsx
@@ -0,0 +1,205 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { useCallback, useMemo, useRef } from "react";
+import { AgGridReact } from "ag-grid-react";
+import type {
+ ColDef,
+ GridReadyEvent,
+ CellEditingStoppedEvent,
+ RowDataTransaction,
+} from "ag-grid-community";
+import type { FieldTypesWithExternalType } from "@/components/data-table/types";
+import { cn } from "@/utils/cn";
+import { useTheme } from "@/theme/useTheme";
+import type { DataType } from "../vega/vega-loader";
+import { Button } from "@/components/ui/button";
+import { PlusIcon } from "lucide-react";
+
+export interface DataEditorProps<T> {
+ data: T[];
+ pagination: boolean;
+ pageSize: number;
+ fieldTypes: FieldTypesWithExternalType | null | undefined;
+ edits: Array<{
+ rowIdx: number;
+ columnId: string;
+ value: unknown;
+ }>;
+ onAddEdits: (
+ edits: Array<{
+ rowIdx: number;
+ columnId: string;
+ value: unknown;
+ }>,
+ ) => void;
+ onAddRows: (newRows: object[]) => void;
+}
+
+function cellEditorForDataType(dataType: DataType) {
+ switch (dataType) {
+ case "string":
+ return "agTextCellEditor";
+ case "number":
+ return "agNumberCellEditor";
+ case "boolean":
+ return "agCheckboxCellEditor";
+ // TODO: not working properly
+ // case "date":
+ // return 'agDateCellEditor';
+ default:
+ return "agTextCellEditor";
+ }
+}
+
+function getHeaderKeys(data: object[]) {
+ if (data.length === 0) {
+ return [];
+ }
+ return Object.keys(data[0]);
+}
+
+const DataEditor: React.FC<DataEditorProps<object>> = ({
+ data,
+ edits,
+ pagination,
+ pageSize,
+ fieldTypes,
+ onAddEdits,
+ onAddRows,
+}) => {
+ const { theme } = useTheme();
+ const gridRef = useRef<AgGridReact>(null);
+ const headerKeys = useMemo(() => {
+ return getHeaderKeys(data);
+ }, [data]);
+
+ const finalRowData = useMemo(() => {
+ for (const edit of edits) {
+ if (edit.rowIdx >= data.length) {
+ // Add a new row if rowIndex is out of bounds
+ const newRow = { [edit.columnId]: edit.value };
+ data.push(newRow);
+ } else {
+ const row = data[edit.rowIdx];
+ (row as Record<string, unknown>)[edit.columnId] = edit.value;
+ }
+ }
+ return data;
+ }, [data, edits]);
+
+ const columnDefs = useMemo(() => {
+ const defs: ColDef[] = [];
+ for (const header of headerKeys) {
+ defs.push({
+ field: header,
+ editable: true,
+ sortable: false,
+ filter: false,
+ cellEditorSelector: (params) => {
+ const colId = params.column.getColId();
+ const dataType = fieldTypes?.[colId];
+ if (dataType) {
+ if (typeof params.value === "string" && params.value.length > 60) {
+ return { component: "agLargeTextCellEditor", popup: true };
+ }
+ return { component: cellEditorForDataType(dataType[0]) };
+ }
+ return;
+ },
+ });
+ }
+ return defs;
+ }, [headerKeys, fieldTypes]);
+
+ const defaultColDef = useMemo<ColDef>(() => {
+ return {
+ sortable: true,
+ filter: true,
+ };
+ }, []);
+
+ const onGridReady = useCallback((params: GridReadyEvent) => {
+ params.api.sizeColumnsToFit();
+ }, []);
+
+ const onCellEditingStopped = useCallback(
+ (event: CellEditingStoppedEvent) => {
+ if (!event.valueChanged || event.rowIndex === null) {
+ return;
+ }
+ const edit = {
+ rowIdx: event.rowIndex,
+ columnId: event.column.getColId(),
+ value: event.newValue,
+ };
+ onAddEdits([edit]);
+ },
+ [onAddEdits],
+ );
+
+ const totalRows = data.length;
+ const needsPagination = pagination && totalRows > pageSize;
+
+ const handleAddRow = useCallback(() => {
+ const newRow = Object.fromEntries(
+ headerKeys.map((key) => {
+ const dataType = fieldTypes?.[key]?.[0] || "string";
+ switch (dataType) {
+ case "boolean":
+ return [key, false];
+ case "integer":
+ case "number":
+ return [key, 0];
+ case "date":
+ return [key, new Date()];
+ default:
+ return [key, ""];
+ }
+ }),
+ );
+ onAddRows([newRow]);
+
+ // Update the grid with the new row
+ const transaction: RowDataTransaction = {
+ add: [newRow],
+ addIndex: finalRowData.length,
+ };
+ gridRef.current?.api.applyTransaction(transaction);
+ }, [fieldTypes, onAddRows, headerKeys, finalRowData]);
+
+ return (
+ <div
+ className={cn(
+ theme === "dark" ? "ag-theme-quartz-dark" : "ag-theme-quartz",
+ "ag-theme-marimo flex h-[400px] flex-col",
+ "relative",
+ )}
+ >
+ <AgGridReact
+ ref={gridRef}
+ rowData={finalRowData}
+ columnDefs={columnDefs}
+ defaultColDef={defaultColDef}
+ cellSelection={true}
+ pagination={needsPagination}
+ paginationPageSize={pageSize}
+ onGridReady={onGridReady}
+ undoRedoCellEditing={true}
+ stopEditingWhenCellsLoseFocus={true}
+ onCellEditingStopped={onCellEditingStopped}
+ animateRows={false}
+ singleClickEdit={true}
+ suppressFieldDotNotation={true}
+ headerHeight={40}
+ rowHeight={35}
+ />
+ <div className="p-2 border-t flex justify-end">
+ <Button variant="text" size="xs" onClick={handleAddRow}>
+ <PlusIcon className="w-3 h-3 mr-1" />
+ Add Row
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+export default DataEditor;
diff --git a/frontend/src/plugins/impl/data-editor/grid.css b/frontend/src/plugins/impl/data-editor/grid.css
new file mode 100644
index 0000000000..c151c420ce
--- /dev/null
+++ b/frontend/src/plugins/impl/data-editor/grid.css
@@ -0,0 +1,51 @@
+.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/plugins.ts b/frontend/src/plugins/plugins.ts
index 9ffa25a491..25b922b4e2 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -47,6 +47,7 @@ import { DateTimePickerPlugin } from "./impl/DateTimePickerPlugin";
import { DateRangePickerPlugin } from "./impl/DateRangePlugin";
import { MimeRendererPlugin } from "./layout/MimeRenderPlugin";
import { ChatPlugin } from "./impl/chat/ChatPlugin";
+import { DataEditorPlugin } from "./impl/DataEditorPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -80,6 +81,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
DataFramePlugin,
LazyPlugin,
AnyWidgetPlugin,
+ DataEditorPlugin,
];
// List of output / layout plugins
diff --git a/marimo/_plugins/core/web_component.py b/marimo/_plugins/core/web_component.py
index d4772f9d30..49fa56b8b3 100644
--- a/marimo/_plugins/core/web_component.py
+++ b/marimo/_plugins/core/web_component.py
@@ -34,6 +34,7 @@ JSONType: TypeAlias = Union[
int,
float,
bool,
+ object,
MIME, # MIME is a JSONType since we have a custom JSONEncoder for it
None,
]
diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.py
index a4289c4731..20553b484b 100644
--- a/marimo/_plugins/ui/__init__.py
+++ b/marimo/_plugins/ui/__init__.py
@@ -20,6 +20,7 @@ __all__ = [
"date_range",
"date",
"datetime",
+ "experimental_data_editor",
"dictionary",
"dropdown",
"file_browser",
@@ -45,6 +46,9 @@ from marimo._plugins.ui._impl.altair_chart import altair_chart
from marimo._plugins.ui._impl.array import array
from marimo._plugins.ui._impl.batch import batch
from marimo._plugins.ui._impl.chat.chat import chat
+from marimo._plugins.ui._impl.data_editor import (
+ data_editor as experimental_data_editor,
+)
from marimo._plugins.ui._impl.data_explorer import data_explorer
from marimo._plugins.ui._impl.dataframes.dataframe import dataframe
from marimo._plugins.ui._impl.dates import (
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index 784bdd6f9b..f211af3947 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -13,7 +13,7 @@ from marimo._plugins.ui._impl.tables.utils import (
)
if TYPE_CHECKING:
- import narwhals as nw # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import narwhals.stable.v1 as nw
import pandas as pd
import polars as pl
@@ -100,7 +100,7 @@ def _data_to_json_string(data: _DataType) -> str:
return as_str
if DependencyManager.narwhals.has():
- import narwhals # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import narwhals
if isinstance(data, narwhals.DataFrame):
return _data_to_json_string(narwhals.to_native(data))
diff --git a/marimo/_plugins/ui/_impl/data_editor.py b/marimo/_plugins/ui/_impl/data_editor.py
new file mode 100644
index 0000000000..80302f21d4
--- /dev/null
+++ b/marimo/_plugins/ui/_impl/data_editor.py
@@ -0,0 +1,220 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Final,
+ List,
+ Optional,
+ TypedDict,
+ Union,
+)
+
+import narwhals.stable.v1 as nw
+from narwhals.typing import IntoDataFrame
+
+import marimo._output.data.data as mo_data
+from marimo._output.rich_help import mddoc
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.tables.utils import get_table_manager
+
+
+@dataclass
+class DataEditorValue:
+ # Row-oriented data
+ data: List[Dict[str, Any]]
+
+
+class PositionalEdit(TypedDict):
+ rowIdx: int
+ columnId: str
+ value: Any
+
+
+class DataEdits(TypedDict):
+ edits: List[PositionalEdit]
+
+
+RowOrientedData = List[Dict[str, Any]]
+ColumnOrientedData = Dict[str, List[Any]]
+
+
+@mddoc
+class data_editor(
+ UIElement[
+ DataEdits,
+ Union[RowOrientedData, ColumnOrientedData, IntoDataFrame],
+ ]
+):
+ """
+ **[EXPERIMENTAL]**
+
+ This component is experimental and intentionally limited in features,
+ if you have any feature requests, please file an issue at
+ https://github.com/marimo-team/marimo/issues.
+
+ A data editor component for editing tabular data.
+
+ The data can be supplied as:
+ 1. a Pandas, Polars, or Pyarrow DataFrame
+ 2. a list of dicts, with one dict for each row, keyed by column names
+ 3. a dict of lists, with each list representing a column
+
+ **Examples.**
+
+ Create a data editor from a Pandas dataframe:
+
+ ```python
+ import pandas as pd
+
+ df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ editor = mo.ui.experimental_data_editor(data=df, label="Edit Data")
+ ```
+
+ Create a data editor from a list of dicts:
+
+ ```python
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
+ ```
+
+ Create a data editor from a dict of lists:
+
+ ```python
+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"]}
+ editor = mo.ui.experimental_data_editor(data=data, label="Edit Data")
+ ```
+
+ **Attributes.**
+
+ - `value`: the current state of the edited data
+ - `data`: the original data passed to the editor
+
+ **Initialization Args.**
+
+ - `data`: The data to be edited. Can be a Pandas dataframe,
+ a list of dicts, or a dict of lists.
+ - `label`: markdown label for the element
+ - `on_change`: optional callback to run when this element's value changes
+ """
+
+ _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,
+ label: str = "",
+ on_change: Optional[
+ Callable[
+ [Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]],
+ None,
+ ]
+ ] = None,
+ ) -> None:
+ table_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 = data
+ self._edits: DataEdits | None = None
+ field_types = table_manager.get_field_types()
+
+ super().__init__(
+ component_name=data_editor._name,
+ label=label,
+ initial_value={"edits": []},
+ args={
+ "data": mo_data.csv(table_manager.to_csv()).url,
+ "field-types": field_types or None,
+ "pagination": pagination,
+ "page-size": page_size,
+ },
+ on_change=on_change,
+ )
+
+ @property
+ def data(
+ self,
+ ) -> Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]:
+ return self._data
+
+ def _convert_value(
+ self, value: DataEdits
+ ) -> Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]:
+ self._edits = value
+ return apply_edits(self._data, value)
+
+ def __hash__(self) -> int:
+ return id(self)
+
+
+def apply_edits(
+ data: Union[RowOrientedData, ColumnOrientedData, IntoDataFrame],
+ edits: DataEdits,
+) -> Union[RowOrientedData, ColumnOrientedData, IntoDataFrame]:
+ if len(edits["edits"]) == 0:
+ return data
+ # If row-oriented, apply edits to the data
+ if isinstance(data, list):
+ return _apply_edits_row_oriented(data, edits)
+ # If column-oriented, apply edits to the data
+ elif isinstance(data, dict):
+ return _apply_edits_column_oriented(data, edits)
+
+ # narwhalify
+ try:
+ return _apply_edits_dataframe(data, edits) # type: ignore[no-any-return]
+ except Exception as e:
+ raise ValueError(
+ f"Data editor does not support this type of data: {type(data)}"
+ ) from e
+
+
+def _apply_edits_column_oriented(
+ data: ColumnOrientedData,
+ edits: DataEdits,
+) -> 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))
+ column[edit["rowIdx"]] = edit["value"]
+
+ return data
+
+
+def _apply_edits_row_oriented(
+ data: RowOrientedData,
+ edits: DataEdits,
+) -> 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)
+ data[edit["rowIdx"]][edit["columnId"]] = edit["value"]
+
+ return data
+
+
+def _apply_edits_dataframe(
+ df: nw.DataFrame[Any], edits: DataEdits
+) -> nw.DataFrame[Any]:
+ column_oriented = df.to_dict(as_series=False)
+ new_data = _apply_edits_column_oriented(column_oriented, edits)
+ native_namespace = nw.get_native_namespace(df)
+ return nw.from_dict(new_data, native_namespace=native_namespace)
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 0b85bf270b..cb17368a5c 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import functools
from dataclasses import dataclass
from typing import (
- TYPE_CHECKING,
Any,
Callable,
Dict,
@@ -16,6 +15,8 @@ from typing import (
Union,
)
+from narwhals.typing import IntoDataFrame
+
import marimo._output.data.data as mo_data
from marimo import _loggers
from marimo._data.models import NonNestedLiteral
@@ -42,12 +43,6 @@ from marimo._runtime.functions import EmptyArgs, Function
LOGGER = _loggers.marimo_logger()
-if TYPE_CHECKING:
- import pandas as pd
- import polars as pl
- import pyarrow as pa # ignore
-
-
@dataclass
class DownloadAsArgs:
format: Literal["csv", "json"]
@@ -99,9 +94,7 @@ class SortArgs:
@mddoc
-class table(
- UIElement[List[str], Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]]
-):
+class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):
"""
A table component with selectable rows. Get the selected rows with
`table.value`.
@@ -215,9 +208,7 @@ class table(
ListOrTuple[Union[str, int, float, bool, MIME, None]],
ListOrTuple[Dict[str, JSONType]],
Dict[str, ListOrTuple[JSONType]],
- "pd.DataFrame",
- "pl.DataFrame",
- "pa.Table",
+ "IntoDataFrame",
],
pagination: Optional[bool] = None,
selection: Optional[Literal["single", "multi"]] = "multi",
@@ -236,9 +227,7 @@ class table(
Union[
List[JSONType],
Dict[str, ListOrTuple[JSONType]],
- "pd.DataFrame",
- "pl.DataFrame",
- "pa.Table",
+ "IntoDataFrame",
]
],
None,
@@ -392,7 +381,7 @@ class table(
def _convert_value(
self, value: list[str]
- ) -> Union[List[JSONType], "pd.DataFrame", "pl.DataFrame"]:
+ ) -> Union[List[JSONType], "IntoDataFrame"]:
indices = [int(v) for v in value]
self._selected_manager = self._searched_manager.select_rows(indices)
self._has_any_selection = len(indices) > 0
diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.py
index e913a8647f..e34325a361 100644
--- a/marimo/_plugins/ui/_impl/tables/utils.py
+++ b/marimo/_plugins/ui/_impl/tables/utils.py
@@ -54,7 +54,7 @@ def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:
# Unpack narwhal dataframe wrapper
if DependencyManager.narwhals.imported():
- import narwhals # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501
+ import narwhals
if isinstance(data, narwhals.DataFrame):
return get_table_manager_or_none(narwhals.to_native(data))
diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.py
index bd34074b03..fd506a9a83 100644
--- a/marimo/_plugins/ui/_impl/utils/dataframe.py
+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py
@@ -2,7 +2,6 @@
from __future__ import annotations
from typing import (
- TYPE_CHECKING,
Dict,
List,
Tuple,
@@ -10,15 +9,12 @@ from typing import (
Union,
)
+from narwhals.typing import IntoDataFrame
+
from marimo import _loggers
from marimo._output.mime import MIME
from marimo._plugins.core.web_component import JSONType
-if TYPE_CHECKING:
- import pandas as pd
- import polars as pl
- import pyarrow as pa # type: ignore
-
LOGGER = _loggers.marimo_logger()
T = TypeVar("T")
@@ -31,7 +27,5 @@ TableData = Union[
ListOrTuple[Union[str, int, float, bool, MIME, None]],
ListOrTuple[Dict[str, JSONType]],
Dict[str, ListOrTuple[JSONType]],
- "pd.DataFrame",
- "pl.DataFrame",
- "pa.Table",
+ IntoDataFrame,
]
diff --git a/marimo/_smoke_tests/editable_df.py b/marimo/_smoke_tests/editable_df.py
new file mode 100644
index 0000000000..59f8fb3662
--- /dev/null
+++ b/marimo/_smoke_tests/editable_df.py
@@ -0,0 +1,121 @@
+import marimo
+
+__generated_with = "0.9.4"
+app = marimo.App(width="medium")
+
+
+def __():
+ import polars as pl
+ import pandas as pd
+ import marimo as mo
+
+ params = [
+ "Weight",
+ "Torque",
+ "Width",
+ "Height",
+ "Efficiency",
+ "Power",
+ "Displacement",
+ ]
+ return mo, params, pd, pl
+
+
+def __(params, pd, pl):
+ row_oriented = [
+ dict(Model=i, **{param: 0 for param in params}) for i in range(1, 5)
+ ]
+ column_oriented = {param: [0 for _ in range(1, 5)] for param in params}
+ polars_df = pl.DataFrame(row_oriented)
+ pandas_df = pd.DataFrame(row_oriented)
+ return column_oriented, pandas_df, polars_df, row_oriented
+
+
+def __(mo):
+ mo.md(r"""## Editing different inputs (dicts, lists, polars, pandas)""")
+ return
+
+
[email protected](hide_code=True)
+def __(column_oriented, mo, pandas_df, polars_df, row_oriented):
+ df = mo.ui.dropdown(
+ {
+ "polars": polars_df,
+ "pandas": pandas_df,
+ "row": row_oriented,
+ "column": column_oriented,
+ },
+ value="polars",
+ label="Table",
+ )
+ df
+ return (df,)
+
+
+def __(df, mo):
+ edited = mo.ui.experimental_data_editor(df.value)
+ edited
+ return (edited,)
+
+
+def __(edited, flatten_edits, mo):
+ mo.vstack(
+ [
+ mo.ui.table(edited.value, selection=None),
+ flatten_edits(edited._edits["edits"]),
+ ]
+ )
+ return
+
+
+def __():
+ def flatten_edits(edits):
+ return [
+ f"{edit['rowIdx']}.{edit['columnId']} -> {edit['value']}"
+ for edit in edits
+ ]
+ return (flatten_edits,)
+
+
+def __(mo):
+ mo.md(r"""## Editing different data types""")
+ return
+
+
+def __(pd):
+ large_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
+
+ varying_data = {
+ "strings": ["a", "b", "c", large_text],
+ "numbers": [1, 2, 3, 4],
+ "bools": [True, False, True, False],
+ "dates": [pd.Timestamp("2021-01-01") for _ in range(4)],
+ "none": [None for _ in range(4)],
+ "lists": [[1, 2], [3, 4], [5, 6], [7, 8]],
+ }
+ return large_text, varying_data
+
+
+def __(mo, pl, varying_data):
+ edited_df = mo.ui.experimental_data_editor(pl.DataFrame(varying_data))
+ edited_df
+ return (edited_df,)
+
+
+def __(edited_df):
+ edited_df.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/openapi/api.yaml b/openapi/api.yaml
index d7f9f79eee..4d9dfe340d 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -970,6 +970,8 @@ components:
- type: integer
- type: number
- type: boolean
+ - additionalProperties: true
+ type: object
- $ref: '#/components/schemas/MIME'
nullable: true
type: object
@@ -1907,7 +1909,7 @@ components:
type: object
info:
title: marimo API
- version: 0.9.1
+ version: 0.9.4
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 0375ad0892..f942551f68 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2363,6 +2363,9 @@ export interface components {
| string
| number
| boolean
+ | {
+ [key: string]: unknown;
+ }
| components["schemas"]["MIME"]
)
| null;
diff --git a/pyproject.toml b/pyproject.toml
index 4cdefc5cca..85478c4647 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,6 +41,8 @@ dependencies = [
"psutil>=5.0",
# required dependency in Starlette for SessionMiddleware support
"itsdangerous>=2.0.0",
+ # for dataframe support
+ "narwhals>=1.0.0",
# for cell formatting; if user version is not compatible, no-op
# so no lower bound needed
"ruff",
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index 3a429f345e..5b12a31a0e 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -343,7 +343,7 @@ def test_parse_spec_pandas() -> None:
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_parse_spec_narwhal() -> None:
import altair as alt
- import narwhals as nw
+ import narwhals.stable.v1 as nw
data = nw.from_native(pd.DataFrame({"values": [1, 2, 3]}))
chart = alt.Chart(data).mark_point().encode(x="values:Q")
diff --git a/tests/_plugins/ui/_impl/test_data_editor.py b/tests/_plugins/ui/_impl/test_data_editor.py
new file mode 100644
index 0000000000..cca3da0846
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_data_editor.py
@@ -0,0 +1,192 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins import ui
+from marimo._plugins.ui._impl.data_editor import (
+ DataEdits,
+ apply_edits,
+)
+
+data_editor = ui.experimental_data_editor
+
+HAS_PANDAS = DependencyManager.pandas.has()
+HAS_POLARS = DependencyManager.polars.has()
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_initialization():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ editor = data_editor(data=data, label="Test Editor")
+ assert editor._data == data
+ assert editor._edits == {"edits": []}
+ assert editor._component_args["pagination"] is True
+ assert editor._component_args["page-size"] == 50
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_with_column_oriented_data():
+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"]}
+ editor = data_editor(data=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)
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_apply_edits_row_oriented():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ edits = {"edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]}
+ result = apply_edits(data, edits)
+ assert result == [
+ {"A": 1, "B": "a"},
+ {"A": 2, "B": "x"},
+ {"A": 3, "B": "c"},
+ ]
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_apply_edits_column_oriented():
+ data = {"A": [1, 2, 3], "B": ["a", "b", "c"]}
+ edits = {"edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]}
+ result = apply_edits(data, edits)
+ assert result == {"A": [1, 2, 3], "B": ["a", "x", "c"]}
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_apply_edits_new_row():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}]
+ edits = {"edits": [{"rowIdx": 2, "columnId": "A", "value": 3}]}
+ result = apply_edits(data, edits)
+ assert result == [
+ {"A": 1, "B": "a"},
+ {"A": 2, "B": "b"},
+ {"A": 3, "B": None},
+ ]
+
+
+ not DependencyManager.pandas.has(), reason="Pandas not installed"
+)
+def test_apply_edits_dataframe():
+ import pandas as pd
+
+ df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ edits: DataEdits = {
+ "edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]
+ }
+ result = apply_edits(df, edits)
+ assert pd.DataFrame({"A": [1, 2, 3], "B": ["a", "x", "c"]}).equals(result)
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_value_property():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ editor = data_editor(data=data)
+ assert editor.data == data
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_convert_value():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ editor = data_editor(data=data)
+ edits: DataEdits = {
+ "edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]
+ }
+ result = editor._convert_value(edits)
+ assert result == [
+ {"A": 1, "B": "a"},
+ {"A": 2, "B": "x"},
+ {"A": 3, "B": "c"},
+ ]
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_hash():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ editor1 = data_editor(data=data)
+ editor2 = data_editor(data=data)
+ assert hash(editor1) != hash(editor2)
+
+
+ not DependencyManager.pandas.has(), reason="Pandas not installed"
+)
+def test_data_editor_with_pandas_dataframe():
+ import pandas as pd
+
+ df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ editor = data_editor(data=df)
+ assert isinstance(editor.data, pd.DataFrame)
+ assert df.equals(editor.data)
+
+
+ not DependencyManager.polars.has(), reason="Polars not installed"
+)
+def test_data_editor_with_polars_dataframe():
+ import polars as pl
+
+ df = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]})
+ editor = data_editor(data=df)
+ assert isinstance(editor.data, pl.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_on_change_callback():
+ data = [{"A": 1, "B": "a"}, {"A": 2, "B": "b"}, {"A": 3, "B": "c"}]
+ callback_called = False
+
+ def on_change(new_data: Any):
+ nonlocal callback_called
+ callback_called = True
+ assert new_data == [
+ {"A": 1, "B": "a"},
+ {"A": 2, "B": "x"},
+ {"A": 3, "B": "c"},
+ ]
+
+ editor = data_editor(data=data, on_change=on_change)
+ editor._update({"edits": [{"rowIdx": 1, "columnId": "B", "value": "x"}]})
+ assert callback_called
diff --git a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
index 598cce8e9b..a0d1104bfe 100644
--- a/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
+++ b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
@@ -65,7 +65,7 @@ def test_get_row_headers_list() -> None:
reason="optional dependencies not installed",
)
def test_get_table_manager() -> None:
- import narwhals as nw
+ import narwhals.stable.v1 as nw
import pandas as pd
import polars as pl
import pyarrow as pa