Skip to content

Commit d65b7e6

Browse files
committed
feat(core): onNodesChange / onEdgesChange, Svelte Flow 2's change filters
- New props: the flow's own writes arrive as a NodeChangeset / EdgeChangeset (@xyflow/system 1.0) before they land; the callback drops or adds changes and the flow applies what is left. Covered: drag + arrow-key positions, selection (click, box, keyboard), measured dimensions, NodeResizer (resizing true/false, setAttributes), deletions, uncontrolled connections, reconnects, and addNodes / addEdges / updateNode / updateNodeData / updateEdge / changeParent / deleteElements. Not: setNodes / setEdges and the user's own writes. - core/changes.ts: one queue per axis. Writers check active() once per call; unset they run today's code unchanged. Gestures + measurement queue() (one changeset per task, microtask flush, as Svelte Flow 2; user picked batching); commands deliver() at once (keeps optimistic actions atomic); the selection writers flush the queue before Solid's flush() (XYDrag reads selection back in the same event). - commands/applyChanges.ts applies the changeset through the existing raw writers (writeNodePositions, writeNode/writeEdge, writeSelectionDelta, writeNodeChanges, row inserts/removals), not applyTo's new array: leaf writes, sidecars and optimistic stores behave as without the callback. Adds first, removes last; a position change without `dragging` is a plain field write. - updateNode/updateEdge describe Svelte's split (position / data / select / update with only the keys that differ); updateNodeData is a `data` change; selection follows updateNode's pass-through rule. - Exports NodeChangeset, EdgeChangeset and the change types (React Flow 13's set). Playground example NodeChanges; README section, CHANGELOG 1.0.0 entry (unpublished, edited in place), llms.txt, ARCHITECTURE. - Tests first: core changeCallbacks.test.ts (11, all failing before), e2e node-changes.spec.ts (locked drag, kept delete, resize capped at 200). Gate: 611 unit, 19 SSR, 5 + 6 hydration, 97 e2e. Bench A/B (unset path) vs bfabf7f pending: machine on battery; arms .agent/tools/wt/nc-{base,new}, runner .agent/bench/runs/nc/run.sh.
1 parent bfabf7f commit d65b7e6

21 files changed

Lines changed: 1117 additions & 57 deletions

‎CHANGELOG.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,10 @@
4747

4848
- New stylesheet `@dschz/solid-flow/xy-theme.css` (and `./dist/xy-theme.css`): the xyflow theme React Flow 13 and Svelte Flow 2 ship under the same name, over `base.css`. Every node, custom types included, is rounded and centered with a soft shadow and an accent border when selected; handles are outlined and highlight where a connection can start or end; the canvas is tinted; group nodes and NodeResizer handles are themed. Its `--xy-theme-*` variables match upstream's; the accent, `--xy-theme-primary`, is Solid Flow's `#446b9e` (selected `#518ac8`). Import it instead of `style.css`.
4949

50+
- `onNodesChange` / `onEdgesChange`, as Svelte Flow 2's `onnodeschange` / `onedgeschange`: the flow's own writes (drags and arrow-key moves, selection, measured and resized sizes, deletions, new connections on an uncontrolled edges axis, reconnects, and the commands `addNodes`, `addEdges`, `updateNode`, `updateNodeData`, `updateEdge`, `changeParent`, `deleteElements`) arrive as a `NodeChangeset` / `EdgeChangeset` before they land; drop changes or add your own, and the flow applies what is left through its usual per-row writes. Gesture and measurement writes are batched per task; commands and click selection deliver at once. Unset, writes land directly as before. `NodeChangeset`, `EdgeChangeset` and the change types (`NodeChange`, `EdgeChange`, `PositionChange`, `SelectionChange`, …) are exported. See "Intercepting the flow's writes" in the README.
51+
5052
- 486f358: Declare `autoPanSpeed`, `panOnScrollSpeed`, and `ariaLiveMessage` as proper `SolidFlowProps`. The flow already consumed all three, but they were never on the public type, so passing them was a type error.
51-
- 2e1cd74: Event-callback parity with React Flow: `onNodeDoubleClick`, `onEdgeDoubleClick`, `onEdgePointerMove`, `onPaneScroll`, `onPanePointerEnter` / `onPanePointerMove` / `onPanePointerLeave`, and `onViewportChange` (fires on every viewport change, programmatic ones included). The event surface now covers everything Svelte Flow exposes plus the React Flow set, except `onNodesChange`/`onEdgesChange`, which don't exist by design in a store-based flow.
53+
- 2e1cd74: Event-callback parity with React Flow: `onNodeDoubleClick`, `onEdgeDoubleClick`, `onEdgePointerMove`, `onPaneScroll`, `onPanePointerEnter` / `onPanePointerMove` / `onPanePointerLeave`, and `onViewportChange` (fires on every viewport change, programmatic ones included). The event surface now covers everything Svelte Flow exposes plus the React Flow set.
5254
- b2c1b44: `useSolidFlow()` returns `{ flow, commands }`. `flow` (`FlowState`) is the canonical read surface: the graph roots, the `internalNodes` and `connections` records, `selection`, viewport, interaction and config state; every property read in a tracked scope is a live subscription. `commands` (`FlowCommands`) is the write surface, and every command is also spread onto the returned object for upstream familiarity, so `const { fitView } = useSolidFlow()` keeps working. New commands: `setNodes`, `setEdges`, `panBy` and `updateNodeInternals`. `FlowState`, `FlowSelection`, `FlowCommands`, `ConnectionsRecord` and `connectionKey` are exported from the package entrypoint.
5355

5456
Breaking: the imperative getters are removed (`getNode`, `getNodes`, `getEdge`, `getEdges`, `getViewport`, `getZoom`, `getInternalNode`, `getHandleConnections`). Read the same state from `flow` instead (`flow.nodes`, `flow.internalNodes[id]`, `flow.viewport`, `flow.connections`), or use the new `getNodeConnections` command; in Solid, reads inside event handlers are already untracked, so no getter wrapper is needed. The per-edge geometry the renderers draw is internal, as in React Flow and Svelte Flow: a custom edge receives its geometry as props (`sourceX`, `targetY`, …). `useNodes()` and `useEdges()` return `readonly` arrays: mutate through commands, not array methods.

‎README.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,28 @@ The stores you pass as `nodes` / `edges` props are **controlled** — a delibera
193193

194194
**Prefer letting the flow own the data?** Pass `defaultNodes` / `defaultEdges` instead of `nodes` / `edges` for an **uncontrolled** flow (React Flow parity): the arrays seed the flow once (rows are copied, so the flow's draft never writes onto your objects; later values are ignored), and membership belongs to the flow — commands like `addNodes` and completed connections persist with no adoption step. Read live state through `useSolidFlow()`'s `flow.nodes` / `flow.edges`. The two axes are independent, so you can control edges while leaving nodes uncontrolled (or vice versa); supplying both props on one axis is a mistake (`nodes` wins, with a dev warning).
195195

196+
### Intercepting the flow's writes (`onNodesChange`)
197+
198+
The flow's own writes can pass through you first, as Svelte Flow 2's `onnodeschange` / `onedgeschange`: with `onNodesChange` / `onEdgesChange` set, each write arrives as a `NodeChangeset` / `EdgeChangeset` (@xyflow/system 1.0, the type React Flow 13 hands its `onNodesChange`). Drop changes or add your own, and the flow applies what is left through its usual per-row writes:
199+
200+
```tsx
201+
import { type NodeChangeset, SolidFlow } from "@dschz/solid-flow";
202+
203+
const onNodesChange = (changes: NodeChangeset) => {
204+
// "locked" never moves
205+
for (const change of changes.getForNode("locked")) {
206+
if (change.type === "position") changes.remove(change);
207+
}
208+
};
209+
210+
<SolidFlow nodes={nodes} edges={edges} onNodesChange={onNodesChange} />;
211+
```
212+
213+
- **What passes through:** drags and arrow-key moves (`position`), selection (`select`), measured and resized sizes (`dimensions`), deletions (`remove`), new connections on an uncontrolled edges axis and reconnects, and the commands `addNodes` / `addEdges`, `updateNode` / `updateNodeData` / `updateEdge`, `changeParent` and `deleteElements`. `setNodes` / `setEdges` and your own store writes do not; they are already yours.
214+
- **When:** gesture and measurement writes are batched into one changeset per task, applied right after your callback. Commands deliver at once (so they stay inside an optimistic action), and so does a click's selection, which a drag reads back in the same event.
215+
- **Unset, nothing changes:** the writes land directly, exactly as without the prop.
216+
- `onDelete`, `onNodesDelete` and `onEdgesDelete` still report the deletion `onBeforeDelete` allowed; dropping a `remove` change keeps the element after them.
217+
196218
## Loading your graph from an API
197219

198220
Both stores accept an async seed — pass `async () => data` instead of an array. No memo, no lifecycle juggling: reads are not-ready until the data lands (SolidJS 2.0's async model), so a `<Loading>` boundary holds the flow and swaps in the graph when it arrives. Afterwards the stores behave exactly like their array-seeded counterparts — drafts, adoption, wholesale replacement.
@@ -352,6 +374,7 @@ const edgeId = useEdgeId();
352374
Some React Flow hooks intentionally have no Solid Flow equivalent, because Solid's fine-grained reactivity makes them unnecessary:
353375

354376
- `useOnViewportChange` — reading `flow.viewport` in a tracked scope IS the subscription; wrap side effects in `createEffect` over that read.
377+
- `applyNodeChanges` / `applyEdgeChanges` — `onNodesChange` / `onEdgesChange` hand you the changeset before the flow applies it; there is nothing for you to apply (see [Intercepting the flow's writes](#intercepting-the-flows-writes-onnodeschange)).
355378
- `useNodesState` / `useEdgesState` — use `createNodeStore` / `createEdgeStore` instead.
356379
- `useStore` — the reactive `flow` struct is the supported read surface; there is no public escape hatch into internals.
357380

‎docs/ARCHITECTURE.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ Four rules keep the graph correct under 2.0's async model:
7474

7575
Async seeds and async generators need no special machinery: `createStore` accepts them natively, so `createNodeStore(async () => …)` and live streams are the same code path as arrays.
7676

77+
## onNodesChange / onEdgesChange (`core/changes.ts`)
78+
79+
Every flow-initiated write has one writer: drag and arrow-key positions (`updateNodePositions`), the selection writers, the measuring pass's write-back (`applyNodeChanges`), the connection writer (`addEdge`), NodeResizeControl, and the node/edge commands. Each asks its axis's queue `active()` once per call: unset, it writes exactly as before (the zero-cost contract); set, it describes the write as `NodeChange` / `EdgeChange` records instead. Gesture and measurement writes `queue()` them into one changeset per task (a microtask flush, as Svelte Flow 2's); commands `deliver()` at once, so a command inside an optimistic action stays in the action; and the selection writers `flush()` the queue before Solid's `flush()`, because XYDrag reads selection back in the same event. The callback runs untracked, then `commands/applyChanges.ts` writes what is left through the same raw writers (`writeNodePositions`, `writeNode`, `writeSelectionDelta`, `writeNodeChanges`, the row inserts and removals) rather than `applyTo`'s new array, so per-row leaf writes, the sidecars and optimistic stores behave as they do without the callback. Additions apply first, removals last.
80+
7781
## Rendering and performance
7882

7983
### The trade, stated once

‎e2e/node-changes.spec.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { centerOf, drag, expect, getViewport, gotoExample, nodeById, test } from "./helpers";
2+
3+
// onNodesChange in a real browser: XYDrag's position writes, click
4+
// selection and keyboard deletion pass through the callback, which drops
5+
// some of them (playground/examples/node-changes).
6+
test.describe("onNodesChange", () => {
7+
test("a dropped position change keeps the node in place; the others move", async ({ page }) => {
8+
await gotoExample(page, "NodeChanges");
9+
const locked = nodeById(page, "locked");
10+
const free = nodeById(page, "free");
11+
12+
const lockedBefore = await centerOf(locked);
13+
await drag(page, lockedBefore, { x: lockedBefore.x + 80, y: lockedBefore.y + 60 });
14+
expect(await centerOf(locked)).toEqual(lockedBefore);
15+
// the click that started the drag selected it: select changes passed
16+
await expect(locked).toHaveClass(/\bselected\b/);
17+
18+
const freeBefore = await centerOf(free);
19+
await drag(page, freeBefore, { x: freeBefore.x + 80, y: freeBefore.y + 60 });
20+
const freeAfter = await centerOf(free);
21+
expect(freeAfter.x - freeBefore.x).toBeGreaterThan(60);
22+
expect(freeAfter.y - freeBefore.y).toBeGreaterThan(40);
23+
await expect(page.getByTestId("last-changes")).toHaveText("position");
24+
});
25+
26+
test("a dropped remove change keeps the node through a keyboard delete", async ({ page }) => {
27+
await gotoExample(page, "NodeChanges");
28+
const kept = nodeById(page, "kept");
29+
await kept.click();
30+
await page.keyboard.press("Backspace");
31+
await expect(page.getByTestId("last-changes")).toHaveText("remove");
32+
await expect(kept).toBeVisible();
33+
34+
await nodeById(page, "free").click();
35+
await page.keyboard.press("Backspace");
36+
await expect(nodeById(page, "free")).toHaveCount(0);
37+
});
38+
39+
test("NodeResizer sizes pass through it; a dropped one keeps the size", async ({ page }) => {
40+
await gotoExample(page, "NodeChanges");
41+
const { zoom } = await getViewport(page);
42+
const box = nodeById(page, "box");
43+
await box.click();
44+
const before = (await box.boundingBox())!;
45+
const handle = box.locator(".solid-flow__resize-control.handle.bottom.right");
46+
const corner = await centerOf(handle);
47+
48+
// a small resize lands (flow width stays under 200)
49+
await drag(page, corner, { x: corner.x + 15, y: corner.y + 10 });
50+
await expect(page.getByTestId("last-changes")).toHaveText("dimensions");
51+
const grown = (await box.boundingBox())!;
52+
expect(grown.width).toBeGreaterThan(before.width + 5);
53+
54+
// every frame past 200 flow units wide is dropped: the box stops there
55+
const corner2 = await centerOf(handle);
56+
await drag(page, corner2, { x: corner2.x + 400, y: corner2.y });
57+
const after = (await box.boundingBox())!;
58+
expect(after.width).toBeGreaterThan(grown.width);
59+
expect(after.width / zoom).toBeLessThanOrEqual(201);
60+
});
61+
});

‎llms.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import "@dschz/solid-flow/style.css"; // required, import once (base.css: minima
1111

1212
## Unlearn these (React Flow priors that are WRONG here)
1313

14-
- NO `onNodesChange` / `onEdgesChange` / `applyNodeChanges` / `applyEdgeChanges` — state is store-based; mutate your store.
14+
- NO `applyNodeChanges` / `applyEdgeChanges` and no state ownership in `onNodesChange` — state is store-based; mutate your store. `onNodesChange` / `onEdgesChange` exist as Svelte Flow 2's filters: they receive the flow's own pending writes as a `NodeChangeset` / `EdgeChangeset` (drop or add changes) and the flow applies what is left; leave them unset unless you need to veto or rewrite flow writes.
1515
- NO `useReactFlow` — it is `useSolidFlow()`, called INSIDE `<SolidFlow>` (or under `<SolidFlowProvider>`).
1616
- Events are pointer-named: `onNodePointerEnter`, not `onNodeMouseEnter` (same for edges/pane).
1717
- NO `colorMode` / `colorModeSSR` / `useColorMode` — the flow follows the OS in CSS; `forceColorMode="light" | "dark"` forces one. Theme with `--xy-*` variables (set `--xy-node-background-color`, not the `-default` one); library CSS is in the `xyflow` cascade layer, so plain app rules override it.

‎playground/constants.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
LiveFlow,
1818
Intersections,
1919
MovingHandles,
20+
NodeChanges,
2021
NodeResizer,
2122
NodeToolbar,
2223
Overview,
@@ -56,6 +57,7 @@ export const SolidFlowExamplesMap = {
5657
LiveFlow,
5758
Intersections,
5859
MovingHandles,
60+
NodeChanges,
5961
NodeResizer,
6062
NodeToolbar,
6163
Overview,

‎playground/examples/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export { Interaction } from "./interaction/page";
1515
export { InteractiveMinimap } from "./interactive-minimap/page";
1616
export { Intersections } from "./intersections/page";
1717
export { MovingHandles } from "./moving-handles/page";
18+
export { NodeChanges } from "./node-changes/page";
1819
export { NodeResizer } from "./node-resizer/page";
1920
export { NodeToolbar } from "./node-toolbar/page";
2021
export { LiveFlow } from "./liveflow/page";
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { createSignal } from "solid-js";
2+
3+
import {
4+
Background,
5+
createEdgeStore,
6+
createNodeStore,
7+
type NodeChangeset,
8+
type NodeProps,
9+
NodeResizer,
10+
Panel,
11+
SolidFlow,
12+
} from "@/index";
13+
14+
const ResizableNode = (props: NodeProps<{ label: string }>) => (
15+
<>
16+
<NodeResizer visible={!!props.selected} />
17+
<div>{props.data.label}</div>
18+
</>
19+
);
20+
21+
const nodeTypes = { resizable: ResizableNode };
22+
23+
// onNodesChange as a filter: the flow's own writes arrive as a changeset
24+
// before they land. "Locked" never moves, "Kept" cannot be deleted, "Box"
25+
// cannot grow wider than 200, and the panel lists the change types of the
26+
// last changeset. e2e/node-changes.spec.ts drives it.
27+
export const NodeChanges = () => {
28+
const [nodes] = createNodeStore<typeof nodeTypes>([
29+
{ id: "locked", type: "default", data: { label: "Locked" }, position: { x: 0, y: 0 } },
30+
{ id: "free", type: "default", data: { label: "Free" }, position: { x: 250, y: 0 } },
31+
{ id: "kept", type: "default", data: { label: "Kept" }, position: { x: 125, y: 150 } },
32+
{
33+
id: "box",
34+
type: "resizable",
35+
data: { label: "Box" },
36+
position: { x: 300, y: 150 },
37+
width: 120,
38+
height: 60,
39+
style: { border: "1px solid #222" },
40+
},
41+
]);
42+
const [edges] = createEdgeStore([{ id: "free-kept", source: "free", target: "kept" }]);
43+
const [lastTypes, setLastTypes] = createSignal("");
44+
45+
const onNodesChange = (changes: NodeChangeset) => {
46+
setLastTypes([...new Set(changes.toArray().map((change) => change.type))].join(","));
47+
for (const change of changes.getForNode("locked")) {
48+
if (change.type === "position") changes.remove(change);
49+
}
50+
for (const change of changes.getForNode("kept")) {
51+
if (change.type === "remove") changes.remove(change);
52+
}
53+
for (const change of changes.getForNode("box")) {
54+
if (change.type === "dimensions" && (change.dimensions?.width ?? 0) > 200) {
55+
changes.removeForNode("box");
56+
break;
57+
}
58+
}
59+
};
60+
61+
return (
62+
<SolidFlow
63+
nodes={nodes}
64+
edges={edges}
65+
nodeTypes={nodeTypes}
66+
onNodesChange={onNodesChange}
67+
fitView
68+
>
69+
<Background />
70+
<Panel position="top-left">
71+
<span data-testid="last-changes">{lastTypes()}</span>
72+
</Panel>
73+
</SolidFlow>
74+
);
75+
};

‎src/__tests__/publicSurface.test.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ const PUBLIC_RUNTIME_EXPORTS = [
1515
"ConnectionMode",
1616
"ControlButton",
1717
"Controls",
18+
"EdgeChangeset",
1819
"EdgeLabel",
1920
"EdgeLabelRenderer",
2021
"EdgeReconnectAnchor",
@@ -23,6 +24,7 @@ const PUBLIC_RUNTIME_EXPORTS = [
2324
"MarkerType",
2425
"MiniMap",
2526
"MiniMapNode",
27+
"NodeChangeset",
2628
"NodeResizeControl",
2729
"NodeResizer",
2830
"NodeToolbar",

0 commit comments

Comments
 (0)