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: charts addition (#4608)
Shahmir Varqha6b605ab856db
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__/spec-snapshot.test.ts.snapsimilarity index 56%rename from frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/test-chart-spec.test.ts.snaprename to frontend/src/components/data-table/chart-transforms/__tests__/__snapshots__/spec-snapshot.test.ts.snapindex 9d991e535d..e2c2f2e2de 100644--- 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__/spec-snapshot.test.ts.snap@@ -39,29 +39,13 @@ exports[`createVegaSpec > Bar Chart > should create a horizontal bar chart 1`] =],},"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,+ "type": "nominal",},"y": {- "bin": undefined,"field": "category",- "stack": undefined,"title": "category","type": "nominal",},@@ -116,94 +100,20 @@ exports[`createVegaSpec > Bar Chart > should create a stacked bar chart with gro"encoding": {"color": {"field": "group",- "scale": {- "scheme": undefined,- },+ "scale": {},"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": {@@ -214,7 +124,7 @@ exports[`createVegaSpec > Edge cases > should handle NONE_GROUP_BY for groupByCo}`;-exports[`createVegaSpec > Edge cases > should handle missing xColumn field 1`] = `+exports[`createVegaSpec > Edge cases > should handle NONE_GROUP_BY for groupByColumn 1`] = `{"$schema": "https://vega.github.io/schema/vega-lite/v5.json","background": "white",@@ -254,106 +164,21 @@ exports[`createVegaSpec > Edge cases > should handle missing xColumn field 1`] =},"encoding": {"color": {- "field": undefined,- "scale": {- "scheme": undefined,- },+ "field": "None",+ "scale": {},"type": "nominal",},- "tooltip": undefined,"x": {- "bin": undefined,- "field": undefined,- "stack": undefined,- "title": undefined,+ "field": "category",+ "title": "category","type": "nominal",},- "xOffset": {- "field": undefined,- },"y": {- "bin": undefined,"field": "value",- "scale": undefined,- "stack": undefined,+ "stack": true,"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": {@@ -364,6 +189,10 @@ exports[`createVegaSpec > Edge cases > should handle missing yColumn field 1`] =}`;+exports[`createVegaSpec > Edge cases > should handle missing xColumn field 1`] = `"X-axis column is required"`;++exports[`createVegaSpec > Edge cases > should handle missing yColumn field 1`] = `"Y-axis column is required"`;+exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`] = `{"$schema": "https://vega.github.io/schema/vega-lite/v5.json",@@ -403,31 +232,15 @@ exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`]],},"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",+ "type": "nominal",},},"height": 300,@@ -439,84 +252,7 @@ exports[`createVegaSpec > Line Chart > should create a basic line chart spec 1`]}`;-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 > Pie Chart > should create a pie chart with tooltips 1`] = `"Color by column is required"`;exports[`createVegaSpec > Scatter Chart > should create a scatter chart with grouping 1`] = `{@@ -559,29 +295,18 @@ exports[`createVegaSpec > Scatter Chart > should create a scatter chart with gro"encoding": {"color": {"field": "group",- "scale": {- "scheme": undefined,- },+ "scale": {},"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",+ "type": "nominal",},},"height": 300,@@ -632,31 +357,15 @@ exports[`createVegaSpec > Theme variations > should create a chart with dark the],},"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",+ "type": "nominal",},},"height": 300,@@ -707,31 +416,16 @@ exports[`createVegaSpec > should create a bar chart with binning 1`] = `],},"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",+ "type": "nominal",},},"height": 300,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__/spec-snapshot.test.tssimilarity index 75%rename from frontend/src/components/data-table/chart-transforms/__tests__/test-chart-spec.test.tsrename to frontend/src/components/data-table/chart-transforms/__tests__/spec-snapshot.test.tsindex 759bb07860..1fe5054bcd 100644--- a/frontend/src/components/data-table/chart-transforms/__tests__/test-chart-spec.test.ts+++ b/frontend/src/components/data-table/chart-transforms/__tests__/spec-snapshot.test.ts@@ -2,14 +2,10 @@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 { DEFAULT_BIN_VALUE, NONE_GROUP_BY } from "../chart-schemas";import type { z } from "zod";-import type { ChartSchema } from "../chart-schemas";+import type { ChartSchema, ChartSchemaType } from "../chart-schemas";+import { NONE_AGGREGATION, ChartType } from "../types";describe("createVegaSpec", () => {// Sample data for testing@@ -37,14 +33,14 @@ describe("createVegaSpec", () => {yColumn: {field: "value",type: "number" as const,- agg: DEFAULT_AGGREGATION as "default",+ aggregate: NONE_AGGREGATION,},},});describe("Bar Chart", () => {it("should create a horizontal bar chart", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,@@ -61,15 +57,15 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});it("should create a stacked bar chart with grouping", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,- groupByColumn: {+ colorByColumn: {field: "group",type: "string" as const,},@@ -86,12 +82,12 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});it("should create a bar chart with binning", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),xAxis: { bin: { binned: true, step: DEFAULT_BIN_VALUE } },};@@ -105,12 +101,12 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});describe("Line Chart", () => {it("should create a basic line chart spec", () => {- const formValues = createBasicFormValues();+ const formValues: ChartSchemaType = createBasicFormValues();const spec = createVegaSpec(ChartType.LINE,sampleData,@@ -120,13 +116,13 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});describe("Pie Chart", () => {it("should create a pie chart with tooltips", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,@@ -146,17 +142,17 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});describe("Scatter Chart", () => {it("should create a scatter chart with grouping", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,- groupByColumn: {+ colorByColumn: {field: "group",type: "string" as const,},@@ -172,13 +168,13 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});describe("Theme variations", () => {it("should create a chart with dark theme", () => {- const formValues = createBasicFormValues();+ const formValues: ChartSchemaType = createBasicFormValues();const spec = createVegaSpec(ChartType.BAR,sampleData,@@ -188,13 +184,13 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});describe("Edge cases", () => {it("should handle missing xColumn field", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,@@ -214,18 +210,18 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});it("should handle missing yColumn field", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,yColumn: {field: undefined,type: "number" as const,- agg: DEFAULT_AGGREGATION as "default",+ aggregate: NONE_AGGREGATION,},},};@@ -239,15 +235,15 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});it("should handle NONE_GROUP_BY for groupByColumn", () => {- const formValues = {+ const formValues: ChartSchemaType = {...createBasicFormValues(),general: {...createBasicFormValues().general,- groupByColumn: {+ colorByColumn: {field: NONE_GROUP_BY,type: "string" as const,},@@ -264,7 +260,20 @@ describe("createVegaSpec", () => {height,);- expect(spec).toMatchSnapshot();+ expect(removeUndefined(spec)).toMatchSnapshot();});});});++function removeUndefined<T>(obj: T): T {+ if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {+ const result = {} as T;+ for (const key in obj) {+ if (obj[key] !== undefined) {+ result[key] = removeUndefined(obj[key]);+ }+ }+ return result;+ }+ return obj;+}diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/spec.test.ts b/frontend/src/components/data-table/chart-transforms/__tests__/spec.test.tsnew file mode 100644index 0000000000..97a3cbb8ed--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/__tests__/spec.test.ts@@ -0,0 +1,139 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { getAxisEncoding } from "../chart-spec";+import { ChartType } from "../types";+import { COUNT_FIELD } from "../constants";+import { NONE_AGGREGATION } from "../types";++describe("getAxisEncoding", () => {+ it("should return correct encoding for COUNT_FIELD", () => {+ const result = getAxisEncoding(+ {+ field: COUNT_FIELD,+ selectedDataType: "number",+ aggregate: "sum",+ timeUnit: undefined,+ },+ { binned: true, step: 10 },+ COUNT_FIELD,+ true,+ ChartType.BAR,+ );++ expect(result).toEqual({+ aggregate: "count",+ type: "quantitative",+ bin: { binned: true, step: 10 },+ title: undefined,+ stack: true,+ });+ });++ it("should return correct encoding for numeric field with aggregation", () => {+ const result = getAxisEncoding(+ {+ field: "price",+ selectedDataType: "number",+ aggregate: "mean",+ timeUnit: undefined,+ },+ undefined,+ "Average Price",+ false,+ ChartType.BAR,+ );++ expect(result).toEqual({+ field: "price",+ type: "quantitative",+ bin: undefined,+ title: "Average Price",+ stack: false,+ aggregate: "mean",+ });+ });++ it("should return correct encoding for temporal field with timeUnit", () => {+ const result = getAxisEncoding(+ {+ field: "date",+ selectedDataType: "temporal",+ aggregate: NONE_AGGREGATION,+ timeUnit: "yearmonth",+ },+ undefined,+ "Date",+ undefined,+ ChartType.LINE,+ );++ expect(result).toEqual({+ field: "date",+ type: "temporal",+ bin: undefined,+ title: "Date",+ stack: undefined,+ aggregate: undefined,+ timeUnit: "yearmonth",+ });+ });++ it("should return correct encoding for categorical field", () => {+ const result = getAxisEncoding(+ {+ field: "category",+ selectedDataType: "string",+ aggregate: NONE_AGGREGATION,+ timeUnit: undefined,+ },+ undefined,+ "Category",+ true,+ ChartType.BAR,+ );++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ bin: undefined,+ title: "Category",+ stack: true,+ aggregate: undefined,+ });+ });++ it("should handle undefined bin values", () => {+ const result = getAxisEncoding(+ {+ field: "value",+ selectedDataType: "number",+ aggregate: "sum",+ timeUnit: undefined,+ },+ undefined,+ "Value",+ false,+ ChartType.BAR,+ );++ expect((result as { bin?: unknown }).bin).toBeUndefined();+ });++ it("should handle undefined label", () => {+ const result = getAxisEncoding(+ {+ field: "value",+ selectedDataType: "number",+ aggregate: "sum",+ timeUnit: undefined,+ },+ undefined,+ undefined,+ false,+ ChartType.BAR,+ );++ expect((result as { title?: string }).title).toBeUndefined();+ });+});diff --git a/frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.ts b/frontend/src/components/data-table/chart-transforms/__tests__/storage.test.tssimilarity index 97%rename from frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.tsrename to frontend/src/components/data-table/chart-transforms/__tests__/storage.test.tsindex 373a4314bd..231e28aeef 100644--- a/frontend/src/components/data-table/chart-transforms/__tests__/test-storage.test.ts+++ b/frontend/src/components/data-table/chart-transforms/__tests__/storage.test.ts@@ -2,10 +2,11 @@import { describe, it, expect, beforeEach, vi } from "vitest";import { getDefaultStore } from "jotai";-import { tabsStorageAtom, ChartType, KEY } from "../storage";+import { tabsStorageAtom, KEY } from "../storage";import { ChartSchema } from "../chart-schemas";import type { CellId } from "@/core/cells/ids";import type { TabName } from "../storage";+import { ChartType } from "../types";// Mock localStorageconst mockLocalStorage = {diff --git a/frontend/src/components/data-table/chart-transforms/chart-components.tsx b/frontend/src/components/data-table/chart-transforms/chart-components.tsxnew file mode 100644index 0000000000..9d26868051--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/chart-components.tsx@@ -0,0 +1,265 @@+/* Copyright 2024 Marimo. All rights reserved. */++import type { LucideProps } from "lucide-react";+import { cn } from "@/utils/cn";+import {+ ArrowDownWideNarrowIcon,+ ArrowUpWideNarrowIcon,+ ChevronDown,+ Loader2,+} from "lucide-react";+import { capitalize } from "lodash-es";+import * as SelectPrimitive from "@radix-ui/react-select";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectValue,+} from "@/components/ui/select";+import { CHART_TYPE_ICON, COUNT_FIELD } from "./constants";+import { ErrorBanner } from "@/plugins/impl/common/error-banner";+import { buttonVariants } from "@/components/ui/button";+import { type UseFormReturn, useWatch } from "react-hook-form";+import type { z } from "zod";+import type { ChartSchema } from "./chart-schemas";+import { FieldValidators, TypeConverters } from "./chart-spec";+import {+ ColumnSelector,+ AggregationSelect,+ DataTypeSelect,+ TimeUnitSelect,+ SelectField,+ BooleanField,+ type Field,+} from "./form-components";+import { CHART_TYPES, type ChartType, SORT_TYPES } from "./types";++export const IconWithText: React.FC<{+ Icon: React.ForwardRefExoticComponent<+ Omit<LucideProps, "ref"> & React.RefAttributes<SVGSVGElement>+ >;+ text: string;+}> = ({ Icon, text }) => {+ return (+ <div className="flex items-center">+ <Icon className="w-3 h-3 mr-2" />+ <span>{text}</span>+ </div>+ );+};++export const Title: React.FC<{ text: string }> = ({ text }) => {+ return <span className="font-semibold my-0">{text}</span>;+};++export const TabContainer: React.FC<{+ className?: string;+ children: React.ReactNode;+}> = ({ children, className }) => {+ return <div className={cn("flex flex-col gap-2", className)}>{children}</div>;+};++export const ChartLoadingState: React.FC = () => (+ <div className="flex items-center gap-2 justify-center h-full w-full">+ <Loader2 className="w-10 h-10 animate-spin" strokeWidth={1} />+ <span>Loading chart...</span>+ </div>+);++export const ChartErrorState: React.FC<{ error: Error }> = ({ error }) => (+ <div className="flex items-center justify-center h-full w-full">+ <ErrorBanner error={error} />+ </div>+);++export const ChartTypeSelect: React.FC<{+ value: ChartType;+ onValueChange: (value: ChartType) => void;+}> = ({ value, onValueChange }) => {+ return (+ <Select value={value} onValueChange={onValueChange}>+ <div className="flex flex-row gap-2 items-center">+ <SelectPrimitive.Trigger+ className={buttonVariants({+ variant: "outline",+ className: "user-select-none w-full justify-between px-3",+ })}+ >+ <SelectValue />+ <SelectPrimitive.Icon asChild={true}>+ <ChevronDown className="h-4 w-4 opacity-50" />+ </SelectPrimitive.Icon>+ </SelectPrimitive.Trigger>+ <SelectContent>+ {CHART_TYPES.map((chartType) => (+ <ChartSelectItem key={chartType} chartType={chartType} />+ ))}+ </SelectContent>+ </div>+ </Select>+ );+};++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>+ );+};++export const XAxis: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+}> = ({ form, fields }) => {+ const formValues = useWatch({ control: form.control });+ const xColumn = formValues.general?.xColumn;+ const xColumnExists = FieldValidators.exists(xColumn?.field);++ const inferredXDataType = xColumn?.type+ ? TypeConverters.toSelectableDataType(xColumn.type)+ : "string";++ const selectedXDataType = xColumn?.selectedDataType || inferredXDataType;+ const isXCountField = xColumn?.field === COUNT_FIELD;++ const shouldShowXAggregation =+ xColumnExists && selectedXDataType !== "temporal" && !isXCountField;++ const shouldShowXTimeUnit =+ xColumnExists && selectedXDataType === "temporal" && !isXCountField;++ return (+ <>+ <Title text="X-Axis" />+ <div className="flex flex-row gap-2 justify-between">+ <ColumnSelector+ form={form}+ name="general.xColumn.field"+ columns={fields}+ />+ {shouldShowXAggregation && (+ <AggregationSelect form={form} name="general.xColumn.aggregate" />+ )}+ </div>+ {xColumnExists && !isXCountField && (+ <DataTypeSelect+ form={form}+ formFieldLabel="Data Type"+ name="general.xColumn.selectedDataType"+ defaultValue={inferredXDataType}+ />+ )}+ {shouldShowXTimeUnit && (+ <TimeUnitSelect+ form={form}+ name="general.xColumn.timeUnit"+ formFieldLabel="Time Resolution"+ />+ )}+ {xColumnExists && !isXCountField && (+ <SelectField+ form={form}+ name="general.xColumn.sort"+ formFieldLabel="Sort"+ options={SORT_TYPES.map((type) => ({+ display: (+ <IconWithText+ Icon={+ type === "ascending"+ ? ArrowUpWideNarrowIcon+ : ArrowDownWideNarrowIcon+ }+ text={capitalize(type)}+ />+ ),+ value: type,+ }))}+ defaultValue={formValues.general?.xColumn?.sort ?? "ascending"}+ />+ )}+ </>+ );+};++export const YAxis: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+}> = ({ form, fields }) => {+ const formValues = useWatch({ control: form.control });+ const yColumn = formValues.general?.yColumn;+ const yColumnExists = FieldValidators.exists(yColumn?.field);++ const inferredYDataType = yColumn?.type+ ? TypeConverters.toSelectableDataType(yColumn.type)+ : "string";++ const selectedYDataType = yColumn?.selectedDataType || inferredYDataType;+ const isYCountField = yColumn?.field === COUNT_FIELD;++ const shouldShowYAggregation =+ yColumnExists && selectedYDataType !== "temporal" && !isYCountField;++ const shouldShowYTimeUnit =+ yColumnExists && selectedYDataType === "temporal" && !isYCountField;++ return (+ <>+ <Title text="Y-Axis" />+ <div className="flex flex-row gap-2 justify-between">+ <ColumnSelector+ form={form}+ name="general.yColumn.field"+ columns={fields}+ />+ {shouldShowYAggregation && (+ <AggregationSelect form={form} name="general.yColumn.aggregate" />+ )}+ </div>++ {yColumnExists && !isYCountField && (+ <DataTypeSelect+ form={form}+ formFieldLabel="Data Type"+ name="general.yColumn.selectedDataType"+ defaultValue={inferredYDataType}+ />+ )}+ {shouldShowYTimeUnit && (+ <TimeUnitSelect+ form={form}+ name="general.yColumn.timeUnit"+ formFieldLabel="Time Resolution"+ />+ )}+ </>+ );+};++export const ColorByAxis: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+}> = ({ form, fields }) => {+ return (+ <>+ <BooleanField+ form={form}+ name="general.horizontal"+ formFieldLabel="Horizontal chart"+ />+ <Title text="Color by" />+ <div className="flex flex-row justify-between">+ <ColumnSelector+ form={form}+ name="general.colorByColumn.field"+ columns={fields}+ />+ <AggregationSelect form={form} name="general.colorByColumn.aggregate" />+ </div>+ </>+ );+};diff --git a/frontend/src/components/data-table/chart-transforms/chart-schemas.ts b/frontend/src/components/data-table/chart-transforms/chart-schemas.tsindex 1dd5768b28..f0641c3419 100644--- a/frontend/src/components/data-table/chart-transforms/chart-schemas.ts+++ b/frontend/src/components/data-table/chart-transforms/chart-schemas.ts@@ -1,42 +1,49 @@/* Copyright 2024 Marimo. All rights reserved. */+/**+ * Zod schema validation for marimo chart configuration.+ */+import { DATA_TYPES } from "@/core/kernel/messages";-import { AGGREGATION_FNS } from "@/plugins/impl/data-frames/types";import { z } from "zod";+import {+ AGGREGATION_FNS,+ NONE_AGGREGATION,+ SELECTABLE_DATA_TYPES,+ SORT_TYPES,+ TIME_UNITS,+} from "./types";+import { DEFAULT_COLOR_SCHEME, EMPTY_VALUE } from "./constants";-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(),+ maxbins: z.number().optional(),});+export const AxisSchema = z+ .object({+ field: z.string().optional(),+ type: z.enum([...DATA_TYPES, EMPTY_VALUE]).optional(),+ selectedDataType: z+ .enum([...SELECTABLE_DATA_TYPES, EMPTY_VALUE])+ .optional(),+ aggregate: z.enum(AGGREGATION_FNS).default(NONE_AGGREGATION).optional(),+ sort: z.enum(SORT_TYPES).default("ascending").optional(),+ timeUnit: z.enum(TIME_UNITS).optional(),+ })+ .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(),- }),+ xColumn: AxisSchema,+ yColumn: AxisSchema,+ colorByColumn: AxisSchema,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(@@ -50,12 +57,14 @@ export const ChartSchema = z.object({xAxis: z.object({label: z.string().optional(),+ width: z.number().optional(),bin: BinSchema.optional(),}).optional(),yAxis: z.object({label: z.string().optional(),+ height: z.number().optional(),bin: BinSchema.optional(),}).optional(),@@ -66,9 +75,11 @@ export const ChartSchema = z.object({domain: z.array(z.string()).optional(),}).optional(),+ style: z+ .object({+ innerRadius: z.number().optional(),+ })+ .optional(),});-// if groupBy col is nominal,-// color can be a domain with range--// else probably should be a scale+export type ChartSchemaType = z.infer<typeof ChartSchema>;diff --git a/frontend/src/components/data-table/chart-transforms/chart-spec.tsx b/frontend/src/components/data-table/chart-transforms/chart-spec.tsxindex fb8e5f146c..f21f99b8ac 100644--- a/frontend/src/components/data-table/chart-transforms/chart-spec.tsx+++ b/frontend/src/components/data-table/chart-transforms/chart-spec.tsx@@ -1,17 +1,19 @@/* 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,+ type AxisSchema,} from "./chart-schemas";+import {+ ChartType,+ NONE_AGGREGATION,+ type SelectableDataType,+ type TimeUnitTooltip,+} from "./types";import type { z } from "zod";import type { Mark } from "@/plugins/impl/vega/types";import { logNever } from "@/utils/assertNever";@@ -24,6 +26,15 @@ import type {StringFieldDef,} from "vega-lite/build/src/channeldef";import type { ColorScheme } from "vega";+import type { TypedString } from "@/utils/typed";+import { COUNT_FIELD, DEFAULT_COLOR_SCHEME, EMPTY_VALUE } from "./constants";+import type { Tooltip } from "./form-components";++/**+ * Convert marimo chart configuration to Vega-Lite specification.+ */++export type ErrorMessage = TypedString<"ErrorMessage">;export function createVegaSpec(chartType: ChartType,@@ -32,219 +43,408 @@ export function createVegaSpec(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})`;- }+): TopLevelSpec | ErrorMessage {+ const { xColumn, yColumn, colorByColumn, horizontal, stacking, title } =+ formValues.general;- if (formValues.xAxis?.label && formValues.xAxis.label.trim() !== "") {- xAxisLabel = formValues.xAxis.label;+ if (chartType === ChartType.PIE) {+ return getPieChartSpec(data, formValues, theme, width, height);}- if (formValues.yAxis?.label && formValues.yAxis.label.trim() !== "") {- yAxisLabel = formValues.yAxis.label;+ // Validate required fields+ if (!FieldValidators.exists(xColumn?.field)) {+ return "X-axis column is required" as ErrorMessage;+ }+ if (!FieldValidators.exists(yColumn?.field)) {+ return "Y-axis column is required" as ErrorMessage;}- 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;+ // Get axis labels+ const xAxisLabel = FieldValidators.getLabel(+ xColumn.field,+ formValues.xAxis?.label,+ );+ const yAxisLabel = FieldValidators.getLabel(+ FieldValidators.getAggregatedLabel(yColumn.field, yColumn.aggregate),+ formValues.yAxis?.label,+ );- 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,- };+ // Determine encoding keys based on chart type+ const xEncodingKey = "x";+ const yEncodingKey = "y";- const colorInScale = getColorInScale(formValues);+ // Create encodings+ const xEncoding = getAxisEncoding(+ xColumn,+ formValues.xAxis?.bin,+ xAxisLabel,+ colorByColumn?.field && horizontal ? stacking : undefined,+ chartType,+ );- 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 yEncoding = getAxisEncoding(+ yColumn,+ formValues.yAxis?.bin,+ yAxisLabel,+ colorByColumn?.field && !horizontal ? stacking : undefined,+ chartType,+ );- 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),- },+ // Create the final spec+ return {+ ...getBaseSpec(data, formValues, theme, width, height, title),+ mark: { type: TypeConverters.toMark(chartType) },encoding: {- [xEncodingKey]: formValues.general.horizontal ? yEncoding : xEncoding,- [yEncodingKey]: formValues.general.horizontal ? xEncoding : yEncoding,- xOffset: getOffset(chartType, formValues),- ...getColor(chartType, formValues),- tooltip: getTooltips(formValues),+ [xEncodingKey]: horizontal ? yEncoding : xEncoding,+ [yEncodingKey]: horizontal ? xEncoding : yEncoding,+ xOffset: EncodingUtils.getOffset(chartType, formValues),+ ...ColorUtils.getColor(chartType, formValues),+ tooltip: EncodingUtils.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(+export function getAxisEncoding(+ column: NonNullable<z.infer<typeof AxisSchema>>,+ binValues: z.infer<typeof BinSchema> | undefined,+ label: string | undefined,+ stack: boolean | undefined,chartType: ChartType,- formValues: z.infer<typeof ChartSchema>,-) {- if (- chartType === ChartType.PIE ||- formValues.general.groupByColumn?.field === NONE_GROUP_BY- ) {- return undefined;+): PositionDef<string> {+ if (column.field === COUNT_FIELD) {+ return {+ aggregate: "count",+ type: "quantitative",+ bin: EncodingUtils.getBin(binValues),+ title: label === COUNT_FIELD ? undefined : label,+ stack: stack,+ };}- const colorDef: ColorDef<string> = {- field: formValues.general.groupByColumn?.field,- type: convertDataTypeToVegaType(- formValues.general.groupByColumn?.type ?? "unknown",- ),- scale: {- ...getColorInScale(formValues),- },- };-return {- color: colorDef,+ field: column.field,+ type: TypeConverters.toVegaType(column.selectedDataType || "unknown"),+ bin: EncodingUtils.getBin(binValues, chartType),+ title: label,+ stack: stack,+ aggregate:+ column.aggregate === NONE_AGGREGATION ? undefined : column.aggregate,+ timeUnit:+ column.selectedDataType === "temporal" ? column.timeUnit : undefined,};}-function getColorInScale(formValues: z.infer<typeof ChartSchema>) {- const colorRange = formValues.color?.range;- if (colorRange && colorRange.length > 0) {- return {- range: colorRange,- };+function getPieChartSpec(+ data: object[],+ formValues: z.infer<typeof ChartSchema>,+ theme: ResolvedTheme,+ width: number | "container",+ height: number,+) {+ const { yColumn, colorByColumn, title } = formValues.general;++ if (!FieldValidators.exists(colorByColumn?.field)) {+ return "Color by column is required" as ErrorMessage;}- const scheme = formValues.color?.scheme;- if (scheme === DEFAULT_COLOR_SCHEME) {- return undefined;+ if (!FieldValidators.exists(yColumn?.field)) {+ return "Size by column is required" as ErrorMessage;}++ const colorFieldLabel = FieldValidators.getLabel(+ colorByColumn.field,+ formValues.xAxis?.label,+ );++ const thetaFieldLabel = FieldValidators.getLabel(+ yColumn.field,+ formValues.xAxis?.label,+ );++ const thetaEncoding: PolarDef<string> = getAxisEncoding(+ yColumn,+ formValues.xAxis?.bin,+ thetaFieldLabel,+ undefined,+ ChartType.PIE,+ );++ const colorEncoding: ColorDef<string> = {+ field: colorByColumn.field,+ type: TypeConverters.toVegaType(+ colorByColumn.selectedDataType || "unknown",+ ),+ scale: EncodingUtils.getColorInScale(formValues),+ title: colorFieldLabel,+ };+return {- scheme: scheme as ColorScheme,+ ...getBaseSpec(data, formValues, theme, width, height, title),+ mark: {+ type: TypeConverters.toMark(ChartType.PIE),+ innerRadius: formValues.style?.innerRadius,+ },+ encoding: {+ theta: thetaEncoding,+ color: colorEncoding,+ tooltip: EncodingUtils.getTooltips(formValues),+ },};}-function getOffset(- chartType: ChartType,+function getBaseSpec(+ data: object[],formValues: z.infer<typeof ChartSchema>,-): OffsetDef<string> | undefined {- if (- formValues.general.stacking ||- formValues.general.groupByColumn?.field === NONE_GROUP_BY ||- chartType === ChartType.PIE- ) {- return undefined;- }+ theme: ResolvedTheme,+ width: number | "container",+ height: number,+ title?: string,+) {return {- field:- formValues.general.groupByColumn?.field === NONE_GROUP_BY- ? undefined- : formValues.general.groupByColumn?.field,+ $schema: "https://vega.github.io/schema/vega-lite/v5.json",+ background: theme === "dark" ? "dark" : "white",+ title: title,+ data: { values: data },+ height: formValues.yAxis?.height ?? height,+ width: formValues.xAxis?.width ?? width,};}-function getBin(binValues?: z.infer<typeof BinSchema>) {- if (binValues?.binned) {- if (binValues.step === DEFAULT_BIN_VALUE) {- return true;+// Type conversion utilities+export const TypeConverters = {+ toVegaType(dataType: DataType | SelectableDataType): Type | undefined {+ switch (dataType) {+ case "number":+ case "integer":+ return "quantitative";+ case "string":+ case "boolean":+ case "unknown":+ return "nominal";+ case "date":+ case "datetime":+ case "time":+ case "temporal":+ return "temporal";+ default:+ logNever(dataType);+ return undefined;}+ },- return {- binned: true,- step: binValues.step,- };- }-}+ toSelectableDataType(type: DataType): SelectableDataType {+ switch (type) {+ case "number":+ case "integer":+ return "number";+ case "string":+ case "boolean":+ case "unknown":+ return "string";+ case "date":+ case "datetime":+ case "time":+ return "temporal";+ default:+ logNever(type);+ return "string";+ }+ },-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),- }),- );-}+ toMark(chartType: ChartType): Mark {+ switch (chartType) {+ case ChartType.PIE:+ return "arc";+ case ChartType.SCATTER:+ return "point";+ case ChartType.HEATMAP:+ return "rect";+ default:+ return chartType;+ }+ },+};-function getTooltipFormat(dataType: DataType): string | undefined {- switch (dataType) {- case "integer":- return ",d";- case "number":- return ".2f";- default:+// Field validation utilities+export const FieldValidators = {+ exists(field: string | undefined): field is string {+ return field !== undefined && field.trim() !== EMPTY_VALUE;+ },++ getLabel(field: string, label?: string): string {+ return label?.trim() || field;+ },++ getAggregatedLabel(field: string, agg?: string): string {+ if (!agg || agg === NONE_AGGREGATION) {+ return field;+ }+ return `${agg.toUpperCase()}(${field})`;+ },+};++// Encoding utilities+const EncodingUtils = {+ getBin(binValues?: z.infer<typeof BinSchema>, chartType?: ChartType) {+ if (chartType === ChartType.HEATMAP) {+ return { maxbins: binValues?.maxbins };+ }++ if (!binValues?.binned) {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";- }-}+ return binValues.step === DEFAULT_BIN_VALUE+ ? true+ : { binned: true, step: binValues.step };+ },-function convertChartTypeToMark(chartType: ChartType): Mark {- switch (chartType) {- case ChartType.PIE:- return "arc";- case ChartType.SCATTER:- return "point";- default:- return chartType;- }-}+ getColorInScale(formValues: z.infer<typeof ChartSchema>) {+ const colorRange = formValues.color?.range;+ if (colorRange?.length) {+ return { range: colorRange };+ }++ const scheme = formValues.color?.scheme;+ return scheme === DEFAULT_COLOR_SCHEME+ ? undefined+ : { scheme: scheme as ColorScheme };+ },++ getOffset(+ chartType: ChartType,+ formValues: z.infer<typeof ChartSchema>,+ ): OffsetDef<string> | undefined {+ // Offset only applies to bar charts, to unstack them+ if (+ formValues.general.stacking ||+ !FieldValidators.exists(formValues.general.colorByColumn?.field) ||+ chartType !== ChartType.BAR+ ) {+ return undefined;+ }+ return { field: formValues.general.colorByColumn?.field };+ },++ getTooltipAggregate(+ field: string,+ yColumn?: z.infer<typeof AxisSchema>,+ ): "count" | "sum" | "mean" | "median" | "min" | "max" | undefined {+ if (field !== yColumn?.field) {+ return undefined;+ }+ return yColumn.aggregate === NONE_AGGREGATION+ ? undefined+ : (yColumn.aggregate as+ | "count"+ | "sum"+ | "mean"+ | "median"+ | "min"+ | "max");+ },++ getTooltipFormat(dataType: DataType): string | undefined {+ switch (dataType) {+ case "integer":+ return ",.0f"; // Use comma grouping and no decimals+ case "number":+ return ",.2f"; // Use comma grouping and 2 decimal places+ default:+ return undefined;+ }+ },++ getTooltipTimeUnit(+ tooltip: Tooltip,+ formValues: z.infer<typeof ChartSchema>,+ ): TimeUnitTooltip | undefined {+ const xColumn = formValues.general.xColumn;+ const yColumn = formValues.general.yColumn;+ const colorByColumn = formValues.general.colorByColumn;+ const columns = [xColumn, yColumn, colorByColumn];++ // Check if tooltip field matches any temporal column with timeUnit+ const matchingColumn = columns.find(+ (col) =>+ tooltip.field === col?.field &&+ col?.selectedDataType === "temporal" &&+ col?.timeUnit,+ );++ if (matchingColumn?.timeUnit) {+ return matchingColumn.timeUnit;+ }++ switch (tooltip.type) {+ case "datetime":+ return "yearmonthdatehoursminutesseconds";+ case "date":+ return "yearmonthdate";+ case "time":+ return "hoursminutesseconds";+ default:+ return undefined;+ }+ },++ getTooltips(formValues: z.infer<typeof ChartSchema>) {+ if (!formValues.general.tooltips) {+ return undefined;+ }++ return formValues.general.tooltips.map(+ (tooltip): StringFieldDef<string> => {+ const timeUnit = this.getTooltipTimeUnit(tooltip, formValues);+ return {+ field: tooltip.field,+ aggregate: this.getTooltipAggregate(+ tooltip.field,+ formValues.general.yColumn,+ ),+ format: this.getTooltipFormat(tooltip.type),+ timeUnit: timeUnit,+ title: timeUnit ? tooltip.field : undefined,+ };+ },+ );+ },+};++// Color encoding utilities+const ColorUtils = {+ getColor(+ chartType: ChartType,+ formValues: z.infer<typeof ChartSchema>,+ ): { color?: ColorDef<string> } | undefined {+ if (+ chartType === ChartType.PIE ||+ !FieldValidators.exists(formValues.general.colorByColumn?.field)+ ) {+ return undefined;+ }++ const colorByColumn = formValues.general.colorByColumn;+ if (colorByColumn.field === COUNT_FIELD) {+ return {+ color: {+ aggregate: "count",+ type: "quantitative",+ },+ };+ }++ const aggregate = formValues.general.colorByColumn.aggregate;++ return {+ color: {+ field: colorByColumn.field,+ type: TypeConverters.toVegaType(+ colorByColumn.selectedDataType || "unknown",+ ),+ scale: EncodingUtils.getColorInScale(formValues),+ aggregate: aggregate === NONE_AGGREGATION ? undefined : aggregate,+ },+ };+ },+};diff --git a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsxindex 96e6630301..83c3e98173 100644--- a/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx+++ b/frontend/src/components/data-table/chart-transforms/chart-transforms.tsx@@ -3,76 +3,67 @@import React, { useState, useMemo, useRef, useEffect } from "react";import { Button } from "@/components/ui/button";import {- ChartBarIcon,- InfoIcon,- Loader2,- SquareFunctionIcon,TableIcon,XIcon,+ InfoIcon,+ DatabaseIcon,+ PaintRollerIcon,} 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 { useForm, useWatch, 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 { ChartSchema } from "./chart-schemas";+import { Form } 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 TabName, tabsStorageAtom, tabNumberAtom } 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 {+ AggregationSelect,BooleanField,ColorArrayField,ColumnSelector,+ type Field,InputField,NumberField,+ DataTypeSelect,SelectField,+ SliderField,+ TooltipSelect,} from "./form-components";-import {- AGGREGATION_TYPE_ICON,- CHART_TYPE_ICON,- COLOR_SCHEMES,-} from "./constants";-import { Multiselect } from "@/plugins/impl/MultiselectPlugin";+import { COLOR_SCHEMES, DEFAULT_COLOR_SCHEME } from "./constants";import { useDebouncedCallback } from "@/hooks/useDebounce";-import { cn } from "@/utils/cn";import { inferFieldTypes } from "../columns";import { LazyChart } from "./lazy-chart";+import { FieldValidators, TypeConverters } from "./chart-spec";+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/components/ui/accordion";+import {+ TabContainer,+ Title,+ ChartLoadingState,+ ChartErrorState,+ ChartTypeSelect,+ YAxis,+ ColorByAxis,+ XAxis,+} from "./chart-components";+import { ChartType } from "./types";const NEW_TAB_NAME = "Chart" as TabName;const NEW_CHART_TYPE = "line" as ChartType;const DEFAULT_TAB_NAME = "table" as TabName;+const CHART_HEIGHT = 300;export interface TablePanelProps {dataTable: JSX.Element;@@ -104,24 +95,9 @@ export const TablePanel: React.FC<TablePanelProps> = ({// 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;- }- }-+ const cellElement = HTMLCellId.findElementThroughShadowDOMs(+ containerRef.current,+ );if (cellElement) {setCellId(HTMLCellId.parse(cellElement.id));}@@ -231,19 +207,14 @@ export const TablePanel: React.FC<TablePanelProps> = ({/></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>+ <Button+ variant="text"+ size="icon"+ onClick={handleAddTab}+ title="Add chart"+ >+ ++ </Button></TabsList><TabsContent className="mt-1 overflow-hidden" value={DEFAULT_TAB_NAME}>@@ -293,7 +264,7 @@ export const ChartPanel: React.FC<{resolver: zodResolver(ChartSchema),});- const [chartTypeSelected, setChartTypeSelected] =+ const [selectedChartType, setSelectedChartType] =useState<ChartType>(chartType);const { data, loading, error } = useAsyncData(async () => {@@ -330,89 +301,57 @@ export const ChartPanel: React.FC<{// Prevent unnecessary re-renders of the chartconst 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>- );+ return <ChartLoadingState />;}if (error) {- return (- <div className="flex items-center justify-center h-full w-full">- Error: ""- </div>- );+ return <ChartErrorState error={error} />;}return (- <Chart- chartType={chartTypeSelected}+ <LazyChart+ chartType={selectedChartType}formValues={memoizedFormValues}data={data}+ width="container"+ height={CHART_HEIGHT}/>);- }, [loading, error, memoizedFormValues, data, chartTypeSelected]);+ }, [loading, error, memoizedFormValues, data, selectedChartType]);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}+ <div className="flex flex-row gap-2 h-full rounded-md border pr-2">+ <div className="flex flex-col gap-2 w-[300px] overflow-auto px-2 py-3 scrollbar-thin">+ <ChartTypeSelect+ value={selectedChartType}onValueChange={(value) => {- setChartTypeSelected(value as ChartType);- saveChartType(value as ChartType);+ setSelectedChartType(value);+ saveChartType(value);}}- >- <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+ />++ <ChartFormContainerform={form}saveChart={saveChart}fieldTypes={fieldTypes}- chartType={chartTypeSelected}+ chartType={selectedChartType}/></div>- {memoizedChart}+ <div className="flex-1">{memoizedChart}</div></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 = ({+const ChartFormContainer = ({form,saveChart,fieldTypes,chartType,-}: ChartFormProps) => {- const fields = fieldTypes?.map((field) => {+}: {+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ chartType: ChartType;+ saveChart: (formValues: z.infer<typeof ChartSchema>) => void;+ fieldTypes?: FieldTypesWithExternalType | null;+}) => {+ const fields: Field[] | undefined = fieldTypes?.map((field) => {return {name: field[0],type: field[1][0],@@ -424,190 +363,49 @@ const ChartForm = ({saveChart(values);}, 300);+ let ChartForm = CommonChartForm;++ if (chartType === ChartType.PIE) {+ ChartForm = PieChartForm;+ } else if (chartType === ChartType.HEATMAP) {+ ChartForm = HeatmapChartForm;+ }+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>+ <Tabs defaultValue="data">+ <TabsList className="w-full">+ <TabsTrigger value="data" className="w-1/2 h-6">+ <DatabaseIcon className="w-4 h-4 mr-2" />+ Data+ </TabsTrigger>+ <TabsTrigger value="style" className="w-1/2 h-6">+ <PaintRollerIcon className="w-4 h-4 mr-2" />+ Style+ </TabsTrigger></TabsList>- <TabsContent value="general">++ <TabsContent value="data">+ <hr className="my-2" /><TabContainer>- <BooleanField- form={form}- name="general.horizontal"- formFieldLabel="Horizontal chart"- />- <ColumnSelector+ <ChartFormform={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>- )}+ fields={fields ?? []}+ saveForm={debouncedSave}+ chartType={chartType}/></TabContainer></TabsContent>- {chartType !== ChartType.PIE && (- <>- <AxisTabContent axis="x" form={form} />- <AxisTabContent axis="y" form={form} />- </>- )}- <TabsContent value="color">++ <TabsContent value="style">+ <hr className="my-2" /><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+ <StyleFormform={form}- name="color.range"- formFieldLabel="Color range"+ fields={fields ?? []}+ saveForm={debouncedSave}/>- <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>@@ -616,60 +414,251 @@ const ChartForm = ({);};-interface AxisTabContentProps {- axis: "x" | "y";+const CommonChartForm: React.FC<{form: UseFormReturn<z.infer<typeof ChartSchema>>;-}+ fields: Field[];+ saveForm: () => void;+ chartType: ChartType;+}> = ({ form, fields, saveForm, chartType }) => {+ const formValues = useWatch({ control: form.control });+ const yColumn = formValues.general?.yColumn;+ const groupByColumn = formValues.general?.colorByColumn;-const AxisTabContent: React.FC<AxisTabContentProps> = ({ axis, form }) => {- const axisName = axis === "x" ? "X" : "Y";+ const yColumnExists = FieldValidators.exists(yColumn?.field);+ const showStacking = FieldValidators.exists(groupByColumn?.field);return (- <TabsContent value={`${axis}-axis`}>- <TabContainer className="gap-1">- <InputField+ <>+ <XAxis form={form} fields={fields} />+ <YAxis form={form} fields={fields} />++ {yColumnExists && (+ <>+ <ColorByAxis form={form} fields={fields} />+ {showStacking && (+ <div className="flex flex-row gap-2">+ <BooleanField+ form={form}+ name="general.stacking"+ formFieldLabel="Stacked"+ />+ </div>+ )}+ </>+ )}++ <hr className="my-2" />+ <TooltipSelect+ form={form}+ name="general.tooltips"+ fields={fields}+ saveFunction={saveForm}+ formFieldLabel="Tooltips"+ />+ </>+ );+};++const HeatmapChartForm: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+ saveForm: () => void;+ chartType: ChartType;+}> = ({ form, fields, saveForm, chartType }) => {+ const formValues = useWatch({ control: form.control });+ const xColumnExists = FieldValidators.exists(+ formValues.general?.xColumn?.field,+ );+ const yColumnExists = FieldValidators.exists(+ formValues.general?.yColumn?.field,+ );++ return (+ <>+ <XAxis form={form} fields={fields} />+ {xColumnExists && (+ <NumberFieldform={form}- name={`${axis}Axis.label`}- formFieldLabel={`${axisName}-axis Label`}+ name="xAxis.bin.maxbins"+ formFieldLabel="Number of boxes (max)"+ className="justify-between"/>- <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>+ )}+ <YAxis form={form} fields={fields} />+ {yColumnExists && (+ <NumberField+ form={form}+ name="yAxis.bin.maxbins"+ formFieldLabel="Number of boxes (max)"+ className="justify-between"+ />+ )}+ <ColorByAxis form={form} fields={fields} />+ </>);};-const Chart: React.FC<{+const PieChartForm: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+ saveForm: () => void;chartType: ChartType;- formValues: z.infer<typeof ChartSchema>;- data?: object[];-}> = ({ chartType, formValues, data }) => {+}> = ({ form, fields, saveForm, chartType }) => {+ const formValues = useWatch({ control: form.control });+ const colorByColumn = formValues.general?.colorByColumn;++ const inferredColorByDataType = colorByColumn?.type+ ? TypeConverters.toSelectableDataType(colorByColumn.type)+ : "string";+return (- <LazyChart- chartType={chartType}- formValues={formValues}- data={data}- width="container"- height={300}- />+ <>+ <Title text="Color by" />+ <ColumnSelector+ form={form}+ name="general.colorByColumn.field"+ columns={fields}+ includeCountField={false}+ />+ {FieldValidators.exists(colorByColumn?.field) && (+ <DataTypeSelect+ form={form}+ name="general.colorByColumn.selectedDataType"+ formFieldLabel="Data Type"+ defaultValue={inferredColorByDataType}+ />+ )}++ <Title text="Size by" />+ <div className="flex flex-row justify-between">+ <ColumnSelector+ form={form}+ name="general.yColumn.field"+ columns={fields}+ />+ <AggregationSelect form={form} name="general.yColumn.aggregate" />+ </div>++ <hr />+ <Title text="General" />+ <TooltipSelect+ form={form}+ name="general.tooltips"+ fields={fields}+ saveFunction={saveForm}+ formFieldLabel="Tooltips"+ />+ <NumberField+ form={form}+ name="style.innerRadius"+ formFieldLabel="Donut size"+ className="w-32"+ />+ </>);};-const TabContainer: React.FC<{- className?: string;- children: React.ReactNode;-}> = ({ children, className }) => {- return <div className={cn("flex flex-col gap-3", className)}>{children}</div>;+const StyleForm: React.FC<{+ form: UseFormReturn<z.infer<typeof ChartSchema>>;+ fields: Field[];+ saveForm: () => void;+}> = ({ form }) => {+ const renderBinFields = (axis: "x" | "y") => {+ return (+ <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>+ );+ };++ return (+ <Accordion type="multiple">+ <AccordionItem value="general" className="border-none">+ <AccordionTrigger className="pt-0 pb-2">+ <Title text="General" />+ </AccordionTrigger>+ <AccordionContent wrapperClassName="pb-2">+ <InputField+ form={form}+ formFieldLabel="Plot title"+ name="general.title"+ />+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="xAxis" className="border-none">+ <AccordionTrigger className="py-2">+ <Title text="X-Axis" />+ </AccordionTrigger>+ <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">+ <InputField form={form} formFieldLabel="Label" name="xAxis.label" />+ <SliderField+ form={form}+ name="xAxis.width"+ formFieldLabel="Width"+ value={400}+ start={200}+ stop={800}+ />+ {renderBinFields("x")}+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="yAxis" className="border-none">+ <AccordionTrigger className="py-2">+ <Title text="Y-Axis" />+ </AccordionTrigger>+ <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">+ <InputField form={form} formFieldLabel="Label" name="yAxis.label" />+ <SliderField+ form={form}+ name="yAxis.height"+ formFieldLabel="Height"+ value={300}+ start={150}+ stop={600}+ />+ {renderBinFields("y")}+ </AccordionContent>+ </AccordionItem>++ <AccordionItem value="color" className="border-none">+ <AccordionTrigger className="py-2">+ <Title text="Color" />+ </AccordionTrigger>+ <AccordionContent wrapperClassName="pb-2 flex flex-col gap-2">+ <SelectField+ form={form}+ name="color.scheme"+ formFieldLabel="Color scheme"+ defaultValue={DEFAULT_COLOR_SCHEME}+ options={COLOR_SCHEMES.map((scheme) => ({+ display: 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>+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ );};diff --git a/frontend/src/components/data-table/chart-transforms/constants.ts b/frontend/src/components/data-table/chart-transforms/constants.tsindex 74fee6ee0d..0deb8474d3 100644--- a/frontend/src/components/data-table/chart-transforms/constants.ts+++ b/frontend/src/components/data-table/chart-transforms/constants.ts@@ -5,34 +5,56 @@ import {BarChartIcon,PieChartIcon,SigmaIcon,- CircleSlash2,- MinusIcon,- PlusIcon,- BinaryIcon,+ HashIcon,+ BaselineIcon,+ AlignCenterVerticalIcon,+ ArrowDownToLineIcon,+ ArrowUpToLineIcon,ChartScatterIcon,+ SquareFunctionIcon,+ TableIcon,+ AreaChartIcon,} 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";+import type {+ AggregationFn,+ ChartType,+ SelectableDataType,+ TimeUnit,+} from "./types";++export const COUNT_FIELD = "__count__";+export const DEFAULT_COLOR_SCHEME = "default";export const CHART_TYPE_ICON: Record<ChartType, React.ElementType> = {line: LineChartIcon,bar: BarChartIcon,pie: PieChartIcon,scatter: ChartScatterIcon,+ heatmap: TableIcon,+ area: AreaChartIcon,};-export const AGGREGATION_TYPE_ICON: Record<- (typeof AGGREGATION_FNS)[number],- React.ElementType-> = {- count: BinaryIcon,+export const AGGREGATION_TYPE_ICON: Record<AggregationFn, React.ElementType> = {+ none: SquareFunctionIcon,+ count: HashIcon,sum: SigmaIcon,- mean: CircleSlash2,- median: CircleSlash2,- min: MinusIcon,- max: PlusIcon,+ mean: BaselineIcon,+ median: AlignCenterVerticalIcon,+ min: ArrowDownToLineIcon,+ max: ArrowUpToLineIcon,+ distinct: HashIcon,+};++export const AGGREGATION_TYPE_DESCRIPTIONS: Record<AggregationFn, string> = {+ none: "No aggregation",+ count: "Count of records",+ sum: "Sum of values",+ mean: "Mean of values",+ median: "Median of values",+ min: "Minimum value",+ max: "Maximum value",+ distinct: "Distinct values",};export const COLOR_SCHEMES: Array<ColorScheme | typeof DEFAULT_COLOR_SCHEME> = [@@ -87,3 +109,32 @@ export const COLOR_SCHEMES: Array<ColorScheme | typeof DEFAULT_COLOR_SCHEME> = ["rainbow","sinebow",] as const;++export const SCALE_TYPE_DESCRIPTIONS: Record<SelectableDataType, string> = {+ number: "Continuous numerical scale",+ string: "Discrete categorical scale (inputs treated as strings)",+ temporal: "Continuous temporal scale",+};++// Set a field to this to reflect that it is not set+export const EMPTY_VALUE = "";++export const TIME_UNIT_DESCRIPTIONS: Record<+ TimeUnit,+ [title: string, description: string]+> = {+ year: ["Year", "2025"],+ quarter: ["Quarter", "Q1 2025"],+ month: ["Month", "Jan 2025"],+ week: ["Week", "Jan 01, 2025"],+ day: ["Day", "Jan 01, 2025"],+ hours: ["Hour", "Jan 01, 2025 12:00"],+ minutes: ["Minute", "Jan 01, 2025 12:34"],+ seconds: ["Second", "Jan 01, 2025 12:34:56"],+ milliseconds: ["Millisecond", "Jan 01, 2025 12:34:56.789"],+ date: ["Date", "Jan 01, 2025"],+ dayofyear: ["Day of Year", "Day 1 of 2025"],+ yearmonth: ["Year Month", "Jan 2025"],+ yearmonthdate: ["Year Month Date", "Jan 01, 2025"],+ monthdate: ["Month Date", "Jan 01"],+};diff --git a/frontend/src/components/data-table/chart-transforms/form-components.tsx b/frontend/src/components/data-table/chart-transforms/form-components.tsxindex 678ae737dd..457cdc3bd7 100644--- a/frontend/src/components/data-table/chart-transforms/form-components.tsx+++ b/frontend/src/components/data-table/chart-transforms/form-components.tsx@@ -1,89 +1,178 @@/* Copyright 2024 Marimo. All rights reserved. */+import React from "react";+import { capitalize } from "lodash-es";+import { XIcon, PlusIcon, SquareFunctionIcon } from "lucide-react";+import type { UseFormReturn, Path, PathValue } from "react-hook-form";+import type { z } from "zod";++import type { DataType } from "@/core/kernel/messages";+import type { NumberFieldProps } from "@/components/ui/number-field";+import type { ChartSchema } from "./chart-schemas";+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,+ SelectLabel,+ SelectSeparator,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";+import { cn } from "@/utils/cn";+import { Multiselect } from "@/plugins/impl/MultiselectPlugin";++import { DEFAULT_BIN_VALUE } from "./chart-schemas";+import {+ AGGREGATION_FNS,+ COMBINED_TIME_UNITS,+ NONE_AGGREGATION,+ SELECTABLE_DATA_TYPES,+ SINGLE_TIME_UNITS,+ type TimeUnit,+} from "./types";+import {+ AGGREGATION_TYPE_DESCRIPTIONS,+ AGGREGATION_TYPE_ICON,+ COUNT_FIELD,+ EMPTY_VALUE,+ SCALE_TYPE_DESCRIPTIONS,+ TIME_UNIT_DESCRIPTIONS,+} from "./constants";+import { TypeConverters } from "./chart-spec";+import { IconWithText } from "./chart-components";+import { Slider } from "@/components/ui/slider";++const CLEAR_VALUE = "__clear__";++export interface Field {+ name: string;+ type: DataType;+}++export interface Tooltip {+ field: string;+ type: string;+}++interface BaseFormFieldProps<T extends object> {+ form: UseFormReturn<T>;+ name: Path<T>;+ formFieldLabel: string;+ className?: string;+}export const ColumnSelector = <T extends object>({form,name,- formFieldLabel,columns,- includeNoneOption = false,+ onValueChange,+ includeCountField = true,}: {form: UseFormReturn<T>;name: Path<T>;- formFieldLabel: string;columns: Array<{ name: string; type: DataType }>;- includeNoneOption?: boolean;+ onValueChange?: (fieldName: string, type: DataType | undefined) => void;+ includeCountField?: boolean;}) => {+ type AnyPath = Path<T>;+ type AnyPathValue = PathValue<T, Path<T>>;+ const ANY_VALUE = EMPTY_VALUE as AnyPathValue;+ const pathType = name.replace(".field", ".type") as AnyPath;+ const pathSelectedDataType = name.replace(+ ".field",+ ".selectedDataType",+ ) as AnyPath;++ const clear = () => {+ form.setValue(name, ANY_VALUE);+ form.setValue(pathType, ANY_VALUE);+ form.setValue(pathSelectedDataType, ANY_VALUE);+ onValueChange?.(EMPTY_VALUE, undefined);+ };+return (<FormFieldcontrol={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>>);+ // Handle clear+ if (value === CLEAR_VALUE) {+ clear();+ return;+ }++ // Handle count+ if (value === COUNT_FIELD) {+ form.setValue(name, value as AnyPathValue);+ form.setValue(pathType, ANY_VALUE);+ form.setValue(pathSelectedDataType, ANY_VALUE);+ onValueChange?.(name, "number");return;}+ // Handle column selectionconst 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(name, value as AnyPathValue);+ form.setValue(pathType, column.type as AnyPathValue);form.setValue(- typeFieldName,- column.type as PathValue<T, Path<T>>,+ pathSelectedDataType,+ TypeConverters.toSelectableDataType(+ column.type,+ ) as AnyPathValue,);+ onValueChange?.(name, column.type);}}}- value={field.value ?? ""}+ value={field.value ?? EMPTY_VALUE}>- <SelectTrigger className="w-40">- <SelectValue />+ <SelectTrigger+ className="w-40 truncate"+ onClear={field.value ? clear : undefined}+ >+ <SelectValue placeholder="Select column" /></SelectTrigger><SelectContent>- {includeNoneOption && (- <SelectItem value={NONE_GROUP_BY}>- <div className="flex items-center">- <SquareFunctionIcon className="w-3 h-3 mr-2" />- None+ {field.value && (+ <SelectItem value={CLEAR_VALUE}>+ <div className="flex items-center truncate">+ <XIcon className="w-3 h-3 mr-2" />+ Clear</div></SelectItem>)}+ {includeCountField && (+ <>+ <SelectItem key={COUNT_FIELD} value={COUNT_FIELD}>+ <div className="flex items-center truncate">+ <SquareFunctionIcon className="w-3 h-3 mr-2" />+ Count of records+ </div>+ </SelectItem>+ <SelectSeparator />+ </>+ )}{columns.map((column) => {+ if (column.name.trim() === EMPTY_VALUE) {+ return null;+ }const DataTypeIcon = DATA_TYPE_ICON[column.type];return (<SelectItem key={column.name} value={column.name}>@@ -109,75 +198,66 @@ export const SelectField = <T extends object>({formFieldLabel,options,defaultValue,-}: {- form: UseFormReturn<T>;- name: Path<T>;- formFieldLabel: string;- options: Array<{ label: string; value: string }>;+}: BaseFormFieldProps<T> & {+ options: Array<{ display: React.ReactNode; 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) => (+}) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className="flex flex-row items-center justify-between">+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={field.onChange}+ value={field.value ?? defaultValue}+ >+ <SelectTrigger className="truncate">+ <SelectValue placeholder="Select an option" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {options+ .filter((option) => option.value !== EMPTY_VALUE)+ .map((option) => (<SelectItem key={option.value} value={option.value}>- {option.label}+ {option.display}</SelectItem>))}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </FormItem>- )}- />- );-};+ </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>- )}- />- );-};+}: BaseFormFieldProps<T>) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className="flex flex-row gap-2 items-center">+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <DebouncedInput+ {...field}+ value={field.value ?? EMPTY_VALUE}+ onValueChange={field.onChange}+ className="text-xs h-5"+ />+ </FormControl>+ </FormItem>+ )}+ />+);export const NumberField = <T extends object>({form,@@ -185,57 +265,108 @@ export const NumberField = <T extends object>({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>- )}- />- );-};+}: BaseFormFieldProps<T> &+ Omit<NumberFieldProps, "value" | "onValueChange">) => (+ <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}+ className="w-16"+ />+ </FormControl>+ </FormItem>+ )}+ />+);export const BooleanField = <T extends object>({form,name,formFieldLabel,className,-}: {- form: UseFormReturn<T>;- name: Path<T>;- formFieldLabel: string;- className?: string;-}) => {+}: BaseFormFieldProps<T>) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className={cn("flex flex-row items-center gap-2", className)}>+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Checkbox+ checked={field.value}+ onCheckedChange={field.onChange}+ className="w-4 h-4"+ />+ </FormControl>+ </FormItem>+ )}+ />+);++interface SliderFieldProps<T extends object> extends BaseFormFieldProps<T> {+ value: number;+ start: number;+ stop: number;+ step?: number;+}++export const SliderField = <T extends object>({+ form,+ name,+ formFieldLabel,+ value,+ start,+ stop,+ step,+ className,+ ...props+}: SliderFieldProps<T>) => {+ const [internalValue, setInternalValue] = React.useState(value);++ // Update internal value on prop change+ React.useEffect(() => {+ setInternalValue(value);+ }, [value]);+return (<FormFieldcontrol={form.control}name={name}render={({ field }) => (- <FormItem className={cn("flex flex-row items-center gap-1", className)}>+ <FormItem+ className={cn("flex flex-row items-center gap-2 w-1/2", className)}+ ><FormLabel>{formFieldLabel}</FormLabel><FormControl>- <Checkbox- checked={field.value}- onCheckedChange={field.onChange}- className="w-4 h-4"+ <Slider+ {...field}+ {...props}+ id={name}+ className="relative flex items-center select-none"+ value={[internalValue]}+ min={start}+ max={stop}+ step={step}+ // Triggered on slider drag+ onValueChange={([nextValue]) => {+ setInternalValue(nextValue);+ field.onChange(nextValue);+ }}+ // Triggered on mouse up+ onValueCommit={([nextValue]) => {+ field.onChange(nextValue);+ form.setValue(name, nextValue as PathValue<T, Path<T>>);+ }}+ valueMap={(value) => value}/></FormControl></FormItem>@@ -249,12 +380,7 @@ export const ColorArrayField = <T extends object>({name,formFieldLabel,className,-}: {- form: UseFormReturn<T>;- name: Path<T>;- formFieldLabel: string;- className?: string;-}) => {+}: BaseFormFieldProps<T>) => {const formValue = form.watch(name);const [colors, setColors] = React.useState<string[]>(formValue ?? []);@@ -321,3 +447,244 @@ export const ColorArrayField = <T extends object>({/>);};++export const TimeUnitSelect = <T extends object>({+ form,+ name,+ formFieldLabel,+}: BaseFormFieldProps<T>) => {+ const clear = () => {+ form.setValue(name, EMPTY_VALUE as PathValue<T, Path<T>>);+ };++ const renderTimeUnit = (unit: TimeUnit) => {+ const [label, description] = TIME_UNIT_DESCRIPTIONS[unit];+ return (+ <SelectItem+ key={unit}+ value={unit}+ className="flex flex-row"+ subtitle={+ <span className="text-xs text-muted-foreground ml-auto">+ {description}+ </span>+ }+ >+ {label}+ </SelectItem>+ );+ };+ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className="flex flex-row items-center justify-between w-full">+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={(value) => {+ if (value === CLEAR_VALUE) {+ clear();+ } else {+ field.onChange(value);+ }+ }}+ value={field.value}+ >+ <SelectTrigger onClear={field.value ? clear : undefined}>+ <SelectValue placeholder="Select unit" />+ </SelectTrigger>+ <SelectContent className="w-72">+ {field.value && (+ <>+ <SelectItem value={CLEAR_VALUE}>+ <div className="flex items-center truncate">+ <XIcon className="w-3 h-3 mr-2" />+ Clear+ </div>+ </SelectItem>+ <SelectSeparator />+ </>+ )}+ <SelectGroup>+ {COMBINED_TIME_UNITS.map(renderTimeUnit)}+ <SelectSeparator />+ {SINGLE_TIME_UNITS.map(renderTimeUnit)}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const DataTypeSelect = <T extends object>({+ form,+ name,+ formFieldLabel,+ defaultValue,+ onValueChange,+}: BaseFormFieldProps<T> & {+ defaultValue: string;+ onValueChange?: (value: string) => void;+}) => {+ const [isOpen, setIsOpen] = React.useState(false);++ return (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem className="flex flex-row items-center justify-between w-full">+ <FormLabel>{formFieldLabel}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={(value) => {+ field.onChange(value);+ onValueChange?.(value);+ }}+ value={field.value ?? defaultValue}+ open={isOpen}+ onOpenChange={setIsOpen}+ >+ <SelectTrigger>+ <SelectValue placeholder="Select an option" />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ {SELECTABLE_DATA_TYPES.map((type) => {+ const Icon = DATA_TYPE_ICON[type];+ return (+ <SelectItem+ key={type}+ value={type}+ className="flex flex-col items-start justify-center"+ subtitle={+ isOpen && (+ <span className="text-xs text-muted-foreground">+ {SCALE_TYPE_DESCRIPTIONS[type]}+ </span>+ )+ }+ >+ <IconWithText Icon={Icon} text={capitalize(type)} />+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+ );+};++export const AggregationSelect = <T extends object>({+ form,+ name,+}: { form: UseFormReturn<T>; name: Path<T> }) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => (+ <FormItem>+ <FormControl>+ <Select+ {...field}+ value={field.value ?? NONE_AGGREGATION}+ onValueChange={field.onChange}+ >+ <SelectTrigger variant="ghost">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Aggregation</SelectLabel>+ {AGGREGATION_FNS.map((agg) => {+ const Icon = AGGREGATION_TYPE_ICON[agg];+ return (+ <SelectItem+ key={agg}+ value={agg}+ className="flex flex-col items-start justify-center"+ subtitle={+ <span className="text-xs text-muted-foreground pr-10">+ {AGGREGATION_TYPE_DESCRIPTIONS[agg]}+ </span>+ }+ >+ <div className="flex items-center">+ <Icon className="w-3 h-3 mr-2" />+ {capitalize(agg)}+ </div>+ </SelectItem>+ );+ })}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ )}+ />+);++export const TooltipSelect = <T extends z.infer<typeof ChartSchema>>({+ form,+ name,+ formFieldLabel,+ fields,+ saveFunction,+}: {+ form: UseFormReturn<T>;+ formFieldLabel?: string;+ name: Path<T>;+ fields: Field[];+ saveFunction: () => void;+}) => (+ <FormField+ control={form.control}+ name={name}+ render={({ field }) => {+ const tooltips = field.value as Tooltip[] | undefined;+ return (+ <FormItem className="flex flex-row gap-2 items-center">+ {formFieldLabel && <FormLabel>{formFieldLabel}</FormLabel>}+ <FormControl>+ <Multiselect+ options={fields?.map((field) => field.name) ?? []}+ value={tooltips?.map((t) => t.field) ?? []}+ setValue={(values) => {+ const selectedValues =+ typeof values === "function" ? values([]) : values;++ const tooltipObjects = selectedValues.map((fieldName) => {+ const fieldType = fields?.find(+ (f) => f.name === fieldName,+ )?.type;++ return {+ field: fieldName,+ type: fieldType ?? "string",+ };+ });++ field.onChange(tooltipObjects);+ saveFunction();+ }}+ label={null}+ fullWidth={false}+ />+ </FormControl>+ </FormItem>+ );+ }}+ />+);diff --git a/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx b/frontend/src/components/data-table/chart-transforms/lazy-chart.tsxindex 2ac8a4c045..b5eb24a7ea 100644--- a/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx+++ b/frontend/src/components/data-table/chart-transforms/lazy-chart.tsx@@ -1,42 +1,19 @@/* Copyright 2024 Marimo. All rights reserved. */import React from "react";-import type { ChartType } from "./storage";+import type { ChartType } from "./types";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";+import type { ErrorMessage } from "./chart-spec";+import { ChartPieIcon } from "lucide-react";+import { createVegaSpec } from "./chart-spec";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>;@@ -50,33 +27,55 @@ export const LazyChart: React.FC<{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>;- }+ const specOrMessage = createVegaSpec(+ chartType,+ data,+ formValues,+ theme,+ width,+ height,+ );++ const renderChart = (specOrMessage: TopLevelSpec | ErrorMessage) => {+ if (typeof specOrMessage === "string") {+ return <ChartEmptyState>{specOrMessage}</ChartEmptyState>;+ }- return (- <React.Suspense fallback={<div>Loading Vega...</div>}>- <LazyVega- spec={vegaSpec}- theme={theme === "dark" ? "dark" : undefined}- />- </React.Suspense>- );+ return (+ <React.Suspense fallback={<LoadingChart />}>+ <LazyVega+ spec={specOrMessage}+ theme={theme === "dark" ? "dark" : undefined}+ height={height}+ actions={{+ export: true,+ source: false,+ compiled: false,+ editor: true,}}- </LazyChartSpec>+ /></React.Suspense>+ );+ };++ return (+ <div className="h-full m-auto rounded-md mt-4 w-full">+ {renderChart(specOrMessage)}+ </div>+ );+};++const LoadingChart = () => {+ return <ChartEmptyState>Loading chart...</ChartEmptyState>;+};++const ChartEmptyState = ({ children }: { children: React.ReactNode }) => {+ return (+ <div className="h-full flex flex-col items-center justify-center gap-4">+ <ChartPieIcon className="w-10 h-10 text-muted-foreground" />+ <span className="text-md font-semibold text-muted-foreground">+ {children}+ </span></div>);};diff --git a/frontend/src/components/data-table/chart-transforms/storage.ts b/frontend/src/components/data-table/chart-transforms/storage.tsindex 258fcd577e..952b4771f5 100644--- a/frontend/src/components/data-table/chart-transforms/storage.ts+++ b/frontend/src/components/data-table/chart-transforms/storage.ts@@ -3,28 +3,35 @@import type { CellId } from "@/core/cells/ids";import type { TypedString } from "@/utils/typed";import { atomWithStorage } from "jotai/utils";-import type { z } from "zod";+import { z } from "zod";import { atom } from "jotai";-import type { ChartSchema } from "./chart-schemas";+import { ChartSchema } from "./chart-schemas";import { Logger } from "@/utils/Logger";-export type TabName = TypedString<"TabName">;-export const KEY = "marimo:charts:v1";+import type { ChartType } from "./types";-export enum ChartType {- LINE = "line",- BAR = "bar",- PIE = "pie",- SCATTER = "scatter",-}-export const CHART_TYPES = Object.values(ChartType);+export type TabName = TypedString<"TabName">;+export const KEY = "marimo:charts:v2";interface TabStorage {tabName: TabName; // unique within cellchartType: ChartType;config: z.infer<typeof ChartSchema>;}+type TabStorageMap = Map<CellId, TabStorage[]>;+const TabStorageSchema = z.object({+ tabName: z.string().transform((name) => name as TabName),+ chartType: z.string().transform((type) => type as ChartType),+ config: ChartSchema,+});+const TabStorageEntriesSchema = z.array(+ z.tuple([+ z.string().transform((name) => name as CellId),+ z.array(TabStorageSchema),+ ]),+);+// Custom storage adapter to ensure objects are serialized as mapsconst mapStorage = {getItem: (key: string): TabStorageMap => {@@ -33,8 +40,12 @@ const mapStorage = {if (!value) {return new Map();}- const parsed = JSON.parse(value);- return new Map(parsed as Array<[CellId, TabStorage[]]>);+ const parsedResult = TabStorageEntriesSchema.safeParse(JSON.parse(value));+ if (!parsedResult.success) {+ Logger.warn("Error parsing chart storage", parsedResult.error);+ return new Map();+ }+ return new Map(parsedResult.data);} catch (error) {Logger.warn("Error getting chart storage", error);return new Map();diff --git a/frontend/src/components/data-table/chart-transforms/types.ts b/frontend/src/components/data-table/chart-transforms/types.tsnew file mode 100644index 0000000000..170d171460--- /dev/null+++ b/frontend/src/components/data-table/chart-transforms/types.ts@@ -0,0 +1,82 @@+/* Copyright 2024 Marimo. All rights reserved. */++/**+ * Similar to VegaLite's ScaleType, https://vega.github.io/vega-lite/docs/scale.html#type+ */+export const SELECTABLE_DATA_TYPES = ["number", "string", "temporal"] as const;+export type SelectableDataType = (typeof SELECTABLE_DATA_TYPES)[number];++/**+ * Similar to VegaLite's TimeUnit, https://vega.github.io/vega-lite/docs/timeunit.html+ */+export const SINGLE_TIME_UNITS = [+ // Individual units+ "year", // Gregorian calendar years.+ "quarter", // Three-month intervals, starting in one of January, April, July, and October.+ "month", // Calendar months (January, February, etc.).+ "date", // Calendar day of the month (January 1, January 2, etc.).+ "week", // Sunday-based weeks. Days before the first Sunday of the year are considered to be in week 0, the first Sunday of the year is the start of week 1, the second Sunday week 2, etc..+ "day", // Day of the week (Sunday, Monday, etc.).+ "dayofyear", // Day of the year (1, 2, …, 365, etc.).+ "hours", // Hours of the day (12:00am, 1:00am, etc.).+ "minutes", // Minutes in an hour (12:00, 12:01, etc.).+ "seconds", // Seconds in a minute (12:00:00, 12:00:01, etc.).+ "milliseconds", // Milliseconds in a second.+] as const;+// Common combinations of the above+export const COMBINED_TIME_UNITS = [+ "yearmonth",+ "yearmonthdate",+ "monthdate",+] as const;+export const TIME_UNITS = [+ ...SINGLE_TIME_UNITS,+ ...COMBINED_TIME_UNITS,+] as const;+export type TimeUnit = (typeof TIME_UNITS)[number];++// Time units that are not selectable options but are used for tooltips+export const TIME_UNIT_TOOLTIPS = [+ ...TIME_UNITS,+ "yearmonthdatehoursminutesseconds",+ "yearmonthdate",+ "hoursminutesseconds",+] as const;+export type TimeUnitTooltip = (typeof TIME_UNIT_TOOLTIPS)[number];++/**+ * Similar to VegaLite's SortOrder, https://vega.github.io/vega-lite/docs/sort.html#order+ */+export const SORT_TYPES = ["ascending", "descending"] as const;+export type SortType = (typeof SORT_TYPES)[number];++export const NONE_AGGREGATION = "none";++/**+ * Subset of VegaLite's AggregateOp, https://vega.github.io/vega-lite/docs/aggregate.html#op+ */+export const AGGREGATION_FNS = [+ NONE_AGGREGATION,+ "count",+ "sum",+ "mean",+ "median",+ "min",+ "max",+ "distinct",+] as const;+export type AggregationFn = (typeof AGGREGATION_FNS)[number];++/**+ * Subset of VegaLite's MarkType, https://vega.github.io/vega-lite/docs/mark.html#types+ */+export const ChartType = {+ LINE: "line",+ BAR: "bar",+ PIE: "pie",+ SCATTER: "scatter",+ HEATMAP: "heatmap",+ AREA: "area",+} as const;+export type ChartType = (typeof ChartType)[keyof typeof ChartType];+export const CHART_TYPES = Object.values(ChartType);diff --git a/frontend/src/components/datasets/icons.tsx b/frontend/src/components/datasets/icons.tsxindex 922ccfb3c3..ff50ec74b0 100644--- a/frontend/src/components/datasets/icons.tsx+++ b/frontend/src/components/datasets/icons.tsx@@ -11,17 +11,20 @@ import {ClockIcon,CurlyBracesIcon,} from "lucide-react";+import type { SelectableDataType } from "../data-table/chart-transforms/types";/*** Maps a data type to an icon.*/-export const DATA_TYPE_ICON: Record<DataType, LucideIcon> = {- boolean: ToggleLeftIcon,- date: CalendarIcon,- time: ClockIcon,- datetime: CalendarClockIcon,- number: HashIcon,- string: TypeIcon,- integer: HashIcon,- unknown: CurlyBracesIcon,-};+export const DATA_TYPE_ICON: Record<DataType | SelectableDataType, LucideIcon> =+ {+ boolean: ToggleLeftIcon,+ date: CalendarIcon,+ time: ClockIcon,+ datetime: CalendarClockIcon,+ temporal: CalendarClockIcon,+ number: HashIcon,+ string: TypeIcon,+ integer: HashIcon,+ unknown: CurlyBracesIcon,+ };diff --git a/frontend/src/components/ui/accordion.tsx b/frontend/src/components/ui/accordion.tsxindex 0c202fb97f..4755b9bea9 100644--- a/frontend/src/components/ui/accordion.tsx+++ b/frontend/src/components/ui/accordion.tsx@@ -41,8 +41,10 @@ AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;const AccordionContent = React.forwardRef<React.ElementRef<typeof AccordionPrimitive.Content>,- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>->(({ className, children, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content> & {+ wrapperClassName?: string;+ }+>(({ className, children, wrapperClassName, ...props }, ref) => (<AccordionPrimitive.Contentref={ref}className={cn(@@ -51,7 +53,7 @@ const AccordionContent = React.forwardRef<)}{...props}>- <div className="pb-4 pt-0">{children}</div>+ <div className={cn("pb-4 pt-0", wrapperClassName)}>{children}</div></AccordionPrimitive.Content>));AccordionContent.displayName = AccordionPrimitive.Content.displayName;diff --git a/frontend/src/components/ui/select.tsx b/frontend/src/components/ui/select.tsxindex 0fe2c0ddbc..ccd4037424 100644--- a/frontend/src/components/ui/select.tsx+++ b/frontend/src/components/ui/select.tsx@@ -114,8 +114,10 @@ SelectLabel.displayName = SelectPrimitive.Label.displayName;const SelectItem = React.forwardRef<React.ElementRef<typeof SelectPrimitive.Item>,- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>->(({ className, children, ...props }, ref) => (+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item> & {+ subtitle?: React.ReactNode; // Subtitle is not displayed in input field+ }+>(({ className, children, subtitle, ...props }, ref) => (<SelectPrimitive.Itemref={ref}className={cn(@@ -136,6 +138,7 @@ const SelectItem = React.forwardRef<>{children}</SelectPrimitive.ItemText>+ {subtitle}</SelectPrimitive.Item>));SelectItem.displayName = SelectPrimitive.Item.displayName;diff --git a/frontend/src/core/cells/ids.ts b/frontend/src/core/cells/ids.tsindex 8bb33d2f3b..2bd1653f63 100644--- a/frontend/src/core/cells/ids.ts+++ b/frontend/src/core/cells/ids.ts@@ -47,6 +47,32 @@ export const HTMLCellId = {findElement(element: Element): (Element & { id: HTMLCellId }) | null {return element.closest('div[id^="cell-"]');},++ /**+ * Find the cell element through shadow DOMs.+ */+ findElementThroughShadowDOMs(+ element: Element,+ ): (Element & { id: HTMLCellId }) | null {+ let currentElement: Element | null = element;++ while (currentElement) {+ const cellElement = HTMLCellId.findElement(currentElement);+ if (cellElement) {+ return cellElement;+ }++ const root = currentElement.getRootNode();+ currentElement =+ root instanceof ShadowRoot ? root.host : currentElement.parentElement;++ if (currentElement === root) {+ break;+ }+ }++ return null;+ },};/**diff --git a/frontend/src/css/common.css b/frontend/src/css/common.cssindex 1c95950609..e5e1a8cd1d 100644--- a/frontend/src/css/common.css+++ b/frontend/src/css/common.css@@ -36,3 +36,8 @@.mo-dropdown-icon {@apply mr-2 h-3.5 w-3.5 text-muted-foreground/70;}++.scrollbar-thin {+ scrollbar-width: thin;+ scrollbar-color: var(--scrollbar-thumb) var(--scrollbar-track);+}