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: support selection when using 'layer' in altair/vega spec (#753)
Myles Scolnick2b06c5849b2e
diff --git a/frontend/src/core/static/files.ts b/frontend/src/core/static/files.tsindex b4c72c84b9..68f85ca0ac 100644--- a/frontend/src/core/static/files.ts+++ b/frontend/src/core/static/files.ts@@ -49,9 +49,10 @@ export function patchFetch(// eslint-disable-next-line @typescript-eslint/no-base-to-stringconst urlString = input instanceof Request ? input.url : input.toString();- const url = urlString.startsWith("/")- ? new URL(urlString, window.location.origin)- : new URL(urlString);+ const url =+ urlString.startsWith("/") || urlString.startsWith("./")+ ? new URL(urlString, window.location.origin)+ : new URL(urlString);if (files[url.pathname]) {const { base64 } = files[url.pathname];diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsxindex 7d585c1a17..9ea0dedc06 100644--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx@@ -21,6 +21,7 @@ import { fixRelativeUrl } from "./fix-relative-url";import "./vega.css";import { useThemeForPlugin } from "@/theme/useTheme";import { Objects } from "@/utils/objects";+import { asURL } from "@/utils/url";interface Data {spec: VegaLiteSpec;@@ -93,21 +94,23 @@ export const VegaComponent = ({return spec;}- // Skip non-relative URLs- if (!spec.data.url.startsWith("/")) {+ // Parse URL+ let url: URL;+ try {+ url = asURL(spec.data.url);+ } catch {return spec;}- const url = spec.data.url;- const data = await vegaLoadData(url, spec.data.format);+ const data = await vegaLoadData(url.href, spec.data.format);return {...spec,data: {- name: url,+ name: url.pathname,},datasets: {...spec.datasets,- [url]: data,+ [url.pathname]: data,},} as VegaLiteSpec;}, [spec]);diff --git a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snapindex 4532ad1af4..471158a507 100644--- a/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap+++ b/frontend/src/plugins/impl/vega/__tests__/__snapshots__/make-selectable.test.ts.snap@@ -460,3 +460,116 @@ exports[`makeSelectable > should skip field selection if empty or false 1`] = `],}`;++exports[`makeSelectable > should work for multi-layered charts 1`] = `+{+ "data": {+ "name": "source",+ },+ "datasets": {+ "source": [+ {+ "yield_center": 32.4,+ "yield_error": 7.5522,+ },+ {+ "yield_center": 30.96667,+ "yield_error": 6.9775,+ },+ {+ "yield_center": 33.966665,+ "yield_error": 3.9167,+ },+ {+ "yield_center": 30.45,+ "yield_error": 11.9732,+ },+ ],+ },+ "layer": [+ {+ "encoding": {+ "x": {+ "field": "yield_center",+ "scale": {+ "zero": false,+ },+ "title": "yield",+ "type": "quantitative",+ },+ "xError": {+ "field": "yield_error",+ },+ "y": {+ "field": "variety",+ "type": "nominal",+ },+ },+ "mark": {+ "ticks": true,+ "type": "errorbar",+ },+ },+ {+ "encoding": {+ "opacity": {+ "condition": {+ "test": {+ "and": [+ {+ "param": "select_point",+ },+ {+ "param": "select_interval",+ },+ ],+ },+ "value": 1,+ },+ "value": 0.2,+ },+ "x": {+ "field": "yield_center",+ "type": "quantitative",+ },+ },+ "mark": {+ "color": "black",+ "cursor": "pointer",+ "filled": true,+ "tooltip": true,+ "type": "point",+ },+ "params": [+ {+ "name": "select_point",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "type": "point",+ },+ },+ {+ "name": "select_interval",+ "select": {+ "encodings": [+ "x",+ "y",+ ],+ "mark": {+ "fill": "#669EFF",+ "fillOpacity": 0.07,+ "stroke": "#669EFF",+ "strokeOpacity": 0.4,+ },+ "type": "interval",+ },+ },+ ],+ },+ ],+ "width": "container",+}+`;diff --git a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.tsindex 8c196482ed..eac0565624 100644--- a/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts+++ b/frontend/src/plugins/impl/vega/__tests__/make-selectable.test.ts@@ -2,6 +2,7 @@import { expect, describe, it } from "vitest";import { makeSelectable } from "../make-selectable";import { VegaLiteSpec } from "../types";+import { getSelectionParamNames } from "../params";describe("makeSelectable", () => {it("should return correctly if mark is not string", () => {@@ -24,12 +25,12 @@ describe("makeSelectable", () => {const spec = {mark: "point",} as VegaLiteSpec;- expect(- makeSelectable(spec, {- chartSelection: false,- fieldSelection: false,- }),- ).toEqual(spec);+ const newSpec = makeSelectable(spec, {+ chartSelection: false,+ fieldSelection: false,+ });+ expect(newSpec).toEqual(spec);+ expect(getSelectionParamNames(newSpec)).toEqual([]);});it("should return the same spec for not-defined and true", () => {@@ -82,12 +83,16 @@ describe("makeSelectable", () => {type: "point",},} as VegaLiteSpec;- expect(- makeSelectable(spec, {- chartSelection: true,- fieldSelection: true,- }),- ).toMatchSnapshot();+ const newSpec = makeSelectable(spec, {+ chartSelection: true,+ fieldSelection: true,+ });+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toEqual([+ "legend_selection_Origin",+ "select_point",+ "select_interval",+ ]);});it("should skip field selection if empty or false", () => {@@ -117,9 +122,15 @@ describe("makeSelectable", () => {},} as VegaLiteSpec;- expect(- makeSelectable(spec, { chartSelection: true, fieldSelection: false }),- ).toMatchSnapshot();+ const newSpec = makeSelectable(spec, {+ chartSelection: true,+ fieldSelection: false,+ });+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toEqual([+ "select_point",+ "select_interval",+ ]);// These are the sameexpect(@@ -144,7 +155,14 @@ describe("makeSelectable", () => {},} as VegaLiteSpec;- expect(makeSelectable(spec, {})).toMatchSnapshot();+ const newSpec = makeSelectable(spec, {});+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toEqual([+ "legend_selection_colorField",+ "legend_selection_sizeField",+ "select_point",+ "select_interval",+ ]);});it("should return correctly if existing legend selection", () => {@@ -190,6 +208,87 @@ describe("makeSelectable", () => {},],} as VegaLiteSpec;- expect(makeSelectable(spec, {})).toMatchSnapshot();+ const newSpec = makeSelectable(spec, {});+ expect(newSpec).toMatchSnapshot();+ expect(getSelectionParamNames(newSpec)).toEqual([+ "param_1",+ "legend_selection_series",+ "select_point",+ ]);+ });++ it("should work for multi-layered charts", () => {+ const spec = {+ layer: [+ {+ mark: {+ type: "errorbar",+ ticks: true,+ },+ encoding: {+ x: {+ field: "yield_center",+ scale: {+ zero: false,+ },+ title: "yield",+ type: "quantitative",+ },+ xError: {+ field: "yield_error",+ },+ y: {+ field: "variety",+ type: "nominal",+ },+ },+ },+ {+ mark: {+ type: "point",+ color: "black",+ filled: true,+ },+ encoding: {+ x: {+ field: "yield_center",+ type: "quantitative",+ },+ },+ },+ ],+ data: { name: "source" },+ width: "container",+ datasets: {+ source: [+ {+ yield_error: 7.5522,+ yield_center: 32.4,+ },+ {+ yield_error: 6.9775,+ yield_center: 30.966_67,+ },+ {+ yield_error: 3.9167,+ yield_center: 33.966_665,+ },+ {+ yield_error: 11.9732,+ yield_center: 30.45,+ },+ ],+ },+ } as VegaLiteSpec;++ const newSpec = makeSelectable(spec, {+ chartSelection: true,+ });+ expect(newSpec).toMatchSnapshot();++ expect(getSelectionParamNames(newSpec)).toEqual([+ "select_point",+ "select_interval",+ ]);});});diff --git a/frontend/src/plugins/impl/vega/fix-relative-url.ts b/frontend/src/plugins/impl/vega/fix-relative-url.tsindex b19eb021fd..7c48964dc7 100644--- a/frontend/src/plugins/impl/vega/fix-relative-url.ts+++ b/frontend/src/plugins/impl/vega/fix-relative-url.ts@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */+import { asURL } from "@/utils/url";import { VegaLiteSpec } from "./types";/**@@ -7,8 +8,8 @@ import { VegaLiteSpec } from "./types";* otherwise vega-lite throws an error.*/export function fixRelativeUrl(spec: VegaLiteSpec) {- if (spec.data && "url" in spec.data && spec.data.url.startsWith("/")) {- spec.data.url = `${window.location.origin}${spec.data.url}`;+ if (spec.data && "url" in spec.data) {+ spec.data.url = asURL(spec.data.url).href;}return spec;}diff --git a/frontend/src/plugins/impl/vega/make-selectable.ts b/frontend/src/plugins/impl/vega/make-selectable.tsindex 5802d0e1fc..5bf4e597a4 100644--- a/frontend/src/plugins/impl/vega/make-selectable.ts+++ b/frontend/src/plugins/impl/vega/make-selectable.ts@@ -39,6 +39,19 @@ export function makeSelectable<T extends VegaLiteSpec>(return { ...spec, hconcat: subSpecs };}+ if ("layer" in spec) {+ const subSpecs = spec.layer.map((subSpec, idx) => {+ if (!("mark" in subSpec)) {+ return subSpec;+ }+ let resolvedSpec = subSpec as VegaLiteUnitSpec;+ resolvedSpec = makeChartSelectable(resolvedSpec, chartSelection);+ resolvedSpec = makeChartInteractive(resolvedSpec);+ return resolvedSpec;+ });+ return { ...spec, layer: subSpecs };+ }+if (!("mark" in spec)) {return spec;}@@ -92,7 +105,13 @@ function makeChartSelectable(return spec;}- const mark = Marks.getMarkType(spec.mark);+ let mark: Mark;+ try {+ mark = Marks.getMarkType(spec.mark);+ } catch {+ return spec;+ }+const resolvedChartSelection =chartSelection === true ? getBestSelectionForMark(mark) : [chartSelection];@@ -112,6 +131,9 @@ function makeChartSelectable(} as VegaLiteUnitSpec;}+/**+ * Makes a chart clickable and adds an opacity encoding to the chart.+ */function makeChartInteractive<T extends GenericVegaSpec>(spec: T): T {const prevEncodings = "encoding" in spec ? spec.encoding : undefined;const params = spec.params || [];diff --git a/frontend/src/plugins/impl/vega/params.ts b/frontend/src/plugins/impl/vega/params.tsindex 0e53caccec..cbd5762279 100644--- a/frontend/src/plugins/impl/vega/params.ts+++ b/frontend/src/plugins/impl/vega/params.ts@@ -1,12 +1,15 @@/* Copyright 2024 Marimo. All rights reserved. */+import { TopLevelSpec } from "vega-lite";import { Marks } from "./marks";import {+ Field,Mark,SelectionParameter,SingleDefUnitChannel,- VegaLiteSpec,VegaLiteUnitSpec,} from "./types";+import { LayerSpec, UnitSpec } from "vega-lite/build/src/spec";+import { uniq } from "lodash-es";const ParamNames = {LEGEND_SELECTION: "legend_selection",@@ -89,16 +92,26 @@ export function getEncodingAxisForMark(}}-export function getSelectionParamNames(spec: VegaLiteSpec): string[] {- const params = spec.params;- if (params && params.length > 0) {- return params- .filter((param) => {- return "select" in param && param.select !== undefined;- })- .map((param) => {- return param.name;- });+export function getSelectionParamNames(+ spec: TopLevelSpec | LayerSpec<Field> | UnitSpec<Field>,+): string[] {+ if ("params" in spec && spec.params && spec.params.length > 0) {+ const params = spec.params;+ return (+ params+ // @ts-expect-error TS doesn't know that `param` is an object+ .filter((param) => {+ if (param == null) {+ return false;+ }+ // @ts-expect-error TS doesn't know that `param` is an object+ return "select" in param && param.select !== undefined;+ })+ .map((param) => param.name)+ );+ }+ if ("layer" in spec) {+ return uniq(spec.layer.flatMap(getSelectionParamNames));}return [];}diff --git a/frontend/src/utils/__tests__/url.test.ts b/frontend/src/utils/__tests__/url.test.tsnew file mode 100644index 0000000000..4349db8156--- /dev/null+++ b/frontend/src/utils/__tests__/url.test.ts@@ -0,0 +1,75 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { beforeAll, expect, describe, test } from "vitest";+import { asURL } from "../url";++describe("asURL function", () => {+ describe("when document.baseURI is not set", () => {+ // Mock document.baseURI+ beforeAll(() => {+ Object.defineProperty(document, "baseURI", {+ value: "https://example.com/",+ writable: true,+ });+ });++ test('should handle relative path starting with "./"', () => {+ const path = "./path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe("https://example.com/path/to/resource");+ });++ test('should handle absolute path starting with "/"', () => {+ const path = "/path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe("https://example.com/path/to/resource");+ });++ test("should handle full URL", () => {+ const fullPath = "https://example.com/path/to/resource";+ const result = asURL(fullPath);+ expect(result.toString()).toBe(fullPath);+ });++ test('should handle relative path without "./"', () => {+ const path = "path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe("https://example.com/path/to/resource");+ });+ });++ describe("when document.baseURI is set", () => {+ // Mock document.baseURI+ beforeAll(() => {+ Object.defineProperty(document, "baseURI", {+ value: "https://example.com/base/",+ writable: true,+ });+ });++ test('should handle relative path starting with "./"', () => {+ const path = "./path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe("https://example.com/path/to/resource");+ });++ test('should handle absolute path starting with "/"', () => {+ const path = "/path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe("https://example.com/path/to/resource");+ });++ test("should handle full URL", () => {+ const fullPath = "https://example.com/path/to/resource";+ const result = asURL(fullPath);+ expect(result.toString()).toBe(fullPath);+ });++ test('should handle relative path without "./"', () => {+ const path = "path/to/resource";+ const result = asURL(path);+ expect(result.toString()).toBe(+ "https://example.com/base/path/to/resource",+ );+ });+ });+});diff --git a/frontend/src/utils/url.ts b/frontend/src/utils/url.tsnew file mode 100644index 0000000000..4b4592d8bf--- /dev/null+++ b/frontend/src/utils/url.ts@@ -0,0 +1,20 @@+/* Copyright 2024 Marimo. All rights reserved. */++/**+ * Resolve the path to a URL.+ *+ * If its a relative path, it will be resolved to the current origin.+ *+ * If document.baseURI is set, it will be used as the base URL.+ */+export function asURL(path: string): URL {+ if (path.startsWith("./")) {+ return new URL(path.slice(1), document.baseURI);+ }++ if (path.startsWith("/")) {+ return new URL(path, document.baseURI);+ }++ return new URL(path, document.baseURI);+}diff --git a/marimo/_smoke_tests/altair_charts.py b/marimo/_smoke_tests/altair_charts.pyindex f23c7dd844..a5e98d7510 100644--- a/marimo/_smoke_tests/altair_charts.py+++ b/marimo/_smoke_tests/altair_charts.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.2.1"+__generated_with = "0.2.2"app = marimo.App(width="full")@@ -88,19 +89,21 @@ def __(alt, chart1, chart_selection_value, legend_selection_value, mo):mo.vstack([chart1,- mo.ui.altair_chart(- alt.Chart(chart1.value)- .mark_bar()- .encode(- x="Origin",- y="count()",- color="Origin",- ),- chart_selection=chart_selection_value,- legend_selection=legend_selection_value,- )- if not chart1.value.empty- else mo.md("No selection"),+ (+ mo.ui.altair_chart(+ alt.Chart(chart1.value)+ .mark_bar()+ .encode(+ x="Origin",+ y="count()",+ color="Origin",+ ),+ chart_selection=chart_selection_value,+ legend_selection=legend_selection_value,+ )+ if not chart1.value.empty+ else mo.md("No selection")+ ),chart1.value.head(),])@@ -543,5 +546,55 @@ def __(mo, with_transform):return+def __(mo):+ mo.md("# Layers")+ return+++def __(alt, mo, pd):+ _source = pd.DataFrame(+ {+ "yield_error": [7.5522, 6.9775, 3.9167, 11.9732],+ "yield_center": [32.4, 30.96667, 33.966665, 30.45],+ "variety": ["Glabron", "Manchuria", "No. 457", "No. 462"],+ }+ )++ bar = (+ alt.Chart(_source)+ .mark_errorbar(ticks=True)+ .encode(+ x=alt.X("yield_center:Q").scale(zero=False).title("yield"),+ xError=("yield_error:Q"),+ y=alt.Y("variety:N"),+ )+ .properties(width="container")+ )++ point = (+ alt.Chart(_source)+ .mark_point(filled=True, color="black")+ .encode(+ alt.X("yield_center:Q"),+ alt.Y("variety:N"),+ )+ )++ _chart = bar + point+ # layered_chart = mo.ui.altair_chart(_chart, chart_selection="point")+ layered_chart = mo.ui.altair_chart(_chart, chart_selection="interval")+ return bar, layered_chart, point+++def __(layered_chart, mo):+ mo.vstack(+ [layered_chart, mo.hstack([layered_chart.value, layered_chart.selections])]+ )+ return++if __name__ == "__main__":app.run()