Repository navigation
diagram: shrink the imperative shell — controller extraction, pure interaction cores, render purity - #721
Conversation
The nine simple edit handlers (rename, sim-spec change, equation/table change, the four module handlers, and the create/duplicate-model handlers) all shared an identical tail: apply a patch with allowErrors, log+surface any failure, then round-trip the serialized project and schedule a sim run. Collapse that into one `applyPatchAndRefresh(patch, label)` helper that returns false on failure so the rename handler can still gate its post-success `flowStillBeingCreated` reset. Handlers with genuinely different shapes (optimistic view updates, selection bookkeeping on error) are intentionally left alone. A couple of console labels and fallback messages are unified per operation; no test depended on the old strings. Also three small correctness fixes. EditorError and HostedWebEditorError now `extends Error` instead of `implements Error`, so instances carry a stack and pass `instanceof Error`. Snackbar toasts are keyed by a per-instance monotonic id rather than `name:message`, which collided when two distinct errors shared text and let one toast's auto-hide timer dismiss the other. getSnapshot no longer mints a fresh object URL on every render and never revokes it: the URL is created once when the snapshot blob is produced, stored in state, and revoked when replaced, cleared, or on unmount (the intermediate SVG URL is revoked after decode too).
Two related cleanups to the Editor's lifecycle handling. First, three setTimeout(0) deferrals that existed only to read state after React committed it are replaced with a single componentDidUpdate. onSelectionChanged now fires when prevState.selection differs from the committed selection rather than from a tracked timer inside handleSelection. This is a deliberate semantic improvement: the host sees every committed selection change (delete clearing the selection, module drill-in/back resets, undo/redo resets), not just clicks through handleSelection. EditorHost already debounces and re-checks the path at flush, so the extra notifications are safe, and componentDidUpdate never runs after unmount so the prior timer-cancellation machinery is removed. The cached-error refresh after navigation collapses to one componentDidUpdate trigger on a modelName change, and the viewport-restore setTimeouts in navigate-back / navigate-to-level become setState completion callbacks scoped to that commit. Second, a last-resort React error boundary (ErrorBoundary.tsx, exported from the package index and wrapping <Editor> inside HostedWebEditor) catches synchronous render-phase throws that would otherwise blank the host. The Editor's async handlers keep their own try/catch because those produce contextual messages and dispose orphaned engines, which a boundary cannot; the two comments claiming "no error boundary above" are updated to explain that the boundary cannot catch their async throws anyway.
Addresses adversarial review findings on the prior two refactor commits. The snackbar duplicate-message dismissal was only half-fixed: handleCloseSnackbar still filtered modelErrors by message text, so the first of two identical-message toasts auto-hiding dismissed both. Toast now carries an optional per-instance `id` and reports it through onClose; Editor keys removal on that id (the same value used as the React key). The id is a rest-sibling omission in Toast.render so it never lands on the DOM. handleRename regressed the pre-refactor ordering: it cleared flowStillBeingCreated only after the full engine round-trip, leaving a just-named flow's details panel suppressed longer than before. The shared helper is split into applyPatchOrReportError + refreshFromEngine (with the combined applyPatchAndRefresh wrapper kept for the other eight handlers) so handleRename can interleave its synchronous setState between the patch and the round-trip, exactly as on main. The misleading comment is corrected. ErrorBoundary never reset: once tripped it showed the fallback forever, even after navigating to a healthy project. It now takes an optional resetKey; when it changes (via getDerivedStateFromProps) the caught error is cleared. HostedWebEditor passes the username-and-project-name pair. setSnapshotUrl had a revoke race: it read the previous URL from state, so two snapshots completing before the first commit both saw the same stale value and leaked one. The live URL is now owned by a single instance field, read and revoked synchronously. Also corrects the componentDidUpdate comment and CLAUDE.md, which overstated undo/redo: a normal undo preserves the selection and fires no callback; the selection only resets when the viewed model disappears. New tests cover the dedup, boundary reset, the equal-content-distinct-Set no-fire case, and the Toast id contract.
Two review minors ahead of the flow-attach extraction. loadSim and save() appended caught values to modelErrors with a bare `as Error` cast. modelErrors entries are later used as keys in the errorKey WeakMap during render, which only accepts object keys, so a raw-string throw would crash the render phase. Normalize at each cast site with `e instanceof Error ? e : new Error(String(e))`. takeSnapshot's image.onload/onerror and the nested toBlob callback are async and can fire after the Editor unmounts (a route change mid- snapshot). Without a guard they setState on an unmounted component and, worse, create an object URL after componentWillUnmount's revoke has already run -- stranding the blob. Guard with this.unmounted: bail in onload/onerror after revoking the svg URL, and in toBlob before creating the display URL.
handleFlowAttach was the hairiest interaction path in the editor: ~390 lines mixing pure view/op computation with engine side effects, plus two near-duplicate ~70-line endpoint branches and four near-identical updateStockFlows builders. Extract the pure computation into flow-attach.ts (computeFlowAttachment); Editor.handleFlowAttach becomes a thin shell that reads view/model, calls the core, applies ops via applyPatchOrReportError, then commits the view and selection. The source (first point) and sink (last point) endpoint branches are unified into one reattachEndpoint parameterized by end; they differed only in which point is operated on and whether the recorded idents drive outflows (source) or inflows (sink). The four updateStockFlows builders collapse into one stockFlowsOp helper keyed by list (inflows/outflows) and action (add/remove); every op still carries the full inflow and outflow lists because the engine does full replacement. The one deliberate normalization: exact-duplicate ops are collapsed. The original could in principle emit two byte-identical outflow-add ops (sourceStockIdent from the creation path plus sourceStockAttachingIdent from the reattach path), but those flags are mutually exclusive in practice -- reattachEndpoint never runs during creation because the in-creation flow is not yet a view element -- so the collapse is a defensive no-op under the engine's full-replacement semantics. Behavior is otherwise byte-identical in effect, including: the unknown-uid throw, the non-stock-target throw, the missing-engine early return, the patch-failure path that commits selection/creation flag without updating the view, and the creation cursorMoveDelta zeroing when snapped to a target. The creation sentinels are re-declared locally to keep the core free of React/DOM imports; a test guards them against drift from Canvas.
Behavior tests for the extracted flow-attach core, covering both endpoint directions and all branches: sink reattach (stock->stock, stock->cloud-release, cloud->stock, cloud->empty-space), the four source mirror cases (outflows instead of inflows), and creation (cloud->empty yielding two clouds and selection of the realized flow, stock->target stock yielding upsertFlow plus source-outflow and sink-inflow ops, stock->empty materializing a cloud at fauxTargetCenter). Also: nextUid monotonicity with all element uids valid, the dropped-op guard for a stock missing from the variables map, op-dedup non-collapse of distinct ops, the unknown-uid and non-stock-target throws, and a guard that the creation sentinels stay in sync with Canvas. 98% statements / 95% branch on flow-attach.ts; the two uncovered lines are defensive guards unreachable through the public API.
The behavior tests for computeFlowAttachment pinned op shapes and element counts but never asserted coordinates, so the cloud-placement and UpdateCloudAndFlow reroute math was the one part of flow-attach.ts a future edit could break with every test still green. Add four tests that lock the exact x/y: - detach a sink to empty space: the new cloud lands at oldEnd minus a non-zero cursorMoveDelta (240 = 200 - (-40)); a sign flip would land at 160 and fail. - creation to empty space: the realized sink cloud lands at fauxTargetCenter (280,100) on the source axis, and the flow's last point attaches there. - cloud->stock source reattach: the 200px perpendicular move converts the straight flow to an L-shape with endpoint on the stock, a corner, and the fixed sink preserved -- asserting the full points array. - a 3-point L-shaped flow reattach: the source endpoint slides to the new stock center while the corner and fixed sink are preserved, exercising UpdateCloudAndFlow's multi-segment path through this module.
Extract the non-view coordination logic from Editor.tsx into a plain TypeScript ProjectController class with zero React/DOM dependencies. The controller owns the eight responsibilities that were entangled in the Editor: engine lifecycle (open/reopen/dispose with orphan release), the applyPatch -> serialize -> rebuild pipeline (including optimistic view updates and preserveLiveView), the save queue, undo/redo history, sim runs with the LTM fallback, the cached-error derivation, version/ generation bookkeeping, and the module-navigation stack. State is published as an immutable ProjectSnapshot replaced wholesale on each change so identity comparison detects updates; subscribe()/ getSnapshot() let the Editor mirror it into one state field. Synchronous multi-step mutations coalesce into one notification via an internal batch depth counter, matching the old single-setState batching. Design decisions worth calling out: - The disposed flag latches once; every async continuation short-circuits on it and releases any engine it opened, collapsing the old unmounted/openInitialProjectTimer/undoRedoTimer machinery. StrictMode safety becomes "fresh controller per mount" (the Editor will create it in componentDidMount and dispose in componentWillUnmount). - Navigation methods own modelName/modelStack and apply restored viewBox/zoom internally via queueViewUpdate (modelName updates synchronously first, so getView resolves to the restored model with no setState-callback deferral). They return the restored selection so the Editor can apply that UI consequence; the undo-driven nav reset is surfaced via a navResetSeq counter the Editor watches. - onError forwards transient errors to the host's toast UI; the controller never owns presentation state. The EngineApi/EngineModelApi/EngineRunApi interfaces capture exactly the engine surface used, and open* are injected via config, so the controller is unit-tested against a reusable FakeEngineProject helper covering open success/failure, post-open serialize failure orphan disposal, dispose racing an in-flight open, applyPatch failure leaving the snapshot untouched, the optimistic-view race, view-only updates not consuming undo slots, undo nav-reset, the save queue (queue-one-flush, thrown-onSave release), the LTM sim fallback, model-scoped error caching, navigation, and snapshot immutability + coalescing. Editor is untouched in this commit.
Make the Editor a thin view binding over the headless ProjectController added in the previous commit. The Editor now creates a controller in componentDidMount, subscribes to its immutable snapshots (mirrored into a single `controllerSnapshot` state field so the PureComponent re-renders on snapshot identity change), and disposes it in componentWillUnmount. All the engine/save/undo/sim/error-cache/navigation coordination -- and the openInitialProjectTimer/simRunTimer/saveTimer/undoRedoTimer/unmounted machinery -- is gone from the Editor; the controller's `disposed` latch guards its own async continuations. What stays in the Editor: selection, dial/drawer/tool/showDetails/ flowStillBeingCreated/variableDetailsActiveTab UI state, the snapshot-image URL state, the toast `modelErrors` list (the controller surfaces errors via its onError config callback, which appends here), all op-building handlers (they build ops then call controller.applyPatch/updateView/queueViewUpdate), keyboard handling, and rendering. Binding choices worth noting: - Mirror-into-state over forceUpdate: a new snapshot object per change means the PureComponent's shallow compare detects updates by identity, and reads stay idiomatic (this.state.controllerSnapshot.*). - Navigation: drill-in/back/level call the controller and apply only the UI consequences (selection/showDetails/selectedTool) from the returned NavigationOutcome; the controller restores the viewport internally. The undo-driven navigation reset is observed via the snapshot's navResetSeq counter in componentDidUpdate (an ordinary undo preserves selection). - StrictMode: a mount -> unmount -> mount cycle disposes the first controller and builds a fresh one on the second mount (componentDidMount recreates it when this.controller is undefined). - The only setTimeout left in Editor.tsx is the snapshot-image rasterization defer in handleSnapshot (genuinely UI). Test rework (intent preserved): editor-save-insave, editor-undo-history, and editor-open-project exercised logic that moved wholesale into the controller and are now covered by project-controller.test.ts, so they were removed and replaced by a thin editor-controller-wiring.test.ts pinning the config bridge (onSave format selection, onError -> toast list). editor-unmount was rewritten to assert the controller lifecycle contract (open on mount, dispose on unmount, fresh controller per StrictMode cycle) instead of the deleted timers. editor-details-remount now pins that the panel key derives from the snapshot's projectGeneration (the increment semantics are tested in the controller). editor-selection-changed and editor-drawer-delete got mechanical state-shape updates. No production behavior change beyond notification batching, which the controller coalesces the same way the old single-setState batches did.
Relocate the project/engine invariants in src/diagram/CLAUDE.md to describe ProjectController behavior (optimistic view updates, preserveLiveView, view-only updates not recording history, version/generation bookkeeping, the save queue, engine lifecycle / StrictMode safety, and the navigation stack), and keep the Editor-side ones scoped to rendering and UI-state consequences (details-panel remount key, module-patch targeting, the post-commit selection callback). Add project-controller.ts and the merge-live-view / project-history pure helpers to Key Files, document the tests/fake-engine.ts helper, and rewrite the Editor.tsx entry to describe it as a thin view binding over the controller.
Address two review findings. The fake engine's serializeJson ignored its includeStdlib argument, so the suite could not catch a regression that persisted stdlib models on the save path. The fake now honors includeStdlib (validProjectJson appends a stdlib-prefixed model, matching isStdlibModel's convention, only when the flag is set) and a new ProjectController test asserts the display/rebuild path includes the stdlib model while the save path's serialized payload omits it. handleSelectionDelete / handleCreateVariable / handleFlowAttach guarded on `this.controller` after the refactor, but the controller exists before its engine finishes opening -- a mutation in that brief window would clear the selection or run a dangling optimistic update. Restore exact parity with the pre-refactor `if (!engine) return` by guarding on `this.controller?.getEngine()` so those handlers cleanly no-op until the engine is open.
Canvas.render() mutated instance fields mid-render: renderInitAndCache wrote
this.elements/cachedElements/cachedVersion/selection/selectionUpdates;
connector() wrote this.draggedLinkArc; buildLayers wrote
this.hasAnyModuleReference; the per-element methods pushed into
this.elementBounds via a this.computeBounds side-channel; and render's tail
cleared selectionUpdates/elementBounds. Reasoning about what render produced
required tracking which method had run.
Replace this with a single named derivation, deriveRenderState(), invoked once
at the top of render() and componentDidMount(). It is the only method that
writes the render caches (this.elements, this.cachedVersion, this.derived) and
returns a RenderDerivation { displayElements, elementsByUid, selectionUpdates,
hasAnyModuleReference, draggedLinkArc }. The element-rendering methods now only
read this.derived; they never recompute or mutate a cache during render.
The dragged-link arc previously was computed-and-cached inside connector()
(render path) and read back at pointer-up, which guaranteed the persisted arc
matched the visual but hid the dataflow. It is now computed once in
deriveRenderState (deriveDraggedLinkArc, sharing the snap-target scan with
connector() via findLinkDragTarget) and stored in derived.draggedLinkArc;
connector() and the pointer-up persist path read the identical value, keeping
the same guarantee with an explicit flow.
Element bounds become an explicit pure pass (computeElementBounds) over the
displayed elements, called from componentDidMount (initial bounds) and the
embedded-mode viewBox in render, instead of a side effect populated while
rendering each element. this.elements and this.derived are intentionally not
cleared at render end because event handlers read them after render returns.
The three constrain* movement methods remain (now reading derived.*) but are
dead code; they predate applyGroupMovement and are tracked separately.
Canvas.tsx encoded its discrete gesture state as a bag of mutually-exclusive booleans (isMovingArrow/isMovingSource/isDragSelecting/isPinching/...) plus loose instance fields (deferredSingleSelectUid, draggingSegmentIndex, labelSide, pinch fields, inCreation), and duplicated pure decision logic inline (label-side quadrants, drag-select rectangle membership, the deferred-single- select dance, the click-vs-drag threshold). Add drawing/canvas-interaction.ts: a pure, table-tested model of the discrete interaction state machine with zero React/DOM imports. It exposes a tagged- union InteractionState (idle | panning | dragSelecting | movingSelection | movingEndpoint | movingLabel | editingName | pinching) carrying exactly the data valid for each mode, the semantic InteractionEvent/InteractionEffect types, reduceInteraction(state, event, ctx) for the pointer-down transitions, and the pure helpers the shell composes: decideMouseDownSelection / resolveDeferredSelection (delegating to the existing selection-logic.ts rather than duplicating its set arithmetic), labelSideForPointer, computeDragSelection / isInDragSelectRect, and isDrag. Rewire the shell to use the model: handlePointerDown drives the empty-canvas pan-vs-drag-select decision through reduceInteraction; handleSetSelection routes its element-press selection decision through decideMouseDownSelection; handlePointerCancel resolves the deferred single-select via resolveDeferredSelection and computes drag-select membership via computeDragSelection; handleLabelDrag uses labelSideForPointer. These replace inline duplicates with the single tested module, so the previously untested quadrant/rectangle/threshold logic is now covered by gesture-level tests. Scope: this lands the canonical pure model and routes the shell's pure decisions through it; migrating the shell's remaining runtime boolean CanvasState onto the tagged union (rewriting every state.isMovingArrow read and driving handlePointerDown/handleSetSelection/handlePointerCancel end-to-end through reduceInteraction) is deferred because it cannot be done with behavior-preservation confidence without end-to-end gesture tests through the React reconciler, which do not yet exist. The continuous pinch/pan/momentum physics stay shell-internal by design. Tracked for follow-up. Adds 35 table-driven tests (canvas-interaction.test.ts) covering the transitions and geometry helpers; updates src/diagram/CLAUDE.md with the new modules and the render-purity invariant.
Record two items discovered during the Phase 3 Canvas refactor: (65) the shell's boolean CanvasState is not yet migrated onto the new tagged-union interaction model in canvas-interaction.ts (deferred pending end-to-end gesture tests through the reconciler), and (66) the three dead constrain* movement methods on Canvas that predate applyGroupMovement.
…nches Three review fold-ins for the Canvas interaction model: 1. labelSideForPointer was tested only at cardinal directions, leaving the `<` vs `<=` quadrant-boundary semantics unpinned. Add cases at exactly 45/135/-45/-135 degrees asserting which quadrant owns each boundary (the one whose comparison is `<=`; -135 falls through to the else branch -> right). 2. The older "Link drag arc ownership" invariant in CLAUDE.md still described the arc as cached in the removed `draggedLinkArc` instance field. Reconcile it with the render-purity model: computed once in deriveRenderState (derived.draggedLinkArc), rendered by connector(), read at pointer-up. 3. Only the canvasPointerDown branch of reduceInteraction is shell-driven today; the createTool/flowTool/elementPointerDown branches are the canonical-but-not-yet-wired model (tech-debt #65). Annotate each branch and the corresponding describe blocks as shell-driven vs model-only so the model-pinning tests are not mistaken for coverage of live shell behavior.
Code reviewReviewed the headless No blocking issues found. The dispose latch + per-mount controller is a clean replacement for the prior unmounted-flag/timer machinery, the save-queue A couple of minor observations, not bugs:
Overall correctness: correct |
What this is
A three-phase architectural refactor of the TypeScript React editor (src/diagram), driven by one goal: new features should carry minimal risk of regressions. The strategy throughout is the codebase's own established pattern (selection-logic.ts, group-movement.ts, project-history.ts): hollow out the imperative shell by moving logic into pure, heavily-tested modules, and concentrate the remaining async coordination into one disposable object instead of weaving it through a component.
Every phase was implemented by one agent and adversarially reviewed by a separate fresh agent (line-by-line semantic-equivalence diffs against the pre-refactor code), iterating until no substantial findings remained. 15 commits, each green through the full pre-commit suite. Tests: 956 -> 1023 in src/diagram; app and simlin-serve suites untouched and green.
Phase 1 — Editor.tsx cheap wins (ec68f89..d476538)
applyPatchOrReportError+refreshFromEnginewith anapplyPatchAndRefreshconvenience wrapper.onSelectionChangedand the post-navigation error-cache refresh now fire fromcomponentDidUpdate; viewport restores use setState completion callbacks. This deletes the matching unmount-cancellation machinery.ErrorBoundarycomponent (withresetKey) wraps the editor in HostedWebEditor; previously a render-path throw meant a permanently blank screen.handleFlowAttach(~385 lines, the hairiest interaction path) extracted into pureflow-attach.ts(computeFlowAttachment), deduplicating the copy-pasted source/sink branches and the 4x-duplicated stock-flows op builders. 22 tests pin it, including exact coordinate math and an L-shaped reroute.extends Error,as Errorcasts normalized, unmount guards on async image callbacks.Phase 2 — headless ProjectController (f2120e7..bf9f488)
The core change. Everything in Editor.tsx that was not view code now lives in
project-controller.ts, a plain TypeScript class with zero React/DOM imports: engine lifecycle (open/dispose/orphan cleanup), the patch -> serialize -> rebuild -> error-annotate -> preserve-live-view pipeline, the save queue, undo/redo history, sim runs with the LTM fallback, the error cache, and the module navigation stack. It exposes an immutableProjectSnapshotplussubscribe(); Editor mirrors the snapshot into one state field and keeps only genuine UI state (selection, panels, tools, toasts).Phase 3 — Canvas render purity + interaction core (25093ad..df7bbdd)
deriveRenderState()pass at the top of render computes everything renders used to scribble into fields mid-flight (element maps, selection updates, module-warning flag, the dragged-link arc). The arc the user sees during a link drag and the arc persisted on pointer-up are now provably the same value read from the same derivation.canvas-interaction.ts: the selection decisions, deferred-single-select dance, label-side quadrant math, drag-select rectangle membership, and click-vs-drag threshold all moved out of the pointer handlers into a table-tested module (39 tests). The shell composes it; review confirmed zero logic is duplicated between shell and module.Design decisions and tradeoffs
useSyncExternalStore-compatible so a future hooks conversion of Editor is one line of binding, not a rewrite.navResetSeqin the snapshot rather than the Editor diffing modelName, so coalesced notifications cannot miss a reset.onErrorcallback; presentation state never enters the controller.unmountedflag with a singledisposedlatch that every async continuation checks (and which disposes any engine it opened mid-flight).Behavior changes (all deliberate, all documented)
Everything else was held to semantic equivalence, verified by adversarial review against the pre-refactor code at each phase.
Discovered en route
Test accounting