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: wasm column summary charts (#5390)
Shahmir Varqhaace78130974f
diff --git a/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap b/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snapindex 97a479ef27..a065031d3b 100644--- a/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap+++ b/frontend/src/components/data-table/__tests__/__snapshots__/chart-spec-model.test.ts.snap@@ -1,5 +1,128 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html+exports[`ColumnChartSpecModel > file URL handling > should handle arrow data 1`] = `+{+ "background": "transparent",+ "config": {+ "axis": {+ "domain": false,+ },+ "view": {+ "stroke": "transparent",+ },+ },+ "data": {+ "format": {+ "type": "arrow",+ },+ "values": Uint8Array [+ 65,+ 82,+ 82,+ 79,+ 87,+ 49,+ 10,+ ],+ },+ "height": 100,+ "layer": [+ {+ "encoding": {+ "color": {+ "condition": {+ "test": "datum["bin_maxbins_10_date_range"] === "null"",+ "value": "#cc4e00",+ },+ "value": "#027864",+ },+ "x": {+ "axis": null,+ "bin": true,+ "field": "date",+ "scale": {+ "align": 0,+ "paddingInner": 0,+ "paddingOuter": {+ "expr": "length(data('data_0')) == 2 ? 1 : length(data('data_0')) == 3 ? 0.5 : length(data('data_0')) == 4 ? 0 : 0",+ },+ },+ "type": "temporal",+ },+ "y": {+ "aggregate": "count",+ "axis": null,+ "type": "quantitative",+ },+ },+ "mark": {+ "color": "#027864",+ "type": "bar",+ },+ },+ {+ "encoding": {+ "color": {+ "condition": {+ "test": "datum["bin_maxbins_10_date_range"] === "null"",+ "value": "#cc4e00",+ },+ "value": "#027864",+ },+ "tooltip": [+ {+ "bin": {+ "binned": true,+ },+ "field": "bin_maxbins_10_date",+ "format": "%Y-%m-%d",+ "title": "date (start)",+ "type": "temporal",+ },+ {+ "bin": {+ "binned": true,+ },+ "field": "bin_maxbins_10_date_end",+ "format": "%Y-%m-%d",+ "title": "date (end)",+ "type": "temporal",+ },+ {+ "aggregate": "count",+ "format": ",d",+ "title": "Count",+ "type": "quantitative",+ },+ ],+ "x": {+ "axis": null,+ "bin": true,+ "field": "date",+ "scale": {+ "align": 0,+ "paddingInner": 0,+ "paddingOuter": {+ "expr": "length(data('data_0')) == 2 ? 1 : length(data('data_0')) == 3 ? 0.5 : length(data('data_0')) == 4 ? 0 : 0",+ },+ },+ "type": "temporal",+ },+ "y": {+ "aggregate": "max",+ "axis": null,+ "type": "quantitative",+ },+ },+ "mark": {+ "opacity": 0,+ "type": "bar",+ },+ },+ ],+}+`;+exports[`ColumnChartSpecModel > snapshot > array 1`] = `{"background": "transparent",diff --git a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts b/frontend/src/components/data-table/__tests__/chart-spec-model.test.tsindex a48215060b..eed9c965f9 100644--- a/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts+++ b/frontend/src/components/data-table/__tests__/chart-spec-model.test.ts@@ -222,6 +222,21 @@ describe("ColumnChartSpecModel", () => {expect(model.dataSpec?.values).toBeDefined();});+ it("should handle arrow data", () => {+ const arrowData = "ARROW1\n";+ const model = new ColumnChartSpecModel(+ `data:text/plain;base64,${btoa(arrowData)}`,+ mockFieldTypes,+ mockStats,+ { includeCharts: true },+ );+ const spec = model.getHeaderSummary("date").spec;+ expect(spec).toMatchSnapshot();+ expect(spec?.data?.format?.type).toBe("arrow");+ // @ts-expect-error accessing internal dataSpec+ expect(model.dataSpec?.values).toBeDefined();+ });+it("should handle array data", () => {const arrayData = [{ a: 1, b: 2, c: 3 },diff --git a/frontend/src/components/data-table/chart-spec-model.tsx b/frontend/src/components/data-table/chart-spec-model.tsxindex 6b55bc3014..5e5d63287f 100644--- a/frontend/src/components/data-table/chart-spec-model.tsx+++ b/frontend/src/components/data-table/chart-spec-model.tsx@@ -1,16 +1,31 @@/* Copyright 2024 Marimo. All rights reserved. */import { mint, orange, slate } from "@radix-ui/colors";+// @ts-expect-error vega-typings does not include formats+import { formats } from "vega";import type { TopLevelSpec } from "vega-lite";import { asRemoteURL } from "@/core/runtime/config";import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";+import { arrow } from "@/plugins/impl/vega/formats";import { parseCsvData } from "@/plugins/impl/vega/loader";import { logNever } from "@/utils/assertNever";+import {+ byteStringToBinary,+ extractBase64FromDataURL,+ isDataURLString,+ typedAtob,+} from "@/utils/json/base64";import type { ColumnHeaderStats, ColumnName, FieldTypes } from "./types";// We rely on vega's built-in binning to determine bar widths.const MAX_BAR_HEIGHT = 20; // px+// Arrow formats have a magic number at the beginning of the file.+const ARROW_MAGIC_NUMBER = "ARROW1";++// register arrow reader under type 'arrow'+formats("arrow", arrow);+export class ColumnChartSpecModel<T> {private columnStats = new Map<ColumnName, ColumnHeaderStats>();@@ -44,27 +59,30 @@ export class ColumnChartSpecModel<T> {// We have a few snapshot tests to ensure that the spec is correct for each case.if (typeof this.data === "string") {if (this.data.startsWith("./@file") || this.data.startsWith("/@file")) {- this.dataSpec = {- url: asRemoteURL(this.data).href,- };+ this.dataSpec = { url: asRemoteURL(this.data).href };this.sourceName = "source_0";- } else if (this.data.startsWith("data:text/csv;base64,")) {- const decoded = atob(this.data.split(",")[1]);- this.dataSpec = {- values: parseCsvData(decoded) as T[],- };+ } else if (isDataURLString(this.data)) {this.sourceName = "data_0";+ const base64 = extractBase64FromDataURL(this.data);+ const decoded = typedAtob(base64);++ if (decoded.startsWith(ARROW_MAGIC_NUMBER)) {+ this.dataSpec = {+ values: byteStringToBinary(decoded),+ // @ts-expect-error vega-typings does not include arrow format+ format: { type: "arrow" },+ };+ } else {+ // Assume it's a CSV string+ this.parseCsv(decoded);+ }} else {// Assume it's a CSV string- this.dataSpec = {- values: parseCsvData(this.data) as T[],- };+ this.parseCsv(this.data);this.sourceName = "data_0";}} else {- this.dataSpec = {- values: this.data,- };+ this.dataSpec = { values: this.data };this.sourceName = "source_0";}@@ -83,6 +101,12 @@ export class ColumnChartSpecModel<T> {};}+ private parseCsv(data: string) {+ this.dataSpec = {+ values: parseCsvData(data) as T[],+ };+ }+private getVegaSpec<T>(column: string): TopLevelFacetedUnitSpec | null {if (!this.data) {return null;diff --git a/frontend/src/utils/json/__tests__/base64.test.ts b/frontend/src/utils/json/__tests__/base64.test.tsindex 070d8013cc..90f001718e 100644--- a/frontend/src/utils/json/__tests__/base64.test.ts+++ b/frontend/src/utils/json/__tests__/base64.test.ts@@ -2,8 +2,16 @@import { describe, expect, test } from "vitest";import {type Base64String,+ type ByteString,+ base64ToDataURL,+ byteStringToBinary,+ type DataURLString,deserializeBase64,+ extractBase64FromDataURL,+ isDataURLString,type JsonString,+ typedAtob,+ typedBtoa,} from "../base64";describe("base64Utils", () => {@@ -32,6 +40,57 @@ describe("base64Utils", () => {const jsonDecoded = deserializeBase64(base64Encoded);expect(JSON.parse(jsonDecoded)).toEqual(testData);});++ test("base64ToDataURL should create proper data URL", () => {+ const base64 = "SGVsbG8=" as Base64String;+ const result = base64ToDataURL(base64, "text/plain");+ expect(result).toBe("data:text/plain;base64,SGVsbG8=");+ });++ test("typedAtob and typedBtoa should be reversible", () => {+ const original = "hello world" as ByteString;+ const encoded = typedBtoa(original);+ const decoded = typedAtob(encoded);+ expect(decoded).toBe(original);+ });++ test.each([+ ["data:text/plain;base64,SGVsbG8=", true],+ ["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA", true],+ ["not-a-data-url", false],+ ["base64,SGVsbG8=", false],+ ])("isDataURLString(%s) should return %s", (input, expected) => {+ expect(isDataURLString(input)).toBe(expected);+ });++ test("isDataURLString should reject data URLs without base64", () => {+ expect(isDataURLString("data:text/plain,hello")).toBe(false);+ expect(isDataURLString("data:text/plain;charset=utf-8,hello")).toBe(false);+ });++ test.each([+ ["data:text/plain;base64,SGVsbG8=", "SGVsbG8="],+ [+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA",+ "iVBORw0KGgoAAAANSUhEUgA",+ ],+ ["data:application/json;base64,", ""],+ ["data:text/html;charset=utf-8;base64,PGh0bWw+", "PGh0bWw+"],+ ])("extractBase64FromDataURL(%s) should return %s", (dataUrl, expected) => {+ expect(extractBase64FromDataURL(dataUrl as DataURLString)).toBe(expected);+ });++ test("byteStringToBinary should convert to Uint8Array", () => {+ const bytes = "ABC" as ByteString;+ const result = byteStringToBinary(bytes);+ expect(result).toEqual(new Uint8Array([65, 66, 67]));+ });++ test("byteStringToBinary should handle empty string", () => {+ const bytes = "" as ByteString;+ const result = byteStringToBinary(bytes);+ expect(result).toEqual(new Uint8Array([]));+ });});// Serialization: JSON to Base64diff --git a/frontend/src/utils/json/base64.ts b/frontend/src/utils/json/base64.tsindex f70262d2de..0db101a760 100644--- a/frontend/src/utils/json/base64.ts+++ b/frontend/src/utils/json/base64.ts@@ -37,3 +37,15 @@ export function typedAtob<T>(base64: Base64String<T>): ByteString<T> {export function typedBtoa<T>(bytes: ByteString<T>): Base64String<T> {return window.btoa(bytes) as Base64String<T>;}++export function isDataURLString(str: string): str is DataURLString {+ return str.startsWith("data:") && str.includes(";base64,");+}++export function extractBase64FromDataURL(str: DataURLString): Base64String {+ return str.split(",")[1] as Base64String;+}++export function byteStringToBinary(bytes: ByteString): Uint8Array {+ return Uint8Array.from(bytes, (c) => c.charCodeAt(0));+}