Skip to content

diagram: shrink the imperative shell — controller extraction, pure interaction cores, render purity - #721

Merged
bpowers merged 15 commits into
mainfrom
diagram-react-refactor
Jun 6, 2026
Merged

bpowers merged 15 commits into
mainfrom
diagram-react-refactor

Conversation

@bpowers

@bpowers bpowers commented Jun 6, 2026

Copy link
Copy Markdown
Owner

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)

  • Nine applyPatch handlers shared an identical ~15-line tail (try/catch, error surfacing, serialize, sim re-run). Now one helper, split as applyPatchOrReportError + refreshFromEngine with an applyPatchAndRefresh convenience wrapper.
  • The setTimeout(0) deferrals that existed only to read post-commit state are gone: onSelectionChanged and the post-navigation error-cache refresh now fire from componentDidUpdate; viewport restores use setState completion callbacks. This deletes the matching unmount-cancellation machinery.
  • New ErrorBoundary component (with resetKey) wraps the editor in HostedWebEditor; previously a render-path throw meant a permanently blank screen.
  • handleFlowAttach (~385 lines, the hairiest interaction path) extracted into pure flow-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.
  • Small fixes: snapshot object-URL lifecycle (was leaking one URL per render), toast keys/dismissal by per-instance identity (two same-text errors no longer dismiss together), error classes now extends Error, as Error casts 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 immutable ProjectSnapshot plus subscribe(); 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)

  • All render-phase instance-field mutation is gone. One named 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.
  • New pure 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

  1. A bespoke controller + snapshot/subscribe instead of a state library. Redux/zustand would model this fine, but @simlin/diagram staying dependency-light is worth protecting, and the controller is one file. The shape is deliberately useSyncExternalStore-compatible so a future hooks conversion of Editor is one line of binding, not a rewrite.
  2. The controller owns modelName/modelStack (navigation), not the Editor. The pipeline itself depends on the active model (preserveLiveView, error filtering), so splitting it would have meant two sources of truth. The Editor receives navigation outcomes (restored selection) and applies the UI consequences. Undo-driven navigation resets are signaled by a monotonic navResetSeq in the snapshot rather than the Editor diffing modelName, so coalesced notifications cannot miss a reset.
  3. Toast errors stay in the Editor. The controller reports failures through an onError callback; presentation state never enters the controller.
  4. Controller per mount, created in componentDidMount. This is what makes React 18/19 StrictMode safe by construction: mount/unmount/mount yields dispose + a fresh controller, replacing five hand-cancelled timers and an unmounted flag with a single disposed latch that every async continuation checks (and which disposes any engine it opened mid-flight).
  5. The fractional projectVersion scheme (+0.01 content / +0.001 view) was preserved, not redesigned. Canvas keys its element-map cache on it. Redesigning the cache-invalidation contract would have coupled this refactor to Canvas internals before Phase 3 made them safe to touch; it is unchanged and documented.
  6. onSelectionChanged semantics deliberately broadened. It now fires for every committed selection change (deletion clearing it, drill-in resetting it), not just direct canvas selection. More correct for hosts; the only consumer (simlin-serve EditorHost) debounces and tolerates this. Documented in CLAUDE.md.
  7. One normalization in flow-attach: exact-duplicate ops are collapsed. Review proved the duplicate case was unreachable (creation and reattachment flags are mutually exclusive) and idempotent under the engine's full-replacement upsert semantics, so this is defensive only. Everything else in the extraction was verified byte-equivalent, including element array order (z-rendering) and uid assignment order.
  8. Canvas: derivation is rebuilt every render, not memoized. Only the uid->element map is cached (keyed on version, as before). Memoizing the rest would have required proving a complete dependency key over a dozen inputs including instance fields; rebuilding is what the old code effectively did anyway, and it makes staleness structurally impossible.
  9. The Canvas runtime state migration (boolean bag -> tagged union) was deliberately deferred. The reducer module models the full state machine and the shell genuinely uses its decision functions, but rewiring the three hot pointer handlers' runtime state has no safety net until reconciler-level gesture-sequence tests exist. Both the implementing and reviewing agents independently judged forcing it now to be the highest-regression-risk move in the project, which inverts the goal. Tracked in docs/tech-debt.md (build(deps): bump follow-redirects from 1.14.6 to 1.14.7 #65, with dead constrain* methods as build(deps): bump shelljs from 0.8.4 to 0.8.5 #66); the gating prerequisite (e2e gesture tests) is named there.
  10. Editor stays a class component. A hooks transliteration of 30 instance fields into refs would be strictly worse than the current class; with the controller extracted, a future conversion becomes genuinely simpler, but it is out of scope here per the repo's documented house style.

Behavior changes (all deliberate, all documented)

  • onSelectionChanged broadening (above).
  • Toast dismissal by instance identity instead of message text.
  • A render-path crash now shows a recoverable error boundary instead of a blank screen.
  • Caught non-Error throws are normalized to Error before entering UI state.

Everything else was held to semantic equivalence, verified by adversarial review against the pre-refactor code at each phase.

Discovered en route

Test accounting

  • src/diagram: 956 -> 1023 tests (72 suites). New suites: flow-attach (22), project-controller (~30 incl. save-queue races, undo eviction, orphan-engine disposal, StrictMode lifecycle), canvas-interaction (39), error-boundary, controller wiring.
  • Three editor test files (save-insave, undo-history, open-project) were replaced by controller-level equivalents; review confirmed every assertion has a counterpart.
  • src/app (58) and simlin-serve web (111) green throughout.

bpowers added 15 commits June 5, 2026 20:21
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.
@claude

claude Bot commented Jun 6, 2026

Copy link
Copy Markdown

Code review

Reviewed the headless ProjectController extraction, the pure flow-attach/canvas-interaction modules, the Canvas render-purity work, and the rewired Editor. Focus areas: snapshot/coalescing semantics, save-queue + StrictMode dispose races, the optimistic-view round-trip, computeFlowAttachment op deduplication, and the render-purity invariant in Canvas.deriveRenderState.

No blocking issues found. The dispose latch + per-mount controller is a clean replacement for the prior unmounted-flag/timer machinery, the save-queue finally block correctly releases inSave on a thrown save, preserveLiveView is invoked uniformly through updateProject, and deriveRenderState is the sole writer of the render caches (the dragged-link arc is now computed once and read consistently by both connector() and the pointer-up persist path). The boundary cases (engine-open dispose race, undo restoring a project without the viewed model bumping navResetSeq, view-only updates skipping history/generation) are exercised by direct unit tests against the fake engine.

A couple of minor observations, not bugs:

  • ProjectController.openInitialProject does not consult newEngineShouldPullView/newEngineQueuedView; only openEngineProject (called from undo/redo) replays a queued view. This is fine in practice because the Editor's flow guarantees queueViewUpdate is never called before openInitialProject resolves (Canvas only mounts after a project snapshot exists), but the comment on queueViewUpdate says "stash the view to replay once the engine arrives" without noting the initial-open path doesn't honor it -- worth a one-line clarifier.
  • setSnapshotUrl reads liveSnapshotUrl synchronously, so back-to-back snapshots can't double-revoke; however, if the user clicks "close" while a takeSnapshot() is mid-flight, the in-flight toBlob callback will reopen the snapshot card (it only bails on isUnmounted, not on a user-initiated close). Minor UX regression at most; not data loss.

Overall correctness: correct

@bpowers
bpowers merged commit 1bf5579 into main Jun 6, 2026
11 of 13 checks passed
@bpowers
bpowers deleted the diagram-react-refactor branch June 6, 2026 11:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant