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: mo.ui.data_voyager when keys have a period (#1455)
Myles Scolnick8a59501adc08
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex d5e9dfb0a7..d0d58b3039 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -107,7 +107,7 @@ export const LoadingDataTableComponent = memo(return vegaLoadData(props.data,{ type: "csv", parse: getVegaFieldTypes(props.fieldTypes) },- true,+ { handleBigInt: true },);}, [props.data, props.fieldTypes]);diff --git a/frontend/src/plugins/impl/common/error-banner.tsx b/frontend/src/plugins/impl/common/error-banner.tsxindex 9a7221f91f..63ebc40c06 100644--- a/frontend/src/plugins/impl/common/error-banner.tsx+++ b/frontend/src/plugins/impl/common/error-banner.tsx@@ -11,6 +11,7 @@ import {} from "@/components/ui/alert-dialog";import { cn } from "@/utils/cn";import { VariantProps, cva } from "class-variance-authority";+import { Logger } from "@/utils/Logger";export const ErrorBanner = ({error,@@ -24,6 +25,7 @@ export const ErrorBanner = ({if (!error) {return null;}+ Logger.error(error);const message = prettyError(error);diff --git a/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsxindex 89aa78440b..5b99123bea 100644--- a/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx+++ b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx@@ -87,10 +87,16 @@ export const DataExplorerComponent = ({if (!dataUrl) {return {};}- const chartData = await vegaLoadData(dataUrl, {- type: "csv",- parse: "auto",- });+ const chartData = await vegaLoadData(+ dataUrl,+ {+ type: "csv",+ parse: "auto",+ },+ {+ replacePeriod: true,+ },+ );const schema = cql.schema.build(chartData);actions.setSchema(schema);return { chartData, schema };diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.tsindex cf83fb14e1..f2158c987e 100644--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts@@ -1,11 +1,9 @@/* Copyright 2024 Marimo. All rights reserved. */import { describe, expect, it, vi } from "vitest";-import {- ZERO_WIDTH_SPACE,- uniquifyColumnNames,- vegaLoadData,- vegaLoader,-} from "../loader";+import { vegaLoadData, vegaLoader, exportedForTesting } from "../loader";++const { ZERO_WIDTH_SPACE, replacePeriodsInColumnNames, uniquifyColumnNames } =+ exportedForTesting;describe("vega loader", () => {it("should parse csv data with dates", async () => {@@ -105,7 +103,7 @@ yield_error,yield_centerconst data = await vegaLoadData(csvData,{ type: "csv", parse: "auto" },- true,+ { handleBigInt: true },);expect(data).toMatchInlineSnapshot(`[@@ -115,7 +113,11 @@ yield_error,yield_center]`);- const dataWithoutFlag = await vegaLoadData(csvData, { type: "csv" }, false);+ const dataWithoutFlag = await vegaLoadData(+ csvData,+ { type: "csv" },+ { handleBigInt: false },+ );expect(dataWithoutFlag).toMatchInlineSnapshot(`[{@@ -175,3 +177,34 @@ describe("uniquifyColumnNames", () => {expect(result).toBe(expectedResult);});});++describe("replacePeriodsInColumnNames", () => {+ it("should handle empty cases", () => {+ expect(replacePeriodsInColumnNames("")).toBe("");+ expect(replacePeriodsInColumnNames(" ")).toBe(" ");+ expect(replacePeriodsInColumnNames("\n")).toBe("\n");+ });++ it("should return the same header if no periods exist", () => {+ const csvData = "Name,Age,Location\nAlice,30,New York";+ const result = replacePeriodsInColumnNames(csvData);+ expect(result).toBe(csvData);+ });++ it("should replace periods in headers", () => {+ const csvData =+ "user.name,user.age,user.location\nAlice,30.1,New York\nBob,30.5,New York";+ const expectedResult =+ "user․name,user․age,user․location\nAlice,30.1,New York\nBob,30.5,New York";+ const result = replacePeriodsInColumnNames(csvData);+ expect(result).toBe(expectedResult);+ });++ it("should not replace periods in non-headers", () => {+ const csvData = "Name,Age,Location\nAlice,30.1,New York\nBob,30.5,New York";+ const expectedResult =+ "Name,Age,Location\nAlice,30.1,New York\nBob,30.5,New York";+ const result = replacePeriodsInColumnNames(csvData);+ expect(result).toBe(expectedResult);+ });+});diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.tsindex c4357775d4..4b43855db2 100644--- a/frontend/src/plugins/impl/vega/loader.ts+++ b/frontend/src/plugins/impl/vega/loader.ts@@ -67,8 +67,13 @@ export const vegaLoader = createLoader();export function vegaLoadData(url: string,format: DataFormat | undefined | { type: "csv"; parse: "auto" },- handleBigInt = false,+ opts: {+ handleBigInt?: boolean;+ replacePeriod?: boolean;+ } = {},): Promise<object[]> {+ const { handleBigInt = false, replacePeriod = false } = opts;+return vegaLoader.load(url).then((csvData) => {// CSV data comes columnar and may have duplicate column names.// We need to uniquify the column names before parsing since vega-loader@@ -80,6 +85,11 @@ export function vegaLoadData(if (typeof csvData === "string") {csvData = uniquifyColumnNames(csvData);}+ // Replace periods in column names with a one-dot leader.+ // Some downstream libraries use periods as a nested key separator.+ if (typeof csvData === "string" && replacePeriod) {+ csvData = replacePeriodsInColumnNames(csvData);+ }// We support enabling/disabling since the Table enables it// but Vega does not support BigInts@@ -116,29 +126,54 @@ export function parseCsvData(csvData: string, handleBigInt = true): object[] {return data;}-export function uniquifyColumnNames(csvData: string): string {+/**+ * Make column names unique by appending a zero-width space to the end of each duplicate column name.+ */+function uniquifyColumnNames(csvData: string): string {if (!csvData?.includes(",")) {return csvData;}- const lines = csvData.split("\n");- const header = lines[0];- const headerNames = header.split(",");+ return mapColumnNames(csvData, (headerNames) => {+ const existingNames = new Set<string>();+ return headerNames.map((name) => {+ const uniqueName = getUniqueKey(name, existingNames);+ existingNames.add(uniqueName);+ return uniqueName;+ });+ });+}- const existingNames = new Set<string>();- const newNames = [];- for (const name of headerNames) {- const uniqueName = getUniqueKey(name, existingNames);- newNames.push(uniqueName);- existingNames.add(uniqueName);+/**+ * Replace periods in column names with a one-dot leader.+ * This is because some downstream libraries use periods as a nested key separator.+ */+function replacePeriodsInColumnNames(csvData: string): string {+ // This looks like a period but it's actually a one-dot leader+ // https://www.compart.com/en/unicode/U+2024+ const ONE_DOT_LEADER = "․";+ if (!csvData?.includes(".")) {+ return csvData;}- const uniqueHeader = newNames.join(",");- lines[0] = uniqueHeader;+ return mapColumnNames(csvData, (headerNames) => {+ return headerNames.map((name) => name.replaceAll(".", ONE_DOT_LEADER));+ });+}++function mapColumnNames(+ csvData: string,+ fn: (names: string[]) => string[],+): string {+ const lines = csvData.split("\n");+ const header = lines[0];+ const headerNames = header.split(",");+ const newNames = fn(headerNames);+ lines[0] = newNames.join(",");return lines.join("\n");}-export const ZERO_WIDTH_SPACE = "\u200B";+const ZERO_WIDTH_SPACE = "\u200B";function getUniqueKey(key: string, existingKeys: Set<string>): string {let result = key;@@ -150,3 +185,9 @@ function getUniqueKey(key: string, existingKeys: Set<string>): string {return result;}++export const exportedForTesting = {+ ZERO_WIDTH_SPACE,+ uniquifyColumnNames,+ replacePeriodsInColumnNames,+};diff --git a/marimo/_smoke_tests/bugs/altair-bug.py b/marimo/_smoke_tests/bugs/altair_bug.pysimilarity index 100%rename from marimo/_smoke_tests/bugs/altair-bug.pyrename to marimo/_smoke_tests/bugs/altair_bug.pydiff --git a/marimo/_smoke_tests/bugs/key_with_period.py b/marimo/_smoke_tests/bugs/key_with_period.pynew file mode 100644index 0000000000..5af9692f3c--- /dev/null+++ b/marimo/_smoke_tests/bugs/key_with_period.py@@ -0,0 +1,39 @@+import marimo++__generated_with = "0.6.0"+app = marimo.App()+++def __():+ import marimo as mo+ import pandas as pd+ return mo, pd+++def __():+ json_list = [{"key.with.period": "value"} for _ in range(10)]+ return json_list,+++def __(json_list, mo):+ mo.ui.table(json_list)+ return+++def __(json_list, mo, pd):+ mo.ui.data_explorer(pd.DataFrame(json_list))+ return+++def __(json_list, mo, pd):+ mo.ui.dataframe(pd.DataFrame(json_list))+ return+++if __name__ == "__main__":+ app.run()