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.

fix: allow int columns in mo.ui.dataframe (#1322)

Myles Scolnickd35e128f144f
diff --git a/frontend/.eslintrc.cjs b/frontend/.eslintrc.cjs
index 13eff60e81..40c6cdb5ab 100644
--- a/frontend/.eslintrc.cjs
+++ b/frontend/.eslintrc.cjs
@@ -115,6 +115,18 @@ module.exports = {
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-unsafe-return": "off",
+ // "@typescript-eslint/strict-boolean-expressions": [
+ // "error",
+ // {
+ // // Defaults
+ // allowString: true,
+ // allowNumber: true,
+ // allowNullableObject: true,
+ // // Custom
+ // allowNullableBoolean: true,
+ // allowNullableString: true,
+ // },
+ // ],
// These rules aim to reduce bikeshedding during code reviews
// Often there are multiple ways to do something and this forces consistency
diff --git a/frontend/package.json b/frontend/package.json
index 4e94cb4d37..ec6095d710 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -168,6 +168,7 @@
"@storybook/react-vite": "^8.0.9",
"@storybook/testing-library": "^0.2.2",
"@swc-jotai/react-refresh": "^0.1.0",
+ "@testing-library/react": "^15.0.6",
"@types/emscripten": "^1.39.10",
"@types/katex": "^0.16.7",
"@types/lodash-es": "^4.17.12",
@@ -195,6 +196,7 @@
"prettier": "^3.2.5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
+ "react-test-renderer": "^18.3.1",
"storybook": "^8.0.9",
"stylelint": "^16.4.0",
"stylelint-config-standard": "^36.0.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index a5897d4af2..4e0fa42d5c 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -379,6 +379,9 @@ devDependencies:
'@swc-jotai/react-refresh':
specifier: ^0.1.0
version: 0.1.0
+ '@testing-library/react':
+ specifier: ^15.0.6
'@types/emscripten':
specifier: ^1.39.10
version: 1.39.10
@@ -460,6 +463,9 @@ devDependencies:
react-dom:
specifier: ^18.3.1
version: 18.3.1([email protected])
+ react-test-renderer:
+ specifier: ^18.3.1
+ version: 18.3.1([email protected])
storybook:
specifier: ^8.0.9
@@ -3247,7 +3253,7 @@ packages:
prop-types: 15.8.1
react: 18.3.1
react-dom: 18.3.1([email protected])
- react-is: 18.2.0
+ react-is: 18.3.1
react-transition-group: 4.4.5([email protected])([email protected])
dev: false
@@ -3346,7 +3352,7 @@ packages:
'@types/react': 18.3.1
prop-types: 15.8.1
react: 18.3.1
- react-is: 18.2.0
+ react-is: 18.3.1
dev: false
/@ndelangen/[email protected]:
@@ -7719,6 +7725,20 @@ packages:
engines: {node: '>=12'}
dev: false
+ /@testing-library/[email protected]:
+ resolution: {integrity: sha512-wdsYKy5zupPyLCW2Je5DLHSxSfbIp6h80WoHOQc+RPtmPGA52O9x5MJEkv92Sjonpq+poOAtUKhh1kBGAXBrNA==}
+ engines: {node: '>=18'}
+ dependencies:
+ '@babel/code-frame': 7.24.2
+ '@babel/runtime': 7.24.4
+ '@types/aria-query': 5.0.1
+ aria-query: 5.3.0
+ chalk: 4.1.2
+ dom-accessibility-api: 0.5.12
+ lz-string: 1.5.0
+ pretty-format: 27.5.1
+ dev: true
+
/@testing-library/[email protected]:
resolution: {integrity: sha512-FlS4ZWlp97iiNWig0Muq8p+3rVDjRiYE+YKGbAqXOu9nwJFFOdL00kFpz42M+4huzYi86vAK1sOOfyOG45muIQ==}
engines: {node: '>=14'}
@@ -7765,6 +7785,25 @@ packages:
dev: true
+ resolution: {integrity: sha512-UlbazRtEpQClFOiYp+1BapMT+xyqWMnE+hh9tn5DQ6gmlE7AIZWcGpzZukmDZuFk3By01oiqOf8lRedLS4k6xQ==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ '@types/react': ^18.0.0
+ react: ^18.0.0
+ react-dom: ^18.0.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ dependencies:
+ '@babel/runtime': 7.24.4
+ '@testing-library/dom': 10.1.0
+ '@types/react': 18.3.1
+ '@types/react-dom': 18.3.0
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ dev: true
+
/@testing-library/[email protected](@testing-library/[email protected]):
resolution: {integrity: sha512-YAh82Wh4TIrxYLmfGcixwD18oIjyC1pFQC2Y01F2lzV2HTMiYrI0nze0FD0ocB//CKS/7jIUgae+adPqxK5yCQ==}
engines: {node: '>=12', npm: '>=6'}
@@ -15666,7 +15705,7 @@ packages:
dependencies:
'@jest/schemas': 29.6.3
ansi-styles: 5.2.0
- react-is: 18.2.0
+ react-is: 18.3.1
dev: true
@@ -16125,8 +16164,8 @@ packages:
resolution: {integrity: sha512-Fl7FuabXsJnV5Q1qIOQwx/sagGF18kogb4gpfcG4gjLBWO0WDiiz1ko/ExayuxE7InyQkBLkxRFG5oxY6Uu3Kg==}
dev: true
- resolution: {integrity: sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==}
+ resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}
resolution: {integrity: sha512-g93xcyhAVCSt9kV1svqG1clAEdL6k3U+jjuSzfTV7owaSU9Go6Ph8bl25J+jKfKvIGAEYpe4qj++WHJuc9IaeA==}
@@ -16219,6 +16258,16 @@ packages:
- react-dom
dev: false
+ resolution: {integrity: sha512-oScf2FqQ9LFVQgA73vr86xl2NaOIX73rh+YFqcOp68CWj56tSfgtGKrEbyhCj0rSijyG9M1CYprTh39fBi5hzA==}
+ peerDependencies:
+ react: ^16.0.0 || ^17.0.0 || ^18.0.0
+ dependencies:
+ object-assign: 4.1.1
+ react: 18.3.1
+ react-is: 18.3.1
+ dev: true
+
resolution: {integrity: sha512-IEhKHMT7wijtczA5vtw/kdq9CZuOIF+ReoSimydTFiABRQxWO9ESAl/fToXOUM9qmCdhdqjGJgMAhqTnmheh8g==}
peerDependencies:
@@ -16267,6 +16316,17 @@ packages:
tslib: 2.6.2
dev: false
+ resolution: {integrity: sha512-KkAgygexHUkQqtvvx/otwxtuFu5cVjfzTCtjXLH9boS19/Nbtg84zS7wIQn39G8IlrhThBpQsMKkq5ZHZIYFXA==}
+ peerDependencies:
+ react: ^18.3.1
+ dependencies:
+ react: 18.3.1
+ react-is: 18.3.1
+ react-shallow-renderer: 16.15.0([email protected])
+ scheduler: 0.23.2
+ dev: true
+
resolution: {integrity: sha512-pZcd1MCJoiKiBR2NRxeCRg13uCXbydPnmB4EOeRrY7480qNWO8IIgQG6zlDkm6uRMsURXPuKq0GWtiM59a5Q6g==}
peerDependencies:
diff --git a/frontend/src/components/dependency-graph/utils/layout.ts b/frontend/src/components/dependency-graph/utils/layout.ts
index 15e05a3d4a..852bf2cf29 100644
--- a/frontend/src/components/dependency-graph/utils/layout.ts
+++ b/frontend/src/components/dependency-graph/utils/layout.ts
@@ -23,8 +23,8 @@ export const layoutElements = (
nodes.forEach((node) =>
g.setNode(node.id, {
...node,
- width: node.width || 0,
- height: node.height || 0,
+ width: node.width ?? 0,
+ height: node.height ?? 0,
}),
);
diff --git a/frontend/src/components/editor/actions/types.ts b/frontend/src/components/editor/actions/types.ts
index fe6305fcc0..40b6f5a42e 100644
--- a/frontend/src/components/editor/actions/types.ts
+++ b/frontend/src/components/editor/actions/types.ts
@@ -9,7 +9,7 @@ export interface ActionButton {
label: string;
variant?: "danger";
disableClick?: boolean;
- icon?: React.ReactNode;
+ icon?: React.ReactElement;
hidden?: boolean;
rightElement?: React.ReactNode;
hotkey?: HotkeyAction;
diff --git a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
index b484983c7a..3ac6a8d339 100644
--- a/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
+++ b/frontend/src/components/editor/chrome/panels/snippets-panel.tsx
@@ -101,10 +101,6 @@ const SnippetViewer: React.FC<{ snippet: Snippet }> = ({ snippet }) => {
const lastFocusedCellId = useAtomValue(lastFocusedCellIdAtom);
const handleInsertSnippet = () => {
- if (!snippet) {
- return;
- }
-
// Add below last focused cell in reverse order
for (const section of [...snippet.sections].reverse()) {
if (section.code) {
diff --git a/frontend/src/components/ui/combobox.tsx b/frontend/src/components/ui/combobox.tsx
index e7958a1c21..72ab07c3ed 100644
--- a/frontend/src/components/ui/combobox.tsx
+++ b/frontend/src/components/ui/combobox.tsx
@@ -144,7 +144,7 @@ export const Combobox = <TValue,>({
return placeholder;
}
- if (value) {
+ if (value != null) {
if (Array.isArray(value)) {
if (value.length === 0) {
return placeholder ?? "--";
@@ -204,7 +204,7 @@ export const Combobox = <TValue,>({
<div className={cn("flex flex-col gap-1 items-start", chipsClassName)}>
{Array.isArray(value) &&
value.map((val) => {
- if (!val) {
+ if (val == null) {
return null;
}
return (
@@ -239,7 +239,7 @@ export interface ComboboxItemProps<TValue>
}
export const ComboboxItem = React.forwardRef(
- <TValue extends string | { value: string }>(
+ <TValue extends string | number | { value: string }>(
{ children, className, value, onSelect }: ComboboxItemProps<TValue>,
ref: React.Ref<HTMLDivElement>,
) => {
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index a767b2d90e..d5e9dfb0a7 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { useMemo } from "react";
+import { memo, useMemo } from "react";
import { z } from "zod";
import { DataTable } from "../../components/data-table/data-table";
import {
@@ -98,37 +98,38 @@ interface DataTableProps extends Data<unknown>, Functions {
setValue: (value: S) => void;
}
-export const LoadingDataTableComponent = (
- props: DataTableProps & { data: string },
-) => {
- const { data, loading, error } = useAsyncData<unknown[]>(() => {
- if (!props.data) {
- return Promise.resolve([]);
- }
- return vegaLoadData(
- props.data,
- { type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },
- true,
- );
- }, [props.data, props.fieldTypes]);
+export const LoadingDataTableComponent = memo(
+ (props: DataTableProps & { data: string }) => {
+ const { data, loading, error } = useAsyncData<unknown[]>(() => {
+ if (!props.data) {
+ return Promise.resolve([]);
+ }
+ return vegaLoadData(
+ props.data,
+ { type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },
+ true,
+ );
+ }, [props.data, props.fieldTypes]);
- if (loading && !data) {
- return null;
- }
+ if (loading && !data) {
+ return null;
+ }
- if (error) {
- return (
- <Alert variant="destructive">
- <AlertTitle>Error</AlertTitle>
- <div className="text-md">
- {error.message || "An unknown error occurred"}
- </div>
- </Alert>
- );
- }
+ if (error) {
+ return (
+ <Alert variant="destructive">
+ <AlertTitle>Error</AlertTitle>
+ <div className="text-md">
+ {error.message || "An unknown error occurred"}
+ </div>
+ </Alert>
+ );
+ }
- return <DataTableComponent {...props} data={data || Arrays.EMPTY} />;
-};
+ return <DataTableComponent {...props} data={data || Arrays.EMPTY} />;
+ },
+);
+LoadingDataTableComponent.displayName = "LoadingDataTableComponent";
const DataTableComponent = ({
label,
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index c58202b5c3..6947f6c968 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -6,14 +6,14 @@ import { TransformPanel } from "./panel";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Code2Icon, FunctionSquareIcon } from "lucide-react";
import { CodePanel } from "./python/code-panel";
-import { ColumnDataTypes } from "./types";
+import { ColumnDataTypes, RawColumnDataTypes } from "./types";
import { createPlugin } from "@/plugins/core/builder";
import { rpc } from "@/plugins/core/rpc";
import { useAsyncData } from "@/hooks/useAsyncData";
import { LoadingDataTableComponent } from "../DataTablePlugin";
import { Functions } from "@/utils/functions";
import { Arrays } from "@/utils/arrays";
-import { useState } from "react";
+import { memo, useState } from "react";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Banner, ErrorBanner } from "../common/error-banner";
@@ -54,9 +54,8 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
dataframeName: z.string(),
pageSize: z.number().default(5),
columns: z
- .object({})
- .passthrough()
- .transform((value) => value as ColumnDataTypes),
+ .array(z.tuple([z.string().or(z.number()), z.string()]))
+ .transform((value) => new Map(value as RawColumnDataTypes)),
}),
)
.withFunctions<PluginFunctions>({
@@ -96,83 +95,89 @@ const EMPTY: Transformations = {
transforms: [],
};
-export const DataFrameComponent = ({
- columns,
- dataframeName,
- pageSize,
- value,
- setValue,
- get_dataframe,
- get_column_values,
-}: DataTableProps): JSX.Element => {
- const { data, error } = useAsyncData(
- () => get_dataframe({}),
- [value?.transforms],
- );
- const { url, has_more, total_rows, row_headers } = data || {};
+export const DataFrameComponent = memo(
+ ({
+ columns,
+ dataframeName,
+ pageSize,
+ value,
+ setValue,
+ get_dataframe,
+ get_column_values,
+ }: DataTableProps): JSX.Element => {
+ const { data, error } = useAsyncData(
+ () => get_dataframe({}),
+ [value?.transforms],
+ );
+ console.log("columns", columns);
+ const { url, has_more, total_rows, row_headers } = data || {};
- const [internalValue, setInternalValue] = useState<Transformations>(
- value || EMPTY,
- );
+ const [internalValue, setInternalValue] = useState<Transformations>(
+ value || EMPTY,
+ );
- return (
- <div>
- <Tabs defaultValue="transform">
- <TabsList className="h-8">
- <TabsTrigger value="transform" className="text-xs py-1">
- <FunctionSquareIcon className="w-3 h-3 mr-2" />
- Transform
- </TabsTrigger>
- <TabsTrigger value="code" className="text-xs py-1">
- <Code2Icon className="w-3 h-3 mr-2" />
- Code
- </TabsTrigger>
- </TabsList>
- <TabsContent
- value="transform"
- className="mt-1 border rounded-t overflow-hidden"
- >
- <TransformPanel
- initialValue={internalValue}
- columns={columns}
- onChange={(v) => {
- // Update the value valid changes
- setValue(v);
- setInternalValue(v);
- }}
- onInvalidChange={setInternalValue}
- getColumnValues={get_column_values}
- />
- </TabsContent>
- <TabsContent
- value="code"
- className="mt-1 border rounded-t overflow-hidden"
- >
- <CodePanel dataframeName={dataframeName} transforms={value} />
- </TabsContent>
- </Tabs>
- {error && <ErrorBanner error={error} />}
- {has_more && total_rows && (
- <Banner>Result clipped. Total rows {prettyNumber(total_rows)}.</Banner>
- )}
- <LoadingDataTableComponent
- label={null}
- className="rounded-b border-x border-b"
- data={url || ""}
- hasMore={false} // Handled above
- totalRows={total_rows || 0}
- pageSize={pageSize}
- pagination={true}
- rowHeaders={row_headers || Arrays.EMPTY}
- showDownload={false}
- download_as={Functions.THROW}
- value={Arrays.EMPTY}
- setValue={Functions.NOOP}
- selection={null}
- />
- </div>
- );
-};
+ return (
+ <div>
+ <Tabs defaultValue="transform">
+ <TabsList className="h-8">
+ <TabsTrigger value="transform" className="text-xs py-1">
+ <FunctionSquareIcon className="w-3 h-3 mr-2" />
+ Transform
+ </TabsTrigger>
+ <TabsTrigger value="code" className="text-xs py-1">
+ <Code2Icon className="w-3 h-3 mr-2" />
+ Code
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent
+ value="transform"
+ className="mt-1 border rounded-t overflow-hidden"
+ >
+ <TransformPanel
+ initialValue={internalValue}
+ columns={columns}
+ onChange={(v) => {
+ // Update the value valid changes
+ setValue(v);
+ setInternalValue(v);
+ }}
+ onInvalidChange={setInternalValue}
+ getColumnValues={get_column_values}
+ />
+ </TabsContent>
+ <TabsContent
+ value="code"
+ className="mt-1 border rounded-t overflow-hidden"
+ >
+ <CodePanel dataframeName={dataframeName} transforms={value} />
+ </TabsContent>
+ </Tabs>
+ {error && <ErrorBanner error={error} />}
+ {has_more && total_rows != null && (
+ <Banner>
+ Result clipped. Total rows {prettyNumber(total_rows)}.
+ </Banner>
+ )}
+ <LoadingDataTableComponent
+ label={null}
+ className="rounded-b border-x border-b"
+ data={url || ""}
+ hasMore={false} // Handled above
+ totalRows={total_rows ?? 0}
+ pageSize={pageSize}
+ pagination={true}
+ rowHeaders={row_headers || Arrays.EMPTY}
+ showDownload={false}
+ download_as={Functions.THROW}
+ value={Arrays.EMPTY}
+ setValue={Functions.NOOP}
+ selection={null}
+ />
+ </div>
+ );
+ },
+);
+DataFrameComponent.displayName = "DataFrameComponent";
function prettyNumber(value: number): string {
return new Intl.NumberFormat().format(value);
diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap
new file mode 100644
index 0000000000..176f0b2070
--- /dev/null
+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/__snapshots__/form.test.tsx.snap
@@ -0,0 +1,1085 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`renderZodSchema > should render a form 1`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <div
+ aria-describedby=":r0:-form-item-description"
+ aria-invalid="false"
+ aria-required="false"
+ class="flex flex-row gap-2 pt-1 items-center"
+ dir="ltr"
+ id=":r0:-form-item"
+ role="radiogroup"
+ style="outline: none;"
+ tabindex="0"
+ >
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".operation-keep_rows"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="keep_rows"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".operation-keep_rows"
+ >
+ Keep Rows
+ </label>
+ </div>
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".operation-remove_rows"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="remove_rows"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".operation-remove_rows"
+ >
+ Remove Rows
+ </label>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ />
+ <div
+ class="flex flex-col gap-2 min-w-[220px]"
+ >
+ <div
+ class="text-destructive text-xs font-semibold"
+ >
+ <div>
+ At least 1 required.
+ </div>
+ </div>
+ <div>
+ <button
+ class="disabled:opacity-50 disabled:pointer-events-none inline-flex mb-1 items-center justify-center font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background opacity-80 hover:opacity-100 active:opacity-100 h-7 px-2 rounded-md text-xs hover:text-accent-foreground"
+ data-testid="marimo-plugin-data-frames-add-array-item"
+ >
+ <svg
+ class="lucide lucide-plus w-3.5 h-3.5 mr-1"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M5 12h14"
+ />
+ <path
+ d="M12 5v14"
+ />
+ </svg>
+ Add
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 2`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r3:-form-item"
+ >
+ Columns
+ </label>
+ <div
+ class="relative"
+ >
+ <div
+ aria-controls="radix-:r4:"
+ aria-expanded="false"
+ aria-haspopup="dialog"
+ class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"
+ data-state="closed"
+ type="button"
+ >
+ Select columns
+ <svg
+ class="lucide lucide-chevron-down ml-3 w-4 h-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </div>
+ <div
+ class="flex flex-col gap-1 items-start"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 3`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r5:-form-item"
+ >
+ Column
+ </label>
+ <button
+ aria-autocomplete="none"
+ aria-controls="radix-:r6:"
+ aria-expanded="false"
+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"
+ data-placeholder=""
+ data-state="closed"
+ dir="ltr"
+ role="combobox"
+ type="button"
+ >
+ <span
+ style="pointer-events: none;"
+ >
+ --
+ </span>
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <div
+ class="relative"
+ >
+ <input
+ aria-describedby=":r7:-form-item-description"
+ aria-invalid="false"
+ class="shadow-xsSolid hover:shadow-smSolid disabled:shadow-xsSolid focus-visible:shadow-mdSolid flex h-6 w-full rounded-sm border border-input bg-background px-1.5 py-1 text-sm font-code ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 my-0"
+ id=":r7:-form-item"
+ name=".new_column_id"
+ value=""
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 4`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":rd:-form-item"
+ >
+ Column
+ </label>
+ <button
+ aria-autocomplete="none"
+ aria-controls="radix-:re:"
+ aria-expanded="false"
+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"
+ data-placeholder=""
+ data-state="closed"
+ dir="ltr"
+ role="combobox"
+ type="button"
+ >
+ <span
+ style="pointer-events: none;"
+ >
+ --
+ </span>
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=":rf:-form-item"
+ >
+ Data type (numpy)
+ </label>
+ <button
+ aria-autocomplete="none"
+ aria-controls="radix-:rg:"
+ aria-expanded="false"
+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"
+ data-placeholder=""
+ data-state="closed"
+ dir="ltr"
+ role="combobox"
+ type="button"
+ >
+ <span
+ style="pointer-events: none;"
+ >
+ --
+ </span>
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":rh:-form-item"
+ >
+ Handle errors
+ </label>
+ <div
+ aria-describedby=":rh:-form-item-description"
+ aria-invalid="false"
+ aria-required="false"
+ class="flex flex-row gap-2 pt-1 items-center"
+ dir="ltr"
+ id=":rh:-form-item"
+ role="radiogroup"
+ style="outline: none;"
+ tabindex="0"
+ >
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".errors-ignore"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="ignore"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".errors-ignore"
+ >
+ Ignore
+ </label>
+ </div>
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".errors-raise"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="raise"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".errors-raise"
+ >
+ Raise
+ </label>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 5`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r1f:-form-item"
+ >
+ Column
+ </label>
+ <button
+ aria-autocomplete="none"
+ aria-controls="radix-:r1g:"
+ aria-expanded="false"
+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"
+ data-placeholder=""
+ data-state="closed"
+ dir="ltr"
+ role="combobox"
+ type="button"
+ >
+ <span
+ style="pointer-events: none;"
+ >
+ --
+ </span>
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <div
+ class="flex flex-row items-start space-x-2"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r1h:-form-item"
+ >
+ Ascending
+ </label>
+ <button
+ aria-checked="false"
+ aria-describedby=":r1h:-form-item-description"
+ aria-invalid="false"
+ class="peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
+ data-state="unchecked"
+ data-testid="marimo-plugin-data-frames-boolean-checkbox"
+ id=":r1h:-form-item"
+ role="checkbox"
+ type="button"
+ value="on"
+ />
+ </div>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r1i:-form-item"
+ >
+ N/A position
+ </label>
+ <div
+ aria-describedby=":r1i:-form-item-description"
+ aria-invalid="false"
+ aria-required="false"
+ class="flex flex-row gap-2 pt-1 items-center"
+ dir="ltr"
+ id=":r1i:-form-item"
+ role="radiogroup"
+ style="outline: none;"
+ tabindex="0"
+ >
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".na_position-first"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="first"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".na_position-first"
+ >
+ First
+ </label>
+ </div>
+ <div
+ class="flex items-center gap-1"
+ >
+ <button
+ aria-checked="false"
+ class="h-[16px] w-[16px] transition-shadow data-[state=unchecked]:shadow-xsSolid rounded-full border border-input text-primary ring-offset-background focus:outline-none focus:shadow-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-primary data-[state=checked]:shadow-none"
+ data-radix-collection-item=""
+ data-state="unchecked"
+ id=".na_position-last"
+ role="radio"
+ tabindex="-1"
+ type="button"
+ value="last"
+ />
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=".na_position-last"
+ >
+ Last
+ </label>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 6`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r1q:-form-item"
+ >
+ Columns
+ </label>
+ <div
+ class="relative"
+ >
+ <div
+ aria-controls="radix-:r1r:"
+ aria-expanded="false"
+ aria-haspopup="dialog"
+ class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"
+ data-state="closed"
+ type="button"
+ >
+ Select columns
+ <svg
+ class="lucide lucide-chevron-down ml-3 w-4 h-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </div>
+ <div
+ class="flex flex-col gap-1 items-start"
+ />
+ </div>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=":r1s:-form-item"
+ >
+ Aggregation
+ </label>
+ <button
+ aria-autocomplete="none"
+ aria-controls="radix-:r1t:"
+ aria-expanded="false"
+ class="flex h-6 w-fit items-center justify-between rounded-sm bg-background px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer shadow-xsSolid border border-input hover:shadow-smSolid focus:border-primary focus:shadow-mdSolid disabled:hover:shadow-xsSolid mb-0 min-w-[180px]"
+ data-placeholder=""
+ data-state="closed"
+ dir="ltr"
+ role="combobox"
+ type="button"
+ >
+ <span
+ style="pointer-events: none;"
+ >
+ --
+ </span>
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down h-4 w-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <div
+ class="flex flex-row items-start space-x-2"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r1u:-form-item"
+ >
+ Drop N/A
+ </label>
+ <button
+ aria-checked="false"
+ aria-describedby=":r1u:-form-item-description"
+ aria-invalid="false"
+ class="peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
+ data-state="unchecked"
+ data-testid="marimo-plugin-data-frames-boolean-checkbox"
+ id=":r1u:-form-item"
+ role="checkbox"
+ type="button"
+ value="on"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 7`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-row gap-6 items-start"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r26:-form-item"
+ >
+ Columns
+ </label>
+ <div
+ class="relative"
+ >
+ <div
+ aria-controls="radix-:r27:"
+ aria-expanded="false"
+ aria-haspopup="dialog"
+ class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"
+ data-state="closed"
+ type="button"
+ >
+ Select columns
+ <svg
+ class="lucide lucide-chevron-down ml-3 w-4 h-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </div>
+ <div
+ class="flex flex-col gap-1 items-start"
+ />
+ </div>
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 whitespace-pre"
+ for=":r28:-form-item"
+ >
+ Aggregations
+ </label>
+ <div
+ class="relative"
+ >
+ <div
+ aria-controls="radix-:r29:"
+ aria-expanded="false"
+ aria-haspopup="dialog"
+ class="flex h-6 w-fit mb-1 shadow-xsSolid items-center justify-between rounded-sm border border-input bg-transparent px-2 text-sm font-prose ring-offset-background placeholder:text-muted-foreground hover:shadow-smSolid focus:outline-none focus:ring-1 focus:ring-ring focus:border-primary focus:shadow-mdSolid disabled:cursor-not-allowed disabled:opacity-50 min-w-[180px]"
+ data-state="closed"
+ type="button"
+ >
+ Select aggregations
+ <svg
+ class="lucide lucide-chevron-down ml-3 w-4 h-4 opacity-50"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </div>
+ <div
+ class="flex flex-col gap-1 items-start"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 8`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r2a:-form-item"
+ >
+ Number of rows
+ </label>
+ <div
+ class="my-0"
+ data-rac=""
+ >
+ <div
+ class="shadow-xsSolid hover:shadow-smSolid hover:focus-within:shadow-mdSolid flex h-6 w-full overflow-hidden rounded-sm border border-input bg-background text-sm font-code ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 disabled:shadow-xsSolid focus-within:shadow-mdSolid focus-within:outline-none focus-within:ring-1 focus-within:ring-ring focus-within:border-primary my-0"
+ >
+ <input
+ aria-describedby=":r2a:-form-item-description"
+ aria-roledescription="Number field"
+ autocomplete="off"
+ autocorrect="off"
+ class="flex-1 w-full placeholder:text-muted-foreground outline-none disabled:cursor-not-allowed disabled:opacity-50 px-1.5"
+ data-rac=""
+ id=":r2a:-form-item"
+ inputmode="numeric"
+ spellcheck="false"
+ title=""
+ type="text"
+ value=""
+ />
+ <div
+ class="flex flex-col border-s-2"
+ >
+ <button
+ aria-controls=":r2a:-form-item"
+ aria-label="Increase"
+ class="px-0.5 cursor-default text-muted-foreground pressed:bg-muted-foreground group-disabled:text-disabled-foreground outline-none focus-visible:text-primary disabled:cursor-not-allowed disabled:opacity-50 hover:text-primary hover:bg-muted"
+ data-rac=""
+ slot="increment"
+ tabindex="-1"
+ type="button"
+ >
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-up w-3 h-3 -mb-[1px]"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m18 15-6-6-6 6"
+ />
+ </svg>
+ </button>
+ <div
+ class="h-[1px] flex-shrink-0 divider bg-border z-10"
+ />
+ <button
+ aria-controls=":r2a:-form-item"
+ aria-label="Decrease"
+ class="px-0.5 cursor-default text-muted-foreground pressed:bg-muted-foreground group-disabled:text-disabled-foreground outline-none focus-visible:text-primary disabled:cursor-not-allowed disabled:opacity-50 hover:text-primary hover:bg-muted"
+ data-rac=""
+ slot="decrement"
+ tabindex="-1"
+ type="button"
+ >
+ <svg
+ aria-hidden="true"
+ class="lucide lucide-chevron-down w-3 h-3 -mt-[1px]"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="m6 9 6 6 6-6"
+ />
+ </svg>
+ </button>
+ </div>
+ </div>
+ </div>
+ <input
+ name=".n"
+ type="hidden"
+ value=""
+ />
+ </div>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <button
+ class="disabled:opacity-50 disabled:pointer-events-none inline-flex mb-1 items-center justify-center font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input shadow-smSolid active:shadow-xsSolid h-7 px-2 rounded-md text-xs"
+ data-testid="marimo-plugin-data-frames-random-number-button"
+ >
+ <svg
+ class="lucide lucide-refresh-ccw w-3.5 h-3.5 mr-1"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"
+ />
+ <path
+ d="M3 3v5h5"
+ />
+ <path
+ d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"
+ />
+ <path
+ d="M16 16h5v5"
+ />
+ </svg>
+ Re-sample
+ </button>
+ </div>
+ <div
+ class="flex flex-row align-start"
+ >
+ <div
+ class="flex flex-col gap-1"
+ >
+ <div
+ class="flex flex-row items-start space-x-2"
+ >
+ <label
+ class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ for=":r2j:-form-item"
+ >
+ Sample with replacement
+ </label>
+ <button
+ aria-checked="false"
+ aria-describedby=":r2j:-form-item-description"
+ aria-invalid="false"
+ class="peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground"
+ data-state="unchecked"
+ data-testid="marimo-plugin-data-frames-boolean-checkbox"
+ id=":r2j:-form-item"
+ role="checkbox"
+ type="button"
+ value="on"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+</DocumentFragment>
+`;
+
+exports[`renderZodSchema > should render a form 9`] = `
+<DocumentFragment>
+ <div
+ class="flex flex-col gap-6"
+ >
+ <input
+ name=".type"
+ type="hidden"
+ value=""
+ />
+ <div
+ class="flex flex-row align-start"
+ >
+ <button
+ class="disabled:opacity-50 disabled:pointer-events-none inline-flex mb-1 items-center justify-center font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background bg-secondary text-secondary-foreground hover:bg-secondary/80 border border-input shadow-smSolid active:shadow-xsSolid h-7 px-2 rounded-md text-xs"
+ data-testid="marimo-plugin-data-frames-random-number-button"
+ >
+ <svg
+ class="lucide lucide-refresh-ccw w-3.5 h-3.5 mr-1"
+ fill="none"
+ height="24"
+ stroke="currentColor"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ stroke-width="2"
+ viewBox="0 0 24 24"
+ width="24"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"
+ />
+ <path
+ d="M3 3v5h5"
+ />
+ <path
+ d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"
+ />
+ <path
+ d="M16 16h5v5"
+ />
+ </svg>
+ Re-shuffle
+ </button>
+ </div>
+ </div>
+</DocumentFragment>
+`;
diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx b/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx
new file mode 100644
index 0000000000..10c9c0d19a
--- /dev/null
+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/form.test.tsx
@@ -0,0 +1,41 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, expect, it } from "vitest";
+import { ZodForm } from "../form";
+import { TransformTypeSchema } from "../../schema";
+import { render } from "@testing-library/react";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { ColumnId } from "../../types";
+import { ColumnInfoContext } from "../context";
+
+const ColumnTypes = new Map([
+ [0 as ColumnId, "str"],
+ [1 as ColumnId, "bool"],
+ ["A" as ColumnId, "str"],
+ ["B" as ColumnId, "int"],
+]);
+
+const Subject = (props: { schema: z.ZodType }) => {
+ const form = useForm({
+ resolver: zodResolver(props.schema),
+ defaultValues: {},
+ mode: "onChange",
+ reValidateMode: "onChange",
+ });
+ return (
+ <ColumnInfoContext.Provider value={ColumnTypes}>
+ <ZodForm form={form} schema={props.schema} />
+ </ColumnInfoContext.Provider>
+ );
+};
+
+describe("renderZodSchema", () => {
+ const options = TransformTypeSchema._def.options;
+ // Snapshot each form to make sure they don't change unexpectedly
+ it.each(options)("should render a form", (schema) => {
+ const expected = render(<Subject schema={schema} />);
+
+ expect(expected.asFragment()).toMatchSnapshot();
+ });
+});
diff --git a/frontend/src/plugins/impl/data-frames/forms/context.ts b/frontend/src/plugins/impl/data-frames/forms/context.ts
index 8c6c26c78f..8d2a4a1301 100644
--- a/frontend/src/plugins/impl/data-frames/forms/context.ts
+++ b/frontend/src/plugins/impl/data-frames/forms/context.ts
@@ -2,7 +2,7 @@
import { createContext } from "react";
import { ColumnDataTypes } from "../types";
-export const ColumnInfoContext = createContext<ColumnDataTypes>({});
+export const ColumnInfoContext = createContext<ColumnDataTypes>(new Map());
export const ColumnNameContext = createContext<string>("");
export const ColumnFetchValuesContext = createContext<
diff --git a/frontend/src/plugins/impl/data-frames/forms/form-utils.ts b/frontend/src/plugins/impl/data-frames/forms/form-utils.ts
index 779431c629..31fe09d2ed 100644
--- a/frontend/src/plugins/impl/data-frames/forms/form-utils.ts
+++ b/frontend/src/plugins/impl/data-frames/forms/form-utils.ts
@@ -72,10 +72,10 @@ export function getUnionLiteral<T extends z.ZodType<unknown>>(
if (type instanceof z.ZodLiteral) {
return type;
}
- throw new Error("Invalid schema");
+ throw new Error(`Invalid schema: ${schema._type}`);
}
if (schema instanceof z.ZodUnion) {
return getUnionLiteral(schema._def.options[0]);
}
- throw new Error("Invalid schema");
+ throw new Error(`Invalid schema`);
}
diff --git a/frontend/src/plugins/impl/data-frames/forms/form.tsx b/frontend/src/plugins/impl/data-frames/forms/form.tsx
index 3ae28170b8..4a70f131d6 100644
--- a/frontend/src/plugins/impl/data-frames/forms/form.tsx
+++ b/frontend/src/plugins/impl/data-frames/forms/form.tsx
@@ -60,6 +60,7 @@ import {
TextAreaMultiSelect,
ensureStringArray,
} from "@/components/forms/switchable-multi-select";
+import { ColumnId } from "../types";
interface Props<T extends FieldValues> {
form: UseFormReturn<T>;
@@ -98,6 +99,9 @@ function renderZodSchema<T extends FieldValues, S>(
: inner;
return renderZodSchema(inner, form, path);
}
+ if (special === "column_id") {
+ return <ColumnFormField schema={schema} form={form} path={path} />;
+ }
if (schema instanceof z.ZodObject) {
if (special === "column_filter") {
@@ -133,10 +137,6 @@ function renderZodSchema<T extends FieldValues, S>(
</div>
);
} else if (schema instanceof z.ZodString) {
- if (special === "column_id") {
- return <ColumnFormField schema={schema} form={form} path={path} />;
- }
-
if (special === "column_values") {
return <ColumnValuesFormField schema={schema} form={form} path={path} />;
}
@@ -256,7 +256,7 @@ function renderZodSchema<T extends FieldValues, S>(
const childSpecial = FieldOptions.parse(childType._def.description).special;
// Show column multi-select for array with column_id
- if (childType instanceof z.ZodString && childSpecial === "column_id") {
+ if (childSpecial === "column_id") {
return (
<MultiColumnFormField
schema={childType}
@@ -353,7 +353,7 @@ function renderZodSchema<T extends FieldValues, S>(
return (
<div>
Unknown schema type{" "}
- {schema ? JSON.stringify(schema._type || schema) : path}
+ {schema == null ? path : JSON.stringify(schema._type ?? schema)}
</div>
);
}
@@ -405,7 +405,7 @@ const FormArray = ({
{fields.map((field, index) => {
return (
<div
- className="flex flex-row pl-2 ml-4 border-l-2 border-disabled hover-actions-parent relative pr-5 pt-1 items-center w-fit"
+ className="flex flex-row pl-2 ml-2 border-l-2 border-disabled hover-actions-parent relative pr-5 pt-1 items-center w-fit"
key={field.id}
onKeyDown={Events.onEnter((e) => e.preventDefault())}
>
@@ -445,7 +445,7 @@ const FormArray = ({
};
/**
- * Type: string
+ * Type: string | number
* Special: column_id
*/
const ColumnFormField = ({
@@ -454,10 +454,10 @@ const ColumnFormField = ({
path,
onChange,
}: {
- schema: z.ZodString;
+ schema: z.ZodSchema;
form: UseFormReturn<any>;
path: Path<any>;
- onChange?: (value: string) => void;
+ onChange?: (value: ColumnId) => void;
}) => {
const columns = useContext(ColumnInfoContext);
const { label, description } = FieldOptions.parse(schema._def.description);
@@ -474,20 +474,23 @@ const ColumnFormField = ({
<FormControl>
<Select
data-testid="marimo-plugin-data-frames-column-select"
- value={field.value}
+ value={
+ field.value == null ? field.value : JSON.stringify(field.value)
+ }
onValueChange={(value) => {
- onChange?.(value);
- field.onChange(value);
+ const realValue = JSON.parse(value) as ColumnId;
+ onChange?.(realValue);
+ field.onChange(realValue);
}}
>
- <SelectTrigger className="min-w-[210px]">
+ <SelectTrigger className="min-w-[180px]">
<SelectValue placeholder="--" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
- {Objects.entries(columns).map(([name, dtype]) => {
+ {[...columns.entries()].map(([name, dtype]) => {
return (
- <SelectItem key={name} value={name.toString()}>
+ <SelectItem key={name} value={JSON.stringify(name)}>
<span className="flex items-center gap-2 flex-1">
<DataTypeIcon type={dtype} />
<span className="flex-1">{name}</span>
@@ -498,7 +501,7 @@ const ColumnFormField = ({
</SelectItem>
);
})}
- {Objects.keys(columns).length === 0 && (
+ {columns.size === 0 && (
<SelectItem disabled={true} value="--">
No columns
</SelectItem>
@@ -514,7 +517,7 @@ const ColumnFormField = ({
};
/**
- * Type: string[]
+ * Type: (string | number)[]
* Special: column_ids
*/
const MultiColumnFormField = ({
@@ -523,7 +526,7 @@ const MultiColumnFormField = ({
path,
itemLabel,
}: {
- schema: z.ZodString;
+ schema: z.ZodSchema;
form: UseFormReturn<any>;
path: Path<any>;
itemLabel?: string;
@@ -544,10 +547,10 @@ const MultiColumnFormField = ({
<FormLabel>{itemLabel}</FormLabel>
<FormDescription>{description}</FormDescription>
<FormControl>
- <Combobox
- className="min-w-[210px]"
+ <Combobox<ColumnId>
+ className="min-w-[180px]"
placeholder={placeholder}
- displayValue={(option: string) => option}
+ displayValue={String}
multiple={true}
chips={true}
keepPopoverOpenOnSelect={true}
@@ -556,9 +559,9 @@ const MultiColumnFormField = ({
field.onChange(v);
}}
>
- {Objects.entries(columns).map(([name, dtype]) => {
+ {[...columns.entries()].map(([name, dtype]) => {
return (
- <ComboboxItem key={name} value={name.toString()}>
+ <ComboboxItem key={name} value={name}>
<span className="flex items-center gap-2 flex-1">
<DataTypeIcon type={dtype} />
<span className="flex-1">{name}</span>
@@ -603,7 +606,7 @@ const FilterForm = ({
)?.[1] as unknown as z.ZodString;
// existing values
- const { column_id: columnId, operator } = field.value || {};
+ const { column_id: columnId, operator } = field.value ?? {};
const children = [
<ColumnFormField
@@ -613,8 +616,8 @@ const FilterForm = ({
path={`${path}.column_id`}
onChange={(value) => {
// Reset operator and value if the column type changes
- const currentDtype = columns[columnId];
- const nextDtype = columns[value];
+ const currentDtype = columns.get(columnId);
+ const nextDtype = columns.get(value);
if (nextDtype !== currentDtype) {
form.setValue(`${path}.value`, undefined);
}
@@ -624,7 +627,7 @@ const FilterForm = ({
// When column ID changes, get the new dtype and reset the operator
useEffect(() => {
- const dtype = columns[columnId];
+ const dtype = columns.get(columnId);
const operators = getOperatorForDtype(dtype);
const currentOperator = form.getValues(`${path}.operator`);
@@ -635,8 +638,8 @@ const FilterForm = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [columnId]);
- if (columnId) {
- const dtype = columns[columnId];
+ if (columnId != null) {
+ const dtype = columns.get(columnId);
const operators = getOperatorForDtype(dtype);
if (operators.length === 0) {
@@ -665,7 +668,7 @@ const FilterForm = ({
value={field.value}
onValueChange={field.onChange}
>
- <SelectTrigger className="min-w-[210px]">
+ <SelectTrigger className="min-w-[140px]">
<SelectValue placeholder="--" />
</SelectTrigger>
<SelectContent>
@@ -689,8 +692,8 @@ const FilterForm = ({
}
}
- if (operator) {
- const dtype = columns[columnId];
+ if (operator != null) {
+ const dtype = columns.get(columnId);
const operandSchemas = getSchemaForOperator(dtype, operator);
if (operandSchemas.length === 1) {
children.push(
@@ -709,7 +712,7 @@ const FilterForm = ({
name={path}
render={() => (
<div className="flex flex-col gap-2 bg-red">
- <div className={cn("flex flex-row gap-3")}>{children}</div>
+ <div className={cn("flex flex-row gap-2")}>{children}</div>
<FormMessage />
</div>
)}
@@ -870,7 +873,7 @@ const SelectFormField = ({
value={field.value}
onValueChange={field.onChange}
>
- <SelectTrigger className="min-w-[210px]">
+ <SelectTrigger className="min-w-[180px]">
<SelectValue placeholder="--" />
</SelectTrigger>
<SelectContent>
@@ -945,7 +948,7 @@ const MultiSelectFormField = ({
/>
) : (
<Combobox
- className="min-w-[210px]"
+ className="min-w-[180px]"
placeholder={resolvePlaceholder}
displayValue={(option: string) => Strings.startCase(option)}
multiple={true}
@@ -1011,7 +1014,7 @@ const ColumnValuesFormField = ({
<FormDescription>{description}</FormDescription>
<FormControl>
<Combobox
- className="min-w-[210px]"
+ className="min-w-[180px]"
placeholder={placeholder}
multiple={false}
displayValue={(option: string) => option}
diff --git a/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts b/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
index 8137858457..d220cd7672 100644
--- a/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
+++ b/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts
@@ -9,13 +9,14 @@ import {
STRING_OPERATORS,
} from "../../utils/operators";
import { Objects } from "@/utils/objects";
+import { ColumnId } from "../../types";
describe("pythonPrint", () => {
// Test for column_conversion
it("generates correct Python code for column_conversion", () => {
const transform: TransformType = {
type: "column_conversion",
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
data_type: "int8",
errors: "ignore",
};
@@ -25,12 +26,25 @@ describe("pythonPrint", () => {
);
});
+ it("generates correct Python code for column_conversion, for numeric columns", () => {
+ const transform: TransformType = {
+ type: "column_conversion",
+ column_id: 1 as ColumnId,
+ data_type: "int8",
+ errors: "ignore",
+ };
+ const result = pythonPrint("df", transform);
+ expect(result).toMatchInlineSnapshot(
+ `"df[1].astype("int8", errors="ignore")"`,
+ );
+ });
+
// Test for rename_column
it("generates correct Python code for rename_column", () => {
const transform: TransformType = {
type: "rename_column",
- column_id: "old_name",
- new_column_id: "new_name",
+ column_id: "old_name" as ColumnId,
+ new_column_id: "new_name" as ColumnId,
};
const result = pythonPrint("df", transform);
expect(result).toMatchInlineSnapshot(
@@ -38,11 +52,21 @@ describe("pythonPrint", () => {
);
});
+ it("generates correct Python code for rename_column, for numeric columns", () => {
+ const transform: TransformType = {
+ type: "rename_column",
+ column_id: 1 as ColumnId,
+ new_column_id: 2 as ColumnId,
+ };
+ const result = pythonPrint("df", transform);
+ expect(result).toMatchInlineSnapshot(`"df.rename(columns={1: 2})"`);
+ });
+
// Test for sort_column
it("generates correct Python code for sort_column", () => {
const transform: TransformType = {
type: "sort_column",
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
ascending: false,
na_position: "first",
};
@@ -56,7 +80,7 @@ describe("pythonPrint", () => {
it("generates correct Python code for aggregate", () => {
const transform: TransformType = {
type: "aggregate",
- column_ids: ["my_column"],
+ column_ids: ["my_column"] as ColumnId[],
aggregations: ["mean"],
};
const result = pythonPrint("df", transform);
@@ -64,7 +88,7 @@ describe("pythonPrint", () => {
const transform2: TransformType = {
type: "aggregate",
- column_ids: [],
+ column_ids: [] as ColumnId[],
aggregations: ["mean"],
};
const result2 = pythonPrint("df", transform2);
@@ -72,20 +96,18 @@ describe("pythonPrint", () => {
const transform3: TransformType = {
type: "aggregate",
- column_ids: ["my_column"],
+ column_ids: [2] as ColumnId[],
aggregations: ["mean", "sum"],
};
const result3 = pythonPrint("df", transform3);
- expect(result3).toMatchInlineSnapshot(
- `"df.agg({"my_column": ["mean", "sum"]})"`,
- );
+ expect(result3).toMatchInlineSnapshot(`"df.agg({2: ["mean", "sum"]})"`);
});
// Test for group_by
it("generates correct Python code for group_by", () => {
const transform: TransformType = {
type: "group_by",
- column_ids: ["my_column"],
+ column_ids: ["my_column"] as ColumnId[],
aggregation: "sum",
drop_na: true,
};
@@ -96,13 +118,13 @@ describe("pythonPrint", () => {
const transform2: TransformType = {
type: "group_by",
- column_ids: ["my_column", "my_column2"],
+ column_ids: ["my_column", "my_column2", 3] as ColumnId[],
aggregation: "sum",
drop_na: false,
};
const result2 = pythonPrint("df", transform2);
expect(result2).toMatchInlineSnapshot(
- `"df.groupby(["my_column", "my_column2"]).sum()"`,
+ `"df.groupby(["my_column", "my_column2", 3]).sum()"`,
);
});
});
@@ -111,17 +133,17 @@ describe("pythonPrint", () => {
it("generates correct Python code for select_columns", () => {
const transform: TransformType = {
type: "select_columns",
- column_ids: ["my_column"],
+ column_ids: ["my_column"] as ColumnId[],
};
const result = pythonPrint("df", transform);
expect(result).toMatchInlineSnapshot(`"df["my_column"]"`);
const transform2: TransformType = {
type: "select_columns",
- column_ids: ["my_column", "my_column2"],
+ column_ids: ["my_column", "my_column2", 3] as ColumnId[],
};
const result2 = pythonPrint("df", transform2);
- expect(result2).toMatchInlineSnapshot(`"df[["my_column", "my_column2"]]"`);
+ expect(result2).toMatchInlineSnapshot(`"df[["my_column", "my_column2", 3]]"`);
});
// Test for sample_rows
@@ -153,7 +175,7 @@ describe("pythonPrint: filter", () => {
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: "==",
value: 42,
},
@@ -166,7 +188,7 @@ describe("pythonPrint: filter", () => {
operation: "remove_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: "==",
value: 42,
},
@@ -175,25 +197,40 @@ describe("pythonPrint: filter", () => {
expect(result2).toMatchInlineSnapshot(`"df[~((df["my_column"] == 42))]"`);
});
+ it("handle where clauses with numeric columns", () => {
+ const result = pythonPrint("df", {
+ type: "filter_rows",
+ operation: "keep_rows",
+ where: [
+ {
+ column_id: 2 as ColumnId,
+ operator: "==",
+ value: 43,
+ },
+ ],
+ });
+ expect(result).toMatchInlineSnapshot(`"df[df[2] == 43]"`);
+ });
+
it("handle multiple where clauses", () => {
const result = pythonPrint("df", {
type: "filter_rows",
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: "==",
value: 42,
},
{
- column_id: "my_column2",
+ column_id: 2 as ColumnId,
operator: "==",
value: 43,
},
],
});
expect(result).toMatchInlineSnapshot(
- `"df[(df["my_column"] == 42) & (df["my_column2"] == 43)]"`,
+ `"df[(df["my_column"] == 42) & (df[2] == 43)]"`,
);
});
@@ -206,7 +243,7 @@ describe("pythonPrint: filter", () => {
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: operator,
value: "val",
},
@@ -226,7 +263,7 @@ describe("pythonPrint: filter", () => {
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: operator,
value: true,
},
@@ -246,7 +283,7 @@ describe("pythonPrint: filter", () => {
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: operator,
value: 1000,
},
@@ -266,7 +303,7 @@ describe("pythonPrint: filter", () => {
operation: "keep_rows",
where: [
{
- column_id: "my_column",
+ column_id: "my_column" as ColumnId,
operator: operator,
value: 42,
},
diff --git a/frontend/src/plugins/impl/data-frames/python/python-print.ts b/frontend/src/plugins/impl/data-frames/python/python-print.ts
index 6d26bf83ff..6d9447ef14 100644
--- a/frontend/src/plugins/impl/data-frames/python/python-print.ts
+++ b/frontend/src/plugins/impl/data-frames/python/python-print.ts
@@ -2,6 +2,7 @@
import { TransformType } from "@/plugins/impl/data-frames/schema";
import { logNever } from "@/utils/assertNever";
import { OperatorType } from "../utils/operators";
+import { ColumnId } from "../types";
export function pythonPrintTransforms(
dfName: string,
@@ -19,16 +20,16 @@ export function pythonPrint(dfName: string, transform: TransformType): string {
switch (transform.type) {
case "column_conversion": {
const { column_id, data_type, errors } = transform;
- return `${dfName}["${column_id}"].astype("${data_type}", errors="${errors}")`;
+ return `${dfName}[${asLiteral(column_id)}].astype("${data_type}", errors="${errors}")`;
}
case "rename_column": {
const { column_id, new_column_id } = transform;
- return `${dfName}.rename(columns={"${column_id}": "${new_column_id}"})`;
+ return `${dfName}.rename(columns={${asLiteral(column_id)}: ${asLiteral(new_column_id)}})`;
}
case "sort_column": {
const { column_id, ascending, na_position } = transform;
const args = argsList(
- `by="${column_id}"`,
+ `by=${asLiteral(column_id)}`,
ascending ? "" : "ascending=False",
na_position === "last" ? "" : `na_position="${na_position}"`,
);
@@ -61,7 +62,10 @@ export function pythonPrint(dfName: string, transform: TransformType): string {
return `${dfName}.agg(${listOfStrings(aggregations)})`;
}
return `${dfName}.agg({${column_ids
- .map((column_id) => `"${column_id}": ${listOfStrings(aggregations)}`)
+ .map(
+ (column_id) =>
+ `${asLiteral(column_id)}: ${listOfStrings(aggregations)}`,
+ )
.join(", ")}})`;
}
case "group_by": {
@@ -78,7 +82,7 @@ export function pythonPrint(dfName: string, transform: TransformType): string {
return dfName;
}
if (column_ids.length === 1) {
- return `${dfName}["${column_ids[0]}"]`;
+ return `${dfName}[${asLiteral(column_ids[0])}]`;
}
return `${dfName}[${listOfStrings(column_ids)}]`;
}
@@ -98,7 +102,7 @@ export function pythonPrint(dfName: string, transform: TransformType): string {
function generateWhereClause(
dfName: string,
where: {
- column_id: string;
+ column_id: ColumnId;
operator: OperatorType;
value?: unknown;
},
@@ -106,48 +110,48 @@ function generateWhereClause(
const { column_id, operator, value } = where;
switch (operator) {
case "==":
- return `${dfName}["${column_id}"] == ${asString(value)}`;
+ return `${dfName}[${asLiteral(column_id)}] == ${asLiteral(value)}`;
case "equals":
- return `${dfName}["${column_id}"].eq(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].eq(${asLiteral(value)})`;
case "does_not_equal":
- return `${dfName}["${column_id}"].ne(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].ne(${asLiteral(value)})`;
case "contains":
- return `${dfName}["${column_id}"].str.contains(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].str.contains(${asLiteral(value)})`;
case "regex":
- return `${dfName}["${column_id}"].str.contains(${asString(
+ return `${dfName}[${asLiteral(column_id)}].str.contains(${asLiteral(
value,
)}, regex=True)`;
case "starts_with":
- return `${dfName}["${column_id}"].str.startswith(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].str.startswith(${asLiteral(value)})`;
case "ends_with":
- return `${dfName}["${column_id}"].str.endswith(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].str.endswith(${asLiteral(value)})`;
case "in":
- return `${dfName}["${column_id}"].isin(${listOfStrings(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].isin(${listOfStrings(value)})`;
case "!=":
- return `${dfName}["${column_id}"].ne(${asString(value)})`;
+ return `${dfName}[${asLiteral(column_id)}].ne(${asLiteral(value)})`;
case ">":
- return `${dfName}["${column_id}"] > ${asString(value)}`;
+ return `${dfName}[${asLiteral(column_id)}] > ${asLiteral(value)}`;
case ">=":
- return `${dfName}["${column_id}"] >= ${asString(value)}`;
+ return `${dfName}[${asLiteral(column_id)}] >= ${asLiteral(value)}`;
case "<":
- return `${dfName}["${column_id}"] < ${asString(value)}`;
+ return `${dfName}[${asLiteral(column_id)}] < ${asLiteral(value)}`;
case "<=":
- return `${dfName}["${column_id}"] <= ${asString(value)}`;
+ return `${dfName}[${asLiteral(column_id)}] <= ${asLiteral(value)}`;
case "is_nan":
- return `${dfName}["${column_id}"].isna()`;
+ return `${dfName}[${asLiteral(column_id)}].isna()`;
case "is_not_nan":
- return `${dfName}["${column_id}"].notna()`;
+ return `${dfName}[${asLiteral(column_id)}].notna()`;
case "is_true":
- return `${dfName}["${column_id}"].eq(True)`;
+ return `${dfName}[${asLiteral(column_id)}].eq(True)`;
case "is_false":
- return `${dfName}["${column_id}"].eq(False)`;
+ return `${dfName}[${asLiteral(column_id)}].eq(False)`;
default:
logNever(operator);
return "df";
}
}
-function asString(value: unknown): string {
+function asLiteral(value: unknown): string {
if (typeof value === "string") {
return `"${value}"`;
}
@@ -156,9 +160,9 @@ function asString(value: unknown): string {
function listOfStrings(value: unknown): string {
if (Array.isArray(value)) {
- return `[${value.map(asString).join(", ")}]`;
+ return `[${value.map(asLiteral).join(", ")}]`;
}
- return asString(value);
+ return asLiteral(value);
}
function argsList(...args: string[]): string {
diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.ts
index 295c0e2a3d..8574053868 100644
--- a/frontend/src/plugins/impl/data-frames/schema.ts
+++ b/frontend/src/plugins/impl/data-frames/schema.ts
@@ -1,6 +1,7 @@
/* Copyright 2024 Marimo. All rights reserved. */
import {
AGGREGATION_FNS,
+ ColumnId,
NUMPY_DTYPES,
} from "@/plugins/impl/data-frames/types";
import {
@@ -17,6 +18,8 @@ import {
const column_id = z
.string()
.min(1, "Required")
+ .or(z.number())
+ .transform((v) => v as ColumnId)
.describe(FieldOptions.of({ label: "Column", special: "column_id" }));
const column_id_array = z
@@ -48,6 +51,7 @@ const RenameColumnTransformSchema = z.object({
new_column_id: z
.string()
.min(1, "Required")
+ .transform((v) => v as ColumnId)
.describe(FieldOptions.of({ label: "New column name" })),
});
diff --git a/frontend/src/plugins/impl/data-frames/types.ts b/frontend/src/plugins/impl/data-frames/types.ts
index 757dc56b27..1208b48bcc 100644
--- a/frontend/src/plugins/impl/data-frames/types.ts
+++ b/frontend/src/plugins/impl/data-frames/types.ts
@@ -1,11 +1,21 @@
/* Copyright 2024 Marimo. All rights reserved. */
/**
- * Map of column id to data type
+ * Strongly typed string/number
*/
-export interface ColumnDataTypes {
- [column_id: string]: string;
-}
+export type ColumnId = (string | number) & { __columnId: "columnId" };
+
+/**
+ * List of column Id and their data types
+ *
+ * We cannot use a js map, since maps don't preserve keys as ints (e.g. "1" and 1 are the same key)
+ */
+export type RawColumnDataTypes = Array<[ColumnId, string]>;
+/**
+ * Map of column Id and their data types
+ * ES6 maps preserve keys as ints (e.g. "1" and 1 are different keys)
+ */
+export type ColumnDataTypes = Map<ColumnId, string>;
export const NUMPY_DTYPES = [
"int8",
diff --git a/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts b/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts
index f6ae0462b0..4e6a4d52d0 100644
--- a/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts
@@ -2,50 +2,51 @@
import { expect, describe, it } from "vitest";
import { getUpdatedColumnTypes } from "../getUpdatedColumnTypes";
import { TransformType } from "../../schema";
+import { ColumnId } from "../../types";
-const INITIAL_COLUMN_TYPES = {
- col1: "str",
- col2: "bool",
- col3: "int",
-};
+const INITIAL_COLUMN_TYPES = new Map<ColumnId, string>([
+ ["col1" as ColumnId, "str"],
+ [2 as ColumnId, "bool"],
+ ["col3" as ColumnId, "int"],
+]);
const Transforms = {
COLUMN_CONVERSION: {
type: "column_conversion",
- column_id: "col1",
+ column_id: "col1" as ColumnId,
data_type: "bool",
errors: "ignore",
} satisfies TransformType,
RENAME_COLUMN: {
type: "rename_column",
- column_id: "col2",
- new_column_id: "newCol2",
+ column_id: 2 as ColumnId,
+ new_column_id: "newCol2" as ColumnId,
} satisfies TransformType,
GROUP_BY: {
type: "group_by",
- column_ids: ["col1", "col3"],
+ column_ids: ["col1", "col3"] as ColumnId[],
aggregation: "max",
drop_na: true,
} satisfies TransformType,
GROUP_BY_CHAINED: {
type: "group_by",
- column_ids: ["newCol2"],
+ column_ids: ["newCol2"] as ColumnId[],
aggregation: "max",
drop_na: true,
} satisfies TransformType,
AGGREGATE: {
type: "aggregate",
- column_ids: ["col1"],
+ column_ids: ["col1"] as ColumnId[],
aggregations: ["max"],
} satisfies TransformType,
AGGREGATE_CHAINED: {
type: "aggregate",
- column_ids: ["col1", "col3"],
+ column_ids: ["col1", "col3"] as ColumnId[],
aggregations: ["max"],
} satisfies TransformType,
SELECT_COLUMNS: {
type: "select_columns",
- column_ids: ["col1", "col2"],
+ column_ids: ["col1", 2] as ColumnId[],
} satisfies TransformType,
};
@@ -56,10 +57,10 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col1": "bool",
- "col2": "bool",
- "col3": "int",
+ Map {
+ "col1" => "bool",
+ 2 => "bool",
+ "col3" => "int",
}
`);
});
@@ -70,10 +71,10 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col1": "str",
- "col3": "int",
- "newCol2": "bool",
+ Map {
+ "col1" => "str",
+ "col3" => "int",
+ "newCol2" => "bool",
}
`);
});
@@ -84,8 +85,8 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col2": "bool",
+ Map {
+ 2 => "bool",
}
`);
});
@@ -96,8 +97,8 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col1": "str",
+ Map {
+ "col1" => "str",
}
`);
});
@@ -108,9 +109,9 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col1": "str",
- "col2": "bool",
+ Map {
+ "col1" => "str",
+ 2 => "bool",
}
`);
});
@@ -126,9 +127,9 @@ describe("getUpdatedColumnTypes", () => {
INITIAL_COLUMN_TYPES,
);
expect(result).toMatchInlineSnapshot(`
- {
- "col1": "bool",
- "col3": "int",
+ Map {
+ "col1" => "bool",
+ "col3" => "int",
}
`);
});
diff --git a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
index edd6307f4d..9d2aabc18a 100644
--- a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { logNever } from "@/utils/assertNever";
import { TransformType } from "../schema";
-import { Objects } from "@/utils/objects";
import { ColumnDataTypes } from "../types";
+import { Maps } from "@/utils/maps";
/**
* Given a list of transforms, return the updated column names/types.
@@ -15,7 +15,7 @@ export function getUpdatedColumnTypes(
return columnTypes;
}
- let next: ColumnDataTypes = { ...columnTypes };
+ let next: ColumnDataTypes = new Map(columnTypes);
for (const transform of transforms) {
next = handleTransform(transform, next);
}
@@ -33,33 +33,25 @@ function handleTransform(
return next;
}
- next[transform.column_id] = transform.data_type;
+ next.set(transform.column_id, transform.data_type);
return next;
- case "rename_column":
+ case "rename_column": {
if (!transform.new_column_id) {
return next;
}
- return Objects.fromEntries(
- Objects.entries(next).map(([k, v]) => {
- if (k === transform.column_id) {
- return [transform.new_column_id, v];
- }
- return [k, v];
- }),
- );
+ const type = next.get(transform.column_id);
+ if (type) {
+ next.set(transform.new_column_id, type);
+ next.delete(transform.column_id);
+ }
+ return next;
+ }
case "group_by":
- return Objects.filter(
- next,
- (_v, k) => !transform.column_ids.includes(k as string),
- );
+ return Maps.filterMap(next, (_v, k) => !transform.column_ids.includes(k));
case "aggregate":
- return Objects.filter(next, (_v, k) =>
- transform.column_ids.includes(k as string),
- );
+ return Maps.filterMap(next, (_v, k) => transform.column_ids.includes(k));
case "select_columns":
- return Objects.filter(next, (_v, k) =>
- transform.column_ids.includes(k as string),
- );
+ return Maps.filterMap(next, (_v, k) => transform.column_ids.includes(k));
case "filter_rows":
case "shuffle_rows":
case "sample_rows":
diff --git a/frontend/src/plugins/impl/data-frames/utils/operators.ts b/frontend/src/plugins/impl/data-frames/utils/operators.ts
index eb3aaaf3ea..e101ce2a14 100644
--- a/frontend/src/plugins/impl/data-frames/utils/operators.ts
+++ b/frontend/src/plugins/impl/data-frames/utils/operators.ts
@@ -65,7 +65,9 @@ export const ALL_OPERATORS = {
export type OperatorType = keyof typeof ALL_OPERATORS;
-export function getOperatorForDtype(dtype: string): readonly string[] {
+export function getOperatorForDtype(
+ dtype: string | undefined,
+): readonly string[] {
if (!dtype) {
return [];
}
@@ -84,7 +86,7 @@ export function getOperatorForDtype(dtype: string): readonly string[] {
}
export function getSchemaForOperator(
- dtype: string,
+ dtype: string | undefined,
operator: string,
): [z.ZodType] | [] {
if (!dtype || !operator) {
diff --git a/frontend/src/stories/dataframe.stories.tsx b/frontend/src/stories/dataframe.stories.tsx
index 33e31e33df..fb9bdcbf92 100644
--- a/frontend/src/stories/dataframe.stories.tsx
+++ b/frontend/src/stories/dataframe.stories.tsx
@@ -4,6 +4,7 @@ import type { Meta, StoryObj } from "@storybook/react";
import { useState } from "react";
import { DataFrameComponent } from "@/plugins/impl/data-frames/DataFramePlugin";
import { Transformations } from "@/plugins/impl/data-frames/schema";
+import { ColumnId } from "@/plugins/impl/data-frames/types";
const meta: Meta = {
title: "DataFrame",
@@ -21,12 +22,14 @@ export const DataFrame: StoryObj = {
values: Array.from({ length: 100 }).map((_, i) => `value ${i}`),
too_many_values: false,
})}
- columns={{
- name: "object",
- age: "int",
- height: "float",
- picture: "bytes",
- }}
+ columns={
+ new Map<ColumnId, string>([
+ ["name" as ColumnId, "object"],
+ ["age" as ColumnId, "int"],
+ ["height" as ColumnId, "float"],
+ ["picture" as ColumnId, "bytes"],
+ ])
+ }
dataframeName={"df"}
pageSize={5}
value={value}
diff --git a/frontend/src/utils/maps.ts b/frontend/src/utils/maps.ts
index 6b98c20a8e..84016fd232 100644
--- a/frontend/src/utils/maps.ts
+++ b/frontend/src/utils/maps.ts
@@ -28,4 +28,26 @@ export const Maps = {
return map;
},
+ filterMap<K, V>(
+ map: Map<K, V>,
+ predicate: (value: V, key: K) => boolean,
+ ): Map<K, V> {
+ const result = new Map<K, V>();
+ for (const [key, value] of map) {
+ if (predicate(value, key)) {
+ result.set(key, value);
+ }
+ }
+ return result;
+ },
+ mapValues<K, V, V2>(
+ map: Map<K, V>,
+ mapper: (value: V, key: K) => V2,
+ ): Map<K, V2> {
+ const result = new Map<K, V2>();
+ for (const [key, value] of map) {
+ result.set(key, mapper(value, key));
+ }
+ return result;
+ },
};
diff --git a/frontend/vitest.config.ts b/frontend/vitest.config.ts
index 4fb295ecb5..ddb37f69bd 100644
--- a/frontend/vitest.config.ts
+++ b/frontend/vitest.config.ts
@@ -5,7 +5,7 @@ import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
test: {
environment: "jsdom",
- include: ["src/**/*.test.ts"],
+ include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
setupFiles: ["src/__tests__/setup.ts"],
},
plugins: [tsconfigPaths()],
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index 1cc614e390..c93414c989 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -203,6 +203,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
self._value_frontend = initial_value
self._value = self._initial_value = self._convert_value(initial_value)
self._on_change = on_change
+ self._component_args = args
self._inner_text = build_ui_plugin(
component_name,
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 42ac1e6c88..02e99171a4 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -3,7 +3,16 @@ from __future__ import annotations
import inspect
import sys
-from typing import TYPE_CHECKING, Any, Callable, Dict, Final, List, Optional
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ Final,
+ List,
+ Optional,
+ Union,
+)
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.dataframes.handlers import TransformsContainer
@@ -129,7 +138,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
on_change=on_change,
label="",
args={
- "columns": df.dtypes.to_dict(),
+ "columns": self._get_column_types(),
"dataframe-name": dataframe_name,
"total": len(df),
"page-size": page_size,
@@ -148,6 +157,9 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
),
)
+ def _get_column_types(self) -> List[List[Union[str, int]]]:
+ return [[name, dtype] for name, dtype in self._data.dtypes.items()] # type: ignore
+
def get_dataframe(self, _args: EmptyArgs) -> GetDataFrameResponse:
# Only get the first 100 (for performance reasons)
# Could make this configurable in the arguments later if desired.
@@ -173,7 +185,7 @@ class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):
LIMIT = 500
if args.column not in self._data.columns:
- ColumnNotFound(args.column)
+ raise ColumnNotFound(args.column)
# We get the unique values from the original dataframe, not the
# transformed one
diff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.py
index bebff7c739..7344e7a392 100644
--- a/marimo/_plugins/ui/_impl/dataframes/handlers.py
+++ b/marimo/_plugins/ui/_impl/dataframes/handlers.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from typing import TYPE_CHECKING, Any, List, NoReturn, cast
from marimo._plugins.ui._impl.dataframes.transforms import (
@@ -88,7 +90,7 @@ class TransformHandlers:
df: "pd.DataFrame", transform: SortColumnTransform
) -> "pd.DataFrame":
return df.sort_values(
- by=transform.column_id,
+ by=cast(str, transform.column_id),
ascending=transform.ascending,
na_position=transform.na_position,
)
diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms.py b/marimo/_plugins/ui/_impl/dataframes/transforms.py
index 3bae7e5c0b..819fcb9cdc 100644
--- a/marimo/_plugins/ui/_impl/dataframes/transforms.py
+++ b/marimo/_plugins/ui/_impl/dataframes/transforms.py
@@ -5,7 +5,7 @@ from dataclasses import dataclass
from enum import Enum
from typing import Any, List, Literal, Optional, Union
-ColumnId = str
+ColumnId = Union[str, int]
ColumnIds = List[ColumnId]
NumpyDataType = str
Operator = Literal[
diff --git a/marimo/_smoke_tests/bugs/1319.py b/marimo/_smoke_tests/bugs/1319.py
new file mode 100644
index 0000000000..bd438e2663
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/1319.py
@@ -0,0 +1,52 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.4.11"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __():
+ import pandas as pd
+ return pd,
+
+
+def __():
+ import random
+
+
+ def row(columns):
+ return [
+ "".join(random.choices("abcdefghikjlmnopqrstuvwxyz", k=8)),
+ "".join(random.choices("abcdefghikjlmnopqrstuvwxyz", k=8)),
+ ] + [random.randint(1000, 100000) for i in range(columns - 2)]
+ return random, row
+
+
+def __(pd, row):
+ df = pd.DataFrame([row(3) for _ in range(10)])
+ return df,
+
+
+def __():
+ return
+
+
+def __(df, mo):
+ uidf = mo.ui.dataframe(df)
+ uidf
+ return uidf,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
new file mode 100644
index 0000000000..750c464cf6
--- /dev/null
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -0,0 +1,61 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins import ui
+from marimo._plugins.ui._impl.dataframes.dataframe import (
+ ColumnNotFound,
+ GetColumnValuesArgs,
+ GetColumnValuesResponse,
+)
+
+HAS_DEPS = DependencyManager.has_pandas()
+
+if HAS_DEPS:
+ import numpy as np
+ import pandas as pd
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_dataframe() -> None:
+ df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
+
+ subject = ui.dataframe(df)
+
+ assert subject.value is df
+ assert subject._component_args["columns"] == [
+ ["A", np.dtype("int64")],
+ ["B", np.dtype("O")],
+ ]
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column="A")
+ ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column="B")
+ ) == GetColumnValuesResponse(values=["a"], too_many_values=False)
+
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="idk"))
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_dataframe_numeric_columns() -> None:
+ df = pd.DataFrame({1: [1, 2, 3], 2: ["a", "a", "a"]})
+
+ subject = ui.dataframe(df)
+
+ assert subject.value is df
+ assert subject._component_args["columns"] == [
+ [1, np.dtype("int64")],
+ [2, np.dtype("O")],
+ ]
+
+ assert subject.get_column_values(
+ GetColumnValuesArgs(column=1)
+ ) == GetColumnValuesResponse(values=[1, 2, 3], too_many_values=False)
+
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="idk"))
+ with pytest.raises(ColumnNotFound):
+ subject.get_column_values(GetColumnValuesArgs(column="1"))
diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
index 7ad2e166f5..53fcbf739b 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
import pytest
from marimo._dependencies.dependencies import DependencyManager
@@ -225,6 +227,29 @@ class TestHandlers:
result = TestHandlers.apply(df, transform)
assert result["A"].tolist() == [True, True]
+ @staticmethod
+ def test_handle_filter_rows_unknown_column() -> None:
+ df = pd.DataFrame({"A": [1, 2, 3]})
+ transform = FilterRowsTransform(
+ type=TransformType.FILTER_ROWS,
+ operation="keep_rows",
+ where=[Condition(column_id="B", operator=">=", value=2)],
+ )
+ with pytest.raises(KeyError):
+ TestHandlers.apply(df, transform)
+
+ @staticmethod
+ def test_handle_filter_rows_number_columns() -> None:
+ df = pd.DataFrame({1: [1, 2, 3], 2: [4, 5, 6]})
+ transform = FilterRowsTransform(
+ type=TransformType.FILTER_ROWS,
+ operation="keep_rows",
+ where=[Condition(column_id=1, operator=">=", value=2)],
+ )
+ result = TestHandlers.apply(df, transform)
+ assert result[1].tolist() == [2, 3]
+ assert result[2].tolist() == [5, 6]
+
@staticmethod
def test_handle_group_by() -> None:
df = pd.DataFrame({"A": ["foo", "foo", "bar"], "B": [1, 2, 3]})
diff --git a/tests/_plugins/ui/_impl/utils/test_dataframe.py b/tests/_plugins/ui/_impl/utils/test_dataframe_utils.py
similarity index 100%
rename from tests/_plugins/ui/_impl/utils/test_dataframe.py
rename to tests/_plugins/ui/_impl/utils/test_dataframe_utils.py