Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/548.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`reflex_xy`: unmounting a chart (conditional rendering, client navigation) now releases its view from the `window.__xy_views` registry; previously React's ref teardown left destroyed views behind.
22 changes: 19 additions & 3 deletions python/reflex_xy/assets/XYChart.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,16 @@ function xySocket() {

let nextMountId = 1;

// Drop a mount's `window.__xy_views` entry on unmount. The key is the one the
// mount captured when its effect ran (never a re-read of the DOM ref, which
// React has already cleared by cleanup time), and the entry is removed only
// while it still holds this mount's view, so a later mount reusing the same
// id is never evicted by an earlier mount's cleanup.
function releaseViewKey(key, view) {
const views = window.__xy_views;
if (views && view && views.get(key) === view) views.delete(key);
}

// Reflex owns the mount's CSS dimensions. Payload dimensions are useful for
// standalone exports, but inside a component they must follow that mount or a
// fixed payload can paint beyond the space Reflex reserved in the page flow.
Expand Down Expand Up @@ -396,6 +406,8 @@ export function XYChart(props) {
useEffect(() => {
const el = elRef.current;
if (!src || !el) return undefined;
// Registry key captured once per mount: React clears DOM refs before
// passive effect cleanup, so cleanup must not re-read outerRef.
const key = outerRef.current?.id || `src:${src}`;
let view = null;
let cancelled = false;
Expand Down Expand Up @@ -427,8 +439,8 @@ export function XYChart(props) {
controller.abort();
reclaimTooltipSlot();
if (view) view.destroy();
releaseViewKey(key, view);
view = null;
window.__xy_views?.delete(key);
el.removeEventListener("xy:view_change", handleViewChange);
el.replaceChildren();
};
Expand All @@ -441,6 +453,10 @@ export function XYChart(props) {
if (!liveToken || src || !el) return undefined;
const socket = xySocket();
const mid = `m${nextMountId++}`;
// Debug/e2e registry key, captured once for this live mount. React nulls
// DOM refs before passive effect cleanup, so re-reading outerRef there
// would fall back to `mid` and leak the id-keyed entry (issue #548).
const viewKey = outerRef.current?.id || mid;
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
let view = null;
let destroyed = false;
let clickSeq = 0;
Expand Down Expand Up @@ -821,7 +837,7 @@ export function XYChart(props) {
restoreSelectionMask(selectionMaskRequest);
// Debug/e2e handle (same spirit as the standalone example's
// window.xyLiveDrilldown): headless probes assert on live views.
(window.__xy_views ||= new Map()).set(outerRef.current?.id || mid, view);
(window.__xy_views ||= new Map()).set(viewKey, view);
replayPendingStatePushes(nextPayloadVersion);
};

Expand Down Expand Up @@ -1002,8 +1018,8 @@ export function XYChart(props) {
}
reclaimTooltipSlot();
if (view) view.destroy();
releaseViewKey(viewKey, view);
view = null;
window.__xy_views?.delete(outerRef.current?.id || mid);
el.replaceChildren();
};
}, [liveToken, src]);
Expand Down
69 changes: 57 additions & 12 deletions scripts/reflex_ws_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,24 +370,69 @@ def main() -> None:
# 6) §9 cond/foreach: toggling the split swaps the cond branch from
# the composed board to an rx.foreach grid of plan charts bound to
# a list[DataHandle] var — the board unmounts, three multiples
# mount and sub (net +2 views).
views_before = probe.eval("window.__xy_views.size")
probe.scroll_to("split-btn")
split = probe.eval(
"(() => { const b = document.getElementById('split-btn');"
" const r = b.getBoundingClientRect();"
" return {x: r.x + r.width / 2, y: r.y + r.height / 2}; })()"
# mount and sub (net +2 views). The unmounted board must leave
# the view registry (issue #548: React clears DOM refs before
# effect cleanup), so the counts are exact, both ways.
# Settle the baseline first: a chart registering late would
# otherwise shift the exact count after `views_before` is read.
# One in-page poll bounds the whole wait: it resolves once the
# size has been unchanged for settle_quiet_ms (1.5 seconds) and
# gives up after settle_limit_ms (30 seconds); the CDP call gets
# 5 seconds of slack beyond that, so a stalled page cannot hang it.
settle_quiet_ms = 1_500 # 1.5 seconds without a registry change
settle_limit_ms = 30_000 # 30 seconds maximum wait
views_before = probe.eval(
"new Promise((resolve) => {"
" const start = performance.now();"
" let size = window.__xy_views.size, since = start;"
" const tick = () => {"
" const now = performance.now(), next = window.__xy_views.size;"
" if (next !== size) { size = next; since = now; }"
f" if (now - since >= {settle_quiet_ms}) return resolve(size);"
f" if (now - start >= {settle_limit_ms}) return resolve(null);"
" setTimeout(tick, 250);" # poll every 250 milliseconds
" };"
" tick();"
"})",
timeout_s=settle_limit_ms / 1000 + 5.0,
)
probe.mouse("mouseMoved", split["x"], split["y"])
probe.mouse("mousePressed", split["x"], split["y"], button="left", buttons=1, clickCount=1)
probe.mouse("mouseReleased", split["x"], split["y"], button="left", buttons=0, clickCount=1)
if views_before is None:
raise SystemExit("timeout waiting for the view registry to settle")
assert probe.eval("window.__xy_views.has('board')"), "board view not mounted"

def click_split() -> None:
probe.scroll_to("split-btn")
split = probe.eval(
"(() => { const b = document.getElementById('split-btn');"
" const r = b.getBoundingClientRect();"
" return {x: r.x + r.width / 2, y: r.y + r.height / 2}; })()"
)
probe.mouse("mouseMoved", split["x"], split["y"])
probe.mouse(
"mousePressed", split["x"], split["y"], button="left", buttons=1, clickCount=1
)
probe.mouse(
"mouseReleased", split["x"], split["y"], button="left", buttons=0, clickCount=1
)

click_split()
probe.wait_for(
f"window.__xy_views.size >= {views_before} + 2",
f"window.__xy_views.size === {views_before} + 2"
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
" && !document.getElementById('board') && !window.__xy_views.has('board')",
timeout_s=30.0,
label="foreach small multiples mounting after the cond toggle",
label="small multiples mounted and the board view released after the cond toggle",
)
views_after = probe.eval("window.__xy_views.size")
print(f"cond/foreach: {views_before} -> {views_after} mounted views after split toggle")
click_split()
probe.wait_for(
f"window.__xy_views.size === {views_before}"
" && window.__xy_views.has('board')"
" && Array.from(window.__xy_views.values()).every((v) => !v._destroyed)",
timeout_s=30.0,
label="board remounted and the small multiples released after toggling back",
)
print(f"cond/foreach: back to {views_before} mounted views after toggling back")

# 7) /kinds: every chart kind renders in the browser — 20 data-bound
# plan charts plus the 7 static composites. Each `kind-<name>`
Expand Down
18 changes: 18 additions & 0 deletions spec/design/reflex-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,24 @@ chart during an app-managed disconnect cannot reopen the transport early.
real Socket.IO peers for both creation orders, warm/open/legacy managers,
binary payload dispatch, repeated mounts, cleanup, and app-owned reconnects.

**Unmount releases the view.** Each mount registers its view in the
`window.__xy_views` debug/e2e registry under the element `id`, falling back to
the live mount id (`m<n>`) or `src:<url>` for anonymous mounts. The key is
captured once when the mount's effect runs and reused verbatim at cleanup:
React detaches DOM refs (object refs nulled, callback refs called with `null`)
*before* passive effect cleanup, so re-reading the wrapper ref at teardown
would fall back to the mount id and leave the destroyed, id-keyed view behind
(issue #548). Cleanup deletes the entry only while it still holds that
mount's view, so a newer mount reusing the id is never evicted. The socket
gate detaches every ref before running cleanup — matching React's order — and
asserts the registry is empty after the last unmount, for named and
anonymous live mounts (the shared app transport stays connected after they
unmount) and for static `src` mounts (which never open the data plane); a
same-key case pins that an older mount's
cleanup leaves the newer view registered. The browser smoke settles the
registry before the cond toggle, then requires exact counts both ways with the
board released.

Reflex owns reconnection: its `reconnect()` reopens the shared manager, our
namespace socket re-CONNECTs automatically, and every mounted chart re-`sub`s
on the `connect` event.
Expand Down
102 changes: 100 additions & 2 deletions tests/reflex_socket_connection.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ function loadWrapper(endpoint) {
}
destroy() { this.destroyed = true; }
}
// Refs attached during the latest render, detached before cleanup the way
// React commits a deletion: DOM refs are cleared (callback refs called with
// null, object refs nulled) before passive effect cleanups run.
let attachedRefs = [];
function jsx(tag, props, ...children) {
const el = {
id: props.id,
Expand All @@ -44,27 +48,48 @@ function loadWrapper(endpoint) {
};
if (typeof props.ref === "function") props.ref(el);
else if (props.ref) props.ref.current = el;
if (props.ref) attachedRefs.push(props.ref);
return el;
}
// Static (`src`) mode: a fetched payload asset rendered kernel-less.
const fetchStub = async () => ({ ok: true, arrayBuffer: async () => new ArrayBuffer(0) });
const decodeFrame = () => ({ message: { traces: [] }, buffers: [null] });
const renderStandalone = (el, spec, blob) => new ChartView(el, spec, blob);
const factory = new Function(
"io", "env", "reflexEnvironment", "getBackendURL", "getToken",
"useEffect", "useRef", "useState", "jsx", "ChartView", "window",
"fetch", "decodeFrame", "renderStandalone",
`${wrapper}\nreturn {XYChart, xySocket, getSocket: () => sharedSocket};`,
);
const loaded = factory(
io, { EVENT: endpoint, TRANSPORT: "websocket" }, { version: "test" },
(url) => new URL(url), () => "session-token",
(callback) => effects.push(callback), (current) => ({ current }),
(value) => [value, () => {}], jsx, ChartView, windows,
fetchStub, decodeFrame, renderStandalone,
);
return {
...loaded,
renders,
windows,
mount(id, props = { figure: { token: "figure-token" } }) {
effects = [];
loaded.XYChart({ id, ...props });
attachedRefs = [];
const mountProps = id === undefined ? { ...props } : { id, ...props };
// Reflex attaches its own object ref to id-bearing components.
const externalRef = { current: null };
if (id !== undefined) mountProps.ref = externalRef;
loaded.XYChart(mountProps);
const refs = attachedRefs;
const cleanups = effects.map((effect) => effect()).filter(Boolean);
return () => cleanups.reverse().forEach((cleanup) => cleanup());
return () => {
refs.forEach((ref) => {
if (typeof ref === "function") ref(null);
else ref.current = null;
});
assert.equal(externalRef.current, null, "external object ref detached");
cleanups.reverse().forEach((cleanup) => cleanup());
};
},
};
}
Expand Down Expand Up @@ -142,13 +167,17 @@ for (const order of ["warm-manager", "open-warm-manager", "legacy-auto-connect",
assert.equal(namespaceConnections, 2);
assert.equal(subs.length, 5);
assert.equal(socket.io, app.io);
assert.deepEqual([...loaded.windows.__xy_views.keys()].sort(), ["during-pause", "one", "two"]);

mounts.pop()();
mounts.pop()();
await delay(30);
assert.equal(unsubs.length, 0, "same-token mounts retain the shared room");
assert.deepEqual([...loaded.windows.__xy_views.keys()], ["one"],
"unmounted views leave the registry even after React cleared the DOM ref");
mounts.pop()();
await until(() => unsubs.length === 1, "last mount unsubscribes");
assert.equal(loaded.windows.__xy_views.size, 0, "last unmount empties the view registry");
assert.equal(app.connected, true, "chart cleanup leaves the app transport alive");
assert.equal(socket.connected, true);
} finally {
Expand All @@ -160,6 +189,75 @@ for (const order of ["warm-manager", "open-warm-manager", "legacy-auto-connect",
});
}

test("anonymous mounts register and release their view by mount id", async () => {
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
const http = createServer();
const server = new Server(http, { path: "/_event", transports: ["websocket"] });
server.of("/_event");
server.of("/_xy").on("connection", (socket) => {
socket.on("sub", (request) => socket.emit("payload", {
...request, version: 1, spec: { traces: [] },
buffers: [Buffer.from(new Float32Array([1]).buffer)],
}));
});
await new Promise((resolve) => http.listen(0, "127.0.0.1", resolve));
const origin = `http://127.0.0.1:${http.address().port}`;
const loaded = loadWrapper(`${origin}/_event`);
const app = io(`${origin}/_event`, {
path: "/_event", transports: ["websocket"], protocols: ["test"],
query: { token: "session-token" }, reconnection: false, autoConnect: false,
});
const mounts = [];
try {
mounts.push(loaded.mount(undefined), loaded.mount("named"));
app.connect();
await until(() => loaded.renders.length === 2, "both mounts rendered");
const keys = [...loaded.windows.__xy_views.keys()];
assert.equal(keys.length, 2);
assert.ok(keys.includes("named"));
assert.match(keys.find((key) => key !== "named"), /^m\d+$/);
mounts.shift()();
assert.deepEqual([...loaded.windows.__xy_views.keys()], ["named"]);
mounts.shift()();
assert.equal(loaded.windows.__xy_views.size, 0);
Comment thread
FarhanAliRaza marked this conversation as resolved.
Resolved
assert.ok(loaded.renders.every((view) => view.destroyed), "every view destroyed");
assert.equal(app.connected, true, "chart cleanup leaves the app transport alive");
} finally {
mounts.forEach((cleanup) => cleanup());
loaded.getSocket()?.disconnect();
app.disconnect();
await new Promise((resolve) => server.close(resolve));
}
});

test("static src mounts release their view after React clears the DOM ref", async () => {
const loaded = loadWrapper("http://127.0.0.1:1/_event");
const named = loaded.mount("static-named", { src: "/payload.xybf" });
const anonymous = loaded.mount(undefined, { src: "/other.xybf" });
await until(() => loaded.renders.length === 2, "static payloads rendered");
assert.deepEqual([...loaded.windows.__xy_views.keys()].sort(),
["src:/other.xybf", "static-named"]);
named();
assert.deepEqual([...loaded.windows.__xy_views.keys()], ["src:/other.xybf"]);
anonymous();
assert.equal(loaded.windows.__xy_views.size, 0);
assert.ok(loaded.renders.every((view) => view.destroyed), "every view destroyed");
assert.equal(loaded.getSocket(), null, "static mounts never open the data plane");
});

test("an older mount's cleanup never evicts a newer view under the same key", async () => {
const loaded = loadWrapper("http://127.0.0.1:1/_event");
const older = loaded.mount("shared", { src: "/old.xybf" });
await until(() => loaded.renders.length === 1, "older view rendered");
const newer = loaded.mount("shared", { src: "/new.xybf" });
await until(() => loaded.renders.length === 2, "newer view rendered");
assert.equal(loaded.windows.__xy_views.get("shared"), loaded.renders[1]);
older();
assert.equal(loaded.windows.__xy_views.get("shared"), loaded.renders[1],
"the newer view stays registered after the older mount unmounts");
newer();
assert.equal(loaded.windows.__xy_views.size, 0);
});

test("an unhydrated figure never creates a socket", () => {
const loaded = loadWrapper("http://127.0.0.1:1/_event");
const unmount = loaded.mount("empty", { figure: { token: "" } });
Expand Down
Loading