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
fix: escape special characters in frontend altair chart builder (#6973)
Myles Scolnick5c4ff8b1d104
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 de8f32e172..6ac9b7bae0 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@@ -422,4 +422,166 @@ describe("generateAltairChart", () => {)"`);});++ it("should escape dots in field names", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "name.field" },+ y: { field: "value.data" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='name\\.field'),+ y=alt.Y(field='value\\.data')+ )"+ `);+ });++ it("should escape brackets in field names", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "data[0]" },+ y: { field: "values[key]" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='data\\[0\\]'),+ y=alt.Y(field='values\\[key\\]')+ )"+ `);+ });++ it("should escape colons in field names", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "time:stamp" },+ y: { field: "value" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='time\\:stamp'),+ y=alt.Y(field='value')+ )"+ `);+ });++ it("should escape multiple special characters in field names", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "data[0].name:value" },+ y: { field: "result" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='data\\[0\\]\\.name\\:value'),+ y=alt.Y(field='result')+ )"+ `);+ });++ it("should escape special characters in color encoding", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "category" },+ y: { field: "value" },+ color: { field: "group.name" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='category'),+ y=alt.Y(field='value'),+ color=alt.Color(field='group\\.name')+ )"+ `);+ });++ it("should escape special characters in tooltip", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "category" },+ y: { field: "value" },+ tooltip: { field: "info.details" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='category'),+ y=alt.Y(field='value'),+ tooltip=alt.Tooltip(field='info\\.details')+ )"+ `);+ });++ it("should escape special characters in facet encodings", () => {+ const spec = createSpec({+ mark: "bar",+ encoding: {+ x: { field: "category" },+ y: { field: "value" },+ row: { field: "row.label" },+ column: { field: "col[0]" },+ },+ });+ const datasource = "df";++ const result = generateAltairChart(spec, datasource).toCode();++ expect(result).toMatchInlineSnapshot(`+ "alt.Chart(df)+ .mark_bar()+ .encode(+ x=alt.X(field='category'),+ y=alt.Y(field='value'),+ row=alt.Row(field='row\\.label'),+ column=alt.Column(field='col\\[0\\]')+ )"+ `);+ });});diff --git a/frontend/src/components/data-table/charts/__tests__/spec.test.ts b/frontend/src/components/data-table/charts/__tests__/spec.test.tsindex 13ff6501b2..d9659baff1 100644--- a/frontend/src/components/data-table/charts/__tests__/spec.test.ts+++ b/frontend/src/components/data-table/charts/__tests__/spec.test.ts@@ -2,6 +2,7 @@import type { PositionDef } from "vega-lite/build/src/channeldef";import { describe, expect, it } from "vitest";+import { invariant } from "@/utils/invariant";import {getAggregate,getBinEncoding,@@ -995,3 +996,136 @@ describe("getBinEncoding", () => {}});});++describe("Special character escaping in specs", () => {+ it("should escape dots in field names", () => {+ const result = getAxisEncoding(+ {+ field: "value.data",+ selectedDataType: "number",+ aggregate: "sum",+ timeUnit: undefined,+ },+ undefined,+ "Value",+ false,+ ChartType.BAR,+ );++ invariant("field" in result, "field should be defined");+ expect(result.field).toBe("value\\.data");+ });++ it("should escape brackets in field names", () => {+ const result = getAxisEncoding(+ {+ field: "data[0]",+ selectedDataType: "number",+ aggregate: "mean",+ timeUnit: undefined,+ },+ undefined,+ "Data",+ false,+ ChartType.BAR,+ );++ invariant("field" in result, "field should be defined");+ expect(result.field).toBe("data\\[0\\]");+ });++ it("should escape colons in field names", () => {+ const result = getAxisEncoding(+ {+ field: "time:stamp",+ selectedDataType: "temporal",+ aggregate: NONE_VALUE,+ timeUnit: "yearmonth",+ },+ undefined,+ "Timestamp",+ false,+ ChartType.LINE,+ );++ invariant("field" in result, "field should be defined");+ expect(result.field).toBe("time\\:stamp");+ });++ it("should escape multiple special characters in field names", () => {+ const result = getAxisEncoding(+ {+ field: "data[0].value:result",+ selectedDataType: "number",+ aggregate: "sum",+ timeUnit: undefined,+ },+ undefined,+ "Result",+ false,+ ChartType.BAR,+ );++ invariant("field" in result, "field should be defined");+ expect(result.field).toBe("data\\[0\\]\\.value\\:result");+ });++ it("should escape special characters in color encoding", () => {+ const formValues: ChartSchemaType = {+ general: {+ colorByColumn: {+ field: "group.name",+ selectedDataType: "string",+ aggregate: NONE_VALUE,+ },+ },+ };++ const result = getColorEncoding(ChartType.BAR, formValues);++ invariant(result && "field" in result, "field should be defined");+ expect(result?.field).toBe("group\\.name");+ });++ it("should escape special characters in tooltip field names", () => {+ const formValues: ChartSchemaType = {+ general: {+ xColumn: {+ field: "category",+ selectedDataType: "string",+ aggregate: NONE_VALUE,+ },+ yColumn: {+ field: "value.data",+ selectedDataType: "number",+ aggregate: "sum",+ },+ },+ tooltips: {+ auto: true,+ fields: [],+ },+ };++ const xEncoding: PositionDef<string> = {+ field: "category\\.escaped",+ type: "nominal",+ };++ const yEncoding: PositionDef<string> = {+ field: "value\\.data",+ type: "quantitative",+ aggregate: "sum",+ };++ const result = getTooltips({+ formValues,+ xEncoding,+ yEncoding,+ });++ expect(result).toBeDefined();+ expect(result?.[0]?.field).toBe("category\\.escaped");+ expect(result?.[1]?.field).toBe("value\\.data");+ });+});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 03d2dea7b5..2a64c2eeef 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@@ -8,6 +8,7 @@ import {Variable,VariableDeclaration,} from "@/utils/python-poet/poet";+import { escapeFieldName } from "./utils";/*** Generates Python code for an Altair chart.@@ -154,7 +155,12 @@ function makeKwargs<T extends Record<string, any>>(obj: T) {for (const [key, value] of Object.entries(obj)) {if (value !== undefined) {- result[key] = new Literal(value);+ // Escape special characters in field names+ if (key === "field" && typeof value === "string") {+ result[key] = new Literal(escapeFieldName(value));+ } else {+ result[key] = new Literal(value);+ }}}diff --git a/frontend/src/components/data-table/charts/chart-spec/encodings.ts b/frontend/src/components/data-table/charts/chart-spec/encodings.tsindex e451450689..392d8fe119 100644--- a/frontend/src/components/data-table/charts/chart-spec/encodings.ts+++ b/frontend/src/components/data-table/charts/chart-spec/encodings.ts@@ -19,6 +19,7 @@ import {} from "../types";import { isFieldSet } from "./spec";import { convertDataTypeToVega } from "./types";+import { escapeFieldName } from "./utils";export function getBinEncoding(chartType: ChartType,@@ -123,7 +124,7 @@ export function getColorEncoding(const aggregate = colorByColumn?.aggregate;return {- field: colorByColumn.field,+ field: escapeFieldName(colorByColumn.field),type: convertDataTypeToVega(selectedDataType),scale: getColorInScale(formValues),aggregate: getAggregate(aggregate, selectedDataType),@@ -143,7 +144,7 @@ export function getOffsetEncoding() {return undefined;}- return { field: formValues.general?.colorByColumn?.field };+ return { field: escapeFieldName(formValues.general?.colorByColumn?.field) };}export function getAggregate(diff --git a/frontend/src/components/data-table/charts/chart-spec/spec.ts b/frontend/src/components/data-table/charts/chart-spec/spec.tsindex c7a8aab4b7..03504c54b1 100644--- a/frontend/src/components/data-table/charts/chart-spec/spec.ts+++ b/frontend/src/components/data-table/charts/chart-spec/spec.ts@@ -41,6 +41,7 @@ import {convertChartTypeToMark,convertDataTypeToVega,} from "./types";+import { escapeFieldName } from "./utils";/*** Convert marimo chart configuration to Vega-Lite specification.@@ -178,7 +179,7 @@ export function getAxisEncoding(}return {- field: column.field,+ field: escapeFieldName(column.field),type: convertDataTypeToVega(column.selectedDataType || "unknown"),bin: getBinEncoding(chartType, selectedDataType, binValues),title: label,@@ -211,7 +212,7 @@ export function getFacetEncoding();return {- field: facet.field,+ field: escapeFieldName(facet.field),sort: facet.sort,timeUnit: getFacetTimeUnit(facet),type: convertDataTypeToVega(facet.selectedDataType || "unknown"),@@ -244,7 +245,7 @@ function getPieChartSpec();const colorEncoding: ColorDef<string> = {- field: colorByColumn.field,+ field: escapeFieldName(colorByColumn.field),type: convertDataTypeToVega(colorByColumn.selectedDataType || "unknown"),scale: getColorInScale(formValues),title: getFieldLabel(formValues.yAxis?.label),diff --git a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts b/frontend/src/components/data-table/charts/chart-spec/tooltips.tsindex 78234a54f4..500f652906 100644--- a/frontend/src/components/data-table/charts/chart-spec/tooltips.ts+++ b/frontend/src/components/data-table/charts/chart-spec/tooltips.ts@@ -8,6 +8,7 @@ import type {import type { DataType } from "@/core/kernel/messages";import type { ChartSchemaType } from "../schemas";import { isFieldSet } from "./spec";+import { escapeFieldName } from "./utils";function getTooltipFormat(dataType: DataType): string | undefined {switch (dataType) {@@ -60,7 +61,7 @@ export function getTooltips(}const tooltip: StringFieldDef<string> = {- field: encoding.field,+ field: encoding.field, // Already escaped in the encodingaggregate: encoding.aggregate,timeUnit: encoding.timeUnit,format: getTooltipFormat(type),@@ -159,7 +160,7 @@ export function getTooltips(}const otherTooltip: StringFieldDef<string> = {- field: tooltip.field,+ field: escapeFieldName(tooltip.field),};tooltips.push(otherTooltip);}diff --git a/frontend/src/components/data-table/charts/chart-spec/utils.ts b/frontend/src/components/data-table/charts/chart-spec/utils.tsnew file mode 100644index 0000000000..0180ecb197--- /dev/null+++ b/frontend/src/components/data-table/charts/chart-spec/utils.ts@@ -0,0 +1,23 @@+/* Copyright 2024 Marimo. All rights reserved. */++/**+ * Escapes special characters in field names for Altair/Vega-Lite.+ * Matches the backend implementation in marimo/_data/charts.py+ *+ * Special characters that need escaping:+ * - . (dot)+ * - [ ] (brackets)+ * - : (colon)+ *+ * See: https://altair-viz.github.io/user_guide/troubleshooting.html#encodings-with-special-characters+ */+export function escapeFieldName(field: string | undefined): string | undefined {+ if (!field) {+ return field;+ }+ return field+ .replace(/\./g, "\\.")+ .replace(/\[/g, "\\[")+ .replace(/\]/g, "\\]")+ .replace(/:/g, "\\:");+}diff --git a/marimo/_smoke_tests/altair_examples/special_chars.py b/marimo/_smoke_tests/altair_examples/special_chars.pynew file mode 100644index 0000000000..60a2623668--- /dev/null+++ b/marimo/_smoke_tests/altair_examples/special_chars.py@@ -0,0 +1,98 @@+"""Test Altair chart builder with special characters in column names.++This notebook tests the fix for issue #5956, which ensures that special+characters like dots, brackets, and colons in column names are properly+escaped when generating Altair chart code.+"""++import marimo++__generated_with = "0.17.2"+app = marimo.App(width="medium")+++def _():+ import marimo as mo+ import pandas as pd+ import polars as pl+ import altair as alt+ return alt, mo, pd, pl++[email protected](hide_code=True)+def _(mo):+ mo.md(+ """+ # Testing Altair Charts with Special Characters++ This notebook tests column names with special characters:+ - Dots: `.`+ - Brackets: `[`, `]`+ - Colons: `:`++ These characters need to be escaped in Altair field names.+ """+ )+ return+++def _(pd):+ # Create a Pandas DataFrame with special column names+ pandas_df = pd.DataFrame(+ {+ "category": ["A", "B", "C", "D", "E"],+ "value.data": [10, 20, 15, 25, 30],+ "info[0]": [5, 10, 8, 12, 15],+ "time:stamp": ["2024-01", "2024-02", "2024-03", "2024-04", "2024-05"],+ "complex.name[1]:value": [100, 200, 150, 250, 300],+ }+ )+ pandas_df+ return (pandas_df,)+++def _(pandas_df, pl):+ # Create a Polars DataFrame with special column names+ polars_df = pl.DataFrame(pandas_df)+ polars_df+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ """+ Use the data table chart builder to create a chart using `value.data` column.+ The generated Python code should escape the dot: `field='value\\.data'`++ Repeat for all the other columns+ """+ )+ return+++def _(mo, pandas_df):+ mo.ui.table(pandas_df, selection=None)+ return+++def _(alt, pandas_df):+ chart = (+ alt.Chart(pandas_df)+ .mark_bar()+ .encode(+ x=alt.X(field="category"),+ y=alt.Y(field=r"value\.data"), # Using escaped field name+ )+ )+ chart+ return+++if __name__ == "__main__":+ app.run()