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.

refactor: lazy-load vega plugins (#1376)

Myles Scolnick26436b37b6b2
diff --git a/frontend/package.json b/frontend/package.json
index 339e082254..99968596a1 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -99,7 +99,6 @@
"lodash-es": "^4.17.21",
"lucide-react": "^0.378.0",
"lz-string": "^1.5.0",
- "mathjs": "^12.4.2",
"mermaid": "^10.9.0",
"partysocket": "1.0.1",
"plotly.js": "^2.32.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index bc2fb22e5c..38de22ed30 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -263,9 +263,6 @@ dependencies:
lz-string:
specifier: ^1.5.0
version: 1.5.0
- mathjs:
- specifier: ^12.4.2
- version: 12.4.2
mermaid:
specifier: ^10.9.0
version: 10.9.0
@@ -10154,10 +10151,6 @@ packages:
- vega
dev: false
- resolution: {integrity: sha512-8njCHOTtFFLtegk6zQo0kkVX1rngygb/KQI6z1qZxlFI3scluC+LVTCFbrkWjBv4vvLlbQ9t88IPMC6k95VTTg==}
- dev: false
-
resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==}
engines: {node: '>= 0.6'}
@@ -11011,6 +11004,7 @@ packages:
resolution: {integrity: sha512-VBBaLc1MgL5XpzgIP7ny5Z6Nx3UrRkIViUkPUdtl9aya5amy3De1gsUUSB1g3+3sExYNjCAsAznmukyxCb1GRA==}
+ dev: true
resolution: {integrity: sha512-O8x12RzrUF8xyVcY0KJowWsmaJxQbmy0/EtnNtHRpsOcT7dFk5W598coHqBVpmWo1oQQfsCqfCmkZN5DJrZVdg==}
@@ -11664,10 +11658,6 @@ packages:
resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==}
dev: true
- resolution: {integrity: sha512-nV5aVWW1K0wEiUIEdZ4erkGGH8mDxGyxSeqPzRNtWP7ataw+/olFObw7hujFWlVjNsaDFw5VZ5NzVSIqRgfTiw==}
- dev: false
-
resolution: {integrity: sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==}
engines: {node: '>=0.8.0'}
@@ -12344,10 +12334,6 @@ packages:
engines: {node: '>= 0.6'}
dev: true
- resolution: {integrity: sha512-pwiTgt0Q7t+GHZA4yaLjObx4vXmmdcS0iSJ19o8d/goUGgItX9UZWKWNnLHehxviD8wU2IWRsnR8cD5+yOJP2Q==}
- dev: false
-
resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==}
dev: true
@@ -13561,10 +13547,6 @@ packages:
minimatch: 3.1.2
dev: true
- resolution: {integrity: sha512-nO6jcEfZWQXDhOiBtG2KvKyEptz7RVbpGP4vTD2hLBdmNQSsCiicO2Ioinv6UI4y9ukqnBpy+XZ9H6uLNgJTlw==}
- dev: false
-
resolution: {integrity: sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==}
engines: {node: '>= 10.13.0'}
@@ -14138,22 +14120,6 @@ packages:
engines: {node: '>=0.10.0'}
dev: false
- resolution: {integrity: sha512-lW14EzwAFgbNN7AZikxplmhs7wiXDhMphBOGCA3KS6T29ECEkHJsBtbEW5cnCz7sXtl4nDyvTdR+DqVsZyiiEw==}
- engines: {node: '>= 18'}
- hasBin: true
- dependencies:
- '@babel/runtime': 7.24.4
- complex.js: 2.1.1
- decimal.js: 10.4.3
- escape-latex: 1.2.0
- fraction.js: 4.3.4
- javascript-natural-sort: 0.7.1
- seedrandom: 3.0.5
- tiny-emitter: 2.1.0
- typed-function: 4.1.1
- dev: false
-
resolution: {integrity: sha512-APMBEanjybaPzUrfqU0IMU5I0AswKMH7k8OTLs0vvV4KZpExkTkY87nR/zpbuTPj+gARop7aGUbl11pnDfW6xg==}
dev: true
@@ -17020,10 +16986,6 @@ packages:
resolution: {integrity: sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==}
dev: false
- resolution: {integrity: sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==}
- dev: false
-
resolution: {integrity: sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==}
hasBin: true
@@ -17957,10 +17919,6 @@ packages:
engines: {node: '>=12'}
dev: false
- resolution: {integrity: sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==}
- dev: false
-
resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==}
@@ -18296,11 +18254,6 @@ packages:
possible-typed-array-names: 1.0.0
dev: true
- resolution: {integrity: sha512-Pq1DVubcvibmm8bYcMowjVnnMwPVMeh0DIdA8ad8NZY2sJgapANJmiigSUwlt+EgXxpfIv8MWrQXTIzkfYZLYQ==}
- engines: {node: '>= 14'}
- dev: false
-
resolution: {integrity: sha512-YTSQbzX43yvtpfRtIDAYygoYtgT+Rpjuxy9iOpczrjpXLgGoyG7aS5USJXV2d3nn8uHTeb9rXDvzS27zUg5KYQ==}
dependencies:
diff --git a/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx
new file mode 100644
index 0000000000..89aa78440b
--- /dev/null
+++ b/frontend/src/plugins/impl/data-explorer/ConnectedDataExplorerComponent.tsx
@@ -0,0 +1,258 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+/* eslint-disable @typescript-eslint/no-base-to-string */
+import * as cql from "compassql/build/src";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import React, { useMemo } from "react";
+import { Tooltip } from "@/components/ui/tooltip";
+import { vegaLoadData } from "../vega/loader";
+import { VegaLite } from "react-vega";
+import { ListFilterIcon } from "lucide-react";
+import { QueryForm } from "./components/query-form";
+import {
+ chartSpecAtom,
+ relatedChartSpecsAtom,
+ useChartSpecActions,
+} from "./state/reducer";
+import { Provider, createStore, useAtomValue } from "jotai";
+import { Button } from "@/components/ui/button";
+import { SpecificEncoding } from "./encoding";
+import { Objects } from "@/utils/objects";
+import { Badge } from "@/components/ui/badge";
+import { ErrorBanner } from "../common/error-banner";
+import { ColumnSummary } from "./components/column-summary";
+import { VegaLiteProps } from "react-vega/lib/VegaLite";
+import { useOnMount } from "@/hooks/useLifecycle";
+import { ChartSpec } from "./state/types";
+
+/**
+ * @param label - a label of the table
+ * @param data - the data to display
+ */
+export interface DataExplorerData {
+ label?: string | null;
+ data: string;
+}
+
+// Value is unused for now
+export type DataExplorerState = ChartSpec | undefined;
+
+const ConnectedDataExplorerComponent = (props: DataTableProps): JSX.Element => {
+ const store = useMemo(() => createStore(), []);
+
+ useOnMount(() => {
+ // Subscribe to the store
+ const unsub = store.sub(chartSpecAtom, () => {
+ const value = store.get(chartSpecAtom);
+ const { schema, ...withoutSchema } = value;
+ props.setValue(withoutSchema);
+ });
+
+ // Set the initial value
+ const value = props.value;
+ if (value && Object.keys(value).length > 0) {
+ store.set(chartSpecAtom, value);
+ }
+
+ return unsub;
+ });
+
+ return (
+ <Provider store={store}>
+ <DataExplorerComponent {...props} />
+ </Provider>
+ );
+};
+
+interface DataTableProps extends DataExplorerData {
+ value: DataExplorerState;
+ setValue: (value: DataExplorerState) => void;
+}
+
+const ACTIONS: VegaLiteProps["actions"] = {
+ export: { svg: true, png: true },
+ source: false,
+ compiled: false,
+ editor: false,
+};
+
+const PADDING = { left: 20, right: 20, top: 20, bottom: 20 };
+
+export default ConnectedDataExplorerComponent;
+
+export const DataExplorerComponent = ({
+ data: dataUrl,
+}: DataTableProps): JSX.Element => {
+ const actions = useChartSpecActions();
+ const { data, loading, error } = useAsyncData(async () => {
+ if (!dataUrl) {
+ return {};
+ }
+ const chartData = await vegaLoadData(dataUrl, {
+ type: "csv",
+ parse: "auto",
+ });
+ const schema = cql.schema.build(chartData);
+ actions.setSchema(schema);
+ return { chartData, schema };
+ }, [dataUrl]);
+
+ const { mark } = useAtomValue(chartSpecAtom);
+ const charts = useAtomValue(relatedChartSpecsAtom);
+
+ if (error) {
+ return <ErrorBanner error={error} />;
+ }
+ if (!data) {
+ return <div />;
+ }
+ const { chartData, schema } = data;
+ if (loading || !schema) {
+ return <div />;
+ }
+
+ const mainPlot = charts.main?.plots?.[0];
+ const existingEncodingNames = new Set(
+ mainPlot?.fieldInfos.map((info) => info.fieldDef.field),
+ );
+
+ const renderMainPlot = () => {
+ if (!mainPlot) {
+ return <ColumnSummary schema={schema} />;
+ }
+
+ return (
+ <div className="flex overflow-y-auto justify-center items-center flex-1 w-[90%]">
+ <VegaLite
+ data={{ source: chartData }}
+ padding={PADDING}
+ actions={ACTIONS}
+ spec={makeResponsive(mainPlot.spec)}
+ />
+ </div>
+ );
+ };
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <QueryForm mark={mark} schema={schema} />
+ {renderMainPlot()}
+ </div>
+
+ <HorizontalCarousel>
+ {[
+ charts.histograms?.plots,
+ charts.addCategoricalField?.plots,
+ charts.addQuantitativeField?.plots,
+ charts.addTemporalField?.plots,
+ ]
+ .filter(Boolean)
+ .flat()
+ .map((plot, idx) => (
+ <HorizontalCarouselItem
+ key={idx}
+ title={
+ <div className="flex flex-row gap-1">
+ {plot.fieldInfos.map((info) => {
+ const label =
+ info.fieldDef.field === "*"
+ ? "Count"
+ : info.fieldDef.fn
+ ? `${info.fieldDef.fn}(${info.fieldDef.field})`
+ : info.fieldDef.field.toString();
+ return (
+ <Badge
+ variant={
+ existingEncodingNames.has(info.fieldDef.field)
+ ? "secondary"
+ : "defaultOutline"
+ }
+ key={label}
+ >
+ {label}
+ </Badge>
+ );
+ })}
+ </div>
+ }
+ actions={
+ <Tooltip content="Make main plot">
+ <Button
+ data-testid="marimo-plugin-data-explorer-make-main-plot"
+ variant="text"
+ size={"icon"}
+ onClick={() => {
+ const encoding: SpecificEncoding = Objects.fromEntries(
+ plot.fieldInfos.map((info) => [
+ info.channel,
+ info.fieldDef,
+ ]),
+ );
+ actions.setEncoding(encoding);
+ }}
+ >
+ <ListFilterIcon className="w-4 h-4" />
+ </Button>
+ </Tooltip>
+ }
+ >
+ <VegaLite
+ data={{ source: chartData }}
+ key={idx}
+ actions={false}
+ spec={plot.spec}
+ />
+ </HorizontalCarouselItem>
+ ))}
+ </HorizontalCarousel>
+ </div>
+ );
+};
+
+const HorizontalCarousel = ({
+ children,
+}: {
+ children: React.ReactNode;
+}): React.ReactNode => {
+ if (React.Children.count(children) === 0) {
+ return null;
+ }
+
+ return (
+ <div className="flex flex-row overflow-x-auto overflow-y-hidden gap-4 snap-x pb-4">
+ {children}
+ </div>
+ );
+};
+const HorizontalCarouselItem = ({
+ title,
+ children,
+ actions,
+}: {
+ title?: React.ReactNode;
+ actions?: React.ReactNode;
+ children: React.ReactNode;
+}): React.ReactNode => {
+ return (
+ <div className="flex-shrink-0 bg-card shadow-md border overflow-hidden rounded snap-start">
+ <div className="flex flex-row justify-between items-center bg-[var(--slate-3)] py-0.5 px-2">
+ <div className="text-sm font-medium">{title}</div>
+ {actions}
+ </div>
+ <div className="px-6 pt-2 max-h-[280px] overflow-y-auto">{children}</div>
+ </div>
+ );
+};
+// Make the plot responsive
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+function makeResponsive(spec: any) {
+ // NOTE: for row/column, this applies to the inner plot
+ // so we tend to overflow due to the legends,
+ // So for row/column, we skip the responsive spec
+ // https://vega.github.io/vega-lite/docs/size.html#width-and-height-of-multi-view-displays
+ const hasRowOrColumn = Boolean(spec.encoding?.row || spec.encoding?.column);
+ if (!hasRowOrColumn) {
+ spec.width = "container";
+ }
+ return spec;
+}
diff --git a/frontend/src/plugins/impl/data-explorer/DataExplorerPlugin.tsx b/frontend/src/plugins/impl/data-explorer/DataExplorerPlugin.tsx
index 1a2c66c03f..f7a6eb341d 100644
--- a/frontend/src/plugins/impl/data-explorer/DataExplorerPlugin.tsx
+++ b/frontend/src/plugins/impl/data-explorer/DataExplorerPlugin.tsx
@@ -1,46 +1,20 @@
/* Copyright 2024 Marimo. All rights reserved. */
-/* eslint-disable @typescript-eslint/no-base-to-string */
-import { z } from "zod";
import "../vega/vega.css";
-import * as cql from "compassql/build/src";
-import { createPlugin } from "@/plugins/core/builder";
-import { useAsyncData } from "@/hooks/useAsyncData";
-import React, { useMemo } from "react";
-import { Tooltip, TooltipProvider } from "@/components/ui/tooltip";
-import { vegaLoadData } from "../vega/loader";
-import { VegaLite } from "react-vega";
-import { ListFilterIcon } from "lucide-react";
-import { QueryForm } from "./components/query-form";
-import {
- chartSpecAtom,
- relatedChartSpecsAtom,
- useChartSpecActions,
-} from "./state/reducer";
-import { Provider, createStore, useAtomValue } from "jotai";
-import { Button } from "@/components/ui/button";
-import { SpecificEncoding } from "./encoding";
-import { Objects } from "@/utils/objects";
-import { Badge } from "@/components/ui/badge";
-import { ErrorBanner } from "../common/error-banner";
-import { ColumnSummary } from "./components/column-summary";
-import { VegaLiteProps } from "react-vega/lib/VegaLite";
-import { useOnMount } from "@/hooks/useLifecycle";
-import { ChartSpec } from "./state/types";
+import { z } from "zod";
-/**
- * @param label - a label of the table
- * @param data - the data to display
- */
-interface Data {
- label?: string | null;
- data: string;
-}
+import { createPlugin } from "@/plugins/core/builder";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import React from "react";
+import type { DataExplorerState } from "./ConnectedDataExplorerComponent";
-// Value is unused for now
-type S = ChartSpec | undefined;
+const LazyDataExplorerComponent = React.lazy(
+ () => import("./ConnectedDataExplorerComponent"),
+);
-export const DataExplorerPlugin = createPlugin<S>("marimo-data-explorer")
+export const DataExplorerPlugin = createPlugin<DataExplorerState>(
+ "marimo-data-explorer",
+)
.withData(
z.object({
label: z.string().nullish(),
@@ -49,230 +23,10 @@ export const DataExplorerPlugin = createPlugin<S>("marimo-data-explorer")
)
.renderer((props) => (
<TooltipProvider>
- <ConnectedDataExplorerComponent
+ <LazyDataExplorerComponent
{...props.data}
value={props.value}
setValue={props.setValue}
/>
</TooltipProvider>
));
-
-const ConnectedDataExplorerComponent = (props: DataTableProps): JSX.Element => {
- const store = useMemo(() => createStore(), []);
-
- useOnMount(() => {
- // Subscribe to the store
- const unsub = store.sub(chartSpecAtom, () => {
- const value = store.get(chartSpecAtom);
- const { schema, ...withoutSchema } = value;
- props.setValue(withoutSchema);
- });
-
- // Set the initial value
- const value = props.value;
- if (value && Object.keys(value).length > 0) {
- store.set(chartSpecAtom, value);
- }
-
- return unsub;
- });
-
- return (
- <Provider store={store}>
- <DataExplorerComponent {...props} />
- </Provider>
- );
-};
-
-interface DataTableProps extends Data {
- value: S;
- setValue: (value: S) => void;
-}
-
-const ACTIONS: VegaLiteProps["actions"] = {
- export: { svg: true, png: true },
- source: false,
- compiled: false,
- editor: false,
-};
-const PADDING = { left: 20, right: 20, top: 20, bottom: 20 };
-
-export const DataExplorerComponent = ({
- data: dataUrl,
-}: DataTableProps): JSX.Element => {
- const actions = useChartSpecActions();
- const { data, loading, error } = useAsyncData(async () => {
- if (!dataUrl) {
- return {};
- }
- const chartData = await vegaLoadData(dataUrl, {
- type: "csv",
- parse: "auto",
- });
- const schema = cql.schema.build(chartData);
- actions.setSchema(schema);
- return { chartData, schema };
- }, [dataUrl]);
-
- const { mark } = useAtomValue(chartSpecAtom);
- const charts = useAtomValue(relatedChartSpecsAtom);
-
- if (error) {
- return <ErrorBanner error={error} />;
- }
- if (!data) {
- return <div />;
- }
- const { chartData, schema } = data;
- if (loading || !schema) {
- return <div />;
- }
-
- const mainPlot = charts.main?.plots?.[0];
- const existingEncodingNames = new Set(
- mainPlot?.fieldInfos.map((info) => info.fieldDef.field),
- );
-
- const renderMainPlot = () => {
- if (!mainPlot) {
- return <ColumnSummary schema={schema} />;
- }
-
- return (
- <div className="flex overflow-y-auto justify-center items-center flex-1 w-[90%]">
- <VegaLite
- data={{ source: chartData }}
- padding={PADDING}
- actions={ACTIONS}
- spec={makeResponsive(mainPlot.spec)}
- />
- </div>
- );
- };
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex items-center gap-2">
- <QueryForm mark={mark} schema={schema} />
- {renderMainPlot()}
- </div>
-
- <HorizontalCarousel>
- {[
- charts.histograms?.plots,
- charts.addCategoricalField?.plots,
- charts.addQuantitativeField?.plots,
- charts.addTemporalField?.plots,
- ]
- .filter(Boolean)
- .flat()
- .map((plot, idx) => (
- <HorizontalCarouselItem
- key={idx}
- title={
- <div className="flex flex-row gap-1">
- {plot.fieldInfos.map((info) => {
- const label =
- info.fieldDef.field === "*"
- ? "Count"
- : info.fieldDef.fn
- ? `${info.fieldDef.fn}(${info.fieldDef.field})`
- : info.fieldDef.field.toString();
- return (
- <Badge
- variant={
- existingEncodingNames.has(info.fieldDef.field)
- ? "secondary"
- : "defaultOutline"
- }
- key={label}
- >
- {label}
- </Badge>
- );
- })}
- </div>
- }
- actions={
- <Tooltip content="Make main plot">
- <Button
- data-testid="marimo-plugin-data-explorer-make-main-plot"
- variant="text"
- size={"icon"}
- onClick={() => {
- const encoding: SpecificEncoding = Objects.fromEntries(
- plot.fieldInfos.map((info) => [
- info.channel,
- info.fieldDef,
- ]),
- );
- actions.setEncoding(encoding);
- }}
- >
- <ListFilterIcon className="w-4 h-4" />
- </Button>
- </Tooltip>
- }
- >
- <VegaLite
- data={{ source: chartData }}
- key={idx}
- actions={false}
- spec={plot.spec}
- />
- </HorizontalCarouselItem>
- ))}
- </HorizontalCarousel>
- </div>
- );
-};
-
-const HorizontalCarousel = ({
- children,
-}: {
- children: React.ReactNode;
-}): React.ReactNode => {
- if (React.Children.count(children) === 0) {
- return null;
- }
-
- return (
- <div className="flex flex-row overflow-x-auto overflow-y-hidden gap-4 snap-x pb-4">
- {children}
- </div>
- );
-};
-
-const HorizontalCarouselItem = ({
- title,
- children,
- actions,
-}: {
- title?: React.ReactNode;
- actions?: React.ReactNode;
- children: React.ReactNode;
-}): React.ReactNode => {
- return (
- <div className="flex-shrink-0 bg-card shadow-md border overflow-hidden rounded snap-start">
- <div className="flex flex-row justify-between items-center bg-[var(--slate-3)] py-0.5 px-2">
- <div className="text-sm font-medium">{title}</div>
- {actions}
- </div>
- <div className="px-6 pt-2 max-h-[280px] overflow-y-auto">{children}</div>
- </div>
- );
-};
-
-// Make the plot responsive
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function makeResponsive(spec: any) {
- // NOTE: for row/column, this applies to the inner plot
- // so we tend to overflow due to the legends,
- // So for row/column, we skip the responsive spec
- // https://vega.github.io/vega-lite/docs/size.html#width-and-height-of-multi-view-displays
- const hasRowOrColumn = Boolean(spec.encoding?.row || spec.encoding?.column);
- if (!hasRowOrColumn) {
- spec.width = "container";
- }
- return spec;
-}
diff --git a/frontend/src/plugins/impl/data-explorer/queries/types.ts b/frontend/src/plugins/impl/data-explorer/queries/types.ts
index f1804c98d8..43cdb2166b 100644
--- a/frontend/src/plugins/impl/data-explorer/queries/types.ts
+++ b/frontend/src/plugins/impl/data-explorer/queries/types.ts
@@ -1,9 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { Query } from "compassql/build/src/query";
-import { VisualizationSpec } from "react-vega";
-import { FieldDefinition, EncodingChannel } from "../encoding";
-import { NamedData } from "vega-lite/build/src/data";
-import { TopLevel, FacetedUnitSpec } from "vega-lite/build/src/spec";
+import type { Query } from "compassql/build/src/query";
+import type { VisualizationSpec } from "react-vega";
+import type { FieldDefinition, EncodingChannel } from "../encoding";
+import type { NamedData } from "vega-lite/build/src/data";
+import type { TopLevel, FacetedUnitSpec } from "vega-lite/build/src/spec";
export interface PlotFieldInfo {
fieldDef: FieldDefinition;
diff --git a/frontend/src/plugins/impl/vega/VegaPlugin.tsx b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
index 29f148c928..745152ccc1 100644
--- a/frontend/src/plugins/impl/vega/VegaPlugin.tsx
+++ b/frontend/src/plugins/impl/vega/VegaPlugin.tsx
@@ -1,49 +1,17 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { z } from "zod";
-import type { SignalListeners, View } from "react-vega";
+import { z } from "zod";
import { IPlugin, IPluginProps } from "@/plugins/types";
-import { makeSelectable } from "./make-selectable";
-import { lazy, useMemo, useRef, useState } from "react";
-import { getSelectionParamNames } from "./params";
-import { VegaLiteSpec } from "./types";
-import { Alert, AlertTitle } from "@/components/ui/alert";
-import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
-import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";
-import { debounce } from "lodash-es";
-import useEvent from "react-use-event-hook";
-import { Logger } from "@/utils/Logger";
+import type { VegaLiteSpec } from "./types";
-import { useAsyncData } from "@/hooks/useAsyncData";
-import { fixRelativeUrl } from "./fix-relative-url";
+import type { VegaComponentState, Data } from "./vega-component";
import "./vega.css";
-import { useTheme } from "@/theme/useTheme";
-import { Objects } from "@/utils/objects";
-import { resolveVegaSpecData } from "./resolve-data";
-import { Events } from "@/utils/events";
-
-interface Data {
- spec: VegaLiteSpec;
- chartSelection: boolean | "point" | "interval";
- fieldSelection: boolean | string[];
-}
+import React from "react";
-interface T {
- [channel: string]: {
- // List of selected items
- vlPoint?: { or: unknown[] };
- // Either a range or a list of values
- [field: string]:
- | [number, number]
- | string[]
- | number[]
- | { or: unknown[] }
- | undefined;
- };
-}
+const LazyVegaComponent = React.lazy(() => import("./vega-component"));
-export class VegaPlugin implements IPlugin<T, Data> {
+export class VegaPlugin implements IPlugin<VegaComponentState, Data> {
tagName = "marimo-vega";
validator = z.object({
@@ -57,9 +25,9 @@ export class VegaPlugin implements IPlugin<T, Data> {
fieldSelection: z.union([z.boolean(), z.array(z.string())]).default(true),
});
- render(props: IPluginProps<T, Data>): JSX.Element {
+ render(props: IPluginProps<VegaComponentState, Data>): JSX.Element {
return (
- <VegaComponent
+ <LazyVegaComponent
value={props.value}
setValue={props.setValue}
{...props.data}
@@ -67,155 +35,3 @@ export class VegaPlugin implements IPlugin<T, Data> {
);
}
}
-
-interface VegaComponentProps<T> extends Data {
- value: T;
- setValue: (value: T) => void;
-}
-
-export const VegaComponent = ({
- value,
- setValue,
- chartSelection,
- fieldSelection,
- spec,
-}: VegaComponentProps<T>) => {
- const { data: resolvedSpec } = useAsyncData(async () => {
- // We try to resolve the data before passing it to Vega
- // 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
- return resolveVegaSpecData(spec);
- }, [spec]);
-
- if (!resolvedSpec) {
- return null;
- }
-
- return (
- <LoadedVegaComponent
- value={value}
- setValue={setValue}
- chartSelection={chartSelection}
- fieldSelection={fieldSelection}
- spec={resolvedSpec}
- />
- );
-};
-
-const VegaLite = lazy(() =>
- import("react-vega").then((m) => ({ default: m.VegaLite })),
-);
-
-const LoadedVegaComponent = ({
- value,
- setValue,
- chartSelection,
- fieldSelection,
- spec,
-}: VegaComponentProps<T>): JSX.Element => {
- const { theme } = useTheme();
- const vegaView = useRef<View>();
- const [error, setError] = useState<Error>();
-
- // Debug
- useDebugMounting("VegaComponent");
- usePropsDidChange("VegaComponent", {
- value,
- setValue,
- chartSelection,
- fieldSelection,
- spec,
- });
-
- // Aggressively memoize the spec, so Vega doesn't re-render/re-mount the component
- const selectableSpec = useMemo(() => {
- return makeSelectable(fixRelativeUrl(spec), {
- chartSelection,
- fieldSelection,
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [useDeepCompareMemoize(spec), chartSelection, fieldSelection]);
- const names = useMemo(
- () => getSelectionParamNames(selectableSpec),
- [selectableSpec],
- );
-
- // Update the value when the selection changes
- // Keep the old value from other signals
- const handleUpdateValue = useEvent((newValue: T) => {
- setValue({ ...value, ...newValue });
- });
-
- const signalListeners = useMemo(
- () =>
- names.reduce<SignalListeners>((acc, name) => {
- // Debounce each signal listener, otherwise we may create expensive requests
- acc[name] = debounce((signalName, signalValue) => {
- Logger.debug("[Vega signal]", signalName, signalValue);
-
- handleUpdateValue({
- [signalName]: Objects.mapValues(
- signalValue as object,
- convertSetToList,
- ),
- });
- }, 100);
- return acc;
- }, {}),
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [useDeepCompareMemoize(names), setValue],
- );
-
- const handleError = useEvent((error) => {
- Logger.error(error);
- Logger.debug(selectableSpec);
- setError(error);
- });
-
- const handleNewView = useEvent((view) => {
- Logger.debug("[Vega view] created", view);
- vegaView.current = view;
- setError(undefined);
- });
-
- return (
- <>
- {error && (
- <Alert variant="destructive">
- <AlertTitle>{error.message}</AlertTitle>
- <div className="text-md">{error.stack}</div>
- </Alert>
- )}
- <div
- className="contents"
- // Capture the pointer down event to prevent the parent from handling it
- onPointerDown={Events.stopPropagation()}
- >
- <VegaLite
- spec={selectableSpec}
- theme={theme === "dark" ? "dark" : undefined}
- actions={actions}
- signalListeners={signalListeners}
- onError={handleError}
- onNewView={handleNewView}
- />
- </div>
- </>
- );
-};
-
-const actions = {
- source: false,
- compiled: false,
-};
-
-/**
- * Convert any sets to a list before passing to the BE
- */
-function convertSetToList(value: unknown): unknown {
- if (value instanceof Set) {
- return [...value];
- }
- return value;
-}
diff --git a/frontend/src/plugins/impl/vega/params.ts b/frontend/src/plugins/impl/vega/params.ts
index b1962d1895..8d6ccb754a 100644
--- a/frontend/src/plugins/impl/vega/params.ts
+++ b/frontend/src/plugins/impl/vega/params.ts
@@ -9,7 +9,6 @@ import {
VegaLiteUnitSpec,
} from "./types";
import { LayerSpec, UnitSpec } from "vega-lite/build/src/spec";
-import { uniq } from "lodash-es";
const ParamNames = {
point(layerNum: number | undefined) {
@@ -124,7 +123,7 @@ export function getSelectionParamNames(
);
}
if ("layer" in spec) {
- return uniq(spec.layer.flatMap(getSelectionParamNames));
+ return [...new Set(spec.layer.flatMap(getSelectionParamNames))];
}
return [];
}
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
new file mode 100644
index 0000000000..98687e5317
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -0,0 +1,188 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { VegaLite, type SignalListeners, type View } from "react-vega";
+import { makeSelectable } from "./make-selectable";
+import { useMemo, useRef, useState } from "react";
+import { getSelectionParamNames } from "./params";
+import { VegaLiteSpec } from "./types";
+import { Alert, AlertTitle } from "@/components/ui/alert";
+import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
+import { useDebugMounting, usePropsDidChange } from "@/hooks/debug";
+import { debounce } from "lodash-es";
+import useEvent from "react-use-event-hook";
+import { Logger } from "@/utils/Logger";
+import { useAsyncData } from "@/hooks/useAsyncData";
+import { fixRelativeUrl } from "./fix-relative-url";
+import { useTheme } from "@/theme/useTheme";
+import { Objects } from "@/utils/objects";
+import { resolveVegaSpecData } from "./resolve-data";
+import { Events } from "@/utils/events";
+
+export interface Data {
+ spec: VegaLiteSpec;
+ chartSelection: boolean | "point" | "interval";
+ fieldSelection: boolean | string[];
+}
+
+export interface VegaComponentState {
+ [channel: string]: {
+ // List of selected items
+ vlPoint?: { or: unknown[] };
+ // Either a range or a list of values
+ [field: string]:
+ | [number, number]
+ | string[]
+ | number[]
+ | { or: unknown[] }
+ | undefined;
+ };
+}
+
+interface VegaComponentProps<T> extends Data {
+ value: T;
+ setValue: (value: T) => void;
+}
+
+const VegaComponent = ({
+ value,
+ setValue,
+ chartSelection,
+ fieldSelection,
+ spec,
+}: VegaComponentProps<VegaComponentState>) => {
+ const { data: resolvedSpec } = useAsyncData(async () => {
+ // We try to resolve the data before passing it to Vega
+ // 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
+ return resolveVegaSpecData(spec);
+ }, [spec]);
+
+ if (!resolvedSpec) {
+ return null;
+ }
+
+ return (
+ <LoadedVegaComponent
+ value={value}
+ setValue={setValue}
+ chartSelection={chartSelection}
+ fieldSelection={fieldSelection}
+ spec={resolvedSpec}
+ />
+ );
+};
+
+const LoadedVegaComponent = ({
+ value,
+ setValue,
+ chartSelection,
+ fieldSelection,
+ spec,
+}: VegaComponentProps<VegaComponentState>): JSX.Element => {
+ const { theme } = useTheme();
+ const vegaView = useRef<View>();
+ const [error, setError] = useState<Error>();
+
+ // Debug
+ useDebugMounting("VegaComponent");
+ usePropsDidChange("VegaComponent", {
+ value,
+ setValue,
+ chartSelection,
+ fieldSelection,
+ spec,
+ });
+
+ // Aggressively memoize the spec, so Vega doesn't re-render/re-mount the component
+ const selectableSpec = useMemo(() => {
+ return makeSelectable(fixRelativeUrl(spec), {
+ chartSelection,
+ fieldSelection,
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [useDeepCompareMemoize(spec), chartSelection, fieldSelection]);
+ const names = useMemo(
+ () => getSelectionParamNames(selectableSpec),
+ [selectableSpec],
+ );
+
+ // Update the value when the selection changes
+ // Keep the old value from other signals
+ const handleUpdateValue = useEvent((newValue: VegaComponentState) => {
+ setValue({ ...value, ...newValue });
+ });
+
+ const signalListeners = useMemo(
+ () =>
+ names.reduce<SignalListeners>((acc, name) => {
+ // Debounce each signal listener, otherwise we may create expensive requests
+ acc[name] = debounce((signalName, signalValue) => {
+ Logger.debug("[Vega signal]", signalName, signalValue);
+
+ handleUpdateValue({
+ [signalName]: Objects.mapValues(
+ signalValue as object,
+ convertSetToList,
+ ),
+ });
+ }, 100);
+ return acc;
+ }, {}),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [useDeepCompareMemoize(names), setValue],
+ );
+
+ const handleError = useEvent((error) => {
+ Logger.error(error);
+ Logger.debug(selectableSpec);
+ setError(error);
+ });
+
+ const handleNewView = useEvent((view) => {
+ Logger.debug("[Vega view] created", view);
+ vegaView.current = view;
+ setError(undefined);
+ });
+
+ return (
+ <>
+ {error && (
+ <Alert variant="destructive">
+ <AlertTitle>{error.message}</AlertTitle>
+ <div className="text-md">{error.stack}</div>
+ </Alert>
+ )}
+ <div
+ className="contents"
+ // Capture the pointer down event to prevent the parent from handling it
+ onPointerDown={Events.stopPropagation()}
+ >
+ <VegaLite
+ spec={selectableSpec}
+ theme={theme === "dark" ? "dark" : undefined}
+ actions={actions}
+ signalListeners={signalListeners}
+ onError={handleError}
+ onNewView={handleNewView}
+ />
+ </div>
+ </>
+ );
+};
+
+const actions = {
+ source: false,
+ compiled: false,
+};
+
+/**
+ * Convert any sets to a list before passing to the BE
+ */
+function convertSetToList(value: unknown): unknown {
+ if (value instanceof Set) {
+ return [...value];
+ }
+ return value;
+}
+
+export default VegaComponent;
diff --git a/frontend/src/stories/data-explorer.stories.tsx b/frontend/src/stories/data-explorer.stories.tsx
index a77b44f7af..fb8492021e 100644
--- a/frontend/src/stories/data-explorer.stories.tsx
+++ b/frontend/src/stories/data-explorer.stories.tsx
@@ -1,6 +1,6 @@
/* Copyright 2024 Marimo. All rights reserved. */
/* eslint-disable react-hooks/rules-of-hooks */
-import { DataExplorerComponent } from "@/plugins/impl/data-explorer/DataExplorerPlugin";
+import { DataExplorerComponent } from "@/plugins/impl/data-explorer/ConnectedDataExplorerComponent";
import { ChartSpec } from "@/plugins/impl/data-explorer/state/types";
import type { Meta, StoryObj } from "@storybook/react";
import { useState } from "react";
diff --git a/frontend/src/stories/vega.stories.tsx b/frontend/src/stories/vega.stories.tsx
index 2da40c48b8..52b69b350c 100644
--- a/frontend/src/stories/vega.stories.tsx
+++ b/frontend/src/stories/vega.stories.tsx
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { VegaComponent } from "@/plugins/impl/vega/VegaPlugin";
+import VegaComponent from "@/plugins/impl/vega/vega-component";
import { Meta } from "@storybook/react";
import {
AREA_CHART,
diff --git a/frontend/src/utils/numbers.ts b/frontend/src/utils/numbers.ts
index b5bc837717..e677259b93 100644
--- a/frontend/src/utils/numbers.ts
+++ b/frontend/src/utils/numbers.ts
@@ -1,7 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { format } from "mathjs";
-
export function prettyNumber(value: number): string {
return value.toLocaleString(undefined, {
minimumFractionDigits: 0,
@@ -21,12 +19,23 @@ export function prettyScientificNumber(value: number): string {
return value > 0 ? "Infinity" : "-Infinity";
}
- return Math.trunc(value) === 0
- ? // No integer part, use scientific notation
- format(value, { notation: "auto", precision: 2 })
- : // Number has an integer part, format with 2 decimal places
- value.toLocaleString(undefined, {
- minimumFractionDigits: 0,
- maximumFractionDigits: 2,
- });
+ // Determine if the number should be in scientific notation
+ const absValue = Math.abs(value);
+ if (absValue < 1e-2 || absValue >= 1e6) {
+ return new Intl.NumberFormat(undefined, {
+ minimumFractionDigits: 1,
+ maximumFractionDigits: 1,
+ notation: "scientific",
+ })
+ .format(value)
+ .toLowerCase();
+ }
+
+ // Number has an integer part, format with 2 decimal places
+ const formatter = new Intl.NumberFormat(undefined, {
+ minimumFractionDigits: 0,
+ maximumFractionDigits: 2,
+ });
+
+ return formatter.format(value);
}