A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat [exp]: add charts panel in table (#4405)
Shahmir Varqhaa0dfc16860d2
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 6388a4d75a..55a66d95c3 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1326,6 +1326,28 @@ export const UserConfigForm: React.FC = () => {</div>)}/>+ <FormField+ control={form.control}+ name="experimental.table_charts"+ render={({ field }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">Table Charts</FormLabel>+ <FormControl>+ <Checkbox+ data-testid="data-table-plugin-checkbox"+ checked={field.value === true}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ <FormDescription>+ Enable experimental charting feature on tables. Data is+ saved in local storage. May not be performant.+ </FormDescription>+ </div>+ )}+ /></SettingGroup>);}diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsxindex f20b183ad1..859ff4b3e4 100644--- a/frontend/src/components/data-table/TableActions.tsx+++ b/frontend/src/components/data-table/TableActions.tsx@@ -4,7 +4,7 @@import React from "react";import { Tooltip } from "../ui/tooltip";import { Button } from "../ui/button";-import { SearchIcon } from "lucide-react";+import { SearchIcon, ChartBarIcon } from "lucide-react";import { DataTablePagination } from "./pagination";import { DownloadAs, type DownloadActionProps } from "./download-actions";import type { Table, RowSelectionState } from "@tanstack/react-table";@@ -24,6 +24,8 @@ interface TableActionsProps<TData> {table: Table<TData>;downloadAs?: DownloadActionProps["downloadAs"];getRowIds?: GetRowIds;+ toggleDisplayHeader?: () => void;+ chartsFeatureEnabled?: boolean;}export const TableActions = <TData,>({@@ -38,6 +40,8 @@ export const TableActions = <TData,>({table,downloadAs,getRowIds,+ toggleDisplayHeader,+ chartsFeatureEnabled,}: TableActionsProps<TData>) => {const handleSelectAllRows = (value: boolean) => {if (!onRowSelectionChange) {@@ -97,6 +101,18 @@ export const TableActions = <TData,>({</Button></Tooltip>)}+ {chartsFeatureEnabled && (+ <Tooltip content="Show charts">+ <Button+ variant="text"+ size="xs"+ className="mb-0 mr-auto"+ onClick={toggleDisplayHeader}+ >+ <ChartBarIcon className="w-4 h-4 text-muted-foreground" />+ </Button>+ </Tooltip>+ )}{pagination ? (<DataTablePaginationtotalColumns={totalColumns}diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/test-chart-spec.test.ts.snap b/frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/test-chart-spec.test.ts.snapnew file mode 100644index 0000000000..9d991e535d--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/test-chart-spec.test.ts.snap@@ -0,0 +1,744 @@+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html++exports[`createVegaSpec > Bar Chart > should create a horizontal bar chart 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Bar Chart > should create a stacked bar chart with grouping 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": "group",+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": undefined,+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": true,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Edge cases > should handle NONE_GROUP_BY for groupByColumn 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": undefined,+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Edge cases > should handle missing xColumn field 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": undefined,+ "stack": undefined,+ "title": undefined,+ "type": "nominal",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Edge cases > should handle missing yColumn field 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": undefined,+ "scale": undefined,+ "stack": undefined,+ "title": undefined,+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "line",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Pie Chart > should create a pie chart with tooltips 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "bin": undefined,+ "field": "value",+ "scale": {+ "scheme": undefined,+ },+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ "theta": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "tooltip": [+ {+ "aggregate": undefined,+ "field": "category",+ "format": undefined,+ },+ {+ "aggregate": undefined,+ "field": "value",+ "format": ".2f",+ },+ ],+ "xOffset": undefined,+ },+ "height": 300,+ "mark": {+ "type": "arc",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Scatter Chart > should create a scatter chart with grouping 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": "group",+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": {+ "field": "group",+ },+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "point",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > Theme variations > should create a chart with dark theme 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "dark",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": undefined,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;++exports[`createVegaSpec > should create a bar chart with binning 1`] = `+{+ "$schema": "https://vega.github.io/schema/vega-lite/v5.json",+ "background": "white",+ "data": {+ "values": [+ {+ "category": "A",+ "group": "Group 1",+ "value": 10,+ },+ {+ "category": "B",+ "group": "Group 1",+ "value": 20,+ },+ {+ "category": "C",+ "group": "Group 1",+ "value": 15,+ },+ {+ "category": "A",+ "group": "Group 2",+ "value": 5,+ },+ {+ "category": "B",+ "group": "Group 2",+ "value": 10,+ },+ {+ "category": "C",+ "group": "Group 2",+ "value": 25,+ },+ ],+ },+ "encoding": {+ "color": {+ "field": undefined,+ "scale": {+ "scheme": undefined,+ },+ "type": "nominal",+ },+ "tooltip": undefined,+ "x": {+ "bin": true,+ "field": "category",+ "stack": undefined,+ "title": "category",+ "type": "nominal",+ },+ "xOffset": {+ "field": undefined,+ },+ "y": {+ "bin": undefined,+ "field": "value",+ "scale": undefined,+ "stack": undefined,+ "title": "value",+ "type": "quantitative",+ },+ },+ "height": 300,+ "mark": {+ "type": "bar",+ },+ "title": "Test Chart",+ "width": 400,+}+`;diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/test-chart-spec.test.ts b/frontend/src/components/data-table/chart-transforms/__tests__/test-chart-spec.test.tsnew file mode 100644index 0000000000..759bb07860--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/__tests__/test-chart-spec.test.ts@@ -0,0 +1,270 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, it, expect } from "vitest";+import { createVegaSpec } from "../chart-spec";+import { ChartType } from "../storage";+import {+ DEFAULT_AGGREGATION,+ DEFAULT_BIN_VALUE,+ NONE_GROUP_BY,+} from "../chart-schemas";+import type { z } from "zod";+import type { ChartSchema } from "../chart-schemas";++describe("createVegaSpec", () => {+ // Sample data for testing+ const sampleData = [+ { category: "A", value: 10, group: "Group 1" },+ { category: "B", value: 20, group: "Group 1" },+ { category: "C", value: 15, group: "Group 1" },+ { category: "A", value: 5, group: "Group 2" },+ { category: "B", value: 10, group: "Group 2" },+ { category: "C", value: 25, group: "Group 2" },+ ];++ // Common test parameters+ const width = 400;+ const height = 300;++ // Helper function to create basic form values+ const createBasicFormValues = (): z.infer<typeof ChartSchema> => ({+ general: {+ title: "Test Chart",+ xColumn: {+ field: "category",+ type: "string" as const,+ },+ yColumn: {+ field: "value",+ type: "number" as const,+ agg: DEFAULT_AGGREGATION as "default",+ },+ },+ });++ describe("Bar Chart", () => {+ it("should create a horizontal bar chart", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ horizontal: true,+ },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });++ it("should create a stacked bar chart with grouping", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ groupByColumn: {+ field: "group",+ type: "string" as const,+ },+ stacking: true,+ },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });++ it("should create a bar chart with binning", () => {+ const formValues = {+ ...createBasicFormValues(),+ xAxis: { bin: { binned: true, step: DEFAULT_BIN_VALUE } },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });++ describe("Line Chart", () => {+ it("should create a basic line chart spec", () => {+ const formValues = createBasicFormValues();+ const spec = createVegaSpec(+ ChartType.LINE,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });++ describe("Pie Chart", () => {+ it("should create a pie chart with tooltips", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ tooltips: [+ { field: "category", type: "string" as const },+ { field: "value", type: "number" as const },+ ],+ },+ };++ const spec = createVegaSpec(+ ChartType.PIE,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });++ describe("Scatter Chart", () => {+ it("should create a scatter chart with grouping", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ groupByColumn: {+ field: "group",+ type: "string" as const,+ },+ },+ };++ const spec = createVegaSpec(+ ChartType.SCATTER,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });++ describe("Theme variations", () => {+ it("should create a chart with dark theme", () => {+ const formValues = createBasicFormValues();+ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "dark",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });++ describe("Edge cases", () => {+ it("should handle missing xColumn field", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ xColumn: {+ field: undefined,+ type: "string" as const,+ },+ },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });++ it("should handle missing yColumn field", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ yColumn: {+ field: undefined,+ type: "number" as const,+ agg: DEFAULT_AGGREGATION as "default",+ },+ },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });++ it("should handle NONE_GROUP_BY for groupByColumn", () => {+ const formValues = {+ ...createBasicFormValues(),+ general: {+ ...createBasicFormValues().general,+ groupByColumn: {+ field: NONE_GROUP_BY,+ type: "string" as const,+ },+ stacking: true,+ },+ };++ const spec = createVegaSpec(+ ChartType.BAR,+ sampleData,+ formValues,+ "light",+ width,+ height,+ );++ expect(spec).toMatchSnapshot();+ });+ });+});diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.ts b/frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.tsnew file mode 100644index 0000000000..373a4314bd--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.ts@@ -0,0 +1,116 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, it, expect, beforeEach, vi } from "vitest";+import { getDefaultStore } from "jotai";+import { tabsStorageAtom, ChartType, KEY } from "../storage";+import { ChartSchema } from "../chart-schemas";+import type { CellId } from "@/core/cells/ids";+import type { TabName } from "../storage";++// Mock localStorage+const mockLocalStorage = {+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ clear: vi.fn(),+ length: 0,+ key: vi.fn(),+};++// Mock window.localStorage+Object.defineProperty(window, "localStorage", {+ value: mockLocalStorage,+ writable: true,+});++describe("Chart Transforms Storage", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset the store before each test+ const store = getDefaultStore();+ store.set(tabsStorageAtom, new Map());+ });++ describe("tabsStorageAtom", () => {+ it("should initialize with an empty Map", () => {+ const store = getDefaultStore();+ const value = store.get(tabsStorageAtom);+ expect(value).toBeInstanceOf(Map);+ expect(value.size).toBe(0);+ });++ it("should store and retrieve tab data", () => {+ const store = getDefaultStore();+ const cellId = "cell-1" as CellId;+ const tabData = {+ tabName: "Tab 1" as TabName,+ chartType: ChartType.LINE,+ config: ChartSchema.parse({+ general: {+ xColumn: {},+ yColumn: {},+ },+ }),+ };++ // Set the atom value+ const newMap = new Map();+ newMap.set(cellId, [tabData]);+ store.set(tabsStorageAtom, newMap);++ // Verify the value was set+ const retrievedValue = store.get(tabsStorageAtom);+ expect(retrievedValue.get(cellId)).toEqual([tabData]);+ });++ it("should handle multiple tabs for the same cell", () => {+ const store = getDefaultStore();+ const cellId = "cell-1" as CellId;+ const tabData1 = {+ tabName: "Tab 1" as TabName,+ chartType: ChartType.LINE,+ config: ChartSchema.parse({+ general: {+ xColumn: {},+ yColumn: {},+ },+ }),+ };+ const tabData2 = {+ tabName: "Tab 2" as TabName,+ chartType: ChartType.BAR,+ config: ChartSchema.parse({+ general: {+ xColumn: {},+ yColumn: {},+ },+ }),+ };++ // Set the atom value+ const newMap = new Map();+ newMap.set(cellId, [tabData1, tabData2]);+ store.set(tabsStorageAtom, newMap);++ // Verify the value was set+ const retrievedValue = store.get(tabsStorageAtom);+ expect(retrievedValue.get(cellId)).toEqual([tabData1, tabData2]);+ });+ });++ describe("LocalStorage integration", () => {+ it("should call localStorage.setItem when setting data", () => {+ // Reset the mock to ensure clean state+ mockLocalStorage.setItem.mockReset();++ const store = getDefaultStore();+ const newMap = new Map();+ store.set(tabsStorageAtom, newMap);++ expect(mockLocalStorage.setItem).toHaveBeenCalledWith(+ KEY,+ JSON.stringify([]),+ );+ });+ });+});diff --git a/frontend/src/components/data-table/chart-transforms/chart-schemas.ts b/frontend/src/components/data-table/chart-transforms/chart-schemas.tsnew file mode 100644index 0000000000..1dd5768b28--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/chart-schemas.ts@@ -0,0 +1,74 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { DATA_TYPES } from "@/core/kernel/messages";+import { AGGREGATION_FNS } from "@/plugins/impl/data-frames/types";+import { z } from "zod";++export const DEFAULT_AGGREGATION = "default";+export const DEFAULT_BIN_VALUE = 0;+export const NONE_GROUP_BY = "None";+export const DEFAULT_COLOR_SCHEME = "default";++export const BinSchema = z.object({+ binned: z.boolean().optional(),+ step: z.number().optional(),+});++export const ChartSchema = z.object({+ general: z.object({+ title: z.string().optional(),+ xColumn: z.object({+ field: z.string().optional(),+ type: z.enum(DATA_TYPES).optional(),+ }),+ yColumn: z.object({+ field: z.string().optional(),+ type: z.enum(DATA_TYPES).optional(),+ agg: z+ .enum([...AGGREGATION_FNS, DEFAULT_AGGREGATION])+ .default(DEFAULT_AGGREGATION)+ .optional(),+ }),+ horizontal: z.boolean().optional(),+ groupByColumn: z+ .object({+ field: z.string().default(NONE_GROUP_BY).optional(),+ type: z.enum(DATA_TYPES).optional(),+ binned: z.boolean().optional(),+ })+ .optional(),+ stacking: z.boolean().optional(),+ tooltips: z+ .array(+ z.object({+ field: z.string(),+ type: z.enum(DATA_TYPES),+ }),+ )+ .optional(),+ }),+ xAxis: z+ .object({+ label: z.string().optional(),+ bin: BinSchema.optional(),+ })+ .optional(),+ yAxis: z+ .object({+ label: z.string().optional(),+ bin: BinSchema.optional(),+ })+ .optional(),+ color: z+ .object({+ scheme: z.string().default(DEFAULT_COLOR_SCHEME).optional(),+ range: z.array(z.string()).optional(),+ domain: z.array(z.string()).optional(),+ })+ .optional(),+});++// if groupBy col is nominal,+// color can be a domain with range++// else probably should be a scalediff --git a/frontend/src/components/data-table/chart-transforms/chart-spec.tsx b/frontend/src/components/data-table/chart-transforms/chart-spec.tsxnew file mode 100644index 0000000000..fb8e5f146c--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/chart-spec.tsx@@ -0,0 +1,250 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { TopLevelSpec } from "vega-lite";+import { ChartType } from "./storage";+import type { ResolvedTheme } from "@/theme/useTheme";+import type { DataType } from "@/core/kernel/messages";+import {+ type BinSchema,+ DEFAULT_AGGREGATION,+ DEFAULT_BIN_VALUE,+ NONE_GROUP_BY,+ type ChartSchema,+ DEFAULT_COLOR_SCHEME,+} from "./chart-schemas";+import type { z } from "zod";+import type { Mark } from "@/plugins/impl/vega/types";+import { logNever } from "@/utils/assertNever";+import type { Type } from "vega-lite/build/src/type";+import type {+ ColorDef,+ OffsetDef,+ PolarDef,+ PositionDef,+ StringFieldDef,+} from "vega-lite/build/src/channeldef";+import type { ColorScheme } from "vega";++export function createVegaSpec(+ chartType: ChartType,+ data: object[],+ formValues: z.infer<typeof ChartSchema>,+ theme: ResolvedTheme,+ width: number | "container",+ height: number,+): TopLevelSpec | null {+ let xAxisLabel = formValues.general.xColumn?.field;+ let yAxisLabel = formValues.general.yColumn?.field;++ if (+ formValues.general.yColumn?.agg &&+ formValues.general.yColumn.agg !== DEFAULT_AGGREGATION+ ) {+ yAxisLabel = `${formValues.general.yColumn.agg.toUpperCase()}(${yAxisLabel})`;+ }++ if (formValues.xAxis?.label && formValues.xAxis.label.trim() !== "") {+ xAxisLabel = formValues.xAxis.label;+ }++ if (formValues.yAxis?.label && formValues.yAxis.label.trim() !== "") {+ yAxisLabel = formValues.yAxis.label;+ }++ const xEncodingKey = chartType === ChartType.PIE ? "theta" : "x";+ const yEncodingKey = chartType === ChartType.PIE ? "color" : "y";++ const groupByFieldExists =+ formValues.general.groupByColumn?.field !== NONE_GROUP_BY;++ const shouldApplyStackingToX =+ groupByFieldExists && formValues.general.horizontal;+ const shouldApplyStackingToY =+ groupByFieldExists && !formValues.general.horizontal;++ const xEncoding: PositionDef<string> | PolarDef<string> = {+ field: formValues.general.xColumn?.field,+ type: convertDataTypeToVegaType(+ formValues.general.xColumn?.type ?? "unknown",+ ),+ bin: getBin(formValues.xAxis?.bin),+ title: xAxisLabel,+ stack: shouldApplyStackingToX ? formValues.general.stacking : undefined,+ };++ const colorInScale = getColorInScale(formValues);++ const yEncoding: PositionDef<string> | PolarDef<string> = {+ field: formValues.general.yColumn?.field,+ type: convertDataTypeToVegaType(+ formValues.general.yColumn?.type ?? "unknown",+ ),+ bin: getBin(formValues.yAxis?.bin),+ title: yAxisLabel,+ // If color encoding is used as y, we can define the scheme here+ scale:+ colorInScale && yEncodingKey === "color"+ ? { ...colorInScale }+ : undefined,+ stack: shouldApplyStackingToY ? formValues.general.stacking : undefined,+ };++ const schema: TopLevelSpec = {+ $schema: "https://vega.github.io/schema/vega-lite/v5.json",+ background: theme === "dark" ? "dark" : "white",+ title: formValues.general.title,+ data: {+ values: data,+ },+ height: height,+ width: width,+ mark: {+ type: convertChartTypeToMark(chartType),+ },+ encoding: {+ [xEncodingKey]: formValues.general.horizontal ? yEncoding : xEncoding,+ [yEncodingKey]: formValues.general.horizontal ? xEncoding : yEncoding,+ xOffset: getOffset(chartType, formValues),+ ...getColor(chartType, formValues),+ tooltip: getTooltips(formValues),+ },+ };+ return schema;+}++// color can be used for grouping+// it can also conflict with the color (y) encoding for pie charts, so we return undefined+function getColor(+ chartType: ChartType,+ formValues: z.infer<typeof ChartSchema>,+) {+ if (+ chartType === ChartType.PIE ||+ formValues.general.groupByColumn?.field === NONE_GROUP_BY+ ) {+ return undefined;+ }++ const colorDef: ColorDef<string> = {+ field: formValues.general.groupByColumn?.field,+ type: convertDataTypeToVegaType(+ formValues.general.groupByColumn?.type ?? "unknown",+ ),+ scale: {+ ...getColorInScale(formValues),+ },+ };++ return {+ color: colorDef,+ };+}++function getColorInScale(formValues: z.infer<typeof ChartSchema>) {+ const colorRange = formValues.color?.range;+ if (colorRange && colorRange.length > 0) {+ return {+ range: colorRange,+ };+ }++ const scheme = formValues.color?.scheme;+ if (scheme === DEFAULT_COLOR_SCHEME) {+ return undefined;+ }+ return {+ scheme: scheme as ColorScheme,+ };+}++function getOffset(+ chartType: ChartType,+ formValues: z.infer<typeof ChartSchema>,+): OffsetDef<string> | undefined {+ if (+ formValues.general.stacking ||+ formValues.general.groupByColumn?.field === NONE_GROUP_BY ||+ chartType === ChartType.PIE+ ) {+ return undefined;+ }+ return {+ field:+ formValues.general.groupByColumn?.field === NONE_GROUP_BY+ ? undefined+ : formValues.general.groupByColumn?.field,+ };+}++function getBin(binValues?: z.infer<typeof BinSchema>) {+ if (binValues?.binned) {+ if (binValues.step === DEFAULT_BIN_VALUE) {+ return true;+ }++ return {+ binned: true,+ step: binValues.step,+ };+ }+}++function getTooltips(formValues: z.infer<typeof ChartSchema>) {+ return formValues.general.tooltips?.map(+ (tooltip): StringFieldDef<string> => ({+ field: tooltip.field,+ aggregate: (() => {+ if (tooltip.field !== formValues.general.yColumn?.field) {+ return undefined;+ }+ return formValues.general.yColumn?.agg === DEFAULT_AGGREGATION+ ? undefined+ : formValues.general.yColumn?.agg;+ })(),+ format: getTooltipFormat(tooltip.type),+ }),+ );+}++function getTooltipFormat(dataType: DataType): string | undefined {+ switch (dataType) {+ case "integer":+ return ",d";+ case "number":+ return ".2f";+ default:+ return undefined;+ }+}++function convertDataTypeToVegaType(dataType: DataType): Type {+ switch (dataType) {+ case "number":+ case "integer":+ return "quantitative";+ case "string":+ return "nominal";+ case "boolean":+ return "nominal";+ case "date":+ case "datetime":+ case "time":+ return "temporal";+ case "unknown":+ return "nominal";+ default:+ logNever(dataType);+ return "nominal";+ }+}++function convertChartTypeToMark(chartType: ChartType): Mark {+ switch (chartType) {+ case ChartType.PIE:+ return "arc";+ case ChartType.SCATTER:+ return "point";+ default:+ return chartType;+ }+}diff --git a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsxnew file mode 100644index 0000000000..96e6630301--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx@@ -0,0 +1,675 @@+/* Copyright 2024 Marimo. All rights reserved. */++import React, { useState, useMemo, useRef, useEffect } from "react";+import { Button } from "@/components/ui/button";+import {+ ChartBarIcon,+ InfoIcon,+ Loader2,+ SquareFunctionIcon,+ TableIcon,+ XIcon,+} from "lucide-react";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu";+import { Tabs, TabsTrigger, TabsList, TabsContent } from "@/components/ui/tabs";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+ SelectValue,+} from "../../ui/select";+import type { z } from "zod";+import { useForm, type UseFormReturn } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import {+ ChartSchema,+ DEFAULT_AGGREGATION,+ DEFAULT_COLOR_SCHEME,+} from "./chart-schemas";+import { Form, FormControl, FormField, FormItem } from "@/components/ui/form";+import { getDefaults } from "@/components/forms/form-utils";+import { useAtom } from "jotai";+import { type CellId, HTMLCellId } from "@/core/cells/ids";+import { capitalize } from "lodash-es";+import {+ type TabName,+ tabsStorageAtom,+ ChartType,+ tabNumberAtom,+ CHART_TYPES,+} from "./storage";+import type { FieldTypesWithExternalType } from "../types";+import { useAsyncData } from "@/hooks/useAsyncData";+import { vegaLoadData } from "@/plugins/impl/vega/loader";+import type { GetDataUrl } from "@/plugins/impl/DataTablePlugin";+import { AGGREGATION_FNS } from "@/plugins/impl/data-frames/types";+import {+ BooleanField,+ ColorArrayField,+ ColumnSelector,+ InputField,+ NumberField,+ SelectField,+} from "./form-components";+import {+ AGGREGATION_TYPE_ICON,+ CHART_TYPE_ICON,+ COLOR_SCHEMES,+} from "./constants";+import { Multiselect } from "@/plugins/impl/MultiselectPlugin";+import { useDebouncedCallback } from "@/hooks/useDebounce";+import { cn } from "@/utils/cn";+import { inferFieldTypes } from "../columns";+import { LazyChart } from "./lazy-chart";++const NEW_TAB_NAME = "Chart" as TabName;+const NEW_CHART_TYPE = "line" as ChartType;+const DEFAULT_TAB_NAME = "table" as TabName;++export interface TablePanelProps {+ dataTable: JSX.Element;+ displayHeader: boolean;+ getDataUrl?: GetDataUrl;+ fieldTypes?: FieldTypesWithExternalType | null;+}++export const TablePanel: React.FC<TablePanelProps> = ({+ dataTable,+ getDataUrl,+ fieldTypes,+ displayHeader,+}) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const [cellId, setCellId] = useState<CellId | null>(null);++ const [tabsMap, saveTabsMap] = useAtom(tabsStorageAtom);+ const tabs = cellId ? (tabsMap.get(cellId) ?? []) : [];++ const [tabNum, setTabNum] = useAtom(tabNumberAtom);+ const [selectedTab, setSelectedTab] = useState(DEFAULT_TAB_NAME);++ // Finds cellId in shadow / light DOM+ useEffect(() => {+ if (!containerRef.current) {+ return;+ }++ // If the element is in the light DOM, we can find it directly+ // Otherwise, we need to traverse up through shadow DOM boundaries+ let cellElement = HTMLCellId.findElement(containerRef.current);++ if (!cellElement) {+ const root = containerRef.current.getRootNode();+ let element: Element | null = containerRef.current;++ while (element && element !== root) {+ cellElement = HTMLCellId.findElement(element);+ if (cellElement) {+ break;+ }+ element =+ element.getRootNode() instanceof ShadowRoot+ ? (element.getRootNode() as ShadowRoot).host+ : element.parentElement;+ }+ }++ if (cellElement) {+ setCellId(HTMLCellId.parse(cellElement.id));+ }+ }, [containerRef, displayHeader]);++ if (!displayHeader || (tabs.length === 0 && !displayHeader)) {+ return dataTable;+ }++ const handleAddTab = () => {+ if (!cellId) {+ return;+ }+ const tabName =+ tabNum === 0+ ? NEW_TAB_NAME+ : (`${NEW_TAB_NAME} ${tabNum + 1}` as TabName);++ const newTabs = new Map(tabsMap);+ newTabs.set(cellId, [+ ...tabs,+ {+ tabName,+ chartType: NEW_CHART_TYPE,+ config: getDefaults(ChartSchema),+ },+ ]);++ saveTabsMap(newTabs);+ setTabNum(tabNum + 1);+ setSelectedTab(tabName);+ };++ const handleDeleteTab = (tabName: TabName) => {+ if (!cellId) {+ return;+ }+ const newTabs = new Map(tabsMap);+ newTabs.set(+ cellId,+ tabs.filter((tab) => tab.tabName !== tabName),+ );+ saveTabsMap(newTabs);+ setSelectedTab(DEFAULT_TAB_NAME);+ };++ const saveTabChart = (+ tabName: TabName,+ chartType: ChartType,+ chartConfig: z.infer<typeof ChartSchema>,+ ) => {+ if (!cellId) {+ return;+ }++ const updatedTabs = new Map(tabsMap);+ updatedTabs.set(+ cellId,+ tabs.map((tab) =>+ tab.tabName === tabName+ ? { ...tab, chartType, config: chartConfig }+ : tab,+ ),+ );+ saveTabsMap(updatedTabs);+ };++ const saveTabChartType = (tabName: TabName, chartType: ChartType) => {+ if (!cellId) {+ return;+ }+ const newTabs = new Map(tabsMap);+ newTabs.set(+ cellId,+ tabs.map((tab) =>+ tab.tabName === tabName ? { ...tab, chartType } : tab,+ ),+ );+ saveTabsMap(newTabs);+ };++ return (+ <Tabs value={selectedTab} ref={containerRef} className="-mt-1">+ <TabsList>+ <TabsTrigger+ className="text-xs"+ value={DEFAULT_TAB_NAME}+ onClick={() => setSelectedTab(DEFAULT_TAB_NAME)}+ >+ <TableIcon className="w-3 h-3 mr-2" />+ Table+ </TabsTrigger>+ {tabs.map((tab, idx) => (+ <TabsTrigger+ key={idx}+ className="text-xs"+ value={tab.tabName}+ onClick={() => setSelectedTab(tab.tabName)}+ >+ {tab.tabName}+ <XIcon+ className="w-3 h-3 ml-1 mt-[0.5px] hover:text-red-500 hover:font-semibold"+ onClick={(e) => {+ e.stopPropagation();+ handleDeleteTab(tab.tabName);+ }}+ />+ </TabsTrigger>+ ))}+ <DropdownMenu>+ <DropdownMenuTrigger asChild={true}>+ <Button variant="text" size="icon">+ ++ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem onClick={handleAddTab}>+ <ChartBarIcon className="w-3 h-3 mr-2" />+ Add chart+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </TabsList>++ <TabsContent className="mt-1 overflow-hidden" value={DEFAULT_TAB_NAME}>+ {dataTable}+ </TabsContent>+ {tabs.map((tab, idx) => {+ const saveChart = (formValues: z.infer<typeof ChartSchema>) => {+ saveTabChart(tab.tabName, tab.chartType, formValues);+ };+ const saveChartType = (chartType: ChartType) => {+ saveTabChartType(tab.tabName, chartType);+ };+ return (+ <TabsContent key={idx} value={tab.tabName} className="h-[400px] mt-1">+ <ChartPanel+ chartConfig={tab.config}+ chartType={tab.chartType}+ saveChart={saveChart}+ saveChartType={saveChartType}+ getDataUrl={getDataUrl}+ fieldTypes={fieldTypes ?? inferFieldTypes(dataTable.props.data)}+ />+ </TabsContent>+ );+ })}+ </Tabs>+ );+};++export const ChartPanel: React.FC<{+ chartConfig: z.infer<typeof ChartSchema> | null;+ chartType: ChartType;+ saveChart: (formValues: z.infer<typeof ChartSchema>) => void;+ saveChartType: (chartType: ChartType) => void;+ getDataUrl?: GetDataUrl;+ fieldTypes?: FieldTypesWithExternalType | null;+}> = ({+ chartConfig,+ chartType,+ saveChart,+ saveChartType,+ getDataUrl,+ fieldTypes,+}) => {+ const form = useForm<z.infer<typeof ChartSchema>>({+ defaultValues: chartConfig ?? getDefaults(ChartSchema),+ resolver: zodResolver(ChartSchema),+ });++ const [chartTypeSelected, setChartTypeSelected] =+ useState<ChartType>(chartType);++ const { data, loading, error } = useAsyncData(async () => {+ if (!getDataUrl) {+ return [];+ }++ const response = await getDataUrl({});+ if (Array.isArray(response.data_url)) {+ return response.data_url;+ }++ const chartData = await vegaLoadData(+ response.data_url,+ response.format === "arrow"+ ? { type: "arrow" }+ : response.format === "json"+ ? { type: "json" }+ : { type: "csv", parse: "auto" },+ {+ replacePeriod: true,+ },+ );+ return chartData;+ }, []);++ const formValues = form.watch();++ // This ensures the chart re-renders when the actual values change+ const memoizedFormValues = useMemo(() => {+ return structuredClone(formValues);+ }, [formValues]);++ // Prevent unnecessary re-renders of the chart+ const memoizedChart = useMemo(() => {+ if (loading) {+ return (+ <div className="flex items-center justify-center h-full w-full">+ <Loader2 className="w-10 h-10 animate-spin" strokeWidth={1} />+ </div>+ );+ }+ if (error) {+ return (+ <div className="flex items-center justify-center h-full w-full">+ Error: ""+ </div>+ );+ }+ return (+ <Chart+ chartType={chartTypeSelected}+ formValues={memoizedFormValues}+ data={data}+ />+ );+ }, [loading, error, memoizedFormValues, data, chartTypeSelected]);++ return (+ <div className="flex flex-row gap-6 p-3 h-full rounded-md border overflow-auto">+ <div className="flex flex-col gap-3">+ <Select+ value={chartTypeSelected}+ onValueChange={(value) => {+ setChartTypeSelected(value as ChartType);+ saveChartType(value as ChartType);+ }}+ >+ <div className="flex flex-col gap-1">+ <span className="text-sm">Visualization Type</span>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {CHART_TYPES.map((chartType) => (+ <ChartSelectItem key={chartType} chartType={chartType} />+ ))}+ </SelectContent>+ </div>+ </Select>++ <ChartForm+ form={form}+ saveChart={saveChart}+ fieldTypes={fieldTypes}+ chartType={chartTypeSelected}+ />+ </div>+ {memoizedChart}+ </div>+ );+};++const ChartSelectItem: React.FC<{ chartType: ChartType }> = ({ chartType }) => {+ const Icon = CHART_TYPE_ICON[chartType];+ return (+ <SelectItem value={chartType} className="gap-2">+ <div className="flex items-center">+ <Icon className="w-4 h-4 mr-2" />+ {capitalize(chartType)}+ </div>+ </SelectItem>+ );+};++interface ChartFormProps {+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ chartType: ChartType;+ saveChart: (formValues: z.infer<typeof ChartSchema>) => void;+ fieldTypes?: FieldTypesWithExternalType | null;+}++const ChartForm = ({+ form,+ saveChart,+ fieldTypes,+ chartType,+}: ChartFormProps) => {+ const fields = fieldTypes?.map((field) => {+ return {+ name: field[0],+ type: field[1][0],+ };+ });++ const debouncedSave = useDebouncedCallback(() => {+ const values = form.getValues();+ saveChart(values);+ }, 300);++ return (+ <Form {...form}>+ <form onSubmit={(e) => e.preventDefault()} onChange={debouncedSave}>+ <Tabs defaultValue="general">+ <TabsList>+ <TabsTrigger value="general">General</TabsTrigger>+ {chartType !== ChartType.PIE && (+ <>+ <TabsTrigger value="x-axis">X-Axis</TabsTrigger>+ <TabsTrigger value="y-axis">Y-Axis</TabsTrigger>+ </>+ )}+ <TabsTrigger value="color">Color</TabsTrigger>+ </TabsList>+ <TabsContent value="general">+ <TabContainer>+ <BooleanField+ form={form}+ name="general.horizontal"+ formFieldLabel="Horizontal chart"+ />+ <ColumnSelector+ form={form}+ name="general.xColumn.field"+ formFieldLabel={+ chartType === ChartType.PIE ? "Theta" : "X column"+ }+ columns={fields || []}+ />+ <div className="flex flex-row gap-2">+ <ColumnSelector+ form={form}+ name="general.yColumn.field"+ formFieldLabel={+ chartType === ChartType.PIE ? "Color" : "Y column"+ }+ columns={fields || []}+ />+ <FormField+ control={form.control}+ name="general.yColumn.agg"+ render={({ field }) => (+ <FormItem className="self-end w-24">+ <FormControl>+ <Select+ {...field}+ value={field.value ?? DEFAULT_AGGREGATION}+ onValueChange={field.onChange}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Aggregation</SelectLabel>+ <SelectItem value={DEFAULT_AGGREGATION}>+ <div className="flex items-center">+ <SquareFunctionIcon className="w-3 h-3 mr-2" />+ {capitalize(DEFAULT_AGGREGATION)}+ </div>+ </SelectItem>+ {AGGREGATION_FNS.map((agg) => {+ const Icon = AGGREGATION_TYPE_ICON[agg];+ return (+ <SelectItem key={agg} value={agg}>+ <div className="flex items-center">+ <Icon className="w-3 h-3 mr-2" />+ {capitalize(agg)}+ </div>+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ </div>++ {chartType !== ChartType.PIE && (+ <div className="flex flex-row gap-2">+ <ColumnSelector+ form={form}+ name="general.groupByColumn.field"+ formFieldLabel="Group by (color)"+ columns={fields ?? []}+ includeNoneOption={true}+ />+ <div+ className={cn(+ "flex flex-col self-end gap-1 items-end",+ chartType === ChartType.BAR && "mt-1.5",+ )}+ >+ <BooleanField+ form={form}+ name="general.groupByColumn.binned"+ formFieldLabel="Binned"+ />+ <BooleanField+ form={form}+ name="general.stacking"+ formFieldLabel="Stacked"+ />+ </div>+ </div>+ )}++ <hr />++ <InputField+ form={form}+ formFieldLabel="Plot title"+ name="general.title"+ />+ <FormField+ control={form.control}+ name="general.tooltips"+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Multiselect+ options={fields?.map((field) => field.name) ?? []}+ value={field.value?.map((item) => item.field) ?? []}+ setValue={(values) => {+ const selectedValues =+ typeof values === "function" ? values([]) : values;++ // find the field types and form objects+ const tooltipObjects = selectedValues.map(+ (fieldName) => {+ const fieldType = fields?.find(+ (f) => f.name === fieldName,+ )?.type;++ return {+ field: fieldName,+ type: fieldType ?? "string",+ };+ },+ );++ field.onChange(tooltipObjects);+ // Multiselect doesn't trigger onChange, so we need to save the form manually+ debouncedSave();+ }}+ label="Tooltips"+ fullWidth={false}+ />+ </FormControl>+ </FormItem>+ )}+ />+ </TabContainer>+ </TabsContent>+ {chartType !== ChartType.PIE && (+ <>+ <AxisTabContent axis="x" form={form} />+ <AxisTabContent axis="y" form={form} />+ </>+ )}+ <TabsContent value="color">+ <TabContainer>+ <SelectField+ form={form}+ name="color.scheme"+ formFieldLabel="Color scheme"+ defaultValue={DEFAULT_COLOR_SCHEME}+ options={COLOR_SCHEMES.map((scheme) => ({+ label: capitalize(scheme),+ value: scheme,+ }))}+ />+ <ColorArrayField+ form={form}+ name="color.range"+ formFieldLabel="Color range"+ />+ <p className="text-xs">+ <InfoIcon className="w-2.5 h-2.5 inline mb-1 mr-1" />+ If you are using color range, color scheme will be ignored.+ </p>+ </TabContainer>+ </TabsContent>+ </Tabs>+ </form>+ </Form>+ );+};++interface AxisTabContentProps {+ axis: "x" | "y";+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+}++const AxisTabContent: React.FC<AxisTabContentProps> = ({ axis, form }) => {+ const axisName = axis === "x" ? "X" : "Y";++ return (+ <TabsContent value={`${axis}-axis`}>+ <TabContainer className="gap-1">+ <InputField+ form={form}+ name={`${axis}Axis.label`}+ formFieldLabel={`${axisName}-axis Label`}+ />+ <div className="flex flex-row gap-2 w-full">+ <BooleanField+ form={form}+ name={`${axis}Axis.bin.binned`}+ formFieldLabel="Binned"+ />+ <NumberField+ form={form}+ name={`${axis}Axis.bin.step`}+ formFieldLabel="Bin step"+ step={0.05}+ className="w-32"+ />+ </div>+ </TabContainer>+ </TabsContent>+ );+};++const Chart: React.FC<{+ chartType: ChartType;+ formValues: z.infer<typeof ChartSchema>;+ data?: object[];+}> = ({ chartType, formValues, data }) => {+ return (+ <LazyChart+ chartType={chartType}+ formValues={formValues}+ data={data}+ width="container"+ height={300}+ />+ );+};++const TabContainer: React.FC<{+ className?: string;+ children: React.ReactNode;+}> = ({ children, className }) => {+ return <div className={cn("flex flex-col gap-3", className)}>{children}</div>;+};diff --git a/frontend/src/components/data-table/chart-transforms/constants.ts b/frontend/src/components/data-table/chart-transforms/constants.tsnew file mode 100644index 0000000000..74fee6ee0d--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/constants.ts@@ -0,0 +1,89 @@+/* Copyright 2024 Marimo. All rights reserved. */++import {+ LineChartIcon,+ BarChartIcon,+ PieChartIcon,+ SigmaIcon,+ CircleSlash2,+ MinusIcon,+ PlusIcon,+ BinaryIcon,+ ChartScatterIcon,+} from "lucide-react";+import type { ChartType } from "./storage";+import type { AGGREGATION_FNS } from "@/plugins/impl/data-frames/types";+import type { ColorScheme } from "vega";+import { DEFAULT_COLOR_SCHEME } from "./chart-schemas";++export const CHART_TYPE_ICON: Record<ChartType, React.ElementType> = {+ line: LineChartIcon,+ bar: BarChartIcon,+ pie: PieChartIcon,+ scatter: ChartScatterIcon,+};++export const AGGREGATION_TYPE_ICON: Record<+ (typeof AGGREGATION_FNS)[number],+ React.ElementType+> = {+ count: BinaryIcon,+ sum: SigmaIcon,+ mean: CircleSlash2,+ median: CircleSlash2,+ min: MinusIcon,+ max: PlusIcon,+};++export const COLOR_SCHEMES: Array<ColorScheme | typeof DEFAULT_COLOR_SCHEME> = [+ DEFAULT_COLOR_SCHEME,+ // Categorical schemes+ "accent",+ "category10",+ "category20",+ "category20b",+ "category20c",+ "dark2",+ "paired",+ "pastel1",+ "pastel2",+ "set1",+ "set2",+ "set3",+ "tableau10",+ "tableau20",+ // Sequential single-hue schemes+ "blues",+ "greens",+ "greys",+ "oranges",+ "purples",+ "reds",+ // Sequential multi-hue schemes+ "bluegreen",+ "bluepurple",+ "goldgreen",+ "goldorange",+ "goldred",+ "greenblue",+ "orangered",+ "purplebluegreen",+ "purplered",+ "redpurple",+ "yellowgreenblue",+ "yelloworangered",+ // Diverging schemes+ "blueorange",+ "brownbluegreen",+ "purplegreen",+ "pinkyellowgreen",+ "purpleorange",+ "redblue",+ "redgrey",+ "redyellowblue",+ "redyellowgreen",+ "spectral",+ // Cyclical schemes+ "rainbow",+ "sinebow",+] as const;diff --git a/frontend/src/components/data-table/chart-transforms/form-components.tsx b/frontend/src/components/data-table/chart-transforms/form-components.tsxnew file mode 100644index 0000000000..678ae737dd--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/form-components.tsx@@ -0,0 +1,323 @@+/* Copyright 2024 Marimo. All rights reserved. */++import {+ FormField,+ FormItem,+ FormLabel,+ FormControl,+} from "@/components/ui/form";+import type { UseFormReturn, Path, PathValue } from "react-hook-form";+import type { DataType } from "@/core/kernel/messages";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { DATA_TYPE_ICON } from "@/components/datasets/icons";+import { DebouncedInput, DebouncedNumberInput } from "@/components/ui/input";+import { SquareFunctionIcon } from "lucide-react";+import { Checkbox } from "@/components/ui/checkbox";+import { cn } from "@/utils/cn";+import { DEFAULT_BIN_VALUE, NONE_GROUP_BY } from "./chart-schemas";+import type { NumberFieldProps } from "@/components/ui/number-field";+import { Button } from "@/components/ui/button";+import { XIcon, PlusIcon } from "lucide-react";+import React from "react";++export const ColumnSelector = <T extends object>({+ form,+ name,+ formFieldLabel,+ columns,+ includeNoneOption = false,+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ columns: Array<{ name: string; type: DataType }>;+ includeNoneOption?: boolean;+}) => {+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={(value) => {+ if (value === NONE_GROUP_BY) {+ form.setValue(name, value as PathValue<T, Path<T>>);+ return;+ }++ const column = columns.find((column) => column.name === value);+ if (column) {+ form.setValue(name, value as PathValue<T, Path<T>>);+ const typeFieldName = name.replace(+ ".field",+ ".type",+ ) as Path<T>;+ form.setValue(+ typeFieldName,+ column.type as PathValue<T, Path<T>>,+ );+ }+ }}+ value={field.value ?? ""}+ >+ <SelectTrigger className="w-40">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {includeNoneOption && (+ <SelectItem value={NONE_GROUP_BY}>+ <div className="flex items-center">+ <SquareFunctionIcon className="w-3 h-3 mr-2" />+ None+ </div>+ </SelectItem>+ )}+ {columns.map((column) => {+ const DataTypeIcon = DATA_TYPE_ICON[column.type];+ return (+ <SelectItem key={column.name} value={column.name}>+ <div className="flex items-center truncate">+ <DataTypeIcon className="w-3 h-3 mr-2" />+ {column.name}+ </div>+ </SelectItem>+ );+ })}+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const SelectField = <T extends object>({+ form,+ name,+ formFieldLabel,+ options,+ defaultValue,+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ options: Array<{ label: string; value: string }>;+ defaultValue: string;+}) => {+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={field.onChange}+ value={field.value ?? defaultValue}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {options.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const InputField = <T extends object>({+ form,+ name,+ formFieldLabel,+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+}) => {+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem>+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <DebouncedInput+ {...field}+ value={field.value ?? ""}+ onValueChange={field.onChange}+ className="w-48 text-xs"+ />+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const NumberField = <T extends object>({+ form,+ name,+ formFieldLabel,+ className,+ ...props+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ className?: string;+} & Omit<NumberFieldProps, "value" | "onValueChange">) => {+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className={cn("flex flex-row items-center gap-2", className)}>+ <FormLabel className="whitespace-nowrap">{formFieldLabel}</FormLabel>+ <FormControl>+ <DebouncedNumberInput+ {...field}+ value={field.value ?? DEFAULT_BIN_VALUE}+ onValueChange={field.onChange}+ aria-label={formFieldLabel}+ {...props}+ />+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const BooleanField = <T extends object>({+ form,+ name,+ formFieldLabel,+ className,+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ className?: string;+}) => {+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className={cn("flex flex-row items-center gap-1", className)}>+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={field.onChange}+ className="w-4 h-4"+ />+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const ColorArrayField = <T extends object>({+ form,+ name,+ formFieldLabel,+ className,+}: {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ className?: string;+}) => {+ const formValue = form.watch(name);+ const [colors, setColors] = React.useState<string[]>(formValue ?? []);++ const addColor = () => {+ const newColors = [...colors, "#000000"];+ setColors(newColors);+ form.setValue(name, newColors as PathValue<T, Path<T>>);+ };++ const removeColor = (index: number) => {+ const newColors = colors.filter((_, i) => i !== index);+ setColors(newColors);+ form.setValue(name, newColors as PathValue<T, Path<T>>);+ };++ const updateColor = (index: number, value: string) => {+ const newColors = [...colors];+ newColors[index] = value;+ setColors(newColors);+ form.setValue(name, newColors as PathValue<T, Path<T>>);+ };++ return (+ <FormField+ control={form.control}+ name={name}+ render={() => (+ <FormItem className={cn("flex flex-col gap-2", className)}>+ <FormLabel>{formFieldLabel}</FormLabel>+ <div className="flex flex-col gap-2">+ {colors.map((color, index) => (+ <div key={index} className="flex items-center gap-2">+ <input+ type="color"+ value={color}+ onChange={(e) => updateColor(index, e.target.value)}+ className="w-4 h-4 rounded cursor-pointer"+ />+ <span className="text-xs text-muted-foreground font-mono">+ {color}+ </span>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => removeColor(index)}+ className="h-4 w-4 p-0"+ >+ <XIcon className="h-2 w-2" />+ </Button>+ </div>+ ))}+ <Button+ variant="outline"+ size="sm"+ onClick={addColor}+ className="w-fit h-6 text-xs"+ >+ <PlusIcon className="h-3 w-3 mr-1" />+ Add Color+ </Button>+ </div>+ </FormItem>+ )}+ />+ );+};diff --git a/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx b/frontend/src/components/data-table/chart-transforms/lazy-chart.tsxnew file mode 100644index 0000000000..2ac8a4c045--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx@@ -0,0 +1,82 @@+/* Copyright 2024 Marimo. All rights reserved. */++import React from "react";+import type { ChartType } from "./storage";+import { useTheme } from "@/theme/useTheme";++import type { z } from "zod";+import type { ChartSchema } from "./chart-schemas";+import type { TopLevelSpec } from "vega-lite";+import type { ResolvedTheme } from "@/theme/useTheme";++const LazyVega = React.lazy(() =>+ import("react-vega").then((m) => ({ default: m.Vega })),+);++const LazyChartSpec = React.lazy(() =>+ import("./chart-spec").then((m) => ({+ default: (props: {+ chartType: ChartType;+ data: object[];+ formValues: z.infer<typeof ChartSchema>;+ theme: ResolvedTheme;+ width: number | "container";+ height: number;+ children: (spec: TopLevelSpec | null) => React.ReactNode;+ }) => {+ const spec = m.createVegaSpec(+ props.chartType,+ props.data,+ props.formValues,+ props.theme,+ props.width,+ props.height,+ );+ return props.children(spec);+ },+ })),+);++export const LazyChart: React.FC<{+ chartType: ChartType;+ formValues: z.infer<typeof ChartSchema>;+ data?: object[];+ width: number | "container";+ height: number;+}> = ({ chartType, formValues, data, width, height }) => {+ const { theme } = useTheme();++ if (!data) {+ return <div>No data</div>;+ }++ return (+ <div className="h-full m-auto rounded-md mt-4 w-full">+ <React.Suspense fallback={<div>Loading chart...</div>}>+ <LazyChartSpec+ chartType={chartType}+ data={data}+ formValues={formValues}+ theme={theme}+ width={width}+ height={height}+ >+ {(vegaSpec) => {+ if (!vegaSpec) {+ return <div>This configuration is not supported</div>;+ }++ return (+ <React.Suspense fallback={<div>Loading Vega...</div>}>+ <LazyVega+ spec={vegaSpec}+ theme={theme === "dark" ? "dark" : undefined}+ />+ </React.Suspense>+ );+ }}+ </LazyChartSpec>+ </React.Suspense>+ </div>+ );+};diff --git a/frontend/src/components/data-table/chart-transforms/storage.ts b/frontend/src/components/data-table/chart-transforms/storage.tsnew file mode 100644index 0000000000..258fcd577e--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/storage.ts@@ -0,0 +1,56 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { CellId } from "@/core/cells/ids";+import type { TypedString } from "@/utils/typed";+import { atomWithStorage } from "jotai/utils";+import type { z } from "zod";+import { atom } from "jotai";+import type { ChartSchema } from "./chart-schemas";+import { Logger } from "@/utils/Logger";+export type TabName = TypedString<"TabName">;+export const KEY = "marimo:charts:v1";++export enum ChartType {+ LINE = "line",+ BAR = "bar",+ PIE = "pie",+ SCATTER = "scatter",+}+export const CHART_TYPES = Object.values(ChartType);++interface TabStorage {+ tabName: TabName; // unique within cell+ chartType: ChartType;+ config: z.infer<typeof ChartSchema>;+}+type TabStorageMap = Map<CellId, TabStorage[]>;++// Custom storage adapter to ensure objects are serialized as maps+const mapStorage = {+ getItem: (key: string): TabStorageMap => {+ try {+ const value = localStorage.getItem(key);+ if (!value) {+ return new Map();+ }+ const parsed = JSON.parse(value);+ return new Map(parsed as Array<[CellId, TabStorage[]]>);+ } catch (error) {+ Logger.warn("Error getting chart storage", error);+ return new Map();+ }+ },+ setItem: (key: string, value: TabStorageMap): void => {+ localStorage.setItem(key, JSON.stringify([...value.entries()]));+ },+ removeItem: (key: string): void => {+ localStorage.removeItem(key);+ },+};++export const tabsStorageAtom = atomWithStorage<TabStorageMap>(+ KEY,+ new Map(),+ mapStorage,+);+export const tabNumberAtom = atom(0);diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 00191cf59d..6ddf87cb30 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -72,6 +72,8 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {// ColumnsfreezeColumnsLeft?: string[];freezeColumnsRight?: string[];+ toggleDisplayHeader?: () => void;+ chartsFeatureEnabled?: boolean;}const DataTableInternal = <TData,>({@@ -105,6 +107,8 @@ const DataTableInternal = <TData,>({reloading,freezeColumnsLeft,freezeColumnsRight,+ toggleDisplayHeader,+ chartsFeatureEnabled,}: DataTableProps<TData>) => {const [isSearchEnabled, setIsSearchEnabled] = React.useState<boolean>(false);@@ -213,6 +217,8 @@ const DataTableInternal = <TData,>({table={table}downloadAs={downloadAs}getRowIds={getRowIds}+ toggleDisplayHeader={toggleDisplayHeader}+ chartsFeatureEnabled={chartsFeatureEnabled}/></div>);diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 39e7223b2a..de1907364e 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -16,6 +16,7 @@ export interface ExperimentalFeatures {reactive_tests: boolean;toplevel_defs: boolean;secrets: boolean;+ table_charts: boolean;// Add new feature flags here}@@ -29,6 +30,7 @@ const defaultValues: ExperimentalFeatures = {reactive_tests: false,toplevel_defs: false,secrets: false,+ table_charts: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 4eb283f425..eec2061069 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -49,6 +49,8 @@ import type { CellSelectionState } from "@/components/data-table/cell-selection/import type { CellStyleState } from "@/components/data-table/cell-styling/types";import { Button } from "@/components/ui/button";import { Table2Icon } from "lucide-react";+import { TablePanel } from "@/components/data-table/chart-transforms/chart-transforms";+import { getFeatureFlag } from "@/core/config/feature-flag";type CsvURL = string;type TableData<T> = T[] | CsvURL;@@ -64,6 +66,11 @@ export type GetRowIds = (opts: {}) => Promise<{error: string | null;}>;+export type GetDataUrl = (opts: {}) => Promise<{+ data_url: string | object[];+ format: "csv" | "json" | "arrow";+}>;+/*** Arguments for a data table*@@ -109,6 +116,7 @@ type DataTableFunctions = {total_rows: number | "too_many";cell_styles?: CellStyleState | null;}>;+ get_data_url?: GetDataUrl;get_row_ids?: GetRowIds;};@@ -211,6 +219,12 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")error: z.string().nullable(),}),),+ get_data_url: rpc.input(z.object({}).passthrough()).output(+ z.object({+ data_url: z.union([z.string(), z.array(z.object({}).passthrough())]),+ format: z.enum(["csv", "json", "arrow"]),+ }),+ ),}).renderer((props) => {return (@@ -226,6 +240,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")data={props.data.data}value={props.value}setValue={props.setValue}+ experimentalChartsEnabled={true}/></LazyDataTableComponent></TooltipProvider>@@ -266,6 +281,9 @@ interface DataTableProps<T> extends Data<T>, DataTableFunctions {// FiltersenableFilters?: boolean;cellStyles?: CellStyleState | null;+ experimentalChartsEnabled?: boolean;+ toggleDisplayHeader?: () => void;+ chartsFeatureEnabled?: boolean;}interface DataTableSearchProps {@@ -300,6 +318,7 @@ export const LoadingDataTableComponent = memo(});const [searchQuery, setSearchQuery] = useState<string>("");const [filters, setFilters] = useState<ColumnFiltersState>([]);+ const [displayHeader, setDisplayHeader] = useState(false);// We need to clear the selection when sort, query, or filters change// if we don't have a stable ID for each row, which is determined by@@ -471,25 +490,47 @@ export const LoadingDataTableComponent = memo();}+ const toggleDisplayHeader = () => {+ setDisplayHeader(!displayHeader);+ };++ const chartsFeatureEnabled =+ getFeatureFlag("table_charts") && props.experimentalChartsEnabled;++ const dataTable = (+ <DataTableComponent+ {...props}+ data={data?.rows ?? Arrays.EMPTY}+ columnSummaries={columnSummaries}+ sorting={sorting}+ setSorting={setSorting}+ searchQuery={searchQuery}+ setSearchQuery={setSearchQuery}+ filters={filters}+ setFilters={setFilters}+ reloading={loading}+ totalRows={data?.totalRows ?? props.totalRows}+ paginationState={paginationState}+ setPaginationState={setPaginationState}+ cellStyles={data?.cellStyles ?? props.cellStyles}+ toggleDisplayHeader={toggleDisplayHeader}+ chartsFeatureEnabled={chartsFeatureEnabled}+ />+ );+return (<>{errorComponent}- <DataTableComponent- {...props}- data={data?.rows ?? Arrays.EMPTY}- columnSummaries={columnSummaries}- sorting={sorting}- setSorting={setSorting}- searchQuery={searchQuery}- setSearchQuery={setSearchQuery}- filters={filters}- setFilters={setFilters}- reloading={loading}- totalRows={data?.totalRows ?? props.totalRows}- paginationState={paginationState}- setPaginationState={setPaginationState}- cellStyles={data?.cellStyles ?? props.cellStyles}- />+ {chartsFeatureEnabled ? (+ <TablePanel+ displayHeader={displayHeader}+ dataTable={dataTable}+ getDataUrl={props.get_data_url}+ fieldTypes={props.fieldTypes}+ />+ ) : (+ dataTable+ )}</>);},@@ -528,6 +569,8 @@ const DataTableComponent = ({totalColumns,get_row_ids,cellStyles,+ toggleDisplayHeader,+ chartsFeatureEnabled,}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];@@ -676,6 +719,8 @@ const DataTableComponent = ({freezeColumnsRight={freezeColumnsRight}onCellSelectionChange={handleCellSelectionChange}getRowIds={get_row_ids}+ toggleDisplayHeader={toggleDisplayHeader}+ chartsFeatureEnabled={chartsFeatureEnabled}/></Labeled></ColumnChartContext.Provider>diff --git a/frontend/src/plugins/impl/MultiselectPlugin.tsx b/frontend/src/plugins/impl/MultiselectPlugin.tsxindex 814c8d7016..78546c66fd 100644--- a/frontend/src/plugins/impl/MultiselectPlugin.tsx+++ b/frontend/src/plugins/impl/MultiselectPlugin.tsx@@ -57,7 +57,7 @@ interface MultiselectProps extends Data {const SELECT_ALL_KEY = "__select_all__";const DESELECT_ALL_KEY = "__deselect_all__";-const Multiselect = ({+export const Multiselect = ({options,label,value,diff --git a/frontend/src/utils/localStorage.ts b/frontend/src/utils/localStorage.tsindex c660e80789..ec6ad3edad 100644--- a/frontend/src/utils/localStorage.ts+++ b/frontend/src/utils/localStorage.ts@@ -42,4 +42,8 @@ export class ZodLocalStorage<T> {set(value: T) {window.localStorage.setItem(this.key, JSON.stringify(value));}++ remove() {+ window.localStorage.removeItem(this.key);+ }}diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 961cba629b..7cabf1dac2 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -19,10 +19,12 @@ from narwhals.typing import IntoDataFrameimport marimo._output.data.data as mo_datafrom marimo import _loggersfrom marimo._data.models import NonNestedLiteral+from marimo._dependencies.dependencies import DependencyManagerfrom 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.charts.altair_transformer import _to_marimo_arrowfrom marimo._plugins.ui._impl.dataframes.transforms.apply import (get_handler_for_dataframe,)@@ -124,6 +126,12 @@ class GetRowIdsResponse:error: Optional[str] = None+@dataclass+class GetDataUrlResponse:+ data_url: Union[str, object]+ format: Literal["csv", "json", "arrow"]++LAZY_PREVIEW_ROWS = 10@@ -589,6 +597,11 @@ class table(arg_cls=EmptyArgs,function=self._get_row_ids,),+ Function(+ name="get_data_url",+ arg_cls=EmptyArgs,+ function=self._get_data_url,+ ),),)@@ -765,6 +778,21 @@ class table(is_disabled=False,)+ def _get_data_url(self, args: EmptyArgs) -> GetDataUrlResponse:+ """Get the data URL for the entire table. Used for charting."""+ del args++ if DependencyManager.altair.has():+ result = _to_marimo_arrow(self._searched_manager.data)+ return GetDataUrlResponse(+ data_url=result["url"],+ format=result["format"]["type"],+ )++ return GetDataUrlResponse(+ data_url=self._searched_manager.to_data({}), format="json"+ )+@functools.lru_cache(maxsize=1) # noqa: B019def _apply_filters_query_sort(self,diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex 967bdc621a..b12da19283 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom datetime import date-from typing import Any+from typing import TYPE_CHECKING, Anyimport pytest@@ -25,6 +25,9 @@ from marimo._runtime.runtime import Kernelfrom marimo._utils.data_uri import from_data_urifrom tests._data.mocks import create_dataframes+if TYPE_CHECKING:+ import pandas as pd+@pytest.fixturedef dtm() -> None:@@ -1051,8 +1054,6 @@ def test_show_download():)def test_download_as_pandas() -> None:"""Test downloading table data as different formats with pandas DataFrame."""- import io-import pandas as pdfrom pandas.testing import assert_frame_equal@@ -1066,11 +1067,7 @@ def test_download_as_pandas() -> None:download_str = table_instance._download_as(DownloadAsArgs(format=format_type))- data_bytes = from_data_uri(download_str)[1]-- if format_type == "json":- return pd.read_json(io.BytesIO(data_bytes))- return pd.read_csv(io.BytesIO(data_bytes))+ return convert_data_bytes_to_pandas_df(download_str, format_type)# Test base downloads (full data)for format_type in ["csv", "json"]:@@ -1563,3 +1560,75 @@ def test_lazy_dataframe_with_non_lazy_dataframe():)with pytest.raises(ValueError):table = ui.table.lazy(df)+++ DependencyManager.altair.has(),+ reason="If altair is installed, it will trigger to_marimo_arrow()",+)+def test_get_data_url_no_deps() -> None:+ table = ui.table([1, 2, 3])+ response = table._get_data_url({})+ assert response.data_url == [{"value": 1}, {"value": 2}, {"value": 3}]+ assert response.format == "json"+++ not DependencyManager.altair.has(), reason="Altair not installed"+)+def test_get_data_url_with_altair() -> None:+ table = ui.table([1, 2, 3])+ response = table._get_data_url({})+ assert response.data_url.startswith("data:text/csv;base64,")+ assert response.format == "csv"+++ not DependencyManager.pandas.has(), reason="Pandas not installed"+)+def test_get_data_url_values() -> None:+ table = ui.table([1, 2, 3])+ response = table._get_data_url({})+ initial_data_url = response.data_url+ assert initial_data_url.startswith("data:text/csv;base64,")+ assert response.format == "csv"++ import pandas as pd+ from pandas.testing import assert_frame_equal++ df = convert_data_bytes_to_pandas_df(response.data_url, response.format)+ expected_df = pd.DataFrame({0: [1, 2, 3]})+ assert_frame_equal(df, expected_df)++ # Test search+ table._search(SearchTableArgs(query="2", page_size=3, page_number=0))+ response = table._get_data_url({})++ df = convert_data_bytes_to_pandas_df(response.data_url, response.format)+ expected_df = pd.DataFrame({"value": [2]})+ assert_frame_equal(df, expected_df)+++def convert_data_bytes_to_pandas_df(+ data: str, data_format: str+) -> pd.DataFrame:+ import io++ import pandas as pd++ data_bytes = from_data_uri(data)[1]++ if data_format == "csv":+ df = pd.read_csv(io.BytesIO(data_bytes))+ # Convert column names to integers if they represent integers+ df.columns = pd.Index(+ [+ int(col) if isinstance(col, str) and col.isdigit() else col+ for col in df.columns+ ]+ )+ return df+ elif data_format == "json":+ return pd.read_json(io.BytesIO(data_bytes))+ else:+ raise ValueError(f"Unsupported data_format: {data_format}")