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: remeasure container-width Vega charts when host gains size (#10266)

Shahmir Varqhaf41d52cdd938
diff --git a/frontend/src/components/charts/lazy.tsx b/frontend/src/components/charts/lazy.tsx
index f2dd30fdb9..8adb1f8581 100644
--- a/frontend/src/components/charts/lazy.tsx
+++ b/frontend/src/components/charts/lazy.tsx
@@ -3,5 +3,7 @@
import React from "react";
export const LazyVegaEmbed = React.lazy(() =>
- import("react-vega").then((m) => ({ default: m.VegaEmbed })),
+ import("./vega-embed-container").then((m) => ({
+ default: m.VegaEmbedContainer,
+ })),
);
diff --git a/frontend/src/components/charts/vega-embed-container.tsx b/frontend/src/components/charts/vega-embed-container.tsx
new file mode 100644
index 0000000000..74ef2be6e6
--- /dev/null
+++ b/frontend/src/components/charts/vega-embed-container.tsx
@@ -0,0 +1,18 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useRef } from "react";
+import type { VegaEmbedProps } from "react-vega";
+import { VegaEmbed } from "react-vega";
+import { useVegaContainerRemeasure } from "@/plugins/impl/vega/use-vega-container-remeasure";
+import { getContainerWidth } from "@/plugins/impl/vega/utils";
+
+/**
+ * VegaEmbed that remeasures width:"container" charts when their host gains size
+ * (e.g. after a display:none parent becomes visible).
+ */
+export function VegaEmbedContainer(props: VegaEmbedProps) {
+ const ref = useRef<HTMLDivElement>(null);
+ const enabled = getContainerWidth(props.spec) === "container";
+ useVegaContainerRemeasure(ref, enabled);
+ return <VegaEmbed ref={ref} {...props} />;
+}
diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsx
index cccf4fe46f..f76480c34e 100644
--- a/frontend/src/components/slides/reveal-component.tsx
+++ b/frontend/src/components/slides/reveal-component.tsx
@@ -127,18 +127,6 @@ function useSlideDimensions(ref: React.RefObject<HTMLDivElement | null>) {
return dims;
}
-/**
- * Trigger a resize event on the window
- * Vega elements need to be re-measured when the container width changes.
- */
-function triggerResize(deck: RevealApi | null) {
- if (deck?.getCurrentSlide()?.querySelector(".vega-embed, marimo-vega")) {
- requestAnimationFrame(() => {
- window.dispatchEvent(new Event("resize"));
- });
- }
-}
-
// The speaker view renders this via innerHTML with `white-space: normal`, so
// we materialize `\n` as `<br>` and a lone `---` line as `<hr>`.
const NotesAside = ({ text }: { text: string }) => {
@@ -688,7 +676,6 @@ const RevealSlidesComponent = ({
const handleSlideChange = useEvent(() => {
reportCurrentCell();
- triggerResize(deckRef.current);
});
useEventListener(document, "keydown", handleParkedNavKey, { capture: true });
diff --git a/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts b/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts
new file mode 100644
index 0000000000..f7092d1813
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/__tests__/use-vega-container-remeasure.test.ts
@@ -0,0 +1,102 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useRef } from "react";
+import { useVegaContainerRemeasure } from "../use-vega-container-remeasure";
+
+describe("useVegaContainerRemeasure", () => {
+ let observers: FakeResizeObserver[];
+ let OriginalResizeObserver: typeof ResizeObserver;
+
+ class FakeResizeObserver {
+ callback: ResizeObserverCallback;
+ el: Element | null = null;
+
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ observers.push(this);
+ }
+
+ observe(el: Element) {
+ this.el = el;
+ }
+
+ disconnect() {
+ this.el = null;
+ }
+
+ unobserve() {
+ this.el = null;
+ }
+
+ trigger(width: number) {
+ this.callback(
+ [
+ {
+ target: this.el!,
+ contentRect: {
+ width,
+ height: 100,
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ bottom: 100,
+ right: width,
+ toJSON: () => ({}),
+ },
+ borderBoxSize: [],
+ contentBoxSize: [],
+ devicePixelContentBoxSize: [],
+ } satisfies ResizeObserverEntry,
+ ],
+ this,
+ );
+ }
+ }
+
+ beforeEach(() => {
+ observers = [];
+ OriginalResizeObserver = globalThis.ResizeObserver;
+ globalThis.ResizeObserver =
+ FakeResizeObserver as unknown as typeof ResizeObserver;
+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {
+ cb(0);
+ return 0;
+ });
+ });
+
+ afterEach(() => {
+ globalThis.ResizeObserver = OriginalResizeObserver;
+ vi.unstubAllGlobals();
+ });
+
+ it("dispatches window resize when the container gains width", () => {
+ const el = document.createElement("div");
+ Object.defineProperty(el, "clientWidth", { value: 0, configurable: true });
+ const dispatchSpy = vi.spyOn(window, "dispatchEvent");
+
+ renderHook(() => {
+ const ref = useRef<HTMLDivElement>(el);
+ useVegaContainerRemeasure(ref, true);
+ });
+
+ expect(observers).toHaveLength(1);
+ observers[0].trigger(0);
+ expect(dispatchSpy).not.toHaveBeenCalled();
+
+ observers[0].trigger(640);
+ expect(dispatchSpy).toHaveBeenCalledWith(expect.any(Event));
+ expect(dispatchSpy.mock.calls[0][0].type).toBe("resize");
+ });
+
+ it("is a no-op when disabled", () => {
+ const el = document.createElement("div");
+ renderHook(() => {
+ const ref = useRef<HTMLDivElement>(el);
+ useVegaContainerRemeasure(ref, false);
+ });
+ expect(observers).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/plugins/impl/vega/use-vega-container-remeasure.ts b/frontend/src/plugins/impl/vega/use-vega-container-remeasure.ts
new file mode 100644
index 0000000000..db89645b70
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/use-vega-container-remeasure.ts
@@ -0,0 +1,39 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { type RefObject, useEffect } from "react";
+
+/**
+ * Vega-Lite's width:"container" only remeasures on window.resize — not when a
+ * parent goes from display:none / zero-size to a real layout size. Observe the
+ * embed host and dispatch the event Vega already listens for when the container
+ * gains a positive width.
+ */
+export function useVegaContainerRemeasure(
+ ref: RefObject<HTMLElement | null>,
+ enabled: boolean,
+): void {
+ useEffect(() => {
+ const el = ref.current;
+ if (!el || !enabled || typeof ResizeObserver === "undefined") {
+ return;
+ }
+
+ let lastWidth = el.clientWidth;
+ const observer = new ResizeObserver((entries) => {
+ const width = entries[0]?.contentRect.width ?? 0;
+ if (width <= 0) {
+ lastWidth = 0;
+ return;
+ }
+ if (Math.round(width) === Math.round(lastWidth)) {
+ return;
+ }
+ lastWidth = width;
+ requestAnimationFrame(() => {
+ window.dispatchEvent(new Event("resize"));
+ });
+ });
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [ref, enabled]);
+}
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index a7eb025798..a9049df826 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -27,6 +27,7 @@ import { makeSelectable } from "./make-selectable";
import { getSelectionParamNames, ParamNames } from "./params";
import { resolveVegaSpecData } from "./resolve-data";
import type { VegaLiteSpec } from "./types";
+import { useVegaContainerRemeasure } from "./use-vega-container-remeasure";
import { getContainerWidth } from "./utils";
// register arrow reader under type 'arrow'
@@ -276,6 +277,9 @@ const LoadedVegaComponent = ({
onEmbed: handleNewView,
});
+ const containerWidth = getContainerWidth(selectableSpec);
+ useVegaContainerRemeasure(vegaRef, containerWidth === "container");
+
useEffect(() => {
signalListeners.forEach(({ signalName, handler }) => {
// Existing bug. TODO: Some signal listeners are invalid
@@ -310,10 +314,7 @@ const LoadedVegaComponent = ({
// Capture the pointer down event to prevent the parent from handling it
onPointerDown={Events.stopPropagation()}
>
- <div
- ref={vegaRef}
- data-container-width={getContainerWidth(selectableSpec)}
- />
+ <div ref={vegaRef} data-container-width={containerWidth} />
{renderHelpContent()}
</div>
</>