Skip to content

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.

fix: altair blinking on layered charts (#887)

Myles Scolnick0a0c7906d906
diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
index 32922f528d..614778df6f 100644
--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx
+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
@@ -14,14 +14,13 @@ import { debounce } from "lodash-es";
import useEvent from "react-use-event-hook";
import { Logger } from "@/utils/Logger";
-import { vegaLoadData } from "./loader";
import { useAsyncData } from "@/hooks/useAsyncData";
import { fixRelativeUrl } from "./fix-relative-url";
import "./vega.css";
import { useTheme } from "@/theme/useTheme";
import { Objects } from "@/utils/objects";
-import { asURL } from "@/utils/url";
+import { resolveVegaSpecData } from "./resolve-data";
interface Data {
spec: VegaLiteSpec;
@@ -85,34 +84,7 @@ export const VegaComponent = ({
// otherwise it will try to load it internally and flicker
// Instead we can handle the loading state ourselves,
// and show the previous chart until the new one is ready
-
- if (!spec || !spec.data) {
- return spec;
- }
-
- if (!("url" in spec.data)) {
- return spec;
- }
-
- // Parse URL
- let url: URL;
- try {
- url = asURL(spec.data.url);
- } catch {
- return spec;
- }
-
- const data = await vegaLoadData(url.href, spec.data.format);
- return {
- ...spec,
- data: {
- name: url.pathname,
- },
- datasets: {
- ...spec.datasets,
- [url.pathname]: data,
- },
- } as VegaLiteSpec;
+ return resolveVegaSpecData(spec);
}, [spec]);
if (!resolvedSpec) {
diff --git a/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
new file mode 100644
index 0000000000..7526bcc9db
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/__tests__/resolve-data.test.ts
@@ -0,0 +1,131 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { vegaLoader } from "../loader";
+import { resolveVegaSpecData } from "../resolve-data";
+import { VegaLiteSpec } from "../types";
+
+function asSpec(spec: unknown): VegaLiteSpec {
+ return spec as VegaLiteSpec;
+}
+
+describe("resolveVegaSpecData", () => {
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
+ it("returns the input spec if it is falsy", async () => {
+ expect(await resolveVegaSpecData(null!)).toBeNull();
+ expect(await resolveVegaSpecData(undefined!)).toBeUndefined();
+ });
+
+ it("returns the input spec if it has no data", async () => {
+ const spec = asSpec({ someProperty: "value" });
+ expect(await resolveVegaSpecData(spec)).toEqual(spec);
+ });
+
+ it("returns the input spec if the data does not contain a URL", async () => {
+ const spec = asSpec({ data: { name: "dataset" } });
+ expect(await resolveVegaSpecData(spec)).toEqual(spec);
+ });
+
+ it("returns the input spec if the URL in the data is invalid", async () => {
+ const spec = asSpec({ data: { url: "invalidURL" } });
+ vi.spyOn(vegaLoader, "load").mockRejectedValue(new Error("Invalid URL"));
+ await expect(() => resolveVegaSpecData(spec)).rejects.toThrow(
+ "Invalid URL",
+ );
+ });
+
+ it("resolves the URL data and returns a new spec with the resolved data", async () => {
+ const spec = asSpec({
+ data: { url: "http://example.com/data", format: "json" },
+ });
+ const resolvedData = { some: "data" };
+ vi.spyOn(vegaLoader, "load").mockResolvedValueOnce(resolvedData);
+
+ const expected = {
+ ...spec,
+ data: {
+ name: "/data",
+ },
+ datasets: {
+ "/data": resolvedData,
+ },
+ } as unknown as VegaLiteSpec;
+
+ await expect(resolveVegaSpecData(spec)).resolves.toEqual(expected);
+ expect(vegaLoader.load).toHaveBeenCalledWith("http://example.com/data");
+ });
+
+ it("correctly resolves nested URL data in layers", async () => {
+ const spec = asSpec({
+ mark: "point",
+ layer: [
+ { data: { url: "http://example.com/data1", format: "json" } },
+ { data: { url: "http://example.com/data2", format: "json" } },
+ ],
+ });
+ const resolvedData1 = { some: "data1" };
+ const resolvedData2 = { some: "data2" };
+ vi.spyOn(vegaLoader, "load")
+ .mockResolvedValueOnce(resolvedData1)
+ .mockResolvedValueOnce(resolvedData2);
+
+ const expected = {
+ mark: "point",
+ layer: [
+ {
+ data: { name: "/data1" },
+ },
+ {
+ data: { name: "/data2" },
+ },
+ ],
+ datasets: {
+ "/data1": resolvedData1,
+ "/data2": resolvedData2,
+ },
+ };
+
+ await expect(resolveVegaSpecData(spec)).resolves.toEqual(expected);
+ expect(vegaLoader.load).toHaveBeenCalledTimes(2);
+ });
+
+ it("correctly resolves nested URL data in hconcat and vconcat", async () => {
+ const spec = asSpec({
+ mark: "point",
+ hconcat: [
+ { data: { url: "http://example.com/data1", format: "json" } },
+ { data: { url: "http://example.com/data2", format: "json" } },
+ ],
+ vconcat: [
+ { data: { url: "http://example.com/data3", format: "json" } },
+ { data: { url: "http://example.com/data4", format: "json" } },
+ ],
+ });
+ const resolvedData1 = { some: "data1" };
+ const resolvedData2 = { some: "data2" };
+ const resolvedData3 = { some: "data3" };
+ const resolvedData4 = { some: "data4" };
+ vi.spyOn(vegaLoader, "load")
+ .mockResolvedValueOnce(resolvedData1)
+ .mockResolvedValueOnce(resolvedData2)
+ .mockResolvedValueOnce(resolvedData3)
+ .mockResolvedValueOnce(resolvedData4);
+
+ const expected = {
+ mark: "point",
+ hconcat: [{ data: { name: "/data1" } }, { data: { name: "/data2" } }],
+ vconcat: [{ data: { name: "/data3" } }, { data: { name: "/data4" } }],
+ datasets: {
+ "/data1": resolvedData1,
+ "/data2": resolvedData2,
+ "/data3": resolvedData3,
+ "/data4": resolvedData4,
+ },
+ };
+
+ await expect(resolveVegaSpecData(spec)).resolves.toEqual(expected);
+ expect(vegaLoader.load).toHaveBeenCalledTimes(4);
+ });
+});
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index 52c8592284..b4180b1e75 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -54,7 +54,9 @@ export function vegaLoadData(
// We make the column names unique by appending a number to the end of
// each duplicate column name. If we want to preserve the original key
// we would need to store the data in columnar format.
- csvData = uniquifyColumnNames(csvData);
+ if (typeof csvData === "string") {
+ csvData = uniquifyColumnNames(csvData);
+ }
// We support enabling/disabling since the Table enables it
// but Vega does not support BigInts
diff --git a/frontend/src/plugins/impl/vega/resolve-data.ts b/frontend/src/plugins/impl/vega/resolve-data.ts
new file mode 100644
index 0000000000..32b023436a
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/resolve-data.ts
@@ -0,0 +1,93 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { asURL } from "@/utils/url";
+import { vegaLoadData } from "./loader";
+import {
+ Field,
+ VegaLiteSpec,
+ LayerSpec,
+ UnitSpec,
+ GenericFacetSpec,
+ FacetedUnitSpec,
+} from "./types";
+
+type AnySpec =
+ | VegaLiteSpec
+ | LayerSpec<Field>
+ | UnitSpec<Field>
+ | GenericFacetSpec<FacetedUnitSpec<Field>, LayerSpec<Field>, Field>;
+
+/**
+ * Given a VegaLite spec with URL data, resolve the data and return a new spec with the resolved data.
+ *
+ * This handles top-level URL data, as well as nested URL data in layers.
+ */
+export async function resolveVegaSpecData(
+ spec: VegaLiteSpec,
+): Promise<VegaLiteSpec> {
+ if (!spec) {
+ return spec;
+ }
+
+ const datasets = "datasets" in spec ? { ...spec.datasets } : {};
+
+ const traverse = async <T extends AnySpec>(spec: T): Promise<T> => {
+ if (!spec) {
+ return spec;
+ }
+
+ if ("layer" in spec) {
+ const layers = await Promise.all(spec.layer.map(traverse));
+ spec = {
+ ...spec,
+ layer: layers,
+ };
+ }
+ if ("hconcat" in spec) {
+ const hconcat = await Promise.all(spec.hconcat.map(traverse));
+ spec = {
+ ...spec,
+ hconcat,
+ };
+ }
+ if ("vconcat" in spec) {
+ const vconcat = await Promise.all(spec.vconcat.map(traverse));
+ spec = {
+ ...spec,
+ vconcat,
+ };
+ }
+
+ if (!spec.data) {
+ return spec;
+ }
+
+ if (!("url" in spec.data)) {
+ return spec;
+ }
+
+ // Parse URL
+ let url: URL;
+ try {
+ url = asURL(spec.data.url);
+ } catch {
+ return spec;
+ }
+ const data = await vegaLoadData(url.href, spec.data.format);
+
+ datasets[url.pathname] = data;
+
+ return {
+ ...spec,
+ data: { name: url.pathname },
+ };
+ };
+
+ const resolvedSpec = await traverse(spec);
+ if (Object.keys(datasets).length === 0) {
+ return resolvedSpec;
+ }
+ return {
+ ...resolvedSpec,
+ datasets,
+ };
+}
diff --git a/frontend/src/plugins/impl/vega/types.ts b/frontend/src/plugins/impl/vega/types.ts
index 261ea7d7ef..7f92c381cc 100644
--- a/frontend/src/plugins/impl/vega/types.ts
+++ b/frontend/src/plugins/impl/vega/types.ts
@@ -17,6 +17,12 @@ export type {
SelectionType,
} from "vega-lite/build/src/selection";
export type { DataFormat } from "vega-lite/build/src/data";
+export type {
+ LayerSpec,
+ UnitSpec,
+ GenericFacetSpec,
+ FacetedUnitSpec,
+} from "vega-lite/build/src/spec";
export type VegaLiteUnitSpec = TopLevelUnitSpec<Field>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index 70aec72544..b837903064 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -32,16 +32,8 @@ class AltairFormatter(FormatterFactory):
# the height of the iframe to the height of the contained document
import altair as alt
- # It is required to set this back to the default,
- # since mo.ui.altair_chart sets it to 'marimo'
- if alt.data_transformers.active == "marimo":
- # Re-enable with the previous options
- alt.data_transformers.enable(
- "default", **alt.data_transformers.options
- )
- # We also change the max_rows to 20_000 (default is 5000)
- # since we are able to handle the larger sizes
- # However, we only set it if it is not already set
+ # If the user has not set the max_rows option, we set it to 20_000
+ # since we are able to handle the larger sizes (default is 5000)
if "max_rows" not in alt.data_transformers.options:
alt.data_transformers.options["max_rows"] = 20_000
return (
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 95dba569d7..364807f31e 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -118,7 +118,8 @@ def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:
# instead of using a vega-lite spec
if altair.data_transformers.active == "vegafusion":
return spec.to_dict(format="vega") # type: ignore
- return spec.to_dict() # type: ignore
+ with altair.data_transformers.enable("marimo"):
+ return spec.to_dict() # type: ignore
def _has_transforms(spec: VegaSpec) -> bool:
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index fe123834d8..4db431ef10 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -109,13 +109,10 @@ def register_transformers() -> None:
# We keep the previous options, in case the user has set them
# we don't want to override them.
- options = alt.data_transformers.options
# Default to CSV. Due to the columnar nature of CSV, it is more efficient
# than JSON for large datasets (~80% smaller file size).
alt.data_transformers.register("marimo", _to_marimo_csv)
- alt.data_transformers.enable("marimo", **options)
-
alt.data_transformers.register("marimo_json", _to_marimo_json)
alt.data_transformers.register(
"marimo_csv",