A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
mo.ui.dataframe (#223)
Myles Scolnickac64e08ad406
diff --git a/docs/api/inputs/dataframe.md b/docs/api/inputs/dataframe.mdnew file mode 100644index 0000000000..e27430049a--- /dev/null+++ b/docs/api/inputs/dataframe.md@@ -0,0 +1,28 @@+# Dataframe++The dataframe UI element outputs a visual editor to apply "transforms" to a dataframe, such as filtering rows, applying group-bys and aggregations, and more. The transformed dataframe is shown below the transform editor. The UI output also includes the generated Python used to generate the resulting dataframe, which you can copy paste into a cell. You can programmatically access the resulting dataframe by accessing the element's `.value` attribute.++```{admonition} Pandas Required+:class: note++In order to use the dataframe UI element, you must have the `pandas` package installed.+You can install it with `pip install pandas`.+```++Supported transforms are:++- Filter Rows+- Rename Column+- Column Conversion+- Sort Column+- Group By+- Aggregate++<!-- <iframe class="demo large" src="https://components.marimo.io/?component=dataframe" frameborder="no"></iframe> -->++```{eval-rst}+.. autoclass:: marimo.ui.dataframe+ :members:++ .. autoclasstoc:: marimo._plugins.ui._impl.dataframes.dataframe.dataframe+```diff --git a/docs/api/inputs/index.md b/docs/api/inputs/index.mdindex 92d5b3a5dc..bfa180cbbe 100644--- a/docs/api/inputs/index.md+++ b/docs/api/inputs/index.md@@ -10,6 +10,7 @@buttoncheckboxchart+ dataframedatedictionarydropdown@@ -39,6 +40,7 @@ powerful notebooks and apps. These elements are available in `marimo.ui`.marimo.ui.buttonmarimo.ui.checkboxmarimo.ui.chart+ marimo.ui.dataframemarimo.ui.datemarimo.ui.dictionarymarimo.ui.dropdowndiff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlindex c1c1c65bc8..18870a1cc2 100644--- a/frontend/.storybook/preview-head.html+++ b/frontend/.storybook/preview-head.html@@ -1,7 +1,7 @@<marimo-filename hidden>app.py</marimo-filename><marimo-mode data-mode="edit" hidden></marimo-mode><marimo-user-config- data-config='{"completion":{"activate_on_typing":false},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{"theming":true}}'+ data-config='{"completion":{"activate_on_typing":false, "copilot": true},"save":{"autosave":"off","autosave_delay":0},"keymap":{"preset":"default"},"experimental":{"theming":true}}'hidden></marimo-user-config><marimo-app-config data-config="{}" hidden></marimo-app-config>diff --git a/frontend/package.json b/frontend/package.jsonindex 81939be1c5..e0a0dfb972 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -59,6 +59,7 @@"@textea/json-viewer": "^3.2.2","@types/js-cookie": "^3.0.5","@types/react-grid-layout": "^1.3.4",+ "@uiw/react-codemirror": "^4.21.19","class-variance-authority": "^0.7.0","clsx": "^1.2.1","cmdk": "^0.2.0",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 35b524dac2..a136f28be6 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -149,6 +149,9 @@ dependencies:'@types/react-grid-layout':specifier: ^1.3.4version: 1.3.4+ '@uiw/react-codemirror':+ specifier: ^4.21.19+ version: 4.21.19(@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected])([email protected])class-variance-authority:specifier: ^0.7.0version: 0.7.0@@ -6393,6 +6396,53 @@ packages:eslint-visitor-keys: 3.4.1dev: true+ /@uiw/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected]):+ resolution: {integrity: sha512-FwnzjNSc1mbzlcOlGmZgK2JMFcmPSHDeDUoql4ioyffF6ytiUD6LB9exOlQlAppzAZkKBYHqBwBjd0gdJYpH/w==}+ peerDependencies:+ '@codemirror/autocomplete': '>=6.0.0'+ '@codemirror/commands': '>=6.0.0'+ '@codemirror/language': '>=6.0.0'+ '@codemirror/lint': '>=6.0.0'+ '@codemirror/search': '>=6.0.0'+ '@codemirror/state': '>=6.0.0'+ '@codemirror/view': '>=6.0.0'+ dependencies:+ '@codemirror/autocomplete': 6.10.2(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@lezer/[email protected])+ '@codemirror/commands': 6.3.0+ '@codemirror/language': 6.9.1+ '@codemirror/lint': 6.4.2+ '@codemirror/search': 6.5.4+ '@codemirror/state': 6.3.1+ '@codemirror/view': 6.21.3+ dev: false++ /@uiw/[email protected](@babel/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])([email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-KCm+izhkeRCz9uuPY4WtlMAwEE6HsGR/iHGFDABj2OFq9DfnpAIFyVx2Z87NxMHvHi7zttn6JerxwNLJdV12og==}+ peerDependencies:+ '@babel/runtime': '>=7.11.0'+ '@codemirror/state': '>=6.0.0'+ '@codemirror/theme-one-dark': '>=6.0.0'+ '@codemirror/view': '>=6.0.0'+ codemirror: '>=6.0.0'+ react: '>=16.8.0'+ react-dom: '>=16.8.0'+ dependencies:+ '@babel/runtime': 7.22.5+ '@codemirror/commands': 6.3.0+ '@codemirror/state': 6.3.1+ '@codemirror/theme-one-dark': 6.1.2+ '@codemirror/view': 6.21.3+ '@uiw/codemirror-extensions-basic-setup': 4.21.19(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])+ codemirror: 6.0.1(@lezer/[email protected])+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ transitivePeerDependencies:+ - '@codemirror/autocomplete'+ - '@codemirror/language'+ - '@codemirror/lint'+ - '@codemirror/search'+ dev: false+/@vitejs/[email protected]([email protected]):resolution: {integrity: sha512-m7UaA4Uvz82N/0EOVpZL4XsFIakRqrFKeSNxa1FBLSXGvWrWRBwmZb4qxk+ZIVAZcW3c3dn5YosomDgx62XWcQ==}peerDependencies:diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex bb8c7f93c0..9184cc83b8 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -98,6 +98,7 @@ export function generateColumns<T>(table.toggleAllPageRowsSelected(!!value)}aria-label="Select all"+ className="mx-2"/>) : null,cell: ({ row }) => (@@ -105,7 +106,7 @@ export function generateColumns<T>(checked={row.getIsSelected()}onCheckedChange={(value) => row.toggleSelected(!!value)}aria-label="Select row"- className="ml-1"+ className="mx-2"/>),enableSorting: false,diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 507b7c39d1..614e8fc4da 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -23,8 +23,10 @@ import {} from "@/components/ui/table";import { DataTablePagination } from "./pagination";import { DownloadActionProps, DownloadAs } from "./download-actions";+import { cn } from "@/lib/utils";interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {+ className?: string;columns: Array<ColumnDef<TData, TValue>>;data: TData[];pagination?: boolean;@@ -35,6 +37,7 @@ interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {}export const DataTable = <TData, TValue>({+ className,columns,data,rowSelection,@@ -70,8 +73,8 @@ export const DataTable = <TData, TValue>({});return (- <div className="flex flex-col space-y-4">- <div className="rounded-md border">+ <div className="flex flex-col space-y-2">+ <div className={cn(className || "rounded-md border")}><Table><TableHeader>{table.getHeaderGroups().map((headerGroup) => (diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsxindex 66fb020d8c..012ff1bdd3 100644--- a/frontend/src/components/data-table/pagination.tsx+++ b/frontend/src/components/data-table/pagination.tsx@@ -80,8 +80,12 @@ export const DataTablePagination = <TData,>({<ChevronLeft className="h-4 w-4" /></Button><div className="flex w-[100px] items-center justify-center text-xs font-medium">- Page {table.getState().pagination.pageIndex + 1} of{" "}- {table.getPageCount()}+ Page{" "}+ {Math.min(+ table.getState().pagination.pageIndex + 1,+ table.getPageCount()+ )}{" "}+ of {table.getPageCount()}</div><Buttonsize="xs"diff --git a/frontend/src/components/ui/alert-dialog.tsx b/frontend/src/components/ui/alert-dialog.tsxindex 5c49e35e03..76997c3e4f 100644--- a/frontend/src/components/ui/alert-dialog.tsx+++ b/frontend/src/components/ui/alert-dialog.tsx@@ -50,7 +50,7 @@ const AlertDialogContent = React.forwardRef<<AlertDialogPrimitive.Contentref={ref}className={cn(- "fixed z-50 grid w-full max-w-lg scale-100 gap-4 border bg-background p-6 opacity-100 shadow-sm animate-in fade-in-90 slide-in-from-bottom-10 sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full",+ "fixed z-50 grid w-full max-w-2xl scale-100 gap-4 border bg-background p-6 opacity-100 shadow-sm animate-in fade-in-90 slide-in-from-bottom-10 sm:rounded-lg sm:zoom-in-90 sm:slide-in-from-bottom-0 md:w-full",className)}{...restoreFocus}diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsxindex 2b994ebc00..0a65a20afc 100644--- a/frontend/src/components/ui/button.tsx+++ b/frontend/src/components/ui/button.tsx@@ -66,7 +66,7 @@ const buttonVariants = cva(},size: {default: "h-10 py-2 px-4",- xs: "h-7 px-2 rounded-md",+ xs: "h-7 px-2 rounded-md text-xs",sm: "h-9 px-3 rounded-md",lg: "h-11 px-8 rounded-md",icon: "h-6 w-6",diff --git a/frontend/src/components/ui/dropdown-menu.tsx b/frontend/src/components/ui/dropdown-menu.tsxindex 6bd6f67935..3460b9ab99 100644--- a/frontend/src/components/ui/dropdown-menu.tsx+++ b/frontend/src/components/ui/dropdown-menu.tsx@@ -149,7 +149,7 @@ const DropdownMenuSeparator = React.forwardRef<>(({ className, ...props }, ref) => (<DropdownMenuPrimitive.Separatorref={ref}- className={menuSeparatorVariants({ className })}+ className={cn("mb-1", menuSeparatorVariants({ className }))}{...props}/>));diff --git a/frontend/src/components/ui/form.tsx b/frontend/src/components/ui/form.tsxindex 27d82d347c..25c0edbbb5 100644--- a/frontend/src/components/ui/form.tsx+++ b/frontend/src/components/ui/form.tsx@@ -13,6 +13,8 @@ import {import { cn } from "@/lib/utils";import { Label } from "@/components/ui/label";+import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";+import { AlertCircleIcon } from "lucide-react";const Form = FormProvider;@@ -79,7 +81,11 @@ const FormItem = React.forwardRef<return (<FormItemContext.Provider value={{ id }}>- <div ref={ref} className={cn("space-y-1", className)} {...props} />+ <div+ ref={ref}+ className={cn("flex flex-col gap-1", className)}+ {...props}+ /></FormItemContext.Provider>);});@@ -91,6 +97,10 @@ const FormLabel = React.forwardRef<>(({ className, ...props }, ref) => {const { error, formItemId } = useFormField();+ if (!props.children) {+ return;+ }+return (<Labelref={ref}@@ -129,6 +139,10 @@ const FormDescription = React.forwardRef<>(({ className, ...props }, ref) => {const { formDescriptionId } = useFormField();+ if (!props.children) {+ return null;+ }+return (<pref={ref}@@ -145,7 +159,7 @@ const FormMessage = React.forwardRef<React.HTMLAttributes<HTMLParagraphElement>>(({ className, children, ...props }, ref) => {const { error, formMessageId } = useFormField();- const body = error ? String(error?.message) : children;+ const body = error && error?.message ? String(error?.message) : children;if (!body) {return null;@@ -155,7 +169,7 @@ const FormMessage = React.forwardRef<<pref={ref}id={formMessageId}- className={cn("text-sm font-medium text-destructive", className)}+ className={cn("text-xs font-medium text-destructive", className)}{...props}>{body}@@ -164,6 +178,24 @@ const FormMessage = React.forwardRef<});FormMessage.displayName = "FormMessage";+const FormMessageTooltip = ({ className }: { className: string }) => {+ const { error } = useFormField();+ const body = error && error?.message ? String(error?.message) : null;++ if (!body) {+ return null;+ }++ return (+ <TooltipProvider>+ <Tooltip content={body}>+ <AlertCircleIcon className={cn("stroke-[1.8px]", className)} />+ </Tooltip>+ </TooltipProvider>+ );+};+FormMessageTooltip.displayName = "FormMessageTooltip";+export {useFormField,Form,@@ -172,5 +204,6 @@ export {FormControl,FormDescription,FormMessage,+ FormMessageTooltip,FormField,};diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsxindex 9148a505a1..12ab5117b4 100644--- a/frontend/src/components/ui/input.tsx+++ b/frontend/src/components/ui/input.tsx@@ -2,6 +2,7 @@import * as React from "react";import { cn } from "@/lib/utils";+import { useDebounceControlledState } from "@/hooks/useDebounce";import { Events } from "@/utils/events";export type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {@@ -13,6 +14,10 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>(({ className, type, endAdornment, ...props }, ref) => {const icon = props.icon;+ if (type === "hidden") {+ return <input type="hidden" ref={ref} {...props} />;+ }+return (<div className="relative">{icon && (@@ -44,4 +49,57 @@ const Input = React.forwardRef<HTMLInputElement, InputProps>();Input.displayName = "Input";+export const DebouncedInput = React.forwardRef<+ HTMLInputElement,+ InputProps & {+ value: string;+ onValueChange: (value: string) => void;+ }+>(({ className, onValueChange, ...props }, ref) => {+ // Create a debounced value of 200+ const { value, onChange } = useDebounceControlledState<string>({+ initialValue: props.value,+ delay: 200,+ onChange: onValueChange,+ });++ return (+ <Input+ ref={ref}+ className={className}+ {...props}+ onChange={(evt) => onChange(evt.target.value)}+ value={value}+ />+ );+});+DebouncedInput.displayName = "DebouncedInput";++export const DebouncedNumberInput = React.forwardRef<+ HTMLInputElement,+ InputProps & {+ value: number;+ onValueChange: (valueAsNumber: number) => void;+ }+>(({ className, onValueChange, ...props }, ref) => {+ // Create a debounced value of 200+ const { value, onChange } = useDebounceControlledState<number>({+ initialValue: props.value,+ delay: 200,+ onChange: onValueChange,+ });++ return (+ <Input+ ref={ref}+ type="number"+ className={className}+ {...props}+ onChange={(evt) => onChange(evt.target.valueAsNumber)}+ value={value}+ />+ );+});+DebouncedNumberInput.displayName = "DebouncedNumberInput";+export { Input };diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsxindex 1eb6f400f3..1ede499523 100644--- a/frontend/src/components/ui/select.tsx+++ b/frontend/src/components/ui/select.tsx@@ -18,7 +18,7 @@ const SelectTrigger = React.forwardRef<<SelectPrimitive.Triggerref={ref}className={cn(- "flex h-7 items-center justify-between rounded-md border border-input shadow-sm bg-transparent px-2 py-1 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",+ "flex h-7 items-center justify-between rounded-md border border-input shadow-sm bg-transparent px-2 py-1 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50",className)}{...props}@@ -39,7 +39,7 @@ const SelectContent = React.forwardRef<<SelectPrimitive.Contentref={ref}className={cn(- "relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",+ "max-h-[300px] relative z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",position === "popper" &&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",classNamediff --git a/frontend/src/components/ui/table.tsx b/frontend/src/components/ui/table.tsxindex 9618f51ae8..5720982cb4 100644--- a/frontend/src/components/ui/table.tsx+++ b/frontend/src/components/ui/table.tsx@@ -71,7 +71,7 @@ const TableHead = React.forwardRef<<thref={ref}className={cn(- "h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",+ "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",className)}{...props}@@ -85,7 +85,7 @@ const TableCell = React.forwardRef<>(({ className, ...props }, ref) => (<tdref={ref}- className={cn("p-3 align-middle [&:has([role=checkbox])]:pr-0", className)}+ className={cn("p-2 align-middle [&:has([role=checkbox])]:pr-0", className)}{...props}/>));diff --git a/frontend/src/components/ui/tabs.tsx b/frontend/src/components/ui/tabs.tsxindex 6fd5dd8995..feffcf32ca 100644--- a/frontend/src/components/ui/tabs.tsx+++ b/frontend/src/components/ui/tabs.tsx@@ -28,7 +28,7 @@ const TabsTrigger = React.forwardRef<<TabsPrimitive.Triggerref={ref}className={cn(- "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",+ "inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",className)}{...props}@@ -43,7 +43,7 @@ const TabsContent = React.forwardRef<<TabsPrimitive.Contentref={ref}className={cn(- "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",+ "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2",className)}{...props}diff --git a/frontend/src/core/dom/__tests__/htmlUtils.test.ts b/frontend/src/core/dom/__tests__/htmlUtils.test.tsindex 37e839ba75..8812c65786 100644--- a/frontend/src/core/dom/__tests__/htmlUtils.test.ts+++ b/frontend/src/core/dom/__tests__/htmlUtils.test.ts@@ -1,6 +1,6 @@/* Copyright 2023 Marimo. All rights reserved. */import { describe, expect, it } from "vitest";-import { parseAttrValue, parseInitialValue } from "../htmlUtils";+import { parseInitialValue } from "../htmlUtils";describe("htmlUtils", () => {it.each([false, { a: 1 }, true, 0, 1, [{ a: 1 }, { b: 2 }], "hello", ""])(@@ -17,48 +17,3 @@ describe("htmlUtils", () => {expect(parseInitialValue(div)).toEqual({});});});--it("can parseAttrValue happy path", () => {- expect(parseAttrValue('"hello"')).toEqual("hello");- expect(- parseAttrValue('[false,{"a":1},true,0,1,[{"a":1},{"b":2}],"hello",""]')- ).toEqual([false, { a: 1 }, true, 0, 1, [{ a: 1 }, { b: 2 }], "hello", ""]);-- expect(parseAttrValue("10")).toEqual(10);- expect(parseAttrValue("null")).toEqual(null);-});--it("can parseAttrValue NaN, Infinity, -Infinity", () => {- expect(parseAttrValue("NaN")).toEqual(Number.NaN);- expect(parseAttrValue('{"A":NaN}')).toEqual({ A: Number.NaN });- expect(parseAttrValue("[NaN]")).toEqual([Number.NaN]);- expect(parseAttrValue("[-Infinity]")).toEqual([Number.NEGATIVE_INFINITY]);- expect(parseAttrValue("[Infinity]")).toEqual([Number.POSITIVE_INFINITY]);- expect(parseAttrValue('[NaN,Infinity,-Infinity,{"A": NaN}]')).toEqual([- Number.NaN,- Number.POSITIVE_INFINITY,- Number.NEGATIVE_INFINITY,- { A: Number.NaN },- ]);-- // Prevent false positives as text- expect(parseAttrValue('"NaN"')).toEqual("NaN");- expect(parseAttrValue('"Infinity"')).toEqual("Infinity");- expect(parseAttrValue('"-Infinity"')).toEqual("-Infinity");-- expect(parseAttrValue('"This is NaN"')).toEqual("This is NaN");- expect(parseAttrValue('"To Infinity and Beyond"')).toEqual(- "To Infinity and Beyond"- );- expect(parseAttrValue('"To -Infinity and Beyond"')).toEqual(- "To -Infinity and Beyond"- );-});--it("can fail to parseAttrValue", () => {- // Fail to parse- expect(parseAttrValue("")).toMatchInlineSnapshot("{}");- expect(parseAttrValue("undefined")).toMatchInlineSnapshot("{}");- expect(parseAttrValue(undefined)).toMatchInlineSnapshot("{}");- expect(parseAttrValue("[nan]")).toMatchInlineSnapshot("{}");-});diff --git a/frontend/src/core/dom/htmlUtils.ts b/frontend/src/core/dom/htmlUtils.tsindex 9c218c56a4..32a9fe0fd4 100644--- a/frontend/src/core/dom/htmlUtils.ts+++ b/frontend/src/core/dom/htmlUtils.ts@@ -1,42 +1,13 @@/* Copyright 2023 Marimo. All rights reserved. */import { assertExists } from "@/utils/assertExists";import { UI_ELEMENT_REGISTRY } from "./uiregistry";--// Random unicode character that is unlikely to be used in the JSON string-const CHAR = "◐";+import { jsonParseWithSpecialChar } from "@/utils/json-parser";/*** Parse an attribute value as JSON.*/export function parseAttrValue<T>(value: string | undefined): T {- try {- // This will properly handle NaN, Infinity, and -Infinity- // The python json.dumps encoding will serialize to NaN, Infinity, -Infinity which is not valid JSON,- // but we don't want to change the python encoding because NaN, Infinity, -Infinity are valuable to know.- value = value ?? "";- value = value.replaceAll(- // This was iterated on with GPT. The confidence lies in the unit tests.- /(?<=\s|^|\[|,|:)(NaN|-Infinity|Infinity)(?=(?:[^"'\\]*(\\.|'([^'\\]*\\.)*[^'\\]*'|"([^"\\]*\\.)*[^"\\]*"))*[^"']*$)/g,- `"${CHAR}$1${CHAR}"`- );- return JSON.parse(value, (key, v) => {- if (typeof v !== "string") {- return v;- }- if (v === `${CHAR}NaN${CHAR}`) {- return Number.NaN;- }- if (v === `${CHAR}Infinity${CHAR}`) {- return Number.POSITIVE_INFINITY;- }- if (v === `${CHAR}-Infinity${CHAR}`) {- return Number.NEGATIVE_INFINITY;- }- return v;- }) as T;- } catch {- return {} as T;- }+ return jsonParseWithSpecialChar(value ?? "");}/**diff --git a/frontend/src/core/websocket/useMarimoWebSocket.tsx b/frontend/src/core/websocket/useMarimoWebSocket.tsxindex ecef4f823d..8830a4169b 100644--- a/frontend/src/core/websocket/useMarimoWebSocket.tsx+++ b/frontend/src/core/websocket/useMarimoWebSocket.tsx@@ -21,6 +21,8 @@ import { useVariablesActions } from "../variables/state";import { toast } from "@/components/ui/use-toast";import { renderHTML } from "@/plugins/core/RenderHTML";import { FUNCTIONS_REGISTRY } from "../functions/FunctionRegistry";+import { jsonParseWithSpecialChar } from "@/utils/json-parser";+import { prettyError } from "@/utils/errors";/*** WebSocket that connects to the Marimo kernel and handles incoming messages.@@ -47,6 +49,133 @@ export function useMarimoWebSocket(opts: {const setLayoutData = useSetAtom(layoutDataAtom);const [connStatus, setConnStatus] = useAtom(connectionAtom);+ const handleMessage = (e: MessageEvent<string>) => {+ const msg = jsonParseWithSpecialChar<OperationMessage>(e.data);+ switch (msg.op) {+ case "kernel-ready": {+ const { codes, names, layout, configs } = msg.data;++ // TODO(akshayka): Get rid of this once the kernel sends cell IDs in+ // kernel-ready.+ CellId.reset();++ // Set the layout, initial codes, cells+ const cells = codes.map((code, i) =>+ createCell({+ key: CellId.create(),+ code,+ edited: !autoInstantiate,+ name: names[i],+ config: configs[i],+ })+ );+ if (layout) {+ setLayoutView(layout.type);+ setLayoutData(deserializeLayout(layout.type, layout.data, cells));+ }+ setCells(cells);+ setInitialCodes(codes);+ setInitialConfigs(configs);++ // Auto-instantiate, in future this can be configurable+ // or include initial values+ const objectIds: string[] = [];+ const values: unknown[] = [];+ // If we already have values for some objects, we should+ // send them to the kernel. This may happen after re-connecting+ // to the kernel after the computer wakes from sleep.+ UI_ELEMENT_REGISTRY.entries.forEach((entry, objectId) => {+ objectIds.push(objectId);+ values.push(entry.value);+ });+ // Start the run+ RuntimeState.INSTANCE.registerRunStart();+ // Register the configs+ saveCellConfig({+ configs: Object.fromEntries(+ cells.map((cell) => [cell.key, cell.config])+ ),+ }).catch((error) => {+ showBoundary(+ new Error("Failed to register configs", { cause: error })+ );+ });+ // Send the instantiate message+ if (autoInstantiate) {+ sendInstantiate({ objectIds, values }).catch((error) => {+ showBoundary(new Error("Failed to instantiate", { cause: error }));+ });+ }+ return;+ }+ case "completed-run":+ case "interrupted":+ if (msg.op === "completed-run") {+ RuntimeState.INSTANCE.registerRunEnd();+ }++ if (!RuntimeState.INSTANCE.running()) {+ RuntimeState.INSTANCE.flushUpdates();+ }+ return;+ case "remove-ui-elements": {+ // This removes the element from the registry to (1) clean-up+ // memory and (2) make sure that the old value doesn't get re-used+ // if the same cell-id is later reused for another element.+ const { cell_id } = msg.data;+ UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);+ return;+ }+ case "completion-result":+ AUTOCOMPLETER.resolve(msg.data.completion_id, msg.data);+ return;+ case "function-call-result":+ FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);+ return;+ case "cell-op": {+ /* Register a state transition for a cell.+ *+ * The cell may have a new output, a new console output,+ * it may have been queued, it may have started running, or+ * it may have stopped running. Each of these things+ * affects how the cell should be rendered.+ */+ const body = msg.data;+ handleCellMessage({ cellId: body.cell_id, message: body });+ return;+ }+ case "variables":+ setVariables(+ msg.data.variables.map((v) => ({+ name: v.name,+ declaredBy: v.declared_by,+ usedBy: v.used_by,+ }))+ );+ return;+ case "variable-values":+ setMetadata(+ msg.data.variables.map((v) => ({+ name: v.name,+ dataType: v.datatype,+ value: v.value,+ }))+ );+ return;+ case "alert":+ toast({+ title: msg.data.title,+ description: renderHTML({+ html: msg.data.description,+ }),+ variant: msg.data.variant,+ });+ return;+ default:+ logNever(msg);+ }+ };+const ws = useWebSocket({/*** Unique URL for this session.@@ -63,132 +192,15 @@ export function useMarimoWebSocket(opts: {/*** Message callback. Handle messages sent by the kernel.*/- onMessage: (e: MessageEvent<string>) => {- const msg = JSON.parse(e.data) as OperationMessage;- switch (msg.op) {- case "kernel-ready": {- const { codes, names, layout, configs } = msg.data;-- // TODO(akshayka): Get rid of this once the kernel sends cell IDs in- // kernel-ready.- CellId.reset();-- // Set the layout, initial codes, cells- const cells = codes.map((code, i) =>- createCell({- key: CellId.create(),- code,- edited: !autoInstantiate,- name: names[i],- config: configs[i],- })- );- if (layout) {- setLayoutView(layout.type);- setLayoutData(deserializeLayout(layout.type, layout.data, cells));- }- setCells(cells);- setInitialCodes(codes);- setInitialConfigs(configs);-- // Auto-instantiate, in future this can be configurable- // or include initial values- const objectIds: string[] = [];- const values: unknown[] = [];- // If we already have values for some objects, we should- // send them to the kernel. This may happen after re-connecting- // to the kernel after the computer wakes from sleep.- UI_ELEMENT_REGISTRY.entries.forEach((entry, objectId) => {- objectIds.push(objectId);- values.push(entry.value);- });- // Start the run- RuntimeState.INSTANCE.registerRunStart();- // Register the configs- saveCellConfig({- configs: Object.fromEntries(- cells.map((cell) => [cell.key, cell.config])- ),- }).catch((error) => {- showBoundary(- new Error("Failed to register configs", { cause: error })- );- });- // Send the instantiate message- if (autoInstantiate) {- sendInstantiate({ objectIds, values }).catch((error) => {- showBoundary(- new Error("Failed to instantiate", { cause: error })- );- });- }- return;- }- case "completed-run":- case "interrupted":- if (msg.op === "completed-run") {- RuntimeState.INSTANCE.registerRunEnd();- }-- if (!RuntimeState.INSTANCE.running()) {- RuntimeState.INSTANCE.flushUpdates();- }- return;- case "remove-ui-elements": {- // This removes the element from the registry to (1) clean-up- // memory and (2) make sure that the old value doesn't get re-used- // if the same cell-id is later reused for another element.- const { cell_id } = msg.data;- UI_ELEMENT_REGISTRY.removeElementsByCell(cell_id);- return;- }- case "completion-result":- AUTOCOMPLETER.resolve(msg.data.completion_id, msg.data);- return;- case "function-call-result":- FUNCTIONS_REGISTRY.resolve(msg.data.function_call_id, msg.data);- return;- case "cell-op": {- /* Register a state transition for a cell.- *- * The cell may have a new output, a new console output,- * it may have been queued, it may have started running, or- * it may have stopped running. Each of these things- * affects how the cell should be rendered.- */- const body = msg.data;- handleCellMessage({ cellId: body.cell_id, message: body });- return;- }- case "variables":- setVariables(- msg.data.variables.map((v) => ({- name: v.name,- declaredBy: v.declared_by,- usedBy: v.used_by,- }))- );- return;- case "variable-values":- setMetadata(- msg.data.variables.map((v) => ({- name: v.name,- dataType: v.datatype,- value: v.value,- }))- );- return;- case "alert":- toast({- title: msg.data.title,- description: renderHTML({- html: msg.data.description,- }),- variant: msg.data.variant,- });- return;- default:- logNever(msg);+ onMessage: (e) => {+ try {+ handleMessage(e);+ } catch (error) {+ toast({+ title: "Failed to handle message",+ description: prettyError(error),+ variant: "danger",+ });}},diff --git a/frontend/src/plugins/core/registerReactComponent.tsx b/frontend/src/plugins/core/registerReactComponent.tsxindex 24395a88f9..0cfd56eaa5 100644--- a/frontend/src/plugins/core/registerReactComponent.tsx+++ b/frontend/src/plugins/core/registerReactComponent.tsx@@ -176,6 +176,7 @@ function PluginSlotInternal<T>(namespace: objectId,});if (response.status.code !== "ok") {+ Logger.error(response.status);throw new Error(response.status.message);}return output.parse(response.return_value);diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex edb34089c9..ae03491775 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -78,14 +78,18 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")});interface DataTableProps extends Data<unknown>, Functions {+ className?: string;value: S;setValue: (value: S) => void;}-const LoadingDataTableComponent = (+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" });}, [props.data]);@@ -117,6 +121,7 @@ const DataTableComponent = ({showDownload,rowHeaders,download_as: downloadAs,+ className,setValue,}: DataTableProps & {data: unknown[];@@ -133,6 +138,7 @@ const DataTableComponent = ({<DataTabledata={data}columns={columns}+ className={className}pagination={pagination}pageSize={pageSize}rowSelection={rowSelection}diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxnew file mode 100644index 0000000000..2d5352f6d3--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -0,0 +1,184 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { z } from "zod";++import { Transformations } from "./schema";+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 { 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 { prettyError } from "@/utils/errors";+import { useState } from "react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogContent,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";++/**+ * Arguments for a data table+ *+ * @param label - a label of the table+ * @param data - the data to display+ */+interface Data {+ label?: string | null;+ columns: ColumnDataTypes;+ dataframeName: string;+}++// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type PluginFunctions = {+ get_dataframe: (req: {}) => Promise<{+ url: string;+ row_headers: Array<[string, string[]]>;+ }>;+};++// Value is selection, but it is not currently exposed to the user+type S = Transformations | undefined;++export const DataFramePlugin = createPlugin<S>("marimo-dataframe")+ .withData(+ z.object({+ label: z.string().nullish(),+ dataframeName: z.string(),+ columns: z+ .object({})+ .passthrough()+ .transform((value) => value as ColumnDataTypes),+ })+ )+ .withFunctions<PluginFunctions>({+ // Get the data as a URL+ get_dataframe: rpc.input(z.object({})).output(+ z.object({+ url: z.string(),+ row_headers: z.array(z.tuple([z.string(), z.array(z.any())])),+ })+ ),+ })+ .renderer((props) => (+ <DataFrameComponent+ {...props.data}+ {...props.functions}+ value={props.value}+ setValue={props.setValue}+ />+ ));++interface DataTableProps extends Data, PluginFunctions {+ value: S;+ setValue: (value: S) => void;+}++const EMPTY: Transformations = {+ transforms: [],+};++export const DataFrameComponent = ({+ columns,+ dataframeName,+ value,+ setValue,+ get_dataframe,+}: DataTableProps): JSX.Element => {+ const { data, error } = useAsyncData(+ () => get_dataframe({}),+ [value?.transforms]+ );+ const { url, row_headers } = data || {};++ 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">+ <TransformPanel+ initialValue={internalValue}+ columns={columns}+ onChange={(v) => {+ // Update the value valid changes+ setValue(v);+ setInternalValue(v);+ }}+ onInvalidChange={setInternalValue}+ />+ </TabsContent>+ <TabsContent value="code" className="mt-1">+ <CodePanel dataframeName={dataframeName} transforms={value} />+ </TabsContent>+ </Tabs>+ {error && <ErrorBanner error={error} />}+ <LoadingDataTableComponent+ label={null}+ className="rounded-b border"+ data={url || ""}+ pageSize={5}+ pagination={true}+ rowHeaders={row_headers || Arrays.EMPTY}+ showDownload={false}+ download_as={Functions.THROW}+ value={Arrays.EMPTY}+ setValue={Functions.NOOP}+ selection={null}+ />+ </div>+ );+};++const ErrorBanner = ({ error }: { error: Error }) => {+ const [open, setOpen] = useState(false);++ if (!error) {+ return null;+ }++ const message = prettyError(error);++ return (+ <>+ <div+ className="text-error border-[var(--red-6)] bg-[var(--red-2)] text-sm p-2 border cursor-pointer hover:bg-[var(--red-3)]"+ onClick={() => setOpen(true)}+ >+ <span className="line-clamp-4">{message}</span>+ </div>+ <AlertDialog open={open} onOpenChange={setOpen}>+ <AlertDialogContent className="max-w-[80%]">+ <AlertDialogHeader>+ <AlertDialogTitle className="text-error">Error</AlertDialogTitle>+ </AlertDialogHeader>+ <div className="text-error text-sm p-2 font-mono">{message}</div>+ <AlertDialogFooter>+ <AlertDialogAction autoFocus={true} onClick={() => setOpen(false)}>+ Ok+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </>+ );+};diff --git a/frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.ts b/frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.tsnew file mode 100644index 0000000000..2cbbb67bff--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/__tests__/form-utils.test.ts@@ -0,0 +1,104 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { describe, expect, it } from "vitest";+import { getDefaults } from "@/plugins/impl/data-frames/forms/form-utils";+import { z } from "zod";++describe("getDefaults", () => {+ it("should return default value for ZodLiteral", () => {+ const schema = z.literal("default");+ const result = getDefaults(schema);+ expect(result).toBe("default");+ });++ it("should return default value for ZodDefault", () => {+ const schema = z.string().default("default");+ const result = getDefaults(schema);+ expect(result).toBe("default");+ });++ it("should return '' for ZodString without default and required", () => {+ const schema = z.string();+ const result = getDefaults(schema);+ expect(result).toBe("");+ });++ it("should return undefined for ZodString that is required", () => {+ expect(getDefaults(z.string().optional())).toBe(undefined);+ expect(getDefaults(z.string().nullish())).toBe(undefined);+ expect(getDefaults(z.optional(z.string()))).toBe(undefined);+ });++ it("should return enum value for ZodEnum", () => {+ const schema = z.enum(["default", "other"]);+ const result = getDefaults(schema);+ expect(result).toBe("default");+ });++ it("should return undefined for optional ZodEnum", () => {+ const schema = z.enum(["default", "other"]).optional();+ const result = getDefaults(schema);+ expect(result).toBe(undefined);+ });++ it("should return default value for the first option in ZodUnion", () => {+ const schema = z.union([z.literal("default"), z.string()]);+ const result = getDefaults(schema);+ expect(result).toBe("default");+ });++ it("should return default values for ZodObject", () => {+ const schema = z.object({+ string: z.string().default("default"),+ number: z.number().default(123),+ });+ const result = getDefaults(schema);+ expect(result).toEqual({+ string: "default",+ number: 123,+ });+ });++ it("should return undefined for ZodObject properties without default", () => {+ const schema = z.object({+ string: z.string(),+ number: z.number(),+ });+ const result = getDefaults(schema);+ expect(result).toEqual({+ string: undefined,+ number: undefined,+ });+ });++ it("should return default values for ZodObject and refine", () => {+ const schema = z.object({+ string: z.string().default("foo"),+ number: z.number().default(123),+ });+ const result = getDefaults(schema.refine((v) => v.string === "bar"));+ expect(result).toEqual({+ string: "foo",+ number: 123,+ });+ });++ it("should return default values for ZodArray", () => {+ const schema = z.array(+ z.object({+ string: z.string().default("default"),+ number: z.number().default(123),+ })+ );+ const result = getDefaults(schema);+ expect(result).toEqual([]);++ const schema2 = schema.min(1);+ const result2 = getDefaults(schema2);+ expect(result2).toEqual([+ {+ string: "default",+ number: 123,+ },+ ]);+ });+});diff --git a/frontend/src/plugins/impl/data-frames/forms/context.ts b/frontend/src/plugins/impl/data-frames/forms/context.tsnew file mode 100644index 0000000000..86e8d47e56--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/context.ts@@ -0,0 +1,5 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { createContext } from "react";+import { ColumnDataTypes } from "../types";++export const ColumnContext = createContext<ColumnDataTypes>({});diff --git a/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx b/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsxnew file mode 100644index 0000000000..683b230b13--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/datatype-icon.tsx@@ -0,0 +1,42 @@+/* Copyright 2023 Marimo. All rights reserved. */+import {+ BinaryIcon,+ BracesIcon,+ CalendarIcon,+ CaseSensitiveIcon,+ ToggleLeftIcon,+} from "lucide-react";+import React from "react";++interface Props {+ type: string;+}++export const DataTypeIcon: React.FC<Props> = ({ type }) => {+ const renderIcon = () => {+ if (+ type.startsWith("int") ||+ type.startsWith("float") ||+ type.startsWith("uint") ||+ type.startsWith("complex")+ ) {+ return <BinaryIcon size={14} />;+ }+ if (type.startsWith("object")) {+ return <CaseSensitiveIcon size={14} />;+ }+ if (type.startsWith("date") || type.startsWith("time")) {+ return <CalendarIcon size={14} />;+ }+ if (type.startsWith("bool")) {+ return <ToggleLeftIcon size={14} />;+ }+ return <BracesIcon size={14} />;+ };++ return (+ <div className="border p-[1px] border-border bg-[var(--slate-2)] flex items-center justify-center rounded">+ {renderIcon()}+ </div>+ );+};diff --git a/frontend/src/plugins/impl/data-frames/forms/form-utils.ts b/frontend/src/plugins/impl/data-frames/forms/form-utils.tsnew file mode 100644index 0000000000..11be29c222--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/form-utils.ts@@ -0,0 +1,81 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { z } from "zod";++/**+ * Get default values for a zod schema+ */+export function getDefaults<TSchema extends z.ZodType<T>, T>(+ schema: TSchema+): T {+ const getDefaultValue = (schema: z.ZodTypeAny): unknown => {+ if (schema instanceof z.ZodLiteral) {+ return schema._def.value;+ }+ if (schema instanceof z.ZodDefault) {+ return schema._def.defaultValue();+ }+ if (schema instanceof z.ZodEffects) {+ return getDefaults(schema._def.schema);+ }+ if (!("innerType" in schema._def)) {+ return undefined;+ }+ return getDefaultValue(schema._def.innerType);+ };++ // If union, take the first one+ if (schema instanceof z.ZodUnion) {+ return getDefaultValue(schema._def.options[0]) as T;+ }++ // If array, return an array of 1 item+ if (schema instanceof z.ZodArray) {+ if (schema._def.minLength && schema._def.minLength.value > 0) {+ return [getDefaults(schema._def.type)] as unknown as T;+ }+ return [] as unknown as T;+ }++ // If string, return the default value+ if (schema instanceof z.ZodString) {+ return "" as T;+ }++ // If enum, return the first value+ if (schema instanceof z.ZodEnum) {+ return schema._def.values[0] as T;+ }++ // If not an object, return the default value+ if (!(schema instanceof z.ZodObject)) {+ return getDefaultValue(schema) as T;+ }++ return Object.fromEntries(+ Object.entries(schema.shape).map(([key, value]) => {+ return [key, getDefaultValue(value as z.AnyZodObject)];+ })+ ) as T;+}++/**+ * Get the literal value of a union+ */+export function getUnionLiteral<T extends z.ZodType<unknown>>(+ schema: T+): z.ZodLiteral<string> {+ if (schema instanceof z.ZodLiteral) {+ return schema;+ }+ if (schema instanceof z.ZodObject) {+ const type = schema._def.shape().type;+ if (type instanceof z.ZodLiteral) {+ return type;+ }+ throw new Error("Invalid schema");+ }+ if (schema instanceof z.ZodUnion) {+ return getUnionLiteral(schema._def.options[0]);+ }+ 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.tsxnew file mode 100644index 0000000000..4ef587b301--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/form.tsx@@ -0,0 +1,709 @@+/* Copyright 2023 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { z } from "zod";+import {+ DebouncedInput,+ DebouncedNumberInput,+ Input,+} from "../../../../components/ui/input";+import { Checkbox } from "../../../../components/ui/checkbox";+import {+ FieldValues,+ FormProvider,+ Path,+ UseFormReturn,+ useController,+ useFieldArray,+} from "react-hook-form";+import {+ FormField,+ FormItem,+ FormLabel,+ FormControl,+ FormMessage,+ FormMessageTooltip,+ FormDescription,+} from "../../../../components/ui/form";+import { Objects } from "../../../../utils/objects";+import { Button } from "../../../../components/ui/button";+import { getDefaults, getUnionLiteral } from "./form-utils";+import { PlusIcon, Trash2Icon } from "lucide-react";+import { FieldOptions } from "@/plugins/impl/data-frames/forms/options";+import { cn } from "@/lib/utils";+import React, { useContext, useEffect } from "react";+import { ColumnContext } from "@/plugins/impl/data-frames/forms/context";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { getOperatorForDtype, getSchemaForOperator } from "../utils/operators";+import { Textarea } from "@/components/ui/textarea";+import { Strings } from "@/utils/strings";+import { Label } from "@/components/ui/label";+import { NativeSelect } from "@/components/ui/native-select";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { DataTypeIcon } from "./datatype-icon";+import { Events } from "@/utils/events";++interface Props<T extends FieldValues> {+ form: UseFormReturn<T>;+ schema: z.ZodType<any>;+ path?: Path<T>;+}++export const ZodForm = <T extends FieldValues>({+ schema,+ form,+ path = "" as Path<T>,+}: Props<T>) => {+ return (+ <FormProvider {...form}>{renderZodSchema(schema, form, path)}</FormProvider>+ );+};++function renderZodSchema<T extends FieldValues, S>(+ schema: z.ZodType<S>,+ form: UseFormReturn<T>,+ path: Path<T>+) {+ const {+ label,+ description,+ placeholder,+ disabled,+ special,+ direction = "column",+ } = FieldOptions.parse(schema._def.description || "");++ if (schema instanceof z.ZodDefault) {+ let inner = schema._def.innerType as z.ZodType<unknown>;+ // pass along the description+ inner =+ !inner.description && schema.description+ ? inner.describe(schema.description)+ : inner;+ return renderZodSchema(inner, form, path);+ }++ if (schema instanceof z.ZodObject) {+ if (special === "column_filter") {+ return <FilterForm schema={schema} form={form} path={path} />;+ }++ return (+ <div+ className={cn(+ "flex",+ direction === "row" ? "flex-row gap-6 items-start" : "flex-col gap-6"+ )}+ >+ <FormLabel>{label}</FormLabel>+ {Objects.entries(schema._def.shape()).map(([key, value]) => {+ const isLiteral = value instanceof z.ZodLiteral;+ const childForm = renderZodSchema(+ value as z.ZodType<unknown>,+ form,+ `${path}.${key}` as Path<T>+ );++ if (isLiteral) {+ return <React.Fragment key={key}>{childForm}</React.Fragment>;+ }++ return (+ <div className="flex flex-row align-start" key={key}>+ {childForm}+ </div>+ );+ })}+ </div>+ );+ } else if (schema instanceof z.ZodString) {+ if (special === "column_id") {+ return <ColumnSelector schema={schema} form={form} path={path} />;+ }++ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <DebouncedInput+ {...field}+ value={field.value}+ onValueChange={field.onChange}+ className="my-0"+ placeholder={placeholder}+ disabled={disabled}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodBoolean) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <div className="flex flex-row items-start space-x-2">+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </div>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodNumber) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <DebouncedNumberInput+ {...field}+ type="number"+ className="my-0"+ onValueChange={field.onChange}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodDate) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <DebouncedInput+ {...field}+ onValueChange={field.onChange}+ type="date"+ className="my-0"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodAny) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <DebouncedInput+ {...field}+ onValueChange={field.onChange}+ className="my-0"+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodEnum) {+ if (special === "radio_group") {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <RadioGroup+ className="flex flex-row gap-2 pt-1 items-center"+ value={field.value}+ onValueChange={field.onChange}+ >+ {schema._def.values.map((value: string) => {+ return (+ <div className="flex items-center gap-1" key={value}>+ <RadioGroupItem+ key={value}+ value={value}+ id={`${path}-${value}`}+ />+ <FormLabel+ className="whitespace-pre"+ htmlFor={`${path}-${value}`}+ >+ {Strings.startCase(value)}+ </FormLabel>+ </div>+ );+ })}+ </RadioGroup>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ }++ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="whitespace-pre">{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="min-w-[210px]">+ <SelectValue placeholder="--" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {schema._def.values.map((value: string) => {+ return (+ <SelectItem key={value} value={value}>+ {Strings.startCase(value)}+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ } else if (schema instanceof z.ZodArray) {+ if (special === "text_area_multiline") {+ // new-line separated+ const delimiter = "\n";+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <Textarea+ value={+ Array.isArray(field.value)+ ? field.value.join(delimiter)+ : field.value+ }+ onChange={(e) => {+ if (e.target.value === "") {+ field.onChange([]);+ return;+ }+ field.onChange(e.target.value.split(delimiter));+ }}+ placeholder={placeholder}+ disabled={disabled}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ }++ return (+ <div className="flex flex-col gap-1">+ <Label>{label}</Label>+ <FormArray+ schema={schema._def.type}+ form={form}+ path={path}+ key={path}+ minLength={schema._def.minLength?.value}+ />+ </div>+ );+ } else if (schema instanceof z.ZodUnion) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => {+ const options = schema._def.options as Array<z.ZodType<unknown>>;+ let value: string = field.value;+ const types = options.map((option) => {+ return getUnionLiteral(option)._def.value;+ });++ if (!value) {+ // Default to first+ value = types[0];+ }++ const selectedOption = options.find((option) => {+ return getUnionLiteral(option)._def.value === value;+ });++ return (+ <div className="flex flex-col">+ <FormLabel>{label}</FormLabel>+ <NativeSelect {...field}>+ {types.map((type: string) => {+ return (+ <option key={type} value={type}>+ {type}+ </option>+ );+ })}+ </NativeSelect>+ {selectedOption && renderZodSchema(selectedOption, form, path)}+ </div>+ );+ }}+ />+ );+ } else if (schema instanceof z.ZodLiteral) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => <input {...field} type="hidden" />}+ />+ );+ } else if (+ schema instanceof z.ZodEffects &&+ ["refinement", "transform"].includes(schema._def.effect.type)+ ) {+ return renderZodSchema(schema._def.schema, form, path);+ } else if (schema instanceof z.ZodRecord) {+ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormMessage />+ <FormControl>+ <Input {...field} className="my-0" />+ </FormControl>+ </FormItem>+ )}+ />+ );+ } else {+ return (+ <div>+ Unknown schema type{" "}+ {schema ? JSON.stringify(schema._type || schema) : path}+ </div>+ );+ }+}++const StyledFormMessage = ({ className }: { className?: string }) => {+ return (+ <FormMessageTooltip+ className={cn(+ "absolute -left-6 bottom-0 text-destructive text-xs w-[16px]",+ className+ )}+ />+ );+};++const FormArray = ({+ schema,+ form,+ path,+ minLength,+}: {+ schema: z.ZodType<unknown>;+ form: UseFormReturn<any>;+ path: Path<any>;+ minLength?: number;+}) => {+ const { label, description } = FieldOptions.parse(+ schema._def.description || ""+ );++ const control = form.control;+ // prepend, remove, swap, move, insert, replace+ const { fields, append, remove } = useFieldArray({+ control,+ name: path,+ });++ const isBelowMinLength = minLength != null && fields.length < minLength;+ const canRemove = minLength == null || fields.length > minLength;++ return (+ <div className="flex flex-col gap-2 min-w-[220px]">+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ {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"+ key={field.id}+ onKeyDown={Events.onEnter((e) => e.preventDefault())}+ >+ {renderZodSchema(schema, form, `${path}[${index}]`)}+ {canRemove && (+ <Trash2Icon+ className="w-4 h-4 ml-2 my-1 text-muted-foreground hover-action hover:text-destructive cursor-pointer absolute right-0 bottom-0"+ onClick={() => {+ remove(index);+ }}+ />+ )}+ </div>+ );+ })}+ {isBelowMinLength && (+ <div className="text-destructive text-xs font-semibold">+ <div>At least {minLength} required.</div>+ </div>+ )}+ <div>+ <Button+ size="xs"+ variant="text"+ className="hover:text-accent-foreground"+ onClick={() => {+ append(getDefaults(schema));+ }}+ >+ <PlusIcon className="w-3.5 h-3.5 mr-1" />+ Add+ </Button>+ </div>+ </div>+ );+};++const ColumnSelector = ({+ schema,+ form,+ path,+ onChange,+}: {+ schema: z.ZodString;+ form: UseFormReturn<any>;+ path: Path<any>;+ onChange?: (value: string) => void;+}) => {+ const columns = useContext(ColumnContext);+ const { label, description } = FieldOptions.parse(schema._def.description);++ return (+ <FormField+ control={form.control}+ name={path}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{label}</FormLabel>+ <FormDescription>{description}</FormDescription>+ <StyledFormMessage />+ <FormControl>+ <Select+ value={field.value}+ onValueChange={(value) => {+ onChange?.(value);+ field.onChange(value);+ }}+ >+ <SelectTrigger className="min-w-[210px]">+ <SelectValue placeholder="--" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {Objects.entries(columns).map(([name, dtype]) => {+ return (+ <SelectItem key={name} value={name.toString()}>+ <span className="flex items-center gap-2 flex-1">+ <DataTypeIcon type={dtype} />+ <span className="flex-1">{name}</span>+ <span className="text-muted-foreground text-xs font-semibold">+ ({dtype})+ </span>+ </span>+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ );+};++const FilterForm = ({+ path,+ form,+ schema,+}: {+ schema: z.ZodObject<{}>;+ form: UseFormReturn<any>;+ path: Path<any>;+}) => {+ const { description } = FieldOptions.parse(schema._def.description);+ const columns = useContext(ColumnContext);+ const { field } = useController({ name: path });++ const columnIdSchema = Objects.entries(schema._def.shape()).find(+ ([key, value]) => {+ return key === "column_id";+ }+ )?.[1] as unknown as z.ZodString;++ // existing values+ const { column_id: columnId, operator } = field.value || {};++ const children = [+ <ColumnSelector+ key={`column_id`}+ schema={columnIdSchema}+ form={form}+ path={`${path}.column_id`}+ onChange={(value) => {+ // Reset operator and value if the column type changes+ const currentDtype = columns[columnId];+ const nextDtype = columns[value];+ if (nextDtype !== currentDtype) {+ form.setValue(`${path}.value`, undefined);+ }+ }}+ />,+ ];++ // When column ID changes, get the new dtype and reset the operator+ useEffect(() => {+ const dtype = columns[columnId];+ const operators = getOperatorForDtype(dtype);++ const currentOperator = form.getValues(`${path}.operator`);+ if (!operators.includes(currentOperator)) {+ form.setValue(`${path}.operator`, operators[0]);+ form.setValue(`${path}.value`, undefined);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [columnId]);++ if (columnId) {+ const dtype = columns[columnId];+ const operators = getOperatorForDtype(dtype);++ if (operators.length === 0) {+ children.push(+ <div+ key={`no_operator`}+ className="text-muted-foreground text-xs font-semibold"+ >+ <FormLabel className="whitespace-pre"> </FormLabel>+ <div>This column type does not support filtering.</div>+ </div>+ );+ } else {+ children.push(+ <FormField+ key={`operator`}+ control={form.control}+ name={`${path}.operator`}+ render={({ field }) => (+ <FormItem>+ <FormLabel className="whitespace-pre"> </FormLabel>+ <FormDescription>{description}</FormDescription>+ <FormControl>+ <Select value={field.value} onValueChange={field.onChange}>+ <SelectTrigger className="min-w-[210px]">+ <SelectValue placeholder="Select a fruit" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {operators.map((value: string) => {+ return (+ <SelectItem key={value} value={value}>+ {Strings.startCase(value)}+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ );+ }+ }++ if (operator) {+ const dtype = columns[columnId];+ const operandSchemas = getSchemaForOperator(dtype, operator);+ if (operandSchemas.length === 1) {+ children.push(+ <React.Fragment key={`value`}>+ {renderZodSchema(operandSchemas[0], form, `${path}.value`)}+ </React.Fragment>+ );+ }+ }++ return (+ <FormField+ control={form.control}+ name={path}+ render={() => (+ <div className="flex flex-col gap-2 bg-red">+ <div className={cn("flex flex-row gap-3 items-center")}>+ {children}+ </div>+ <FormMessage />+ </div>+ )}+ />+ );+};diff --git a/frontend/src/plugins/impl/data-frames/forms/options.ts b/frontend/src/plugins/impl/data-frames/forms/options.tsnew file mode 100644index 0000000000..5b7dadd04f--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/forms/options.ts@@ -0,0 +1,34 @@+/* Copyright 2023 Marimo. All rights reserved. */+export interface FieldOptions {+ label?: string;+ description?: string;+ placeholder?: string;+ disabled?: boolean;+ hidden?: boolean;+ direction?: "row" | "column";+ special?:+ | "column_id"+ | "column_type"+ | "radio_group"+ | "column_filter"+ | "text_area_multiline";+}++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const FieldOptions = {+ of(options: FieldOptions): string {+ return JSON.stringify(options);+ },+ parse(options: string | undefined): FieldOptions {+ if (!options) {+ return {};+ }+ try {+ return JSON.parse(options) as FieldOptions;+ } catch {+ return {+ label: options,+ };+ }+ },+};diff --git a/frontend/src/plugins/impl/data-frames/panel.tsx b/frontend/src/plugins/impl/data-frames/panel.tsxnew file mode 100644index 0000000000..096665b9c8--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/panel.tsx@@ -0,0 +1,274 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React, { PropsWithChildren, useEffect, useMemo } from "react";+import {+ TransformType,+ TransformTypeSchema,+ Transformations,+ TransformationsSchema,+} from "./schema";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "../../../components/ui/dropdown-menu";+import { Button } from "../../../components/ui/button";+import { zodResolver } from "@hookform/resolvers/zod";+import { useFieldArray, useForm } from "react-hook-form";+import { z } from "zod";+import { ZodForm } from "./forms/form";+import { getDefaults, getUnionLiteral } from "./forms/form-utils";+import {+ ArrowUpDownIcon,+ ColumnsIcon,+ FilterIcon,+ FunctionSquareIcon,+ GroupIcon,+ MousePointerSquareDashedIcon,+ PencilIcon,+ PlusIcon,+ Trash2Icon,+} from "lucide-react";+import { cn } from "../../../lib/utils";+import { ColumnContext } from "@/plugins/impl/data-frames/forms/context";+import useEvent from "react-use-event-hook";+import { ColumnDataTypes } from "./types";+import { getUpdatedColumnTypes } from "./utils/getUpdatedColumnTypes";+import { Strings } from "@/utils/strings";++interface Props {+ columns: ColumnDataTypes;+ initialValue: Transformations;+ onChange: (value: Transformations) => void;+ onInvalidChange: (value: Transformations) => void;+}++export const TransformPanel: React.FC<Props> = ({+ initialValue,+ columns,+ onChange,+ onInvalidChange,+}) => {+ const form = useForm<z.infer<typeof TransformationsSchema>>({+ resolver: zodResolver(TransformationsSchema),+ defaultValues: initialValue,+ mode: "onChange",+ reValidateMode: "onChange",+ });+ const { handleSubmit, watch, control } = form;++ const onSubmit = useEvent((values: z.infer<typeof TransformationsSchema>) => {+ onChange(values);+ });++ const onInvalidSubmit = useEvent(+ (values: z.infer<typeof TransformationsSchema>) => {+ onInvalidChange(values);+ }+ );++ useEffect(() => {+ const subscription = watch(() => {+ handleSubmit(onSubmit, () => {+ onInvalidSubmit(form.getValues());+ })();+ });+ return () => subscription.unsubscribe();+ }, [handleSubmit, watch, onInvalidSubmit, onSubmit, form]);++ const [selectedTransform, setSelectedTransform] = React.useState<+ number | undefined+ >(initialValue.transforms.length > 0 ? 0 : undefined);++ const transformsField = useFieldArray({+ control: control,+ name: "transforms",+ });++ const transforms = form.watch("transforms");+ const selectedTransformType =+ selectedTransform === undefined+ ? undefined+ : transforms[selectedTransform]?.type;+ const selectedTransformSchema = TransformTypeSchema._def.options.find(+ (option) => {+ return getUnionLiteral(option)._def.value === selectedTransformType;+ }+ );++ const effectiveColumns = useMemo(() => {+ const transformsBeforeSelected = transforms.slice(0, selectedTransform);+ return getUpdatedColumnTypes(transformsBeforeSelected, columns);+ }, [columns, transforms, selectedTransform]);++ const handleAddTransform = (transform: z.ZodType) => {+ const next = getDefaults(transform) as TransformType;+ const nextIdx = transformsField.fields.length;+ transformsField.append(next);+ setSelectedTransform(nextIdx);+ };++ return (+ <ColumnContext.Provider value={effectiveColumns}>+ <form+ onSubmit={(e) => e.preventDefault()}+ className="flex flex-row max-h-[400px] overflow-hidden bg-white border rounded-t"+ >+ <Sidebar+ items={form.watch("transforms")}+ selected={selectedTransform}+ onSelect={(index) => {+ setSelectedTransform(index);+ }}+ onDelete={(index) => {+ transformsField.remove(index);+ const indexBefore = index - 1;+ setSelectedTransform(Math.max(indexBefore, 0));+ }}+ onAdd={handleAddTransform}+ />+ <div className="flex flex-col flex-1 p-4 overflow-auto min-h-[200px] border-l">+ {selectedTransform !== undefined && selectedTransformSchema && (+ <ZodForm+ key={`transforms.${selectedTransform}`}+ form={form}+ schema={selectedTransformSchema}+ path={`transforms.${selectedTransform}`}+ />+ )}+ {(selectedTransform === undefined || !selectedTransformSchema) && (+ <div className="flex flex-col items-center justify-center flex-grow gap-3">+ <MousePointerSquareDashedIcon className="w-8 h-8 text-muted-foreground" />+ <AddTransformDropdown onAdd={handleAddTransform}>+ <Button variant="text" size="xs">+ <div className="text-sm">Select a transform to begin</div>+ </Button>+ </AddTransformDropdown>+ </div>+ )}+ </div>+ </form>+ </ColumnContext.Provider>+ );+};++interface SidebarProps {+ items: TransformType[];+ selected: number | undefined;+ onSelect: (index: number) => void;+ onDelete: (index: number) => void;+ onAdd: (transform: z.ZodType) => void;+}++export const Sidebar: React.FC<SidebarProps> = ({+ items,+ selected,+ onAdd,+ onSelect,+ onDelete,+}) => {+ return (+ <div className="flex flex-col overflow-y-hidden w-[150px] shadow-xs h-full">+ <div className="flex flex-col overflow-y-auto flex-grow">+ {items.map((item, idx) => {+ return (+ <div+ key={`${JSON.stringify(item)}-${idx}`}+ onClick={() => {+ onSelect(idx);+ }}+ className={cn(+ "flex flex-row min-h-[40px] items-center px-2 cursor-pointer hover:bg-accent/50 text-sm overflow-hidden hover-actions-parent border border-muted border-l-2 border-l-transparent",+ {+ "border-l-primary bg-accent text-accent-foreground":+ selected === idx,+ }+ )}+ >+ <div className="flex-grow text-ellipsis">+ {Strings.startCase(item.type)}+ </div>+ <Trash2Icon+ className="w-3 h-3 hover-action text-muted-foreground hover:text-destructive"+ onClick={(e) => {+ onDelete(idx);+ e.stopPropagation();+ }}+ />+ </div>+ );+ })}+ </div>+ <div className="flex flex-row flex-shrink-0 border-t">+ <AddTransformDropdown onAdd={onAdd}>+ <Button+ variant="text"+ className="w-full rounded-none m-0 hover:text-accent-foreground"+ size="xs"+ >+ <PlusIcon className="w-3 h-3 mr-1" />+ Add+ </Button>+ </AddTransformDropdown>+ </div>+ </div>+ );+};++const AddTransformDropdown: React.FC<+ PropsWithChildren<{ onAdd: (transform: z.ZodType) => void }>+> = ({ onAdd, children }) => {+ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>{children}</DropdownMenuTrigger>+ <DropdownMenuContent className="w-56">+ <DropdownMenuLabel>Add Transform</DropdownMenuLabel>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ {Object.values(TransformTypeSchema._def.options).map((type) => {+ const literal = getUnionLiteral(type);+ const Icon = ICONS[literal._def.value as TransformType["type"]];+ return (+ <DropdownMenuItem+ key={literal._def.value}+ onSelect={(evt) => {+ evt.stopPropagation();+ onAdd(type);+ }}+ >+ <Icon className="w-3.5 h-3.5 mr-2" />+ <span>{Strings.startCase(literal._def.value)}</span>+ </DropdownMenuItem>+ );+ })}+ <DropdownMenuItem+ key="_request_"+ onSelect={(evt) => {+ evt.stopPropagation();+ window.open(+ "https://github.com/marimo-team/marimo/issues/new?title=New%20dataframe%20transform:&labels=enhancement&template=feature_request.yaml",+ "_blank"+ );+ }}+ >+ <span className="underline text-primary text-xs cursor-pointer">+ Request a transform+ </span>+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ );+};++const ICONS: Record<TransformType["type"], React.FC<{ className?: string }>> = {+ aggregate: FunctionSquareIcon,+ column_conversion: ColumnsIcon,+ filter_rows: FilterIcon,+ group_by: GroupIcon,+ rename_column: PencilIcon,+ sort_column: ArrowUpDownIcon,+};diff --git a/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snap b/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snapnew file mode 100644index 0000000000..77f945aa01--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/python/__tests__/__snapshots__/python-print.test.ts.snap@@ -0,0 +1,51 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`pythonPrint: filter > filter_rows > date > != 1`] = `"df[df[\\"my_column\\"].ne(1000)]"`;++exports[`pythonPrint: filter > filter_rows > date > < 1`] = `"df[df[\\"my_column\\"] < 1000]"`;++exports[`pythonPrint: filter > filter_rows > date > <= 1`] = `"df[df[\\"my_column\\"] <= 1000]"`;++exports[`pythonPrint: filter > filter_rows > date > == 1`] = `"df[df[\\"my_column\\"] == 1000]"`;++exports[`pythonPrint: filter > filter_rows > date > > 1`] = `"df[df[\\"my_column\\"] > 1000]"`;++exports[`pythonPrint: filter > filter_rows > date > >= 1`] = `"df[df[\\"my_column\\"] >= 1000]"`;++exports[`pythonPrint: filter > filter_rows > date > is_false 1`] = `"df[df[\\"my_column\\"] == False]"`;++exports[`pythonPrint: filter > filter_rows > date > is_nan 1`] = `"df[df[\\"my_column\\"].isna()]"`;++exports[`pythonPrint: filter > filter_rows > date > is_not_nan 1`] = `"df[df[\\"my_column\\"].notna()]"`;++exports[`pythonPrint: filter > filter_rows > date > is_true 1`] = `"df[df[\\"my_column\\"] == True]"`;++exports[`pythonPrint: filter > filter_rows > number > != 1`] = `"df[df[\\"my_column\\"].ne(42)]"`;++exports[`pythonPrint: filter > filter_rows > number > < 1`] = `"df[df[\\"my_column\\"] < 42]"`;++exports[`pythonPrint: filter > filter_rows > number > <= 1`] = `"df[df[\\"my_column\\"] <= 42]"`;++exports[`pythonPrint: filter > filter_rows > number > == 1`] = `"df[df[\\"my_column\\"] == 42]"`;++exports[`pythonPrint: filter > filter_rows > number > > 1`] = `"df[df[\\"my_column\\"] > 42]"`;++exports[`pythonPrint: filter > filter_rows > number > >= 1`] = `"df[df[\\"my_column\\"] >= 42]"`;++exports[`pythonPrint: filter > filter_rows > number > is_nan 1`] = `"df[df[\\"my_column\\"].isna()]"`;++exports[`pythonPrint: filter > filter_rows > number > is_not_nan 1`] = `"df[df[\\"my_column\\"].notna()]"`;++exports[`pythonPrint: filter > filter_rows > string > contains 1`] = `"df[df[\\"my_column\\"].str.contains(\\"val\\")]"`;++exports[`pythonPrint: filter > filter_rows > string > does_not_equal 1`] = `"df[df[\\"my_column\\"].ne(\\"val\\")]"`;++exports[`pythonPrint: filter > filter_rows > string > ends_with 1`] = `"df[df[\\"my_column\\"].str.endswith(\\"val\\")]"`;++exports[`pythonPrint: filter > filter_rows > string > equals 1`] = `"df[df[\\"my_column\\"].eq(\\"val\\")]"`;++exports[`pythonPrint: filter > filter_rows > string > in 1`] = `"df[df[\\"my_column\\"].isin(\\"val\\")]"`;++exports[`pythonPrint: filter > filter_rows > string > regex 1`] = `"df[df[\\"my_column\\"].str.contains(\\"val\\", regex=True)]"`;++exports[`pythonPrint: filter > filter_rows > string > starts_with 1`] = `"df[df[\\"my_column\\"].str.startswith(\\"val\\")]"`;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.tsnew file mode 100644index 0000000000..3a1c72af8f--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/python/__tests__/python-print.test.ts@@ -0,0 +1,244 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { pythonPrint } from "@/plugins/impl/data-frames/python/python-print";+import { TransformType } from "@/plugins/impl/data-frames/schema";+import { expect, describe, it } from "vitest";+import {+ BOOLEAN_OPERATORS,+ DATE_OPERATORS,+ NUMERIC_OPERATORS,+ STRING_OPERATORS,+} from "../../utils/operators";+import { Objects } from "@/utils/objects";++describe("pythonPrint", () => {+ // Test for column_conversion+ it("generates correct Python code for column_conversion", () => {+ const transform: TransformType = {+ type: "column_conversion",+ column_id: "my_column",+ data_type: "int8",+ errors: "ignore",+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchInlineSnapshot(+ '"df[\\"my_column\\"].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",+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchInlineSnapshot(+ '"df.rename(columns={\\"old_name\\": \\"new_name\\"})"'+ );+ });++ // Test for sort_column+ it("generates correct Python code for sort_column", () => {+ const transform: TransformType = {+ type: "sort_column",+ column_id: "my_column",+ ascending: false,+ na_position: "first",+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchInlineSnapshot(+ '"df.sort_values(by=\\"my_column\\", ascending=False, na_position=\\"first\\")"'+ );+ });++ // Test for aggregate+ it("generates correct Python code for aggregate", () => {+ const transform: TransformType = {+ type: "aggregate",+ column_ids: ["my_column"],+ aggregations: ["mean"],+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchInlineSnapshot(+ '"df.agg({\\"my_column\\": [\\"mean\\"]})"'+ );++ const transform2: TransformType = {+ type: "aggregate",+ column_ids: [],+ aggregations: ["mean"],+ };+ const result2 = pythonPrint("df", transform2);+ expect(result2).toMatchInlineSnapshot('"df.agg([\\"mean\\"])"');++ const transform3: TransformType = {+ type: "aggregate",+ column_ids: ["my_column"],+ aggregations: ["mean", "sum"],+ };+ const result3 = pythonPrint("df", transform3);+ expect(result3).toMatchInlineSnapshot(+ '"df.agg({\\"my_column\\": [\\"mean\\", \\"sum\\"]})"'+ );+ });++ // Test for group_by+ it("generates correct Python code for group_by", () => {+ const transform: TransformType = {+ type: "group_by",+ column_ids: ["my_column"],+ aggregation: "sum",+ drop_na: true,+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchInlineSnapshot(+ '"df.groupby([\\"my_column\\"], dropna=True).sum()"'+ );++ const transform2: TransformType = {+ type: "group_by",+ column_ids: ["my_column", "my_column2"],+ aggregation: "sum",+ drop_na: false,+ };+ const result2 = pythonPrint("df", transform2);+ expect(result2).toMatchInlineSnapshot(+ '"df.groupby([\\"my_column\\", \\"my_column2\\"]).sum()"'+ );+ });+});++describe("pythonPrint: filter", () => {+ it("handles filter vs keep", () => {+ const result = pythonPrint("df", {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: "==",+ value: 42,+ },+ ],+ });+ expect(result).toMatchInlineSnapshot('"df[df[\\"my_column\\"] == 42]"');++ const result2 = pythonPrint("df", {+ type: "filter_rows",+ operation: "remove_rows",+ where: [+ {+ column_id: "my_column",+ operator: "==",+ value: 42,+ },+ ],+ });+ expect(result2).toMatchInlineSnapshot(+ '"df[~((df[\\"my_column\\"] == 42))]"'+ );+ });++ it("handle multiple where clauses", () => {+ const result = pythonPrint("df", {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: "==",+ value: 42,+ },+ {+ column_id: "my_column2",+ operator: "==",+ value: 43,+ },+ ],+ });+ expect(result).toMatchInlineSnapshot(+ '"df[(df[\\"my_column\\"] == 42) & (df[\\"my_column2\\"] == 43)]"'+ );+ });++ // Test for filter_rows for strings+ it.each(Objects.entries(STRING_OPERATORS))(+ "filter_rows > string > %s",+ (operator) => {+ const transform: TransformType = {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: operator,+ value: "val",+ },+ ],+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchSnapshot();+ }+ );++ // Test for filter_rows for booleans+ it.each(Objects.entries(BOOLEAN_OPERATORS))(+ "filter_rows > date > %s",+ (operator) => {+ const transform: TransformType = {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: operator,+ value: true,+ },+ ],+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchSnapshot();+ }+ );++ // Test for filter_rows for dates+ it.each(Objects.entries(DATE_OPERATORS))(+ "filter_rows > date > %s",+ (operator) => {+ const transform: TransformType = {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: operator,+ value: 1000,+ },+ ],+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchSnapshot();+ }+ );++ // Test for filter_rows for numbers+ it.each(Objects.entries(NUMERIC_OPERATORS))(+ "filter_rows > number > %s",+ (operator) => {+ const transform: TransformType = {+ type: "filter_rows",+ operation: "keep_rows",+ where: [+ {+ column_id: "my_column",+ operator: operator,+ value: 42,+ },+ ],+ };+ const result = pythonPrint("df", transform);+ expect(result).toMatchSnapshot();+ }+ );+});diff --git a/frontend/src/plugins/impl/data-frames/python/code-panel.tsx b/frontend/src/plugins/impl/data-frames/python/code-panel.tsxnew file mode 100644index 0000000000..8d27ea3387--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/python/code-panel.tsx@@ -0,0 +1,38 @@+/* Copyright 2023 Marimo. All rights reserved. */+import React from "react";+import { Transformations } from "../schema";+import { python } from "@codemirror/lang-python";+import CodeMirror from "@uiw/react-codemirror";+import { pythonPrintTransforms } from "./python-print";++interface Props {+ dataframeName: string;+ transforms?: Transformations;+}++export const CodePanel: React.FC<Props> = ({ transforms, dataframeName }) => {+ if (!transforms) {+ return null;+ }++ return (+ <PythonCode+ code={pythonPrintTransforms(dataframeName, transforms.transforms)}+ />+ );+};++const PythonCode = (props: { code: string }) => {+ return (+ <div className="border-t border-x rounded-t overflow-hidden">+ <CodeMirror+ minHeight="100px"+ height="100%"+ editable={true}+ extensions={[python()]}+ value={props.code}+ readOnly={true}+ />+ </div>+ );+};diff --git a/frontend/src/plugins/impl/data-frames/python/python-print.ts b/frontend/src/plugins/impl/data-frames/python/python-print.tsnew file mode 100644index 0000000000..e48f245415--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/python/python-print.ts@@ -0,0 +1,150 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { TransformType } from "@/plugins/impl/data-frames/schema";+import { logNever } from "@/utils/assertNever";+import { OperatorType } from "../utils/operators";++export function pythonPrintTransforms(+ dfName: string,+ transforms: TransformType[]+): string {+ const dfNextName = `${dfName}_next`;+ const transformStrs = transforms.map(+ (transform) => `${dfNextName} = ${pythonPrint(dfNextName, transform)}`+ );++ return [`${dfNextName} = ${dfName}`, ...transformStrs].join("\n");+}++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}")`;+ }+ case "rename_column": {+ const { column_id, new_column_id } = transform;+ return `${dfName}.rename(columns={"${column_id}": "${new_column_id}"})`;+ }+ case "sort_column": {+ const { column_id, ascending, na_position } = transform;+ const args = argsList(+ `by="${column_id}"`,+ ascending ? "" : "ascending=False",+ na_position === "last" ? "" : `na_position="${na_position}"`+ );+ return `${dfName}.sort_values(${args})`;+ }+ case "filter_rows": {+ const { operation, where } = transform;+ if (where.length === 0) {+ return dfName;+ }++ const whereClauses = where.map((condition) =>+ generateWhereClause(dfName, condition)+ );+ if (operation === "keep_rows" && whereClauses.length === 1) {+ return `${dfName}[${whereClauses[0]}]`;+ }++ const expression = whereClauses+ .map((clause) => `(${clause})`)+ .join(" & ");++ return operation === "keep_rows"+ ? `${dfName}[${expression}]`+ : `${dfName}[~(${expression})]`;+ }+ case "aggregate": {+ const { column_ids, aggregations } = transform;+ if (column_ids.length === 0) {+ return `${dfName}.agg(${listOfStrings(aggregations)})`;+ }+ return `${dfName}.agg({${column_ids+ .map((column_id) => `"${column_id}": ${listOfStrings(aggregations)}`)+ .join(", ")}})`;+ }+ case "group_by": {+ const { column_ids, aggregation, drop_na } = transform;+ const args = argsList(+ listOfStrings(column_ids),+ drop_na ? "dropna=True" : ""+ );+ return `${dfName}.groupby(${args}).${aggregation}()`;+ }++ default:+ logNever(transform);+ return "";+ }+}++function generateWhereClause(+ dfName: string,+ where: {+ column_id: string;+ operator: OperatorType;+ value?: unknown;+ }+): string {+ const { column_id, operator, value } = where;+ switch (operator) {+ case "==":+ return `${dfName}["${column_id}"] == ${asString(value)}`;+ case "equals":+ return `${dfName}["${column_id}"].eq(${asString(value)})`;+ case "does_not_equal":+ return `${dfName}["${column_id}"].ne(${asString(value)})`;+ case "contains":+ return `${dfName}["${column_id}"].str.contains(${asString(value)})`;+ case "regex":+ return `${dfName}["${column_id}"].str.contains(${asString(+ value+ )}, regex=True)`;+ case "starts_with":+ return `${dfName}["${column_id}"].str.startswith(${asString(value)})`;+ case "ends_with":+ return `${dfName}["${column_id}"].str.endswith(${asString(value)})`;+ case "in":+ return `${dfName}["${column_id}"].isin(${listOfStrings(value)})`;+ case "!=":+ return `${dfName}["${column_id}"].ne(${asString(value)})`;+ case ">":+ return `${dfName}["${column_id}"] > ${asString(value)}`;+ case ">=":+ return `${dfName}["${column_id}"] >= ${asString(value)}`;+ case "<":+ return `${dfName}["${column_id}"] < ${asString(value)}`;+ case "<=":+ return `${dfName}["${column_id}"] <= ${asString(value)}`;+ case "is_nan":+ return `${dfName}["${column_id}"].isna()`;+ case "is_not_nan":+ return `${dfName}["${column_id}"].notna()`;+ case "is_true":+ return `${dfName}["${column_id}"] == True`;+ case "is_false":+ return `${dfName}["${column_id}"] == False`;+ default:+ logNever(operator);+ return "df";+ }+}++function asString(value: unknown): string {+ if (typeof value === "string") {+ return `"${value}"`;+ }+ return `${value}`;+}++function listOfStrings(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map(asString).join(", ")}]`;+ }+ return asString(value);+}++function argsList(...args: string[]): string {+ return args.filter(Boolean).join(", ");+}diff --git a/frontend/src/plugins/impl/data-frames/schema.ts b/frontend/src/plugins/impl/data-frames/schema.tsnew file mode 100644index 0000000000..d778c42e24--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/schema.ts@@ -0,0 +1,135 @@+/* Copyright 2023 Marimo. All rights reserved. */+import {+ AGGREGATION_FNS,+ NUMPY_DTYPES,+} from "@/plugins/impl/data-frames/types";+import { FieldOptions } from "@/plugins/impl/data-frames/forms/options";+import { z } from "zod";+import {+ ALL_OPERATORS,+ OperatorType,+ isConditionValueValid,+} from "./utils/operators";++const column_id = z+ .string()+ .min(1, "Required")+ .describe(FieldOptions.of({ label: "Column", special: "column_id" }));++const column_id_array = z+ .array(column_id.describe(FieldOptions.of({ special: "column_id" })))+ .min(1, "At least one column is required")+ .default([""])+ .describe(FieldOptions.of({ label: "Columns" }));++const ColumnConversionTransformSchema = z+ .object({+ type: z.literal("column_conversion"),+ column_id: column_id,+ data_type: z+ .enum(NUMPY_DTYPES)+ .describe(FieldOptions.of({ label: "Data type (numpy)" }))+ .default("bool"),+ errors: z+ .enum(["ignore", "raise"])+ .default("ignore")+ .describe(+ FieldOptions.of({ label: "Handle errors", special: "radio_group" })+ ),+ })+ .describe(FieldOptions.of({}));++const RenameColumnTransformSchema = z.object({+ type: z.literal("rename_column"),+ column_id: column_id,+ new_column_id: z+ .string()+ .min(1, "Required")+ .describe(FieldOptions.of({ label: "New column name" })),+});++const SortColumnTransformSchema = z.object({+ type: z.literal("sort_column"),+ column_id: column_id,+ ascending: z+ .boolean()+ .describe(FieldOptions.of({ label: "Ascending" }))+ .default(true),+ na_position: z+ .enum(["first", "last"])+ .describe(+ FieldOptions.of({ label: "N/A position", special: "radio_group" })+ )+ .default("last"),+});++export const ConditionSchema = z+ .object({+ column_id: column_id,+ operator: z+ .enum(Object.keys(ALL_OPERATORS) as [OperatorType, ...OperatorType[]])+ .describe(FieldOptions.of({ label: " " })),+ value: z.any().describe(FieldOptions.of({ label: "Value" })),+ })+ .describe(FieldOptions.of({ direction: "row", special: "column_filter" }));++const FilterRowsTransformSchema = z.object({+ type: z.literal("filter_rows"),+ operation: z+ .enum(["keep_rows", "remove_rows"])+ .default("keep_rows")+ .describe(FieldOptions.of({ special: "radio_group" })),+ where: z+ .array(ConditionSchema)+ .min(1)+ .transform((value) => {+ return value.filter((condition) => {+ return isConditionValueValid(condition.operator, condition.value);+ });+ })+ .describe(FieldOptions.of({ label: "Value" }))+ .default([{ column_id: "", operator: "==", value: "" }]),+});++const GroupByTransformSchema = z+ .object({+ type: z.literal("group_by"),+ column_ids: column_id_array,+ aggregation: z+ .enum(AGGREGATION_FNS)+ .default("count")+ .describe(FieldOptions.of({ label: "Aggregation" })),+ drop_na: z+ .boolean()+ .default(false)+ .describe(FieldOptions.of({ label: "Drop N/A" })),+ })+ .describe(FieldOptions.of({}));++const AggregateTransformSchema = z+ .object({+ type: z.literal("aggregate"),+ column_ids: column_id_array,+ aggregations: z+ .array(z.enum(AGGREGATION_FNS))+ .default(["count"])+ .describe(FieldOptions.of({ label: "Aggregations" })),+ })+ .describe(FieldOptions.of({ direction: "row" }));++export const TransformTypeSchema = z.union([+ FilterRowsTransformSchema,+ RenameColumnTransformSchema,+ ColumnConversionTransformSchema,+ SortColumnTransformSchema,+ GroupByTransformSchema,+ AggregateTransformSchema,+]);++export type TransformType = z.infer<typeof TransformTypeSchema>;++export const TransformationsSchema = z.object({+ transforms: z.array(TransformTypeSchema),+});++export type Transformations = z.infer<typeof TransformationsSchema>;diff --git a/frontend/src/plugins/impl/data-frames/types.ts b/frontend/src/plugins/impl/data-frames/types.tsnew file mode 100644index 0000000000..9245a4b515--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/types.ts@@ -0,0 +1,41 @@+/* Copyright 2023 Marimo. All rights reserved. */++/**+ * Map of column id to data type+ */+export interface ColumnDataTypes {+ [column_id: string]: string;+}++export const NUMPY_DTYPES = [+ "int8",+ "int16",+ "int32",+ "int64",+ "uint8",+ "uint16",+ "uint32",+ "uint64",+ "float16",+ "float32",+ "float64",+ "float128",+ "complex64",+ "complex128",+ "complex256",+ "bool",+ "object",+ "string_",+ "unicode_",+ "datetime64",+ "timedelta64",+] as const;++export const AGGREGATION_FNS = [+ "count",+ "sum",+ "mean",+ "median",+ "min",+ "max",+] as const;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.tsnew file mode 100644index 0000000000..ed87d1ec59--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/utils/__tests__/getUpdatedColumnTypes.test.ts@@ -0,0 +1,118 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, describe, it } from "vitest";+import { getUpdatedColumnTypes } from "../getUpdatedColumnTypes";+import { TransformType } from "../../schema";++const INITIAL_COLUMN_TYPES = {+ col1: "str",+ col2: "bool",+ col3: "int",+};++const Transforms = {+ COLUMN_CONVERSION: {+ type: "column_conversion",+ column_id: "col1",+ data_type: "bool",+ errors: "ignore",+ } satisfies TransformType,+ RENAME_COLUMN: {+ type: "rename_column",+ column_id: "col2",+ new_column_id: "newCol2",+ } satisfies TransformType,+ GROUP_BY: {+ type: "group_by",+ column_ids: ["col1", "col3"],+ aggregation: "max",+ drop_na: true,+ } satisfies TransformType,+ GROUP_BY_CHAINED: {+ type: "group_by",+ column_ids: ["newCol2"],+ aggregation: "max",+ drop_na: true,+ } satisfies TransformType,+ AGGREGATE: {+ type: "aggregate",+ column_ids: ["col1"],+ aggregations: ["max"],+ } satisfies TransformType,+ AGGREGATE_CHAINED: {+ type: "aggregate",+ column_ids: ["col1", "col3"],+ aggregations: ["max"],+ } satisfies TransformType,+};++describe("getUpdatedColumnTypes", () => {+ it("should update column types for column conversion", () => {+ const result = getUpdatedColumnTypes(+ [Transforms.COLUMN_CONVERSION],+ INITIAL_COLUMN_TYPES+ );+ expect(result).toMatchInlineSnapshot(`+ {+ "col1": "bool",+ "col2": "bool",+ "col3": "int",+ }+ `);+ });++ it("should update column types for rename conversion", () => {+ const result = getUpdatedColumnTypes(+ [Transforms.RENAME_COLUMN],+ INITIAL_COLUMN_TYPES+ );+ expect(result).toMatchInlineSnapshot(`+ {+ "col1": "str",+ "col3": "int",+ "newCol2": "bool",+ }+ `);+ });++ it("should update column types for group-by conversion", () => {+ const result = getUpdatedColumnTypes(+ [Transforms.GROUP_BY],+ INITIAL_COLUMN_TYPES+ );+ expect(result).toMatchInlineSnapshot(`+ {+ "col2": "bool",+ }+ `);+ });++ it("should update column types for aggregate conversion", () => {+ const result = getUpdatedColumnTypes(+ [Transforms.AGGREGATE],+ INITIAL_COLUMN_TYPES+ );+ expect(result).toMatchInlineSnapshot(`+ {+ "col1": "str",+ }+ `);+ });++ it("can chain multiple transforms", () => {+ const result = getUpdatedColumnTypes(+ [+ Transforms.COLUMN_CONVERSION,+ Transforms.RENAME_COLUMN,+ Transforms.GROUP_BY_CHAINED,+ Transforms.AGGREGATE_CHAINED,+ ],+ INITIAL_COLUMN_TYPES+ );+ expect(result).toMatchInlineSnapshot(`+ {+ "col1": "bool",+ "col3": "int",+ }+ `);+ });+});diff --git a/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.ts b/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.tsnew file mode 100644index 0000000000..e6df22b9ae--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/utils/__tests__/operators.test.ts@@ -0,0 +1,85 @@+/* Copyright 2023 Marimo. All rights reserved. */+/* eslint-disable jest/no-conditional-expect */++import { expect, describe, it } from "vitest";+import {+ getOperatorForDtype,+ getSchemaForOperator,+ isConditionValueValid,+ BOOLEAN_OPERATORS,+ DATE_OPERATORS,+ NUMERIC_OPERATORS,+ STRING_OPERATORS,+} from "../operators";++describe("getOperatorForDtype", () => {+ it('should return BOOLEAN_OPERATORS for "bool"', () => {+ expect(getOperatorForDtype("bool")).toEqual(Object.keys(BOOLEAN_OPERATORS));+ });++ it('should return NUMERIC_OPERATORS for "int" and "float"', () => {+ expect(getOperatorForDtype("int")).toEqual(Object.keys(NUMERIC_OPERATORS));+ expect(getOperatorForDtype("float")).toEqual(+ Object.keys(NUMERIC_OPERATORS)+ );+ });++ it('should return DATE_OPERATORS for "datetime64[ns]"', () => {+ expect(getOperatorForDtype("datetime64[ns]")).toEqual(+ Object.keys(DATE_OPERATORS)+ );+ });++ it('should return STRING_OPERATORS for "object" and "string"', () => {+ expect(getOperatorForDtype("object")).toEqual(+ Object.keys(STRING_OPERATORS)+ );+ expect(getOperatorForDtype("string")).toEqual(+ Object.keys(STRING_OPERATORS)+ );+ });++ it("should return empty array for unknown dtype", () => {+ expect(getOperatorForDtype("unknown")).toEqual([]);+ });+});++describe("getSchemaForOperator", () => {+ it("should return the correct schema for the given dtype and operator", () => {+ expect(getSchemaForOperator("bool", "is true")).toEqual(+ BOOLEAN_OPERATORS["is_true"]+ );+ expect(getSchemaForOperator("int", "==")).toEqual(NUMERIC_OPERATORS["=="]);+ expect(getSchemaForOperator("datetime64[ns]", "!=")).toEqual(+ DATE_OPERATORS["!="]+ );+ expect(getSchemaForOperator("string", "contains")).toEqual(+ STRING_OPERATORS["contains"]+ );+ });++ it("should return empty array for unknown dtype or operator", () => {+ expect(getSchemaForOperator("unknown", "==")).toEqual([]);+ expect(getSchemaForOperator("int", "unknown")).toEqual([]);+ });+});++describe("isConditionValueValid", () => {+ it("should return true if the value is valid according to the schema for the given operator", () => {+ expect(isConditionValueValid("is_true", true)).toBe(true);+ expect(isConditionValueValid("==", 123)).toBe(true);+ expect(isConditionValueValid("contains", "test")).toBe(true);+ expect(isConditionValueValid("in", ["test"])).toBe(true);+ });++ it("should return false if the value is not valid according to the schema for the given operator", () => {+ expect(isConditionValueValid("==", "not a number")).toBe(false);+ expect(isConditionValueValid("contains", 123)).toBe(false);+ expect(isConditionValueValid("in", "not an array")).toBe(false);+ });++ it("should return true if the operator does not require a value", () => {+ expect(isConditionValueValid("is_true", null)).toBe(true);+ expect(isConditionValueValid("is_nan", undefined)).toBe(true);+ });+});diff --git a/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.tsnew file mode 100644index 0000000000..871be69d23--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/utils/getUpdatedColumnTypes.ts@@ -0,0 +1,66 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { logNever } from "@/utils/assertNever";+import { TransformType } from "../schema";+import { Objects } from "@/utils/objects";+import { ColumnDataTypes } from "../types";++/**+ * Given a list of transforms, return the updated column names/types.+ */+export function getUpdatedColumnTypes(+ transforms: TransformType[],+ columnTypes: ColumnDataTypes+): ColumnDataTypes {+ if (!transforms || transforms.length === 0) {+ return columnTypes;+ }++ let next: ColumnDataTypes = { ...columnTypes };+ for (const transform of transforms) {+ next = handleTransform(transform, next);+ }++ return next;+}++function handleTransform(+ transform: TransformType,+ next: ColumnDataTypes+): ColumnDataTypes {+ switch (transform.type) {+ case "column_conversion":+ if (!transform.column_id) {+ return next;+ }++ next[transform.column_id] = transform.data_type;+ return next;+ 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];+ })+ );+ case "group_by":+ return Objects.filter(+ next,+ (_v, k) => !transform.column_ids.includes(k as string)+ );+ case "aggregate":+ return Objects.filter(next, (_v, k) =>+ transform.column_ids.includes(k as string)+ );+ case "filter_rows":+ case "sort_column":+ return next;+ default:+ logNever(transform);+ return next;+ }+}diff --git a/frontend/src/plugins/impl/data-frames/utils/operators.ts b/frontend/src/plugins/impl/data-frames/utils/operators.tsnew file mode 100644index 0000000000..51b2826c41--- /dev/null+++ b/frontend/src/plugins/impl/data-frames/utils/operators.ts@@ -0,0 +1,129 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { z } from "zod";+import { FieldOptions } from "../forms/options";++const Schema = {+ number: z.coerce.number().describe(FieldOptions.of({ label: "Value" })),+ string: z+ .string()+ .min(1)+ .describe(FieldOptions.of({ label: "Value" })),+ date: z.coerce.date().describe(FieldOptions.of({ label: "Value" })),+ stringArray: z+ .array(z.string())+ .min(1)+ .describe(+ FieldOptions.of({+ label: "Values",+ description: "New-line separated",+ special: "text_area_multiline",+ })+ ),+};++export const BOOLEAN_OPERATORS = {+ is_true: [],+ is_false: [],+};++export const NUMERIC_OPERATORS = {+ "==": [Schema.number],+ "!=": [Schema.number],+ ">": [Schema.number],+ ">=": [Schema.number],+ "<": [Schema.number],+ "<=": [Schema.number],+ is_nan: [],+ is_not_nan: [],+};++export const DATE_OPERATORS = {+ "==": [Schema.date],+ "!=": [Schema.date],+ ">": [Schema.date],+ ">=": [Schema.date],+ "<": [Schema.date],+ "<=": [Schema.date],+ is_nan: [],+ is_not_nan: [],+};++export const STRING_OPERATORS = {+ equals: [Schema.string],+ does_not_equal: [Schema.string],+ contains: [Schema.string],+ regex: [Schema.string],+ starts_with: [Schema.string],+ ends_with: [Schema.string],+ in: [Schema.stringArray],+};++export const ALL_OPERATORS = {+ ...BOOLEAN_OPERATORS,+ ...NUMERIC_OPERATORS,+ ...DATE_OPERATORS,+ ...STRING_OPERATORS,+};++export type OperatorType = keyof typeof ALL_OPERATORS;++export function getOperatorForDtype(dtype: string): readonly string[] {+ if (!dtype) {+ return [];+ }++ if (dtype === "bool") {+ return Object.keys(BOOLEAN_OPERATORS);+ } else if (dtype.startsWith("int") || dtype.startsWith("float")) {+ return Object.keys(NUMERIC_OPERATORS);+ } else if (dtype === "datetime64[ns]") {+ return Object.keys(DATE_OPERATORS);+ } else if (dtype === "object" || dtype === "string") {+ return Object.keys(STRING_OPERATORS);+ } else {+ return [];+ }+}++export function getSchemaForOperator(+ dtype: string,+ operator: string+): [z.ZodType] | [] {+ if (!dtype || !operator) {+ return [];+ }++ if (dtype === "bool") {+ return safeGet(BOOLEAN_OPERATORS, operator);+ } else if (dtype.startsWith("int") || dtype.startsWith("float")) {+ return safeGet(NUMERIC_OPERATORS, operator);+ } else if (dtype === "datetime64[ns]") {+ return safeGet(DATE_OPERATORS, operator);+ } else if (dtype === "object" || dtype === "string") {+ return safeGet(STRING_OPERATORS, operator);+ } else {+ return [];+ }+}++export function isConditionValueValid(operator: string, value: unknown) {+ const possibleSchemas = [+ safeGet(BOOLEAN_OPERATORS, operator),+ safeGet(DATE_OPERATORS, operator),+ safeGet(NUMERIC_OPERATORS, operator),+ safeGet(STRING_OPERATORS, operator),+ ].flat();++ if (possibleSchemas.length === 0) {+ return true;+ }+ return possibleSchemas.some((schema) => schema.safeParse(value).success);+}++// eslint-disable-next-line @typescript-eslint/no-explicit-any+const safeGet = (obj: any, key: string): [z.ZodType] | [] => {+ if (obj[key]) {+ return obj[key];+ }+ return [];+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex e0c2f316a9..e6c0fbbf52 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -30,9 +30,10 @@ import { DownloadPlugin } from "./layout/DownloadPlugin";import { ProgressPlugin } from "./layout/ProgressPlugin";import { VegaPlugin } from "./impl/vega/VegaPlugin";import { StatPlugin } from "./layout/StatPlugin";+import { DataFramePlugin } from "./impl/data-frames/DataFramePlugin";// List of UI plugins-const UI_PLUGINS: Array<IPlugin<any, unknown>> = [+export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new ButtonPlugin(),new CheckboxPlugin(),DataTablePlugin,@@ -51,6 +52,7 @@ const UI_PLUGINS: Array<IPlugin<any, unknown>> = [new TextAreaPlugin(),new TextInputPlugin(),new VegaPlugin(),+ DataFramePlugin,];// List of output / layout pluginsdiff --git a/frontend/src/stories/dataframe.stories.tsx b/frontend/src/stories/dataframe.stories.tsxnew file mode 100644index 0000000000..7ffacc139b--- /dev/null+++ b/frontend/src/stories/dataframe.stories.tsx@@ -0,0 +1,33 @@+/* Copyright 2023 Marimo. All rights reserved. */+/* eslint-disable react-hooks/rules-of-hooks */+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";++const meta: Meta = {+ title: "DataFrame",+ args: {},+};++export default meta;++export const DataFrame: StoryObj = {+ render: () => {+ const [value, setValue] = useState<Transformations>();+ return (+ <DataFrameComponent+ columns={{+ name: "object",+ age: "int",+ height: "float",+ picture: "bytes",+ }}+ dataframeName={"df"}+ value={value}+ setValue={setValue}+ get_dataframe={() => Promise.reject({})}+ />+ );+ },+};diff --git a/frontend/src/utils/__tests__/json-parser.test.ts b/frontend/src/utils/__tests__/json-parser.test.tsnew file mode 100644index 0000000000..66fc0a5b7e--- /dev/null+++ b/frontend/src/utils/__tests__/json-parser.test.ts@@ -0,0 +1,56 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { expect, it } from "vitest";+import { jsonParseWithSpecialChar } from "../json-parser";++it("can jsonParseWithSpecialChar happy path", () => {+ expect(jsonParseWithSpecialChar('"hello"')).toEqual("hello");+ expect(+ jsonParseWithSpecialChar(+ '[false,{"a":1},true,0,1,[{"a":1},{"b":2}],"hello",""]'+ )+ ).toEqual([false, { a: 1 }, true, 0, 1, [{ a: 1 }, { b: 2 }], "hello", ""]);++ expect(jsonParseWithSpecialChar("10")).toEqual(10);+ expect(jsonParseWithSpecialChar("null")).toEqual(null);+});++it("can jsonParseWithSpecialChar NaN, Infinity, -Infinity", () => {+ expect(jsonParseWithSpecialChar("NaN")).toEqual(Number.NaN);+ expect(jsonParseWithSpecialChar('{"A":NaN}')).toEqual({ A: Number.NaN });+ expect(jsonParseWithSpecialChar("[NaN]")).toEqual([Number.NaN]);+ expect(jsonParseWithSpecialChar("[-Infinity]")).toEqual([+ Number.NEGATIVE_INFINITY,+ ]);+ expect(jsonParseWithSpecialChar("[Infinity]")).toEqual([+ Number.POSITIVE_INFINITY,+ ]);+ expect(+ jsonParseWithSpecialChar('[NaN,Infinity,-Infinity,{"A": NaN}]')+ ).toEqual([+ Number.NaN,+ Number.POSITIVE_INFINITY,+ Number.NEGATIVE_INFINITY,+ { A: Number.NaN },+ ]);++ // Prevent false positives as text+ expect(jsonParseWithSpecialChar('"NaN"')).toEqual("NaN");+ expect(jsonParseWithSpecialChar('"Infinity"')).toEqual("Infinity");+ expect(jsonParseWithSpecialChar('"-Infinity"')).toEqual("-Infinity");++ expect(jsonParseWithSpecialChar('"This is NaN"')).toEqual("This is NaN");+ expect(jsonParseWithSpecialChar('"To Infinity and Beyond"')).toEqual(+ "To Infinity and Beyond"+ );+ expect(jsonParseWithSpecialChar('"To -Infinity and Beyond"')).toEqual(+ "To -Infinity and Beyond"+ );+});++it("can fail to jsonParseWithSpecialChar", () => {+ // Fail to parse+ expect(jsonParseWithSpecialChar("")).toMatchInlineSnapshot("{}");+ expect(jsonParseWithSpecialChar("undefined")).toMatchInlineSnapshot("{}");+ expect(jsonParseWithSpecialChar(undefined!)).toMatchInlineSnapshot("{}");+ expect(jsonParseWithSpecialChar("[nan]")).toMatchInlineSnapshot("{}");+});diff --git a/frontend/src/utils/arrays.ts b/frontend/src/utils/arrays.tsindex d21c7c04b3..5aa436cf04 100644--- a/frontend/src/utils/arrays.ts+++ b/frontend/src/utils/arrays.ts@@ -6,3 +6,8 @@ export function arrayDelete<T>(array: T[], index: number): T[] {export function arrayInsert<T>(array: T[], index: number, value: T): T[] {return [...array.slice(0, index), value, ...array.slice(index)];}++export const Arrays = {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ EMPTY: [] as any[],+};diff --git a/frontend/src/utils/errors.ts b/frontend/src/utils/errors.tsnew file mode 100644index 0000000000..193ca9157b--- /dev/null+++ b/frontend/src/utils/errors.ts@@ -0,0 +1,12 @@+/* Copyright 2023 Marimo. All rights reserved. */++export function prettyError(error: unknown) {+ if (error instanceof Error) {+ return error.message;+ }+ try {+ return JSON.stringify(error);+ } catch {+ return String(error);+ }+}diff --git a/frontend/src/utils/events.ts b/frontend/src/utils/events.tsindex c46a75f31b..5484608141 100644--- a/frontend/src/utils/events.ts+++ b/frontend/src/utils/events.ts@@ -10,4 +10,13 @@ export const Events = {}};},+ onEnter: <E extends Pick<KeyboardEvent, "key">>(+ callback?: (evt: E) => void+ ) => {+ return (event: E) => {+ if (event.key === "Enter" && callback) {+ callback(event);+ }+ };+ },};diff --git a/frontend/src/utils/functions.ts b/frontend/src/utils/functions.tsindex 620229dea5..77b39c7f2c 100644--- a/frontend/src/utils/functions.ts+++ b/frontend/src/utils/functions.ts@@ -3,4 +3,7 @@ export const Functions = {NOOP: () => {return;},+ THROW: () => {+ throw new Error("Should not be called");+ },};diff --git a/frontend/src/utils/json-parser.ts b/frontend/src/utils/json-parser.tsnew file mode 100644index 0000000000..595aa779e3--- /dev/null+++ b/frontend/src/utils/json-parser.ts@@ -0,0 +1,43 @@+/* Copyright 2023 Marimo. All rights reserved. */++/**+ * Parse an attribute value as JSON.+ * This also handles NaN, Infinity, and -Infinity.+ */+export function jsonParseWithSpecialChar<T>(value: string): T {+ // Random unicode character that is unlikely to be used in the JSON string+ const CHAR = "◐";++ if (value == null || value === "") {+ return {} as T;+ }++ try {+ // This will properly handle NaN, Infinity, and -Infinity+ // The python json.dumps encoding will serialize to NaN, Infinity, -Infinity which is not valid JSON,+ // but we don't want to change the python encoding because NaN, Infinity, -Infinity are valuable to know.+ value = value ?? "";+ value = value.replaceAll(+ // This was iterated on with GPT. The confidence lies in the unit tests.+ /(?<=\s|^|\[|,|:)(NaN|-Infinity|Infinity)(?=(?:[^"'\\]*(\\.|'([^'\\]*\\.)*[^'\\]*'|"([^"\\]*\\.)*[^"\\]*"))*[^"']*$)/g,+ `"${CHAR}$1${CHAR}"`+ );+ return JSON.parse(value, (key, v) => {+ if (typeof v !== "string") {+ return v;+ }+ if (v === `${CHAR}NaN${CHAR}`) {+ return Number.NaN;+ }+ if (v === `${CHAR}Infinity${CHAR}`) {+ return Number.POSITIVE_INFINITY;+ }+ if (v === `${CHAR}-Infinity${CHAR}`) {+ return Number.NEGATIVE_INFINITY;+ }+ return v;+ }) as T;+ } catch {+ return {} as T;+ }+}diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.tsindex 6278a3a5bf..995afba865 100644--- a/frontend/src/utils/objects.ts+++ b/frontend/src/utils/objects.ts@@ -66,4 +66,16 @@ export const Objects = {}return result;},+ filter<K extends string | number, V>(+ obj: Record<K, V>,+ predicate: (value: V, key: K) => boolean+ ): Record<K, V> {+ const result: Record<K, V> = {} as Record<K, V>;+ for (const [key, value] of Objects.entries(obj)) {+ if (predicate(value, key)) {+ result[key] = obj[key];+ }+ }+ return result;+ },};diff --git a/frontend/src/utils/strings.ts b/frontend/src/utils/strings.tsnew file mode 100644index 0000000000..35b5d9ab63--- /dev/null+++ b/frontend/src/utils/strings.ts@@ -0,0 +1,25 @@+/* Copyright 2023 Marimo. All rights reserved. */+import { startCase } from "lodash-es";++export const Strings = {+ /**+ * startCase that can handle non-letters+ */+ startCase: (str: string): string => {+ if (!str) {+ return "";+ }++ if (typeof str !== "string") {+ console.error(str);+ throw new TypeError(`Expected string, got ${typeof str}`);+ }++ // If has no letters, return the string+ if (!/[A-Za-z]/.test(str)) {+ return str;+ }++ return startCase(str);+ },+};diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.pyindex 6c2ad15baf..efe7ca478f 100644--- a/marimo/_plugins/core/json_encoder.py+++ b/marimo/_plugins/core/json_encoder.py@@ -24,6 +24,8 @@ class WebComponentEncoder(JSONEncoder):if any([np.issubdtype(obj.dtype, i) for i in dtypes]):return obj.astype(str).tolist()return obj.tolist()+ elif isinstance(obj, np.dtype):+ return str(obj)# Handle pandas objectsif DependencyManager.has_pandas():@@ -41,5 +43,9 @@ class WebComponentEncoder(JSONEncoder):(mimetype, data) = obj._mime_()return {"mimetype": mimetype, "data": data}+ # Handle bytes objects+ if isinstance(obj, bytes):+ return obj.decode("utf-8")+# Fallthrough to default encoderreturn JSONEncoder.default(self, obj)diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex 55746ac763..c92f83e588 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -11,6 +11,7 @@ __all__ = ["button","checkbox","date",+ "dataframe","dictionary","dropdown","file",@@ -31,6 +32,7 @@ __all__ = [from marimo._plugins.ui._impl.altair_chart import altair_chartfrom marimo._plugins.ui._impl.array import arrayfrom marimo._plugins.ui._impl.batch import batch+from marimo._plugins.ui._impl.dataframes.dataframe import dataframefrom marimo._plugins.ui._impl.dictionary import dictionaryfrom marimo._plugins.ui._impl.input import (button,diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.pyindex 3d5f14f8a4..4cc00f0aa1 100644--- a/marimo/_plugins/ui/_impl/altair_chart.py+++ b/marimo/_plugins/ui/_impl/altair_chart.py@@ -50,13 +50,10 @@ def _has_binning(spec: VegaSpec) -> bool:def _filter_dataframe(- df_prev: pd.DataFrame, selection: ChartSelection+ df: pd.DataFrame, selection: ChartSelection) -> pd.DataFrame:import numpy as np- # Make a copy of the DataFrame- df = df_prev.copy()-for _channel, fields in selection.items():# If vlPoint is in the selection,# then the selection is a point selectiondiff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pynew file mode 100644index 0000000000..7102f6d9ac--- /dev/null+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -0,0 +1,126 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import inspect+import sys+from typing import TYPE_CHECKING, Any, Callable, Dict, Final, List, Optional++if TYPE_CHECKING:+ import pandas as pd++from dataclasses import dataclass++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.utils.dataframe import get_row_headers+from marimo._runtime.functions import Function+from marimo._utils.parse_dataclass import parse_raw++from .handlers import TransformsContainer+from .transforms import Transformations+++@dataclass+class EmptyArgs:+ ...+++@dataclass+class GetDataFrameResponse:+ url: str+ row_headers: List[tuple[str, List[str | int | float]]]+++@mddoc+class dataframe(UIElement[Dict[str, Any], "pd.DataFrame"]):+ """+ Run transformations on a DataFrame or series.++ **Example.**++ ```python+ dataframe = mo.ui.dataframe(data)+ ```++ **Attributes.**++ - `value`: the transformed DataFrame or series++ **Initialization Args.**++ - `df`: the DataFrame or series to transform+ """++ _name: Final[str] = "marimo-dataframe"++ def __init__(+ self,+ df: pd.DataFrame,+ on_change: Optional[Callable[[pd.DataFrame], None]] = None,+ ) -> None:+ # HACK: this is a hack to get the name of the variable that was passed+ dataframe_name = "df"+ try:+ frame = inspect.currentframe()+ if frame is not None and frame.f_back is not None:+ for (+ var_name,+ var_value,+ ) in frame.f_back.f_locals.items():+ if var_value is df:+ dataframe_name = var_name+ break+ except Exception:+ pass++ self._data = df+ self._transform_container = TransformsContainer(df)+ self._error: Optional[str] = None++ super().__init__(+ component_name=dataframe._name,+ initial_value={+ "transforms": [],+ },+ on_change=on_change,+ label="",+ args={+ "columns": df.dtypes.to_dict(),+ "dataframe-name": dataframe_name,+ "total": len(df),+ },+ functions=(+ Function(+ name=self.get_dataframe.__name__,+ arg_cls=EmptyArgs,+ function=self.get_dataframe,+ ),+ ),+ )++ def get_dataframe(self, _args: EmptyArgs) -> GetDataFrameResponse:+ if self._error is not None:+ raise Exception(self._error)++ url = mo_data.csv(self._value).url+ return GetDataFrameResponse(+ url=url,+ row_headers=get_row_headers(self._value),+ )++ def _convert_value(self, value: Dict[str, Any]) -> pd.DataFrame:+ if value is None:+ self._error = None+ return self._data++ try:+ transformations = parse_raw(value, Transformations)+ result = self._transform_container.apply(transformations)+ self._error = None+ return result+ except Exception as e:+ error = "Error applying dataframe transform: %s\n\n" % str(e)+ sys.stderr.write(error)+ self._error = error+ return self._datadiff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.pynew file mode 100644index 0000000000..fe44edace7--- /dev/null+++ b/marimo/_plugins/ui/_impl/dataframes/handlers.py@@ -0,0 +1,249 @@+# Copyright 2023 Marimo. All rights reserved.+from typing import TYPE_CHECKING, Any, List, NoReturn, cast++from .transforms import (+ AggregateTransform,+ ColumnConversionTransform,+ FilterRowsTransform,+ GroupByTransform,+ RenameColumnTransform,+ SortColumnTransform,+ Transform,+ Transformations,+ TransformType,+)++if TYPE_CHECKING:+ import pandas as pd+++class TransformHandlers:+ @staticmethod+ def handle(df: "pd.DataFrame", transform: Transform) -> "pd.DataFrame":+ transform_type: TransformType = transform.type++ if transform_type is TransformType.COLUMN_CONVERSION:+ return TransformHandlers.handle_column_conversion(+ df, cast(ColumnConversionTransform, transform)+ )+ elif transform_type is TransformType.RENAME_COLUMN:+ return TransformHandlers.handle_rename_column(+ df, cast(RenameColumnTransform, transform)+ )+ elif transform_type is TransformType.SORT_COLUMN:+ return TransformHandlers.handle_sort_column(+ df, cast(SortColumnTransform, transform)+ )+ elif transform_type is TransformType.FILTER_ROWS:+ return TransformHandlers.handle_filter_rows(+ df, cast(FilterRowsTransform, transform)+ )+ elif transform_type is TransformType.GROUP_BY:+ return TransformHandlers.handle_group_by(+ df, cast(GroupByTransform, transform)+ )+ elif transform_type is TransformType.AGGREGATE:+ return TransformHandlers.handle_aggregate(+ df, cast(AggregateTransform, transform)+ )++ else:+ _assert_never(transform_type)++ @staticmethod+ def handle_column_conversion(+ df: "pd.DataFrame", transform: ColumnConversionTransform+ ) -> "pd.DataFrame":+ df[transform.column_id] = df[transform.column_id].astype(+ transform.data_type,+ errors=transform.errors,+ ) # type: ignore[call-overload]+ return df++ @staticmethod+ def handle_rename_column(+ df: "pd.DataFrame", transform: RenameColumnTransform+ ) -> "pd.DataFrame":+ return df.rename(+ columns={transform.column_id: transform.new_column_id}+ )++ @staticmethod+ def handle_sort_column(+ df: "pd.DataFrame", transform: SortColumnTransform+ ) -> "pd.DataFrame":+ return df.sort_values(+ by=transform.column_id,+ ascending=transform.ascending,+ na_position=transform.na_position,+ )++ @staticmethod+ def handle_filter_rows(+ df: "pd.DataFrame", transform: FilterRowsTransform+ ) -> "pd.DataFrame":+ for condition in transform.where:+ value = _coerce_value(+ df[condition.column_id].dtype, condition.value+ )+ if condition.operator == "==":+ df_filter = df[condition.column_id] == value+ elif condition.operator == "!=":+ df_filter = df[condition.column_id] != value+ elif condition.operator == ">":+ df_filter = df[condition.column_id] > value+ elif condition.operator == "<":+ df_filter = df[condition.column_id] < value+ elif condition.operator == ">=":+ df_filter = df[condition.column_id] >= value+ elif condition.operator == "<=":+ df_filter = df[condition.column_id] <= value+ elif condition.operator == "is_true":+ df_filter = df[condition.column_id] is True+ elif condition.operator == "is_false":+ df_filter = df[condition.column_id] is False+ elif condition.operator == "is_nan":+ df_filter = df[condition.column_id].isna()+ elif condition.operator == "is_not_nan":+ df_filter = df[condition.column_id].notna()+ elif condition.operator == "equals":+ df_filter = df[condition.column_id].eq(value)+ elif condition.operator == "contains":+ df_filter = df[condition.column_id].str.contains(+ value, regex=False+ )+ elif condition.operator == "regex":+ df_filter = df[condition.column_id].str.contains(+ value, regex=True+ )+ elif condition.operator == "starts_with":+ df_filter = df[condition.column_id].str.startswith(value)+ elif condition.operator == "ends_with":+ df_filter = df[condition.column_id].str.endswith(value)+ elif condition.operator == "in":+ df_filter = df[condition.column_id].isin(value)+ else:+ _assert_never(condition.operator)++ if transform.operation == "keep_rows":+ df = df[df_filter]+ elif transform.operation == "remove_rows":+ df = df[~df_filter]+ else:+ _assert_never(transform.operation)+ return df++ @staticmethod+ def handle_group_by(+ df: "pd.DataFrame", transform: GroupByTransform+ ) -> "pd.DataFrame":+ group = df.groupby(transform.column_ids, dropna=transform.drop_na)+ if transform.aggregation == "count":+ return group.count()+ elif transform.aggregation == "sum":+ return group.sum()+ elif transform.aggregation == "mean":+ return group.mean(numeric_only=True)+ elif transform.aggregation == "median":+ return group.median(numeric_only=True)+ elif transform.aggregation == "min":+ return group.min()+ elif transform.aggregation == "max":+ return group.max()+ else:+ _assert_never(transform.aggregation)++ @staticmethod+ def handle_aggregate(+ df: "pd.DataFrame", transform: AggregateTransform+ ) -> "pd.DataFrame":+ dict_of_aggs = {+ column_id: transform.aggregations+ for column_id in transform.column_ids+ }+ return df.agg(dict_of_aggs) # type: ignore[arg-type]+++def apply_transforms(+ df: "pd.DataFrame", transforms: Transformations+) -> "pd.DataFrame":+ if not transforms.transforms:+ return df+ for transform in transforms.transforms:+ df = TransformHandlers.handle(df, transform)+ return df+++def _assert_never(value: NoReturn) -> NoReturn:+ raise AssertionError(f"Unhandled value: {value} ({type(value).__name__})")+++def _coerce_value(dtype: Any, value: Any) -> Any:+ import numpy as np++ return np.array([value]).astype(dtype)[0]+++class TransformsContainer:+ """+ Keeps internal state of the last transformation applied to the dataframe.+ So that we can incrementally apply transformations.+ """++ def __init__(self, df: "pd.DataFrame") -> None:+ self._original_df = df+ # The dataframe for the given transform.+ self._snapshot_df = df+ self._transforms: List[Transform] = []++ def apply(self, transform: Transformations) -> "pd.DataFrame":+ """+ Applies the given transformations to the dataframe.+ """+ # If the new transformations are a superset of the existing ones,+ # then we can just apply the new ones to the snapshot dataframe.+ if self._is_superset(transform):+ transforms_to_apply = self._get_next_transformations(transform)+ self._snapshot_df = apply_transforms(+ self._snapshot_df, transforms_to_apply+ )+ self._transforms = transform.transforms+ return self._snapshot_df++ # If the new transformations are not a superset of the existing ones,+ # then we need to start from the original dataframe.+ else:+ self._snapshot_df = apply_transforms(self._original_df, transform)+ self._transforms = transform.transforms+ return self._snapshot_df++ def _is_superset(self, transforms: Transformations) -> bool:+ """+ Checks if the new transformations are a superset of the existing ones.+ """+ if not self._transforms:+ return False++ # If the new transformations are smaller than the existing ones,+ # then it's not a superset.+ if len(self._transforms) > len(transforms.transforms):+ return False++ for i, transform in enumerate(self._transforms):+ if transform != transforms.transforms[i]:+ return False++ return True++ def _get_next_transformations(+ self, transforms: Transformations+ ) -> Transformations:+ """+ Gets the next transformations to apply.+ """+ if self._is_superset(transforms):+ return Transformations(+ transforms.transforms[len(self._transforms) :]+ )+ else:+ return transformsdiff --git a/marimo/_plugins/ui/_impl/dataframes/test_handlers.py b/marimo/_plugins/ui/_impl/dataframes/test_handlers.pynew file mode 100644index 0000000000..ec04d53a4b--- /dev/null+++ b/marimo/_plugins/ui/_impl/dataframes/test_handlers.py@@ -0,0 +1,309 @@+# Copyright 2023 Marimo. All rights reserved.+import pandas as pd++from marimo._plugins.ui._impl.dataframes.handlers import (+ TransformsContainer,+ apply_transforms,+)+from marimo._plugins.ui._impl.dataframes.transforms import (+ AggregateTransform,+ ColumnConversionTransform,+ Condition,+ FilterRowsTransform,+ GroupByTransform,+ RenameColumnTransform,+ SortColumnTransform,+ Transform,+ Transformations,+ TransformType,+)+++def apply(df: pd.DataFrame, transform: Transform) -> pd.DataFrame:+ return apply_transforms(df, Transformations(transforms=[transform]))+++def test_handle_column_conversion() -> None:+ # 1 string to int+ df = pd.DataFrame({"A": ["1", "2", "3"]})+ transform = ColumnConversionTransform(+ type=TransformType.COLUMN_CONVERSION,+ column_id="A",+ data_type="int",+ errors="raise",+ )+ result = apply(df, transform)+ assert result["A"].dtype == "int"+ # 2 float to string+ df = pd.DataFrame({"A": [1.1, 2.2, 3.3]})+ transform = ColumnConversionTransform(+ type=TransformType.COLUMN_CONVERSION,+ column_id="A",+ data_type="str",+ errors="raise",+ )+ result = apply(df, transform)+ assert result["A"].dtype == "object"+ assert result["A"].tolist() == ["1.1", "2.2", "3.3"]+ # 3 with errors+ df = pd.DataFrame({"A": ["1", "2", "3", "a"]})+ transform = ColumnConversionTransform(+ type=TransformType.COLUMN_CONVERSION,+ column_id="A",+ data_type="int",+ errors="ignore",+ )+ result = apply(df, transform)+ assert result["A"].dtype == "object"+ assert result["A"].tolist() == ["1", "2", "3", "a"]+++def test_handle_rename_column() -> None:+ df = pd.DataFrame({"A": [1, 2, 3]})+ transform = RenameColumnTransform(+ type=TransformType.RENAME_COLUMN, column_id="A", new_column_id="B"+ )+ result = apply(df, transform)+ assert "B" in result.columns+ assert "A" not in result.columns++ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = RenameColumnTransform(+ type=TransformType.RENAME_COLUMN, column_id="B", new_column_id="C"+ )+ result = apply(df, transform)+ assert "C" in result.columns+ assert "B" not in result.columns+++def test_handle_sort_column() -> None:+ df = pd.DataFrame({"A": [3, 2, 1]})+ transform = SortColumnTransform(+ type=TransformType.SORT_COLUMN,+ column_id="A",+ ascending=True,+ na_position="last",+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [1, 2, 3]++ df = pd.DataFrame({"A": [3, 2, 1], "B": [1, 3, 2]})+ transform = SortColumnTransform(+ type=TransformType.SORT_COLUMN,+ column_id="B",+ ascending=False,+ na_position="last",+ )+ result = apply(df, transform)+ assert result["B"].tolist() == [3, 2, 1]+++def test_handle_filter_rows_1() -> None:+ df = pd.DataFrame({"A": [1, 2, 3]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[Condition(column_id="A", operator=">=", value=2)],+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [2, 3]+++def test_handle_filter_rows_2() -> None:+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="remove_rows",+ where=[Condition(column_id="B", operator="!=", value=5)],+ )+ result = apply(df, transform)+ assert result["B"].tolist() == [5]+++def test_handle_filter_rows_3() -> None:+ df = pd.DataFrame({"A": [1, 2, 3, 4, 5]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[Condition(column_id="A", operator="<", value=4)],+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [1, 2, 3]+++def test_handle_filter_rows_4() -> None:+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="remove_rows",+ where=[Condition(column_id="A", operator="==", value=2)],+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [1, 3]+++def test_handle_filter_rows_5() -> None:+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[Condition(column_id="B", operator=">=", value=5)],+ )+ result = apply(df, transform)+ assert result["B"].tolist() == [5, 6]+++def test_handle_filter_rows_6() -> None:+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="remove_rows",+ where=[Condition(column_id="B", operator="<", value=6)],+ )+ result = apply(df, transform)+ assert result["B"].tolist() == [6]+++def test_handle_filter_rows_multiple_conditions_1() -> None:+ df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[+ Condition(column_id="A", operator=">=", value=3),+ Condition(column_id="B", operator="<=", value=3),+ ],+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [3, 4, 5]+ assert result["B"].tolist() == [3, 2, 1]+++def test_handle_filter_rows_multiple_conditions_2() -> None:+ df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="remove_rows",+ where=[+ Condition(column_id="A", operator="==", value=2),+ Condition(column_id="B", operator="==", value=4),+ ],+ )+ result = apply(df, transform)+ assert result["A"].tolist() == [1, 3, 4, 5]+ assert result["B"].tolist() == [5, 3, 2, 1]+++def test_handle_group_by() -> None:+ df = pd.DataFrame({"A": ["foo", "foo", "bar"], "B": [1, 2, 3]})+ transform = GroupByTransform(+ type=TransformType.GROUP_BY,+ column_ids=["A"],+ drop_na=False,+ aggregation="sum",+ )+ result = apply(df, transform)+ assert result["B"].tolist() == [3, 3]++ df = pd.DataFrame({"A": ["foo", "foo", "bar", "bar"], "B": [1, 2, 3, 4]})+ transform = GroupByTransform(+ type=TransformType.GROUP_BY,+ column_ids=["A"],+ drop_na=False,+ aggregation="mean",+ )+ result = apply(df, transform)+ assert set(result["B"].tolist()) == set([1.5, 3.5])+++def test_handle_aggregate() -> None:+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = AggregateTransform(+ type=TransformType.AGGREGATE,+ column_ids=["A", "B"],+ aggregations=["sum"],+ )+ result = apply(df, transform)+ assert result["A"]["sum"] == 6+ assert result["B"]["sum"] == 15++ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ transform = AggregateTransform(+ type=TransformType.AGGREGATE,+ column_ids=["A", "B"],+ aggregations=["min", "max"],+ )+ result = apply(df, transform)+ assert result["A"]["min"] == 1+ assert result["A"]["max"] == 3+ assert result["B"]["min"] == 4+ assert result["B"]["max"] == 6+++def test_transforms_container() -> None:+ # Create a sample dataframe+ df = pd.DataFrame({"A": [1, 2, 3, 4, 5], "B": [5, 4, 3, 2, 1]})+ # Create a TransformsContainer object+ container = TransformsContainer(df)++ # Define some transformations+ sort_transform = SortColumnTransform(+ type=TransformType.SORT_COLUMN,+ column_id="B",+ ascending=False,+ na_position="last",+ )+ filter_transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[Condition(column_id="A", operator=">=", value=2)],+ )+ transformations = Transformations([sort_transform, filter_transform])+ # Verify the next transformation+ assert container._is_superset(transformations) is False+ assert (+ container._get_next_transformations(transformations) == transformations+ )++ # Apply the transformations+ result = container.apply(transformations)++ # Get the transformed dataframe+ # Check that the transformations were applied correctly+ assert result["A"].tolist() == [2, 3, 4, 5]+ assert result["B"].tolist() == [4, 3, 2, 1]++ # Reapply transforms by adding a new one+ filter_again_transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="remove_rows",+ where=[Condition(column_id="B", operator="==", value=4)],+ )+ transformations = Transformations(+ [sort_transform, filter_transform, filter_again_transform]+ )+ # Verify the next transformation+ assert container._is_superset(transformations) is True+ assert container._get_next_transformations(+ transformations+ ) == Transformations([filter_again_transform])+ result = container.apply(+ transformations,+ )+ # Check that the transformations were applied correctly+ assert result["A"].tolist() == [3, 4, 5]+ assert result["B"].tolist() == [3, 2, 1]++ transformations = Transformations([sort_transform, filter_transform])+ # Verify the next transformation+ assert container._is_superset(transformations) is False+ assert (+ container._get_next_transformations(transformations) == transformations+ )+ # Reapply by removing the last transform+ result = container.apply(+ transformations,+ )+ # Check that the transformations were applied correctly+ assert result["A"].tolist() == [2, 3, 4, 5]+ assert result["B"].tolist() == [4, 3, 2, 1]diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms.py b/marimo/_plugins/ui/_impl/dataframes/transforms.pynew file mode 100644index 0000000000..7419ecb0e0--- /dev/null+++ b/marimo/_plugins/ui/_impl/dataframes/transforms.py@@ -0,0 +1,113 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from dataclasses import dataclass+from enum import Enum+from typing import Any, List, Literal, Union++ColumnId = str+ColumnIds = List[ColumnId]+NumpyDataType = str+Operator = Literal[+ "==",+ "!=",+ "<",+ ">",+ "<",+ "<=",+ ">=",+ "is_true",+ "is_false",+ "is_nan",+ "is_not_nan",+ "equals",+ "contains",+ "regex",+ "starts_with",+ "ends_with",+ "in",+]+Aggregation = Literal[+ "count",+ "sum",+ "mean",+ "median",+ "min",+ "max",+]+++class TransformType(Enum):+ COLUMN_CONVERSION = "column_conversion"+ RENAME_COLUMN = "rename_column"+ SORT_COLUMN = "sort_column"+ FILTER_ROWS = "filter_rows"+ GROUP_BY = "group_by"+ AGGREGATE = "aggregate"+++@dataclass+class Condition:+ column_id: ColumnId+ operator: Operator+ value: Any+++@dataclass+class ColumnConversionTransform:+ type: Literal[TransformType.COLUMN_CONVERSION]+ column_id: ColumnId+ data_type: NumpyDataType+ errors: Literal["ignore", "raise"]+++@dataclass+class RenameColumnTransform:+ type: Literal[TransformType.RENAME_COLUMN]+ column_id: ColumnId+ new_column_id: ColumnId+++@dataclass+class SortColumnTransform:+ type: Literal[TransformType.SORT_COLUMN]+ column_id: ColumnId+ ascending: bool+ na_position: Literal["first", "last"]+++@dataclass+class FilterRowsTransform:+ type: Literal[TransformType.FILTER_ROWS]+ operation: Literal["keep_rows", "remove_rows"]+ where: List[Condition]+++@dataclass+class GroupByTransform:+ type: Literal[TransformType.GROUP_BY]+ column_ids: ColumnIds+ drop_na: bool+ aggregation: Aggregation+++@dataclass+class AggregateTransform:+ type: Literal[TransformType.AGGREGATE]+ column_ids: ColumnIds+ aggregations: List[Aggregation]+++Transform = Union[+ ColumnConversionTransform,+ RenameColumnTransform,+ SortColumnTransform,+ FilterRowsTransform,+ GroupByTransform,+ AggregateTransform,+]+++@dataclass+class Transformations:+ transforms: List[Transform]diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex ee51c8c46b..41f1131c85 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -4,7 +4,6 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import (TYPE_CHECKING,- Any,Callable,Dict,Final,@@ -23,6 +22,7 @@ from marimo._output.mime import MIMEfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.ui._impl.utils.dataframe import TableData, get_row_headersfrom marimo._runtime.functions import FunctionLOGGER = _loggers.marimo_logger()@@ -32,12 +32,6 @@ Numeric = Union[int, float]if TYPE_CHECKING:import pandas as pd-TableData = Union[- Sequence[Union[str, int, float, bool, MIME, None]],- Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],- "pd.DataFrame",-]-@dataclassclass DownloadAsArgs:@@ -130,7 +124,7 @@ class table(UIElement[List[str], Union[List[object], "pd.DataFrame"]]):"page-size": page_size,"selection": selection,"show-download": DependencyManager.has_pandas(),- "row-headers": _get_row_headers(data),+ "row-headers": get_row_headers(data),},on_change=on_change,functions=(@@ -213,48 +207,3 @@ def _normalize_data(data: TableData) -> JSONType:# Sequence of dictsreturn data---def _get_row_headers(- data: TableData,-) -> List[tuple[str, List[str | int | float]]]:- if DependencyManager.has_pandas():- import pandas as pd-- if isinstance(data, pd.DataFrame):- return _get_row_headers_for_index(data.index)- return []---def _get_row_headers_for_index(- index: pd.Index[Any],-) -> List[tuple[str, List[str | int | float]]]:- import pandas as pd-- if isinstance(index, pd.RangeIndex):- return []-- if isinstance(index, pd.MultiIndex):- # recurse- headers = []- for i in range(index.nlevels):- headers.extend(- _get_row_headers_for_index(index.get_level_values(i))- )- return headers-- # we only care about the index if it has a name- # or if it is type 'object'- # otherwise, it may look like meaningless number- if isinstance(index, pd.Index):- dtype = str(index.dtype)- if (- index.name- or dtype == "object"- or dtype == "string"- or dtype == "category"- ):- name = str(index.name) if index.name else ""- return [(name, index.tolist())] # type: ignore[list-item]-- return []diff --git a/marimo/_plugins/ui/_impl/test_table.py b/marimo/_plugins/ui/_impl/test_table.pyindex 7593a4f454..361258152f 100644--- a/marimo/_plugins/ui/_impl/test_table.py+++ b/marimo/_plugins/ui/_impl/test_table.py@@ -1,13 +1,12 @@# Copyright 2023 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, List+from typing import Anyfrom marimo._plugins.ui._impl.table import (- TableData,- _get_row_headers,_normalize_data,)+from marimo._plugins.ui._impl.utils.dataframe import TableDatafrom marimo._runtime.conftest import MockedKernelfrom marimo._runtime.runtime import ExecutionContext@@ -78,48 +77,3 @@ def test_normalize_data() -> None:== "data must be a sequence of JSON-serializable types, or a "+ "sequence of dicts.")---def test_get_row_headers() -> None:- try:- import pandas as pd-- expected: List[tuple[str, List[str]]]-- # Test with pandas DataFrame- df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})- df.index.name = "Index"- assert _get_row_headers(df) == []-- # Test with non-DataFrame input- assert _get_row_headers([1, 2, 3]) == []-- # Test with MultiIndex- arrays = [- ["foo", "bar", "baz"],- ["one", "two", "three"],- ]- df_multi = pd.DataFrame({"A": range(3)}, index=arrays)- expected = [- ("", ["foo", "bar", "baz"]),- ("", ["one", "two", "three"]),- ]- assert _get_row_headers(df_multi) == expected-- # Test with RangeIndex- df_range = pd.DataFrame({"A": range(3)})- assert _get_row_headers(df_range) == []-- # Test with categorical Index- df_cat = pd.DataFrame({"A": range(3)})- df_cat.index = pd.CategoricalIndex(["a", "b", "c"])- expected = [("", ["a", "b", "c"])]- assert _get_row_headers(df_cat) == expected-- # Test with named categorical Index- df_cat = pd.DataFrame({"A": range(3)})- df_cat.index = pd.CategoricalIndex(["a", "b", "c"], name="Colors")- expected = [("Colors", ["a", "b", "c"])]- assert _get_row_headers(df_cat) == expected- except ImportError:- passdiff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.pynew file mode 100644index 0000000000..c8e29ff390--- /dev/null+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py@@ -0,0 +1,77 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from typing import (+ TYPE_CHECKING,+ Any,+ Dict,+ List,+ Sequence,+ Union,+)++from marimo import _loggers+from marimo._dependencies.dependencies import DependencyManager+from marimo._output.mime import MIME++LOGGER = _loggers.marimo_logger()++Numeric = Union[int, float]++TableData = Union[+ Sequence[Union[str, int, float, bool, MIME, None]],+ Sequence[Dict[str, Union[str, int, float, bool, MIME, None]]],+ "pd.DataFrame",+]+++if TYPE_CHECKING:+ import pandas as pd+++def get_row_headers(+ data: TableData,+) -> List[tuple[str, List[str | int | float]]]:+ if not DependencyManager.has_pandas():+ return []++ import pandas as pd++ if isinstance(data, pd.DataFrame):+ return _get_row_headers_for_index(data.index)++ return []+++def _get_row_headers_for_index(+ index: pd.Index[Any],+) -> List[tuple[str, List[str | int | float]]]:+ import pandas as pd++ if isinstance(index, pd.RangeIndex):+ return []++ if isinstance(index, pd.MultiIndex):+ # recurse+ headers = []+ for i in range(index.nlevels):+ headers.extend(+ _get_row_headers_for_index(index.get_level_values(i))+ )+ return headers++ # we only care about the index if it has a name+ # or if it is type 'object'+ # otherwise, it may look like meaningless number+ if isinstance(index, pd.Index):+ dtype = str(index.dtype)+ if (+ index.name+ or dtype == "object"+ or dtype == "string"+ or dtype == "category"+ ):+ name = str(index.name) if index.name else ""+ return [(name, index.tolist())] # type: ignore[list-item]++ return []diff --git a/marimo/_plugins/ui/_impl/utils/test_dataframe.py b/marimo/_plugins/ui/_impl/utils/test_dataframe.pynew file mode 100644index 0000000000..8002556d31--- /dev/null+++ b/marimo/_plugins/ui/_impl/utils/test_dataframe.py@@ -0,0 +1,51 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++from typing import List++from marimo._plugins.ui._impl.utils.dataframe import get_row_headers+++def test_get_row_headers() -> None:+ try:+ import pandas as pd++ expected: List[tuple[str, List[str]]]++ # Test with pandas DataFrame+ df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})+ df.index.name = "Index"+ assert get_row_headers(df) == []++ # Test with non-DataFrame input+ assert get_row_headers([1, 2, 3]) == []++ # Test with MultiIndex+ arrays = [+ ["foo", "bar", "baz"],+ ["one", "two", "three"],+ ]+ df_multi = pd.DataFrame({"A": range(3)}, index=arrays)+ expected = [+ ("", ["foo", "bar", "baz"]),+ ("", ["one", "two", "three"]),+ ]+ assert get_row_headers(df_multi) == expected++ # Test with RangeIndex+ df_range = pd.DataFrame({"A": range(3)})+ assert get_row_headers(df_range) == []++ # Test with categorical Index+ df_cat = pd.DataFrame({"A": range(3)})+ df_cat.index = pd.CategoricalIndex(["a", "b", "c"])+ expected = [("", ["a", "b", "c"])]+ assert get_row_headers(df_cat) == expected++ # Test with named categorical Index+ df_cat = pd.DataFrame({"A": range(3)})+ df_cat.index = pd.CategoricalIndex(["a", "b", "c"], name="Colors")+ expected = [("Colors", ["a", "b", "c"])]+ assert get_row_headers(df_cat) == expected+ except ImportError:+ passdiff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 4cc65f7dd7..75e05d41af 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport asyncioimport functools+import jsonimport multiprocessing as mpimport osimport queue@@ -39,6 +40,7 @@ from marimo._ast.app import App, _AppConfigfrom marimo._ast.cell import CellConfigfrom marimo._messaging.ops import Alert, KernelReady, serializefrom marimo._output.formatters.formatters import register_formatters+from marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._runtime import requests, runtimefrom marimo._server.api.status import HTTPStatusfrom marimo._server.layout import LayoutConfig, read_layout_config@@ -72,10 +74,13 @@ class IOSocketHandler(tornado.websocket.WebSocketHandler):"""try:return self.write_message(- {- "op": op,- "data": data,- }+ json.dumps(+ {+ "op": op,+ "data": data,+ },+ cls=WebComponentEncoder,+ ))except tornado.websocket.WebSocketClosedError:LOGGER.info(diff --git a/marimo/_smoke_tests/dataframe.py b/marimo/_smoke_tests/dataframe.pynew file mode 100644index 0000000000..391938fa3b--- /dev/null+++ b/marimo/_smoke_tests/dataframe.py@@ -0,0 +1,55 @@+# Copyright 2023 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.31"+app = marimo.App(width="full")+++def __(cars, mo):+ dataframe = mo.ui.dataframe(cars)+ dataframe+ return dataframe,+++def __(dataframe, mo):+ mo.ui.table(dataframe.value, selection=None)+ return+++def __(dataframe):+ dataframe.value+ return+++def __(dataframe):+ dataframe.value["Cylinders"]+ return+++def __(dataframe, mo):+ mo.hstack([dataframe.value.to_dict("records"), dataframe.value.to_dict()])+ return+++def __():+ import marimo as mo+ return mo,+++def __():+ import pandas as pd+ import vega_datasets++ cars = vega_datasets.data.cars()+ return cars, pd, vega_datasets+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.pyindex 72cb33eca2..35acd7a577 100644--- a/marimo/_utils/parse_dataclass.py+++ b/marimo/_utils/parse_dataclass.py@@ -3,7 +3,17 @@ from __future__ import annotationsimport dataclassesimport json-from typing import Any, Type, TypeVar, get_args, get_origin, get_type_hints+from enum import Enum+from typing import (+ Any,+ Literal,+ Type,+ TypeVar,+ Union,+ get_args,+ get_origin,+ get_type_hints,+)T = TypeVar("T")@@ -37,6 +47,31 @@ def _build_value(value: Any, cls: Type[T]) -> T:for k, v in value.items()})+ elif origin_cls == Union:+ arg_types = get_args(cls)+ for arg_type in arg_types:+ try:+ return _build_value(value, arg_type) # type: ignore # noqa: E501+ except Exception:+ continue+ raise ValueError(f"Value '{value}' does not fit any type of the union")+ elif origin_cls is Literal:+ # if its a single Literal of an enum, we can just return the enum+ arg_types = get_args(cls)+ first_arg_type = arg_types[0]+ if (+ len(arg_types) == 1+ and isinstance(first_arg_type, Enum)+ and first_arg_type.value == value+ ):+ return first_arg_type # type: ignore[return-value]+ if value not in arg_types:+ raise ValueError(+ f"Value '{value}' does not fit any type of the literal"+ )+ return value # type: ignore[no-any-return]+ elif type(cls) == type(Enum) and issubclass(cls, Enum):+ return cls(value) # type: ignore[return-value]elif dataclasses.is_dataclass(cls):return build_dataclass(value, cls) # type: ignore[return-value]else:@@ -52,7 +87,7 @@ def build_dataclass(value: dict[Any, Any], cls: Type[T]) -> T:return cls(**transformed)-def parse_raw(message: bytes, cls: Type[T]) -> T:+def parse_raw(message: Union[bytes, dict[Any, Any]], cls: Type[T]) -> T:"""Utility to parse a message as JSON, and instantiate into supplied type.`cls` must be a dataclass.@@ -69,5 +104,9 @@ def parse_raw(message: bytes, cls: Type[T]) -> T:message: the message to parsecls: the type to instantiate"""+ # If it is a dict, it is already parsed and we can just build the+ # dataclass.+ if isinstance(message, dict):+ return build_dataclass(message, cls)parsed = json.loads(message)return build_dataclass(parsed, cls)diff --git a/marimo/_utils/test_parse_dataclass.py b/marimo/_utils/test_parse_dataclass.pyindex 469854e584..536c2ec680 100644--- a/marimo/_utils/test_parse_dataclass.py+++ b/marimo/_utils/test_parse_dataclass.py@@ -3,7 +3,10 @@ from __future__ import annotationsimport jsonfrom dataclasses import asdict, dataclass-from typing import Any, Dict, List, Tuple+from enum import Enum+from typing import Any, Dict, List, Literal, Tuple, Union++import pytestfrom marimo._server import apifrom marimo._server.api.set_cell_config import SetCellConfig@@ -16,6 +19,33 @@ class Config:gpu: bool+@dataclass+class ConfigOne:+ disabled: bool+++@dataclass+class ConfigTwo:+ gpu: bool+++class AnimalType(Enum):+ DOG = "dog"+ CAT = "cat"+++@dataclass+class Dog:+ type: Literal[AnimalType.DOG]+ bark: bool+++@dataclass+class Cat:+ type: Literal[AnimalType.CAT]+ meow: bool++def serialize(obj: Any) -> bytes:return bytes(json.dumps(asdict(obj) if not isinstance(obj, dict) else obj),@@ -126,6 +156,65 @@ class TestParseRaw:)assert parsed == config+ def test_unions(self) -> None:+ @dataclass+ class Nested:+ config: Union[ConfigOne, ConfigTwo]++ # first+ nested = Nested(config=ConfigOne(disabled=True))+ parsed = parse_raw(serialize(nested), Nested)+ assert parsed == nested++ # other+ nested = Nested(config=ConfigTwo(gpu=True))+ parsed = parse_raw(serialize(nested), Nested)+ assert parsed == nested++ # handle error+ with pytest.raises(ValueError) as e:+ parsed = parse_raw(serialize({"config": "invalid"}), Nested)+ assert "invalid" in str(e.value)++ def test_enums(self) -> None:+ @dataclass+ class Nested:+ config: AnimalType++ parsed = parse_raw(serialize({"config": AnimalType.CAT.value}), Nested)+ assert parsed.config == AnimalType.CAT++ parsed = parse_raw(serialize({"config": AnimalType.DOG.value}), Nested)+ assert parsed.config == AnimalType.DOG++ # handle error+ with pytest.raises(ValueError) as e:+ parsed = parse_raw(serialize({"config": "invalid"}), Nested)+ assert "invalid" in str(e.value)++ def test_descriminated_union(self) -> None:+ @dataclass+ class Nested:+ config: Union[Dog, Cat]++ parsed = parse_raw(+ serialize({"config": {"type": "dog", "bark": True}}),+ Nested,+ )+ assert parsed.config == Dog(type=AnimalType.DOG, bark=True)++ parsed = parse_raw(+ serialize({"config": {"type": "cat", "meow": True}}), Nested+ )+ assert parsed.config == Cat(type=AnimalType.CAT, meow=True)++ # handle error+ with pytest.raises(ValueError) as e:+ parsed = parse_raw(+ serialize({"config": {"invalid": True}}), Nested+ )+ assert "invalid" in str(e.value)+def test_build_empty_dataclass() -> None:@dataclass