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: add chart builder / chart-to-cell functionality within table (#5392)
Shahmir Varqhaeb1f572b4fa8
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsxindex 37ed423892..8466b4a9a9 100644--- a/frontend/src/components/data-table/TableActions.tsx+++ b/frontend/src/components/data-table/TableActions.tsx@@ -3,7 +3,7 @@import type { RowSelectionState, Table } from "@tanstack/react-table";import {- ChartBarIcon,+ ChartAreaIcon,ChartColumnStacked,PanelRightIcon,SearchIcon,@@ -122,7 +122,7 @@ export const TableActions = <TData,>({className="mb-0"onClick={toggleDisplayHeader}>- <ChartBarIcon className="w-4 h-4 text-muted-foreground" />+ <ChartAreaIcon className="w-4 h-4 text-muted-foreground" /></Button></Tooltip>)}diff --git a/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snapindex 758ef512b0..cb1d506cb1 100644--- a/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap+++ b/frontend/src/components/data-table/charts/__tests__/__snapshots__/spec-snapshot.test.ts.snap@@ -4,18 +4,22 @@ exports[`create vega spec > should create and augment a spec 1`] = `{"$schema": "https://vega.github.io/schema/vega-lite/v5.json","background": "white",+ "config": {+ "axis": {+ "grid": false,+ },+ },"data": {"values": [],},"encoding": {"color": undefined,- "column": undefined,- "row": undefined,"tooltip": undefined,"x": {"aggregate": undefined,"bin": undefined,"field": "category",+ "sort": undefined,"stack": undefined,"timeUnit": undefined,"title": undefined,@@ -26,6 +30,7 @@ exports[`create vega spec > should create and augment a spec 1`] = `"aggregate": undefined,"bin": undefined,"field": "value",+ "sort": undefined,"stack": undefined,"timeUnit": undefined,"title": undefined,diff --git a/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.tsindex d72ffd8d52..ed6455f5a8 100644--- a/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/altair-generator.test.ts@@ -183,7 +183,8 @@ describe("generateAltairChart", () => {const result = generateAltairChartSnippet(spec, datasource, "_chart");expect(result).toMatchInlineSnapshot(`- "_chart = (+ "# replace df with your data source+ _chart = (alt.Chart(df).mark_bar().encode(diff --git a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.tsindex b5e1d6488d..2c5d93b53a 100644--- a/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/spec-snapshot.test.ts@@ -9,7 +9,7 @@ import {Y_AXIS_REQUIRED,} from "../chart-spec/spec";import type { ChartSchemaType } from "../schemas";-import { ChartType, NONE_AGGREGATION } from "../types";+import { ChartType, NONE_VALUE } from "../types";describe("create vega spec", () => {// Sample data for testing@@ -33,7 +33,7 @@ describe("create vega spec", () => {yColumn: {field: "value",type: "number" as const,- aggregate: NONE_AGGREGATION,+ aggregate: NONE_VALUE,},},});diff --git a/frontend/src/components/data-table/charts/__tests__/spec.test.ts b/frontend/src/components/data-table/charts/__tests__/spec.test.tsindex 2032836e5b..13ff6501b2 100644--- a/frontend/src/components/data-table/charts/__tests__/spec.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts@@ -2,14 +2,19 @@import type { PositionDef } from "vega-lite/build/src/channeldef";import { describe, expect, it } from "vitest";+import {+ getAggregate,+ getBinEncoding,+ getColorEncoding,+} from "../chart-spec/encodings";import { getAxisEncoding } from "../chart-spec/spec";import { getTooltips } from "../chart-spec/tooltips";-import { COUNT_FIELD } from "../constants";+import { COUNT_FIELD, EMPTY_VALUE } from "../constants";import type { ChartSchemaType } from "../schemas";import {AGGREGATION_FNS,ChartType,- NONE_AGGREGATION,+ NONE_VALUE,STRING_AGGREGATION_FNS,} from "../types";@@ -57,6 +62,7 @@ describe("getAxisEncoding", () => {bin: undefined,title: "Average Price",stack: false,+ timeUnit: undefined,aggregate: "mean",});});@@ -66,7 +72,7 @@ describe("getAxisEncoding", () => {{field: "date",selectedDataType: "temporal",- aggregate: NONE_AGGREGATION,+ aggregate: NONE_VALUE,timeUnit: "yearmonth",},undefined,@@ -91,7 +97,7 @@ describe("getAxisEncoding", () => {{field: "category",selectedDataType: "string",- aggregate: NONE_AGGREGATION,+ aggregate: NONE_VALUE,timeUnit: undefined,},undefined,@@ -162,7 +168,7 @@ describe("getAxisEncoding", () => {const expectedAggregate = (result as { aggregate?: string }).aggregate;// For aggregations that are not valid for string data types, we should return undefined- if (agg === NONE_AGGREGATION || !STRING_AGGREGATION_FNS.includes(agg)) {+ if (agg === NONE_VALUE || !STRING_AGGREGATION_FNS.includes(agg)) {expect(expectedAggregate).toBeUndefined();} else if (STRING_AGGREGATION_FNS.includes(agg)) {expect(expectedAggregate).toEqual(agg);@@ -189,6 +195,26 @@ describe("getAxisEncoding", () => {expect(expectedAggregate).toBeUndefined();}});++ it("should return correct encoding for sorted data", () => {+ for (const sort of ["ascending", "descending"]) {+ const result = getAxisEncoding(+ {+ field: "value",+ selectedDataType: "number",+ sort: sort as "ascending" | "descending",+ aggregate: NONE_VALUE,+ },+ undefined,+ "Value",+ false,+ ChartType.BAR,+ );++ const expectedSort = (result as { sort?: string }).sort;+ expect(expectedSort).toEqual(sort);+ }+ });});describe("getTooltips", () => {@@ -196,7 +222,11 @@ describe("getTooltips", () => {const result = getTooltips({formValues: {general: {- xColumn: { field: "x", type: "string" as const },+ xColumn: {+ field: "x",+ type: "string",+ aggregate: NONE_VALUE,+ },},},xEncoding: { field: "x", type: "nominal" },@@ -215,13 +245,16 @@ describe("getTooltips", () => {const formValues: ChartSchemaType = {general: {xColumn: {- type: "string" as const,+ type: "string",+ aggregate: NONE_VALUE,},yColumn: {- type: "number" as const,+ type: "number",+ aggregate: NONE_VALUE,},colorByColumn: {- type: "integer" as const,+ type: "integer",+ aggregate: NONE_VALUE,},},tooltips: autoTooltips,@@ -287,8 +320,16 @@ describe("getTooltips", () => {const result = getTooltips({formValues: {general: {- xColumn: { field: "x", type: "string" as const },- yColumn: { field: "y", type: "number" as const },+ xColumn: {+ field: "x",+ type: "string",+ aggregate: NONE_VALUE,+ },+ yColumn: {+ field: "y",+ type: "number",+ aggregate: NONE_VALUE,+ },},tooltips: {auto: false,@@ -305,9 +346,12 @@ describe("getTooltips", () => {it("should enhance tooltips with encoding parameters when field name matches encoding field", () => {const formValues = {general: {- xColumn: { type: "string" as const },- yColumn: { type: "number" as const },- colorByColumn: { type: "string" as const },+ xColumn: { type: "string" as const, aggregate: NONE_VALUE },+ yColumn: { type: "number" as const, aggregate: NONE_VALUE },+ colorByColumn: {+ type: "string" as const,+ aggregate: NONE_VALUE,+ },},tooltips: {auto: false,@@ -367,8 +411,16 @@ describe("getTooltips", () => {it("should handle count aggregate with no field set", () => {const formValues = {general: {- xColumn: { field: "category", type: "string" as const },- yColumn: { field: COUNT_FIELD, type: "number" as const },+ xColumn: {+ field: "category",+ type: "string" as const,+ aggregate: NONE_VALUE,+ },+ yColumn: {+ field: COUNT_FIELD,+ type: "number" as const,+ aggregate: NONE_VALUE,+ },},tooltips: {auto: true,@@ -395,4 +447,551 @@ describe("getTooltips", () => {},]);});++ it("should handle time unit in tooltips", () => {+ const result = getTooltips({+ formValues: {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ aggregate: NONE_VALUE,+ },+ yColumn: {+ field: "y",+ type: "number",+ aggregate: NONE_VALUE,+ },+ },+ tooltips: {+ auto: true,+ fields: [],+ },+ },+ xEncoding: { field: "x", type: "nominal", timeUnit: "year" },+ yEncoding: { field: "y", type: "quantitative" },+ });++ expect(result).toEqual([+ {+ field: "x",+ bin: undefined,+ format: undefined,+ timeUnit: "year",+ title: "x", // Should be set to field name+ aggregate: undefined,+ },+ {+ field: "y",+ format: ",.2f",+ timeUnit: undefined,+ title: undefined,+ aggregate: undefined,+ },+ ]);+ });+});++describe("getColorEncoding", () => {+ it("should return undefined for pie charts", () => {+ const result = getColorEncoding(ChartType.PIE, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ },+ });++ expect(result).toBeUndefined();+ });++ it("should return undefined when no color field is set", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ },+ });++ expect(result).toBeUndefined();+ });++ it("should return undefined when color field is NONE_VALUE", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: NONE_VALUE,+ type: "string",+ },+ },+ });++ expect(result).toBeUndefined();+ });++ it("should return undefined when color field is empty string", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: EMPTY_VALUE,+ type: "string",+ },+ },+ });++ expect(result).toBeUndefined();+ });++ it("should return count encoding for COUNT_FIELD", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: COUNT_FIELD,+ type: "number",+ },+ },+ });++ expect(result).toEqual({+ aggregate: "count",+ type: "quantitative",+ });+ });++ it("should use colorByColumn when set", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "category",+ type: "string",+ selectedDataType: "string",+ aggregate: "count",+ },+ },+ color: {+ field: "Color",+ scheme: "category10",+ },+ });++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ scale: { scheme: "category10" },+ aggregate: "count",+ bin: undefined,+ });+ });++ it("should use xColumn when color field matches xColumn field", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "category",+ type: "string",+ selectedDataType: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ },+ color: {+ field: "X",+ scheme: "category10",+ },+ });++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ scale: { scheme: "category10" },+ aggregate: undefined,+ bin: undefined,+ });+ });++ it("should use yColumn when color field matches yColumn field", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "value",+ type: "number",+ selectedDataType: "number",+ aggregate: "sum",+ },+ },+ color: {+ field: "Y",+ scheme: "viridis",+ },+ });++ expect(result).toEqual({+ field: "value",+ type: "quantitative",+ scale: { scheme: "viridis" },+ aggregate: "sum",+ bin: undefined,+ });+ });++ it("should return undefined when color field doesn't match any column", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ },+ color: {+ field: "Color",+ scheme: "category10",+ },+ });++ expect(result).toBeUndefined();+ });++ it("should handle bin encoding for numeric data", () => {+ const result = getColorEncoding(ChartType.HEATMAP, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "value",+ type: "number",+ selectedDataType: "number",+ },+ },+ color: {+ field: NONE_VALUE,+ bin: { maxbins: 10 },+ },+ });++ expect(result).toEqual({+ field: "value",+ type: "quantitative",+ scale: undefined,+ aggregate: undefined,+ bin: { maxbins: 10 },+ });+ });++ it("should handle color range instead of scheme", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "category",+ type: "string",+ selectedDataType: "string",+ },+ },+ color: {+ field: NONE_VALUE,+ range: ["red", "blue", "green"],+ },+ });++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ scale: { range: ["red", "blue", "green"] },+ aggregate: undefined,+ bin: undefined,+ });+ });++ it("should handle temporal data types", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "date",+ type: "datetime",+ selectedDataType: "temporal",+ aggregate: "sum",+ },+ },+ });++ expect(result).toEqual({+ field: "date",+ type: "temporal",+ scale: undefined,+ aggregate: undefined, // temporal data types don't support aggregation+ bin: undefined,+ });+ });++ it("should handle string aggregation functions", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "category",+ type: "string",+ selectedDataType: "string",+ aggregate: "count",+ },+ },+ });++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ scale: undefined,+ aggregate: "count",+ bin: undefined,+ });+ });++ it("should return undefined for invalid string aggregation", () => {+ const result = getColorEncoding(ChartType.BAR, {+ general: {+ xColumn: {+ field: "x",+ type: "string",+ },+ yColumn: {+ field: "y",+ type: "number",+ },+ colorByColumn: {+ field: "category",+ type: "string",+ selectedDataType: "string",+ aggregate: "sum", // sum is not valid for string+ },+ },+ });++ expect(result).toEqual({+ field: "category",+ type: "nominal",+ scale: undefined,+ aggregate: undefined, // sum is not valid for strings+ bin: undefined,+ });+ });+});++describe("getAggregate", () => {+ it("should return undefined for temporal data types", () => {+ const result = getAggregate("sum", "temporal");+ expect(result).toBeUndefined();+ });++ it("should return undefined for NONE_VALUE", () => {+ const result = getAggregate(NONE_VALUE, "number");+ expect(result).toBeUndefined();+ });++ it("should return undefined for BIN_AGGREGATION", () => {+ const result = getAggregate("bin", "number");+ expect(result).toBeUndefined();+ });++ it("should return defaultAggregate when aggregate is undefined", () => {+ const result = getAggregate(undefined, "number", "mean");+ expect(result).toEqual("mean");+ });++ it("should return undefined when aggregate is undefined and no default", () => {+ const result = getAggregate(undefined, "number");+ expect(result).toBeUndefined();+ });++ it("should return valid string aggregation for string data types", () => {+ const result = getAggregate("count", "string");+ expect(result).toEqual("count");+ });++ it("should return undefined for invalid string aggregation", () => {+ const result = getAggregate("sum", "string");+ expect(result).toBeUndefined();+ });++ it("should return aggregate for numeric data types", () => {+ const result = getAggregate("sum", "number");+ expect(result).toEqual("sum");+ });+});++describe("getBinEncoding", () => {+ it("should return maxbins for HEATMAP chart type", () => {+ const result = getBinEncoding(ChartType.HEATMAP, "number", {+ binned: false,+ maxbins: 10,+ });+ expect(result).toEqual({ maxbins: 10 });+ });++ it("should return undefined for HEATMAP without maxbins", () => {+ const result = getBinEncoding(ChartType.HEATMAP, "number", {+ binned: false,+ });+ expect(result).toBeUndefined();+ });++ it("should return undefined when not binned", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: false,+ step: 5,+ });+ expect(result).toBeUndefined();+ });++ it("should return undefined for non-numeric data types", () => {+ const result = getBinEncoding(ChartType.BAR, "string", {+ binned: true,+ step: 5,+ });+ expect(result).toBeUndefined();+ });++ it("should return true when binned with no parameters", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: true,+ });+ expect(result).toBe(true);+ });++ it("should return step parameter when provided", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: true,+ step: 5,+ });+ expect(result).toEqual({ step: 5 });+ });++ it("should return maxbins parameter when provided", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: true,+ maxbins: 20,+ });+ expect(result).toEqual({ maxbins: 20 });+ });++ it("should return both step and maxbins when both provided", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: true,+ step: 5,+ maxbins: 20,+ });+ expect(result).toEqual({ step: 5, maxbins: 20 });+ });++ it("should return undefined when binValues is undefined", () => {+ const result = getBinEncoding(ChartType.BAR, "number");+ expect(result).toBeUndefined();+ });++ it("should return defaultBinValues when binValues is undefined", () => {+ const result = getBinEncoding(ChartType.BAR, "number", undefined, {+ step: 10,+ });+ expect(result).toEqual({ step: 10 });+ });++ it("should handle zero values for step and maxbins", () => {+ const result = getBinEncoding(ChartType.BAR, "number", {+ binned: true,+ step: 0,+ maxbins: 0,+ });+ expect(result).toEqual({ step: 0, maxbins: 0 });+ });++ it("should work with different chart types", () => {+ const chartTypes = [ChartType.BAR, ChartType.LINE, ChartType.SCATTER];++ for (const chartType of chartTypes) {+ const result = getBinEncoding(chartType, "number", {+ binned: true,+ step: 10,+ });+ expect(result).toEqual({ step: 10 });+ }+ });});diff --git a/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts b/frontend/src/components/data-table/charts/chart-spec/altair-generator.tsindex be2ca81665..03d2dea7b5 100644--- a/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts+++ b/frontend/src/components/data-table/charts/chart-spec/altair-generator.ts@@ -107,11 +107,16 @@ export function generateAltairChart(code = code.chain("resolve_scale", axisArgs);}+ // TODO: Add layer support+const propertiesArgs: Record<string, PythonCode> = {};- const propertiesKeys = ["title", "height", "width"];+ const propertiesKeys = ["title", "height", "width", "config"];for (const key of propertiesKeys) {if (key in spec) {- propertiesArgs[key] = new Literal(spec[key as keyof VegaLiteSpec]);+ const value = spec[key as keyof VegaLiteSpec];+ if (value !== undefined) {+ propertiesArgs[key] = new Literal(value);+ }}}@@ -137,6 +142,7 @@ export function generateAltairChartSnippet(): string {const code = generateAltairChart(spec, datasource).toCode();return `+# replace ${datasource} with your data source${new VariableDeclaration(variableName, code).toCode()}${variableName}`.trim();diff --git a/frontend/src/components/data-table/charts/chart-spec/encodings.ts b/frontend/src/components/data-table/charts/chart-spec/encodings.tsindex 922ef9db28..e451450689 100644--- a/frontend/src/components/data-table/charts/chart-spec/encodings.ts+++ b/frontend/src/components/data-table/charts/chart-spec/encodings.ts@@ -6,15 +6,16 @@ import type { ColorDef, OffsetDef } from "vega-lite/build/src/channeldef";import type { Scale } from "vega-lite/build/src/scale";import type { z } from "zod";import { COUNT_FIELD, DEFAULT_COLOR_SCHEME } from "../constants";-import type { BinSchema, ChartSchemaType } from "../schemas";+import type { AxisSchema, BinSchema, ChartSchemaType } from "../schemas";import {type AggregationFn,BIN_AGGREGATION,ChartType,type ColorScheme,- NONE_AGGREGATION,+ NONE_VALUE,type SelectableDataType,STRING_AGGREGATION_FNS,+ type ValidAggregationFn,} from "../types";import { isFieldSet } from "./spec";import { convertDataTypeToVega } from "./types";@@ -23,6 +24,7 @@ export function getBinEncoding(chartType: ChartType,selectedDataType: SelectableDataType,binValues?: z.infer<typeof BinSchema>,+ defaultBinValues?: z.infer<typeof BinSchema>,): boolean | BinParams | undefined {if (chartType === ChartType.HEATMAP) {if (!binValues?.maxbins) {@@ -31,20 +33,20 @@ export function getBinEncoding(return { maxbins: binValues?.maxbins };}- if (!binValues?.binned) {- return undefined;- }-// Don't bin non-numeric dataif (selectedDataType !== "number") {return undefined;}+ if (!binValues?.binned) {+ return defaultBinValues;+ }+const binParams: BinParams = {};- if (binValues.step) {+ if (binValues.step !== undefined) {binParams.step = binValues.step;}- if (binValues.maxbins) {+ if (binValues.maxbins !== undefined) {binParams.maxbins = binValues.maxbins;}@@ -73,14 +75,42 @@ export function getColorEncoding(chartType: ChartType,formValues: ChartSchemaType,): ColorDef<string> | undefined {+ if (chartType === ChartType.PIE) {+ return undefined;+ }++ // Choose colorByColumn if it's set, otherwise use color.field+ // Color.field can be used to set colour scheme of the charts+ let colorByColumn: z.infer<typeof AxisSchema> | undefined;+ if (isFieldSet(formValues.general?.colorByColumn?.field)) {+ colorByColumn = formValues.general?.colorByColumn;+ } else if (isFieldSet(formValues.color?.field)) {+ const field = formValues.color?.field;+ switch (field) {+ case "X":+ colorByColumn = formValues.general?.xColumn;+ break;+ case "Y":+ colorByColumn = formValues.general?.yColumn;+ break;+ case "Color":+ colorByColumn = formValues.general?.colorByColumn;+ break;+ default:+ return undefined;+ }+ } else {+ return undefined;+ }+if (- chartType === ChartType.PIE ||- !isFieldSet(formValues.general?.colorByColumn?.field)+ !colorByColumn ||+ !isFieldSet(colorByColumn.field) ||+ colorByColumn.field === NONE_VALUE) {return undefined;}- const colorByColumn = formValues.general.colorByColumn;if (colorByColumn.field === COUNT_FIELD) {return {aggregate: "count",@@ -90,7 +120,7 @@ export function getColorEncoding(const colorBin = formValues.color?.bin;const selectedDataType = colorByColumn.selectedDataType || "string";- const aggregate = formValues.general.colorByColumn.aggregate;+ const aggregate = colorByColumn?.aggregate;return {field: colorByColumn.field,@@ -119,20 +149,21 @@ export function getOffsetEncoding(export function getAggregate(aggregate: AggregationFn | undefined,selectedDataType: SelectableDataType,+ defaultAggregate?: ValidAggregationFn,): Aggregate | undefined {// temporal data types don't support aggregationif (selectedDataType === "temporal") {return undefined;}- if (- aggregate === NONE_AGGREGATION ||- aggregate === BIN_AGGREGATION ||- !aggregate- ) {+ if (aggregate === NONE_VALUE || aggregate === BIN_AGGREGATION) {return undefined;}+ if (!aggregate) {+ return defaultAggregate ? (defaultAggregate as Aggregate) : undefined;+ }+if (selectedDataType === "string") {return STRING_AGGREGATION_FNS.includes(aggregate)? (aggregate as Aggregate)diff --git a/frontend/src/components/data-table/charts/chart-spec/spec.ts b/frontend/src/components/data-table/charts/chart-spec/spec.tsindex 54b624bfb3..c7a8aab4b7 100644--- a/frontend/src/components/data-table/charts/chart-spec/spec.ts+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts@@ -7,12 +7,19 @@ import type {PolarDef,PositionDef,} from "vega-lite/build/src/channeldef";+import type { Encoding } from "vega-lite/build/src/encoding";import type { Resolve } from "vega-lite/build/src/resolve";import type { FacetFieldDef } from "vega-lite/build/src/spec/facet";import type { z } from "zod";import type { ResolvedTheme } from "@/theme/useTheme";import type { TypedString } from "@/utils/typed";-import { COUNT_FIELD, EMPTY_VALUE } from "../constants";+import {+ COUNT_FIELD,+ DEFAULT_AGGREGATION,+ DEFAULT_MAX_BINS_FACET,+ DEFAULT_TIME_UNIT,+ EMPTY_VALUE,+} from "../constants";import type {AxisSchema,BinSchema,@@ -20,7 +27,7 @@ import type {ColumnFacet,RowFacet,} from "../schemas";-import { ChartType } from "../types";+import { ChartType, type ValidAggregationFn } from "../types";import {getAggregate,getBinEncoding,@@ -29,7 +36,11 @@ import {getOffsetEncoding,} from "./encodings";import { getTooltips } from "./tooltips";-import { convertChartTypeToMark, convertDataTypeToVega } from "./types";+import {+ type BaseSpec,+ convertChartTypeToMark,+ convertDataTypeToVega,+} from "./types";/*** Convert marimo chart configuration to Vega-Lite specification.@@ -57,7 +68,7 @@ export function createSpecWithoutData(} = formValues.general ?? {};if (chartType === ChartType.PIE) {- return getPieChartSpec([], formValues, theme, width, height);+ return getPieChartSpec(formValues, theme, width, height);}// Validate required fields@@ -81,12 +92,18 @@ export function createSpecWithoutData(chartType,);+ let defaultYAggregation: ValidAggregationFn = DEFAULT_AGGREGATION;+ if (yColumn?.selectedDataType === "string") {+ defaultYAggregation = "count";+ }+const yEncoding = getAxisEncoding(yColumn,formValues.yAxis?.bin,getFieldLabel(formValues.yAxis?.label),colorByColumn?.field && !horizontal ? stacking : undefined,chartType,+ defaultYAggregation,);const rowFacet = facet?.row.field@@ -97,26 +114,36 @@ export function createSpecWithoutData(: undefined;const colorByEncoding = getColorEncoding(chartType, formValues);+ const baseSpec = getBaseSpec(+ chartType,+ formValues,+ theme,+ width,+ height,+ title,+ );+ const baseEncoding: Encoding<Field> = {+ [xEncodingKey]: horizontal ? yEncoding : xEncoding,+ [yEncodingKey]: horizontal ? xEncoding : yEncoding,+ xOffset: getOffsetEncoding(chartType, formValues),+ color: colorByEncoding,+ tooltip: getTooltips({+ formValues,+ xEncoding,+ yEncoding,+ colorByEncoding,+ }),+ ...(rowFacet && { row: rowFacet }),+ ...(columnFacet && { column: columnFacet }),+ };+ const resolve = getResolve(facet?.column, facet?.row);- // Create the final spec+ // Create the final spec for other chart typesreturn {- ...getBaseSpec([], formValues, theme, width, height, title),+ ...baseSpec,mark: { type: convertChartTypeToMark(chartType) },- encoding: {- [xEncodingKey]: horizontal ? yEncoding : xEncoding,- [yEncodingKey]: horizontal ? xEncoding : yEncoding,- xOffset: getOffsetEncoding(chartType, formValues),- color: colorByEncoding,- tooltip: getTooltips({- formValues,- xEncoding,- yEncoding,- colorByEncoding,- }),- row: rowFacet,- column: columnFacet,- },- ...getResolve(facet?.column, facet?.row),+ encoding: baseEncoding,+ ...resolve,};}@@ -136,6 +163,7 @@ export function getAxisEncoding(label: string | undefined,stack: boolean | undefined,chartType: ChartType,+ defaultAggregate?: ValidAggregationFn,): PositionDef<string> {const selectedDataType = column.selectedDataType || "string";@@ -155,7 +183,12 @@ export function getAxisEncoding(bin: getBinEncoding(chartType, selectedDataType, binValues),title: label,stack: stack,- aggregate: getAggregate(column.aggregate, selectedDataType),+ aggregate: getAggregate(+ column.aggregate,+ selectedDataType,+ defaultAggregate,+ ),+ sort: column.sort,timeUnit: getTimeUnit(column),};}@@ -164,6 +197,9 @@ export function getFacetEncoding(facet: z.infer<typeof RowFacet> | z.infer<typeof ColumnFacet>,chartType: ChartType,): FacetFieldDef<Field> {+ const defaultBinValues = {+ maxbins: DEFAULT_MAX_BINS_FACET,+ };const binValues = getBinEncoding(chartType,facet.selectedDataType || "string",@@ -171,24 +207,24 @@ export function getFacetEncoding(maxbins: facet.maxbins,binned: facet.binned,},+ defaultBinValues,);return {field: facet.field,sort: facet.sort,- timeUnit: getTimeUnit(facet),+ timeUnit: getFacetTimeUnit(facet),type: convertDataTypeToVega(facet.selectedDataType || "unknown"),bin: binValues,};}function getPieChartSpec(- data: object[],formValues: ChartSchemaType,theme: ResolvedTheme,width: number | "container",height: number,-) {+): TopLevelSpec | ErrorMessage {const { yColumn, colorByColumn, title } = formValues.general ?? {};if (!isFieldSet(colorByColumn?.field)) {@@ -215,7 +251,7 @@ function getPieChartSpec(};return {- ...getBaseSpec(data, formValues, theme, width, height, title),+ ...getBaseSpec(ChartType.PIE, formValues, theme, width, height, title),mark: {type: convertChartTypeToMark(ChartType.PIE),innerRadius: formValues.style?.innerRadius,@@ -234,20 +270,31 @@ function getPieChartSpec(}function getBaseSpec(- data: object[],+ chartType: ChartType,formValues: ChartSchemaType,theme: ResolvedTheme,width: number | "container",height: number,title?: string,-) {+): BaseSpec {+ let gridLines = formValues.style?.gridLines ?? false;+ // Scatter charts have grid lines by default+ if (chartType === ChartType.SCATTER) {+ gridLines = true;+ }+return {$schema: "https://vega.github.io/schema/vega-lite/v5.json",background: theme === "dark" ? "dark" : "white",title: title,- data: { values: data },+ data: { values: [] },height: formValues.yAxis?.height ?? height,width: formValues.xAxis?.width ?? width,+ config: {+ axis: {+ grid: gridLines,+ },+ },};}@@ -263,7 +310,16 @@ function getFieldLabel(label?: string): string | undefined {function getTimeUnit(column: z.infer<typeof AxisSchema>) {if (column.selectedDataType === "temporal") {- return column.timeUnit;+ return column.timeUnit ?? DEFAULT_TIME_UNIT;+ }+ return undefined;+}++function getFacetTimeUnit(+ facet: z.infer<typeof RowFacet> | z.infer<typeof ColumnFacet>,+) {+ if (facet.selectedDataType === "temporal") {+ return facet.timeUnit ?? DEFAULT_TIME_UNIT;}return undefined;}diff --git a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts b/frontend/src/components/data-table/charts/chart-spec/tooltips.tsindex b6fde87bc4..efcc003688 100644--- a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts+++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts@@ -53,6 +53,12 @@ export function getTooltips(}if (encoding && "field" in encoding && isFieldSet(encoding.field)) {+ if (encoding.timeUnit && !title) {+ // When there is a time unit, we want to show the field name as the title+ // otherwise the title becomes too verbose+ title = encoding.field;+ }+const tooltip: StringFieldDef<string> = {field: encoding.field,aggregate: encoding.aggregate,diff --git a/frontend/src/components/data-table/charts/chart-spec/types.ts b/frontend/src/components/data-table/charts/chart-spec/types.tsindex 631f93e10c..5aba268f9a 100644--- a/frontend/src/components/data-table/charts/chart-spec/types.ts+++ b/frontend/src/components/data-table/charts/chart-spec/types.ts@@ -6,6 +6,20 @@ import type { Mark } from "@/plugins/impl/vega/types";import { logNever } from "@/utils/assertNever";import { ChartType, type SelectableDataType } from "../types";+export interface BaseSpec {+ $schema: string;+ background: string;+ title: string | undefined;+ data: { values: object[] };+ height: number;+ width: number | "container";+ config: {+ axis: {+ grid: boolean;+ };+ };+}+export function convertDataTypeToVega(dataType: DataType | SelectableDataType,): StandardType {diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsxindex 007ad99a17..e86f7085d4 100644--- a/frontend/src/components/data-table/charts/charts.tsx+++ b/frontend/src/components/data-table/charts/charts.tsx@@ -4,20 +4,23 @@ import { zodResolver } from "@hookform/resolvers/zod";import { useAtom } from "jotai";import {ChartColumnIcon,+ ChevronLeftIcon,+ ChevronRightIcon,CodeIcon,DatabaseIcon,+ InfoIcon,PaintRollerIcon,- TableIcon,XIcon,} from "lucide-react";import type { JSX } from "react";import React, { useMemo, useState } from "react";import { type UseFormReturn, useForm } from "react-hook-form";+import useResizeObserver from "use-resize-observer";import { PythonIcon } from "@/components/editor/cell/code/icons";-import { getDefaults } from "@/components/forms/form-utils";import { Button } from "@/components/ui/button";import { Form } from "@/components/ui/form";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { Tooltip } from "@/components/ui/tooltip";import type { CellId } from "@/core/cells/ids";import { useAsyncData } from "@/hooks/useAsyncData";import { useDebouncedCallback } from "@/hooks/useDebounce";@@ -40,13 +43,13 @@ import { CommonChartForm, StyleForm } from "./forms/common-chart";import { HeatmapForm } from "./forms/heatmap";import { PieForm } from "./forms/pie";import { LazyChart } from "./lazy-chart";-import { ChartSchema, type ChartSchemaType } from "./schemas";+import { ChartSchema, type ChartSchemaType, getChartDefaults } from "./schemas";import { getChartTabName, type TabName, tabsStorageAtom } from "./storage";import { ChartType } from "./types";const NEW_CHART_TYPE = "bar" as ChartType;const DEFAULT_TAB_NAME = "table" as TabName;-const CHART_HEIGHT = 300;+const CHART_HEIGHT = 290;export interface TablePanelProps {cellId: CellId | null;@@ -85,7 +88,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({{tabName,chartType: NEW_CHART_TYPE,- config: getDefaults(ChartSchema),+ config: getChartDefaults(),},]);@@ -163,7 +166,6 @@ export const TablePanel: React.FC<TablePanelProps> = ({value={DEFAULT_TAB_NAME}onClick={() => setSelectedTab(DEFAULT_TAB_NAME)}>- <TableIcon className="w-3 h-3 mr-2" />Table</TabsTrigger>{tabs.map((tab, idx) => (@@ -237,12 +239,15 @@ export const ChartPanel: React.FC<{}) => {const { theme } = useTheme();const form = useForm<ChartSchemaType>({- defaultValues: chartConfig ?? getDefaults(ChartSchema),+ defaultValues: chartConfig ?? getChartDefaults(),resolver: zodResolver(ChartSchema),});const [selectedChartType, setSelectedChartType] =useState<ChartType>(chartType);+ const [formCollapsed, setFormCollapsed] = useState(false);++ const { ref: chartContainerRef } = useResizeObserver();const { data, isPending, error } = useAsyncData(async () => {if (!getDataUrl) {@@ -303,37 +308,44 @@ export const ChartPanel: React.FC<{if (typeof specWithoutData !== "string") {altairCodeSnippet = generateAltairChartSnippet(specWithoutData,- "df",+ "_df","_chart",);}return (<Tabs defaultValue="chart">- <TabsList>- <TabsTrigger value="chart" className="h-6">- <ChartColumnIcon className="text-muted-foreground mr-2 w-4 h-4" />- Chart- </TabsTrigger>- <TabsTrigger value="code" className="h-6">- <PythonIcon className="text-muted-foreground mr-2" />- Python code- </TabsTrigger>- {developmentMode && (- <>- <TabsTrigger value="formValues" className="h-6">- <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />- Form values (debug)- </TabsTrigger>- <TabsTrigger value="vegaSpec" className="h-6">- <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />- Vega spec (debug)- </TabsTrigger>- </>- )}- </TabsList>-- <TabsContent value="chart">{memoizedChart}</TabsContent>+ <div className="flex flex-row gap-1.5 items-center">+ <TabsList>+ <TabsTrigger value="chart" className="h-6">+ <ChartColumnIcon className="text-muted-foreground mr-2 w-4 h-4" />+ Chart+ </TabsTrigger>+ <TabsTrigger value="code" className="h-6">+ <PythonIcon className="text-muted-foreground mr-2" />+ Python code+ </TabsTrigger>+ {developmentMode && (+ <>+ <TabsTrigger value="formValues" className="h-6">+ <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />+ Form values (debug)+ </TabsTrigger>+ <TabsTrigger value="vegaSpec" className="h-6">+ <CodeIcon className="text-muted-foreground mr-2 w-4 h-4" />+ Vega spec (debug)+ </TabsTrigger>+ </>+ )}+ </TabsList>+ <Tooltip content="Charts are saved in local storage but as it remains experimental, we encourage saving the generated Python code in a new cell">+ <InfoIcon className="w-4 h-4 text-muted-foreground" />+ </Tooltip>+ </div>++ <TabsContent value="chart" ref={chartContainerRef}>+ {memoizedChart}+ </TabsContent><TabsContent value="code"><CodeSnippet code={altairCodeSnippet} language="python" /></TabsContent>@@ -357,23 +369,44 @@ export const ChartPanel: React.FC<{);};+ const chartForm = (+ <>+ <ChartTypeSelect+ value={selectedChartType}+ onValueChange={(value) => {+ setSelectedChartType(value);+ saveChartType(value);+ }}+ />++ <ChartFormContainer+ form={form}+ saveChart={saveChart}+ fieldTypes={fieldTypes}+ chartType={selectedChartType}+ />+ </>+ );+return (<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) => {- setSelectedChartType(value);- saveChartType(value);- }}- />-- <ChartFormContainer- form={form}- saveChart={saveChart}- fieldTypes={fieldTypes}- chartType={selectedChartType}- />+ <div+ className={`relative flex flex-col gap-2 overflow-auto px-2 py-3 scrollbar-thin transition-width duration-200 ${formCollapsed ? "w-8" : "w-[300px]"}`}+ >+ {!formCollapsed && chartForm}+ <Button+ variant="outline"+ size="icon"+ className="absolute bottom-1 right-1 border-border"+ onClick={() => setFormCollapsed((prev) => !prev)}+ title={formCollapsed ? "Expand sidebar" : "Collapse sidebar"}+ >+ {formCollapsed ? (+ <ChevronRightIcon className="w-4 h-4" />+ ) : (+ <ChevronLeftIcon className="w-4 h-4" />+ )}+ </Button></div><div className="flex-1 overflow-auto h-full w-full mt-3">{renderChartDisplay()}@@ -417,7 +450,7 @@ const ChartFormContainer = ({}return (- <ChartFormContext value={{ fields, saveForm: debouncedSave }}>+ <ChartFormContext value={{ fields, saveForm: debouncedSave, chartType }}><Form {...form}><form onSubmit={(e) => e.preventDefault()} onChange={debouncedSave}><Tabs defaultValue="data">diff --git a/frontend/src/components/data-table/charts/components/chart-items.tsx b/frontend/src/components/data-table/charts/components/chart-items.tsxindex aae1e65569..59e9c758aa 100644--- a/frontend/src/components/data-table/charts/components/chart-items.tsx+++ b/frontend/src/components/data-table/charts/components/chart-items.tsx@@ -17,10 +17,21 @@ import type { DataType } from "@/core/kernel/messages";import { ErrorBanner } from "@/plugins/impl/common/error-banner";import { isFieldSet } from "../chart-spec/spec";import { convertDataTypeToSelectable } from "../chart-spec/types";-import { CHART_TYPE_ICON, COUNT_FIELD, type EMPTY_VALUE } from "../constants";+import {+ CHART_TYPE_ICON,+ COUNT_FIELD,+ DEFAULT_AGGREGATION,+ DEFAULT_MAX_BINS_FACET,+ type EMPTY_VALUE,+} from "../constants";import { useChartFormContext } from "../context";import type { ChartSchema } from "../schemas";-import { CHART_TYPES, type ChartType, type SelectableDataType } from "../types";+import {+ type AggregationFn,+ CHART_TYPES,+ ChartType,+ type SelectableDataType,+} from "../types";import {AggregationSelect,BinFields,@@ -42,6 +53,13 @@ function isNonCountField(field?: { field?: string }) {return isFieldSet(field?.field) && field?.field !== COUNT_FIELD;}+function isStringField(field?: {+ field?: string;+ selectedDataType?: SelectedDataType;+}) {+ return field?.selectedDataType === "string" && isNonCountField(field);+}+function isNumberField(field?: {field?: string;selectedDataType?: SelectedDataType;@@ -85,9 +103,16 @@ const ColumnSelectorWithAggregation: React.FC<{type?: FieldDataType;selectedDataType?: SelectedDataType;};+ defaultAggregation?: AggregationFn;columns: Array<{ name: string; type: DataType }>;binFieldName: FieldName;-}> = ({ columnFieldName, column, columns, binFieldName }) => {+}> = ({+ columnFieldName,+ column,+ columns,+ binFieldName,+ defaultAggregation,+}) => {const { selectedDataType } = getColumnDataTypes(column);return (@@ -100,6 +125,7 @@ const ColumnSelectorWithAggregation: React.FC<{}selectedDataType={selectedDataType}binFieldName={binFieldName}+ defaultAggregation={defaultAggregation}/>)}</div>@@ -167,6 +193,11 @@ export const XAxis: React.FC = () => {const xColumn = formValues.general?.xColumn;const { inferredDataType } = getColumnDataTypes(xColumn);+ const allowSorting =+ context.chartType === ChartType.LINE ||+ context.chartType === ChartType.BAR ||+ context.chartType === ChartType.AREA;+return (<FieldSection><Title text="X-Axis" />@@ -189,7 +220,7 @@ export const XAxis: React.FC = () => {label="Time Resolution"/>)}- {isNonCountField(xColumn) && (+ {isNonCountField(xColumn) && allowSorting && (<><SortFieldfieldName="general.xColumn.sort"@@ -214,6 +245,15 @@ export const YAxis: React.FC = () => {const xColumnExists = isFieldSet(xColumn?.field);const { inferredDataType } = getColumnDataTypes(yColumn);+ let defaultAggregation: AggregationFn | undefined;+ if (isNumberField(yColumn)) {+ // Set default for perf reasons+ defaultAggregation = DEFAULT_AGGREGATION;+ } else if (isStringField(yColumn)) {+ // Y-columns tend to be measurements, so we default to count+ defaultAggregation = "count";+ }+return (<FieldSection><Title text="Y-Axis" />@@ -222,6 +262,7 @@ export const YAxis: React.FC = () => {column={yColumn}columns={context.fields}binFieldName="yAxis.bin.binned"+ defaultAggregation={defaultAggregation}/>{isNonCountField(yColumn) && (@@ -311,11 +352,13 @@ export const Facet: React.FC = () => {<BooleanFieldfieldName={`general.facet.${facet}.binned`}label="Binned"+ defaultValue={true}/><NumberFieldfieldName={`general.facet.${facet}.maxbins`}label="Max Bins"- placeholder="10"+ placeholder={DEFAULT_MAX_BINS_FACET.toString()}+ defaultValue={DEFAULT_MAX_BINS_FACET}/></div>)}diff --git a/frontend/src/components/data-table/charts/components/form-fields.tsx b/frontend/src/components/data-table/charts/components/form-fields.tsxindex c57385809a..189050c4bb 100644--- a/frontend/src/components/data-table/charts/components/form-fields.tsx+++ b/frontend/src/components/data-table/charts/components/form-fields.tsx@@ -41,6 +41,7 @@ import {AGGREGATION_TYPE_DESCRIPTIONS,AGGREGATION_TYPE_ICON,COUNT_FIELD,+ DEFAULT_TIME_UNIT,EMPTY_VALUE,SCALE_TYPE_DESCRIPTIONS,TIME_UNIT_DESCRIPTIONS,@@ -49,9 +50,10 @@ import { useChartFormContext } from "../context";import type { BinSchema, ChartSchema, ChartSchemaType } from "../schemas";import {AGGREGATION_FNS,+ type AggregationFn,BIN_AGGREGATION,COMBINED_TIME_UNITS,- NONE_AGGREGATION,+ NONE_VALUE,SELECTABLE_DATA_TYPES,type SelectableDataType,SINGLE_TIME_UNITS,@@ -509,46 +511,48 @@ export const TimeUnitSelect = ({<FormFieldcontrol={form.control}name={fieldName}- render={({ field }) => (- <FormItem className="flex flex-row items-center justify-between w-full">- <FormLabel>{label}</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>+ render={({ field }) => {+ return (+ <FormItem className="flex flex-row items-center justify-between w-full">+ <FormLabel>{label}</FormLabel>+ <FormControl>+ <Select+ {...field}+ onValueChange={(value) => {+ if (value === CLEAR_VALUE) {+ clear();+ } else {+ field.onChange(value);+ }+ }}+ value={field.value ?? DEFAULT_TIME_UNIT}+ >+ <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 />- </>- )}- <SelectGroup>- {COMBINED_TIME_UNITS.map(renderTimeUnit)}- <SelectSeparator />- {SINGLE_TIME_UNITS.map(renderTimeUnit)}- </SelectGroup>- </SelectContent>- </Select>- </FormControl>- </FormItem>- )}+ {SINGLE_TIME_UNITS.map(renderTimeUnit)}+ </SelectGroup>+ </SelectContent>+ </Select>+ </FormControl>+ </FormItem>+ );+ }}/>);};@@ -592,6 +596,8 @@ export const DataTypeSelect = ({<SelectGroup>{SELECTABLE_DATA_TYPES.map((type) => {const Icon = DATA_TYPE_ICON[type];+ // Categorical is a clearer name for how we will aggregate this+ const name = type === "string" ? "categorical" : type;return (<SelectItemkey={type}@@ -605,7 +611,7 @@ export const DataTypeSelect = ({)}>- <IconWithText Icon={Icon} text={capitalize(type)} />+ <IconWithText Icon={Icon} text={capitalize(name)} /></SelectItem>);})}@@ -623,10 +629,12 @@ export const AggregationSelect = ({fieldName,selectedDataType,binFieldName,+ defaultAggregation,}: {fieldName: FieldName;selectedDataType: SelectableDataType;binFieldName: FieldName;+ defaultAggregation?: AggregationFn;}) => {const form = useFormContext();const availableAggregations =@@ -681,7 +689,11 @@ export const AggregationSelect = ({<FormControl><Select{...field}- value={(field.value ?? NONE_AGGREGATION).toString()}+ value={(+ field.value ??+ defaultAggregation ??+ NONE_VALUE+ ).toString()}onValueChange={(value) => {handleFieldChange(value, field.value, field.onChange);}}@@ -700,10 +712,10 @@ export const AggregationSelect = ({const selectItem = renderSelectItem(agg, Icon, subtitle);if (agg === BIN_AGGREGATION) {return (- <>+ <div key={agg}><SelectSeparator />{selectItem}- </>+ </div>);}return selectItem;diff --git a/frontend/src/components/data-table/charts/components/layouts.tsx b/frontend/src/components/data-table/charts/components/layouts.tsxindex d3b04c18f9..abc4d92196 100644--- a/frontend/src/components/data-table/charts/components/layouts.tsx+++ b/frontend/src/components/data-table/charts/components/layouts.tsx@@ -1,16 +1,29 @@/* Copyright 2024 Marimo. All rights reserved. */-import type { LucideProps } from "lucide-react";+import { InfoIcon, type LucideProps } from "lucide-react";import { ReadonlyCode } from "@/components/editor/code/readonly-python-code";import {AccordionContent,AccordionItem,AccordionTrigger,} from "@/components/ui/accordion";+import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/utils/cn";-export const Title: React.FC<{ text: string }> = ({ text }) => {- return <h2 className="font-semibold my-0">{text}</h2>;+export const Title: React.FC<{ text: string; tooltip?: string }> = ({+ text,+ tooltip,+}) => {+ return (+ <h2 className="font-semibold my-0 flex items-center gap-1">+ {text}+ {tooltip && (+ <Tooltip content={tooltip}>+ <InfoIcon className="w-3 h-3 mt-0.5" />+ </Tooltip>+ )}+ </h2>+ );};export const TabContainer: React.FC<{@@ -96,6 +109,9 @@ export const CodeSnippet: React.FC<{maxHeight="330px"code={code}language={language}+ showHideCode={false}+ showCopyCode={false}+ insertNewCell={true}/>);};diff --git a/frontend/src/components/data-table/charts/constants.ts b/frontend/src/components/data-table/charts/constants.tsindex b28684ce13..9e10d2ff23 100644--- a/frontend/src/components/data-table/charts/constants.ts+++ b/frontend/src/components/data-table/charts/constants.ts@@ -24,10 +24,13 @@ import type {ColorScheme,SelectableDataType,TimeUnit,+ ValidAggregationFn,} from "./types";export const COUNT_FIELD = "__count__";export const DEFAULT_COLOR_SCHEME = "default";+export const DEFAULT_TIME_UNIT = "yearmonthdate";+export const DEFAULT_MAX_BINS_FACET = 6;// Set a field to this to reflect that it is not setexport const EMPTY_VALUE = "";@@ -41,6 +44,7 @@ export const CHART_TYPE_ICON: Record<ChartType, React.ElementType> = {area: AreaChartIcon,};+export const DEFAULT_AGGREGATION: ValidAggregationFn = "mean"; // For y-axis, we default to meanexport const AGGREGATION_TYPE_ICON: Record<AggregationFn, React.ElementType> = {none: SquareFunctionIcon,count: HashIcon,diff --git a/frontend/src/components/data-table/charts/context.ts b/frontend/src/components/data-table/charts/context.tsindex 9590477b4d..9edeafc367 100644--- a/frontend/src/components/data-table/charts/context.ts+++ b/frontend/src/components/data-table/charts/context.ts@@ -3,13 +3,16 @@import { createContext, use } from "react";import { Functions } from "@/utils/functions";import type { Field } from "./components/form-fields";+import { ChartType } from "./types";export const ChartFormContext = createContext<{fields: Field[];saveForm: () => void;+ chartType: ChartType;}>({fields: [],saveForm: Functions.NOOP,+ chartType: ChartType.LINE,});export const useChartFormContext = () => {diff --git a/frontend/src/components/data-table/charts/forms/common-chart.tsx b/frontend/src/components/data-table/charts/forms/common-chart.tsxindex 3b91812b77..b43fa7fdee 100644--- a/frontend/src/components/data-table/charts/forms/common-chart.tsx+++ b/frontend/src/components/data-table/charts/forms/common-chart.tsx@@ -24,6 +24,7 @@ import {import { COLOR_SCHEMES, DEFAULT_COLOR_SCHEME } from "../constants";import { useChartFormContext } from "../context";import type { ChartSchemaType } from "../schemas";+import { ChartType, COLOR_BY_FIELDS, NONE_VALUE } from "../types";export const CommonChartForm: React.FC = () => {const form = useFormContext<ChartSchemaType>();@@ -33,7 +34,12 @@ export const CommonChartForm: React.FC = () => {const groupByColumn = formValues.general?.colorByColumn;const yColumnExists = isFieldSet(yColumn?.field);- const showStacking = isFieldSet(groupByColumn?.field);++ const { chartType } = useChartFormContext();++ const showStacking =+ isFieldSet(groupByColumn?.field) &&+ (chartType === ChartType.BAR || chartType === ChartType.LINE);return (<>@@ -58,6 +64,8 @@ export const CommonChartForm: React.FC = () => {};export const StyleForm: React.FC = () => {+ const { chartType } = useChartFormContext();+return (<Accordion type="multiple"><AccordionFormItem value="general">@@ -66,6 +74,11 @@ export const StyleForm: React.FC = () => {</AccordionFormTrigger><AccordionFormContent><InputField label="Plot title" fieldName="general.title" />+ <BooleanField+ fieldName="style.gridLines"+ label="Show grid lines"+ defaultValue={chartType === ChartType.SCATTER}+ /></AccordionFormContent></AccordionFormItem>@@ -106,6 +119,15 @@ export const StyleForm: React.FC = () => {<Title text="Color" /></AccordionFormTrigger><AccordionFormContent>+ <SelectField+ fieldName="color.field"+ label="Field"+ options={COLOR_BY_FIELDS.map((field) => ({+ display: capitalize(field),+ value: field,+ }))}+ defaultValue={NONE_VALUE}+ /><SelectFieldfieldName="color.scheme"label="Color scheme"@@ -137,7 +159,10 @@ export const OtherOptions: React.FC = () => {<Accordion type="multiple"><AccordionFormItem value="facet"><AccordionFormTrigger className="pt-0">- <Title text="Faceting" />+ <Title+ text="Faceting"+ tooltip="Repeat the chart for each unique field value"+ /></AccordionFormTrigger><AccordionFormContent><Facet />@@ -149,7 +174,10 @@ export const OtherOptions: React.FC = () => {<Title text="Tooltips" /></AccordionFormTrigger><AccordionFormContent wrapperClassName="flex-row justify-between">- <BooleanField fieldName="tooltips.auto" label="Auto" />+ <BooleanField+ fieldName="tooltips.auto"+ label="Include X, Y and Color"+ />{!autoTooltips && (<TooltipSelectfieldName="tooltips.fields"diff --git a/frontend/src/components/data-table/charts/schemas.ts b/frontend/src/components/data-table/charts/schemas.tsindex 12a2a25a69..991edfad07 100644--- a/frontend/src/components/data-table/charts/schemas.ts+++ b/frontend/src/components/data-table/charts/schemas.ts@@ -6,10 +6,15 @@import { z } from "zod";import { DATA_TYPES } from "@/core/kernel/messages";-import { DEFAULT_COLOR_SCHEME, EMPTY_VALUE } from "./constants";+import {+ DEFAULT_COLOR_SCHEME,+ DEFAULT_MAX_BINS_FACET,+ EMPTY_VALUE,+} from "./constants";import {AGGREGATION_FNS,- NONE_AGGREGATION,+ COLOR_BY_FIELDS,+ NONE_VALUE,SELECTABLE_DATA_TYPES,SORT_TYPES,TIME_UNITS,@@ -30,18 +35,19 @@ const BaseColumnSchema = z.object({});export const AxisSchema = BaseColumnSchema.extend({- aggregate: z.enum(AGGREGATION_FNS).default(NONE_AGGREGATION).optional(),+ aggregate: z.enum(AGGREGATION_FNS).default(NONE_VALUE).optional(),});export const RowFacet = BaseColumnSchema.extend({- linkYAxis: z.boolean().default(true).optional(),- binned: z.boolean().default(true).optional(),- maxbins: z.number().optional(),+ linkYAxis: z.boolean().default(true),+ binned: z.boolean().default(true),+ maxbins: z.number().default(DEFAULT_MAX_BINS_FACET),});+export const ColumnFacet = BaseColumnSchema.extend({- linkXAxis: z.boolean().default(true).optional(),- binned: z.boolean().default(true).optional(),- maxbins: z.number().optional(),+ linkXAxis: z.boolean().default(true),+ binned: z.boolean().default(true),+ maxbins: z.number().default(DEFAULT_MAX_BINS_FACET),});export const ChartSchema = z.object({@@ -77,6 +83,7 @@ export const ChartSchema = z.object({.optional(),color: z.object({+ field: z.enum([...COLOR_BY_FIELDS, NONE_VALUE]).default(NONE_VALUE),scheme: z.string().default(DEFAULT_COLOR_SCHEME).optional(),range: z.array(z.string()).optional(),domain: z.array(z.string()).optional(),@@ -86,6 +93,7 @@ export const ChartSchema = z.object({style: z.object({innerRadius: z.number().optional(),+ gridLines: z.boolean().optional(),}).optional(),tooltips: z@@ -103,3 +111,30 @@ export const ChartSchema = z.object({});export type ChartSchemaType = z.infer<typeof ChartSchema>;++export function getChartDefaults(): ChartSchemaType {+ return {+ general: {+ facet: {+ row: {+ linkYAxis: true,+ binned: true,+ maxbins: DEFAULT_MAX_BINS_FACET,+ },+ column: {+ linkXAxis: true,+ binned: true,+ maxbins: DEFAULT_MAX_BINS_FACET,+ },+ },+ },+ color: {+ field: NONE_VALUE,+ scheme: "default",+ },+ tooltips: {+ auto: true,+ fields: [],+ },+ };+}diff --git a/frontend/src/components/data-table/charts/types.ts b/frontend/src/components/data-table/charts/types.tsindex 3ede1226f2..14f7200ecb 100644--- a/frontend/src/components/data-table/charts/types.ts+++ b/frontend/src/components/data-table/charts/types.ts@@ -68,14 +68,13 @@ export type TimeUnitTooltip = (typeof TIME_UNIT_TOOLTIPS)[number];export const SORT_TYPES = ["ascending", "descending"] as const;export type SortType = (typeof SORT_TYPES)[number];-export const NONE_AGGREGATION = "none";+export const NONE_VALUE = "none";export const BIN_AGGREGATION = "bin"; // We use this not to aggregate, but to bin/*** Subset of VegaLite's AggregateOp, https://vega.github.io/vega-lite/docs/aggregate.html#op*/-export const AGGREGATION_FNS = [- NONE_AGGREGATION,+export const VALID_AGGREGATION_FNS = ["count","sum","mean",@@ -88,14 +87,19 @@ export const AGGREGATION_FNS = ["stdevp","variance","variancep",+];+export const AGGREGATION_FNS = [+ NONE_VALUE,BIN_AGGREGATION,+ ...VALID_AGGREGATION_FNS,] as const;export type AggregationFn = (typeof AGGREGATION_FNS)[number];+export type ValidAggregationFn = (typeof VALID_AGGREGATION_FNS)[number];/** Subset of AGGREGATION_FNS that are valid for string data types*/-export const STRING_AGGREGATION_FNS: AggregationFn[] = [+export const STRING_AGGREGATION_FNS: ValidAggregationFn[] = ["none","count","distinct",@@ -115,3 +119,6 @@ export const ChartType = {} as const;export type ChartType = (typeof ChartType)[keyof typeof ChartType];export const CHART_TYPES = Object.values(ChartType);++export const COLOR_BY_FIELDS = ["X", "Y", "Color", NONE_VALUE] as const;+export type ColorByField = (typeof COLOR_BY_FIELDS)[number];diff --git a/frontend/src/components/datasources/datasources.tsx b/frontend/src/components/datasources/datasources.tsxindex c969297e3e..92a28a811e 100644--- a/frontend/src/components/datasources/datasources.tsx+++ b/frontend/src/components/datasources/datasources.tsx@@ -21,10 +21,7 @@ import { CopyClipboardIcon } from "@/components/icons/copy-icon";import { Button } from "@/components/ui/button";import { Command, CommandInput, CommandItem } from "@/components/ui/command";import { Tooltip } from "@/components/ui/tooltip";-import {- maybeAddAltairImport,- maybeAddMarimoImport,-} from "@/core/cells/add-missing-import";+import { maybeAddMarimoImport } from "@/core/cells/add-missing-import";import { cellIdsAtom, useCellActions } from "@/core/cells/cells";import { useLastFocusedCellId } from "@/core/cells/focus";import { autoInstantiateAtom } from "@/core/config/config";@@ -60,6 +57,7 @@ import { cn } from "@/utils/cn";import { Events } from "@/utils/events";import { ErrorBoundary } from "../editor/boundary/ErrorBoundary";import { PythonIcon } from "../editor/cell/code/icons";+import { useAddCodeToNewCell } from "../editor/cell/useAddCell";import { PanelEmptyState } from "../editor/chrome/panels/empty-state";import { AddDatabaseDialog } from "../editor/database/add-database-form";import { DatasetColumnPreview } from "./column-preview";@@ -533,6 +531,7 @@ const DatasetTableItem: React.FC<{const autoInstantiate = useAtomValue(autoInstantiateAtom);const lastFocusedCellId = useLastFocusedCellId();const { createNewCell } = useCellActions();+ const addCodeToNewCell = useAddCodeToNewCell();const handleAddTable = () => {maybeAddMarimoImport(autoInstantiate, createNewCell, lastFocusedCellId);@@ -560,11 +559,7 @@ const DatasetTableItem: React.FC<{}};- createNewCell({- code: getCode(),- before: false,- cellId: lastFocusedCellId ?? "__end__",- });+ addCodeToNewCell(getCode());};const renderRowsByColumns = () => {@@ -693,23 +688,14 @@ const DatasetColumnItem: React.FC<{});}- const autoInstantiate = useAtomValue(autoInstantiateAtom);- const lastFocusedCellId = useLastFocusedCellId();- const { createNewCell } = useCellActions();+ const addCodeToNewCell = useAddCodeToNewCell();const { columnsPreviews } = useDatasets();const isPrimaryKey = table.primary_keys?.includes(column.name) || false;const isIndexed = table.indexes?.includes(column.name) || false;const handleAddColumn = (chartCode: string) => {- if (chartCode.includes("alt")) {- maybeAddAltairImport(autoInstantiate, createNewCell, lastFocusedCellId);- }- createNewCell({- code: chartCode,- before: false,- cellId: lastFocusedCellId ?? "__end__",- });+ addCodeToNewCell(chartCode);};const renderItemSubtext = ({diff --git a/frontend/src/components/editor/cell/useAddCell.ts b/frontend/src/components/editor/cell/useAddCell.tsnew file mode 100644index 0000000000..98c30ad68e--- /dev/null+++ b/frontend/src/components/editor/cell/useAddCell.ts@@ -0,0 +1,25 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { useAtomValue } from "jotai";+import { maybeAddAltairImport } from "@/core/cells/add-missing-import";+import { useCellActions } from "@/core/cells/cells";+import { useLastFocusedCellId } from "@/core/cells/focus";+import { autoInstantiateAtom } from "@/core/config/config";++export function useAddCodeToNewCell(): (code: string) => void {+ const autoInstantiate = useAtomValue(autoInstantiateAtom);+ const lastFocusedCellId = useLastFocusedCellId();+ const { createNewCell } = useCellActions();++ return (code: string) => {+ if (code.includes("alt")) {+ maybeAddAltairImport(autoInstantiate, createNewCell, lastFocusedCellId);+ }++ createNewCell({+ code: code,+ before: false,+ cellId: lastFocusedCellId ?? "__end__",+ });+ };+}diff --git a/frontend/src/components/editor/code/readonly-python-code.tsx b/frontend/src/components/editor/code/readonly-python-code.tsxindex 7c69810b8a..ff9c93770b 100644--- a/frontend/src/components/editor/code/readonly-python-code.tsx+++ b/frontend/src/components/editor/code/readonly-python-code.tsx@@ -5,8 +5,9 @@ import CodeMirror, {EditorView,type ReactCodeMirrorProps,} from "@uiw/react-codemirror";-import { CopyIcon, EyeIcon, EyeOffIcon } from "lucide-react";+import { CopyIcon, EyeIcon, EyeOffIcon, PlusIcon } from "lucide-react";import { memo, useState } from "react";+import { useAddCodeToNewCell } from "@/components/editor/cell/useAddCell";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";import { toast } from "@/components/ui/use-toast";@@ -22,12 +23,25 @@ const pythonExtensions = [];const sqlExtensions = [sql(), EditorView.lineWrapping];+/**+ * A readonly code component that can be used to display code in a readonly state.+ *+ * @param props.className - The class name to apply to the component.+ * @param props.code - The code to display.+ * @param props.initiallyHideCode - Whether to initially hide the code.+ * @param props.showHideCode - Whether to show the hide code button.+ * @param props.insertNewCell - Whether to add a insert new cell button; when clicked will add a new cell next to the current cell or at the end of the file+ * @param props.language - The language of the code. Default is "python".+ */export const ReadonlyCode = memo((props: {className?: string;code: string;initiallyHideCode?: boolean;+ showHideCode?: boolean;+ showCopyCode?: boolean;+ insertNewCell?: boolean;language?: "python" | "sql";} & ReactCodeMirrorProps,) => {@@ -36,6 +50,9 @@ export const ReadonlyCode = memo(code,className,initiallyHideCode,+ showHideCode = true,+ showCopyCode = true,+ insertNewCell,language = "python",...rest} = props;@@ -48,19 +65,19 @@ export const ReadonlyCode = memo(className,)}>- {hideCode && (+ {showHideCode && hideCode && (<HideCodeButtontooltip="Show code"onClick={() => setHideCode(false)}/>)}- {!hideCode && (- <div className="absolute top-0 right-0 my-1 mx-2 z-10 hover-action flex gap-2">- <CopyButton text={code} />-+ <div className="absolute top-0 right-0 my-1 mx-2 z-10 hover-action flex gap-2">+ {showCopyCode && <CopyButton text={code} />}+ {insertNewCell && <InsertNewCell code={code} />}+ {showHideCode && !hideCode && (<EyeCloseButton onClick={() => setHideCode(true)} />- </div>- )}+ )}+ </div><CodeMirror{...rest}className={cn("cm", hideCode && "opacity-20 h-8 overflow-hidden")}@@ -120,3 +137,24 @@ export const HideCodeButton = (props: {</div>);};++const InsertNewCell = (props: { code: string }) => {+ const addCodeToNewCell = useAddCodeToNewCell();++ const handleClick = () => {+ addCodeToNewCell(props.code);+ };++ return (+ <Tooltip content="Add code to notebook" usePortal={false}>+ <Button+ onClick={handleClick}+ size="xs"+ className="py-0"+ variant="secondary"+ >+ <PlusIcon size={14} strokeWidth={1.5} />+ </Button>+ </Tooltip>+ );+};