Repository navigation
diagram: Canvas interaction-model migration and hooks conversion - #723
Conversation
Lean brief for the tech-debt #65/#66 follow-up to PRs #721/#722: a reconciler-level gesture-sequence test suite gates migrating Canvas's boolean CanvasState onto the canvas-interaction.ts tagged union, followed by the class-to-hooks conversion. Captures the state inventory, jsdom harness constraints (SSR parity, no instance poking), and the per-piece adversarial review protocol.
Piece 1a of the canvas-interaction migration (tech-debt #65): a jsdom/RTL gesture-sequence suite that drives the real <Canvas> through PointerEvent down/move/up/cancel sequences and asserts only on prop callbacks and rendered DOM, never on instance internals. It is the gate for the upcoming class->tagged-union and class->hooks conversions, so it must stay green and untouched across both -- props in, events in, callbacks/DOM out. A shared harness builds tiny Project/Model/StockFlowView fixtures and installs the jsdom polyfills the Canvas needs (PointerEvent, DOMMatrix/ DOMPoint, setPointerCapture, createSVGPoint/getScreenCTM, ResizeObserver, a fixed bounding rect) in test code only -- no production changes. The container rect, viewBox, and zoom are pinned so client coords map 1:1 to model coords. onSetSelection is wired to commit the selection back into props and re-render, mirroring the real Editor host's same-batch state update so render paths like isValidTarget's only(selection) during an arrowhead drag see a consistent selection. The three suites cover all sixteen checklist gestures (click-select, drag-select with the aux corner-hit rule, modifier toggle, deferred-single-select collapse, group drag, segment drag, label drag, link/flow endpoint drag and cloud reattach, creation tools, link/flow tool from a named element, pan, pinch, name editing, and pointercancel reset). Two current-behavior surprises are pinned with comments: the empty-canvas press has no sub-threshold guard so any wobble renders a drag rect, and pointercancel shares the pointer-up handler so it commits an in-progress move rather than discarding it.
constrainFlowMovement, constrainCloudMovement, and constrainStockMovement have no callers (tech-debt #66). They predate the group-movement extraction to group-movement.ts/applyGroupMovement, which now owns all live element movement geometry. Removing them also drops the UpdateCloudAndFlow / UpdateFlow / UpdateStockAndFlows imports they alone pulled in from ./Flow. Done first, as its own commit, so the upcoming tagged-union migration diff stays focused on the interaction-state change.
Replaces Canvas's bag of mutually-exclusive boolean modes (isMovingCanvas/isDragSelecting/isEditingName/isMovingArrow/isMovingSource/ isMovingLabel/isPinching) and the loose pinch/label/deferred instance fields (labelSide, editNameOnPointerUp, flowStillBeingCreated, the pinch reference, draggingSegmentIndex, deferredSingleSelectUid, deferredIsText, dragPointerType) with a single `interaction: InteractionState` field (tech-debt #65). The discrete mode now lives in one tagged union (canvas-interaction.ts); the continuous companions (moveDelta, dragSelectionPoint, movingCanvasOffset, the inCreation concrete elements, and the Slate editingName value) stay outside it because they are per-frame physics / DOM-adjacent state, not discrete mode. The shell drives every pointer-DOWN and mode-entry transition through reduceInteraction: the empty-canvas press, the aux/stock/module and flow creation tools, pinch enter/exit, and label-drag start are now reducer events whose returned effects (setSelection / clearSelectedTool / capturePointer) the shell executes in order. canvas-interaction.ts grows pinchStart / pinchEnd / labelDragStart events and an elementPointerDown.pointerType field; the down branches carry the real pointer type into the movingEndpoint variant so the touch-is-always-straight link rule reads the actual value. Pointer-UP resolution stays in the shell by design -- it is dominated by geometry (drag target, faux-target centers, dragged-link arc) and interleaved branches (a deferred-select resolution falls through into the generic move-commit path) -- so handlePointerCancel reads state.interaction, composes the pure helpers, and constructs the next InteractionState directly, coalescing the former piecemeal boolean clears into a single per-event transition to preserve React's batched net state change. selection-logic.pointerStateReset shrinks to reset `interaction: idle` plus the continuous companions. The reconciler-level gesture suite (the behavior contract) is untouched and green; canvas-interaction.test.ts gains table tests for the new events and selection-logic.test.ts / canvas-editing-name-done.test.ts are updated to the new state shape (the latter keeps the flowStillBeingCreated regression as interaction.editingName.creatingFlow). Also deletes the dead constrain* methods were removed in the preceding commit (#66).
The c2a391a migration folded the old two-field name-edit state (isEditingName = "the inline editor is showing NOW" and editNameOnPointerUp = "enter editing AFTER this creation drag ends") onto the single editingName union variant, separated by onPointerUp. But the editingNameMode accessor returned true for the staging case too, so during an aux/stock/module creation drag HEAD wrongly mounted an empty EditableLabel overlay, made the full-canvas overlay div pointer-event-capturing, and suppressed the staged element's own text label. Rename the accessor to showingNameEditor with the correct mode === 'editingName' && !onPointerUp semantics, route every "editor visible now" reader through it (aux/stock/module/flow label props, the render overlay + deferred tool-change commit, and the handleEditingNameDone guard), and pin the behavior with new gesture assertions that fail against the unfixed code. Also delete the elementPointerDown event kind and reducer branch: its docstring claimed the shell drives element/arrowhead/source presses through reduceInteraction, but handleSetSelection builds the union variant directly. That resolution is geometry-dominated (hit element, cloud-vs-flow reattachment, link/flow-tool staging, deferred-single- select) and interleaved with shell-only concerns, so the shell is the single source of truth; the parallel reducer model was dead and only invited skew. With it gone, InteractionContext.canEditName is dead and is removed. Finally drop movingEndpoint.inCreation -- it was written but never read; the concrete CanvasState.inCreation element is the single source of truth for the in-creation companion. Honest test labels and docstrings follow.
The elementPointerDown reducer branch was deleted in the tagged-union migration, leaving the setSelection and clearSelectedTool effect arms unreachable -- nothing emits them; the reducer only ever returns capturePointer. Remove both variants from InteractionEffect and collapse Canvas.runEffects to its single live arm. The reducer table test already only asserts on capturePointer and empty effect lists, so no test change is needed beyond the surrounding doc comments.
Convert the Canvas imperative shell from a React.PureComponent to a React.memo function component (Piece 2 of the canvas-interaction migration). Behavior-preserving: the four reconciler-level gesture test files stay byte-identical and green, and the Rust-vs-TS SVG byte-parity test stays green. State shape: per-field useState, the closest match to the class's setState merge + React 18 batching (multiple setter calls in one handler coalesce into a single re-render carrying the net transition, exactly as setState batching did). The former instance fields (elements/derived caches, cachedVersion, activePointers, momentum/velocity, pointerId, mouseDownPoint, selectionCenterOffset, prevSelectedTool, ResizeObserver) move into one refs object. Stale closures: every event-time reader that escapes the render closure -- the native non-passive wheel/Safari-gesture listeners, the momentum rAF loop, the ResizeObserver callback, and the deferred tool-change name-commit (setTimeout) -- reads a ref refreshed synchronously each render with the current props + discrete/continuous state, so they see CURRENT values exactly as this.props/this.state always did. React-event handlers read it too, for a uniform 'event-time reads go through latest' rule that also keeps the handler identities stable. (handlePointerCancel and friends read state set by earlier ticks, where a fresh per-render closure would also suffice; routing them through latest is uniform and harmless.) Render purity: deriveRenderState remains the sole writer of the render caches and runs once at the top of the render body (and once in the mount effect). Writing those refs during render reproduces the class's identical this.* writes and is kept idempotent -- the version cache short-circuits -- so a StrictMode double-render is safe. The mount/ unmount logic becomes one empty-deps useEffect whose cleanup is symmetric (disconnect observer, remove the same listener instances, stop momentum, clear pointer/velocity state) so a StrictMode mount/unmount/mount cycle leaves nothing stuck. buildSelectionMap becomes a module-level exported function (was the static Canvas.buildSelectionMap); its test imports it directly. The old canvas-editing-name-done.test.ts constructed the class and poked state, which is impossible for a function component, so it is replaced by canvas-gestures-name-edit-lifecycle.test.tsx -- three harness-driven regressions (just-created-flow name cancel deletes; commit does not and clears the creatingFlow latch; a later unrelated rename-cancel does not delete) that pass against both the pre-conversion class and the function component. React.memo replaces PureComponent's shallow-prop gate; state changes always re-render in both. No consumer holds a Canvas ref (Editor and StaticDiagram pass props only).
The canvas-interaction migration and hooks conversion land on this branch, so the tech-debt entries get the repo-conventional (Resolved) annotations, including the review-adjudicated deviation from #65's suspected fix: element-press and pointer-up resolution intentionally stay in the shell, and the reducer's never-shell-driven elementPointerDown branch was deleted rather than kept as a parallel model. Also removes deriveRenderState's inCreationArg/inCreationCloudArg parameters (flagged in the piece-2 adversarial review): both call sites used the defaults, so the parameters were dead capability and their doc comment overstated what the mount effect does.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0cb8bce46b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| @@ -0,0 +1,181 @@ | |||
| # Canvas Interaction-Model Migration (tech-debt #65 + #66) and Hooks Conversion | |||
There was a problem hiding this comment.
Index the new design plan in README
Adding this file under docs/ also needs a matching entry in docs/README.md; I checked the current index with rg "canvas-interaction|2026-06-07" docs/README.md and this new design plan is not listed, which violates docs/AGENTS.md's instruction to update the documentation index whenever docs files are added, moved, or renamed.
Useful? React with 👍 / 👎.
Code reviewI traced the diff against the pre-change Canvas/ No correctness bugs to flag. A few notes worth recording:
Overall correctness verdictCorrect. The class-to-hooks conversion and boolean-to-tagged-union migration preserve semantics; the new gesture suite gates both refactors at the prop/DOM boundary as advertised; no introduced bugs found. |
The PR #721/#722 follow-up: resolves tech-debt #65 (Canvas boolean CanvasState -> tagged-union interaction model) and #66 (dead constrain* methods), then converts Canvas to a function component. Working plan in docs/design-plans/2026-06-07-canvas-interaction-migration.md.
What changed, in order
<Canvas>through PointerEvent down/move/up/cancel sequences, asserting only on prop-callback payloads and rendered DOM -- never instance internals -- so the same suite gates both refactors unchanged. Covers click/modifier/deferred selection, drag-select (incl. aux corner-hit), pan, pinch enter/exit, label drag, link/flow endpoint drags, all five creation tools, name-edit lifecycle, and pointercancel. Two pre-existing surprises are pinned as current behavior: the empty-canvas press has no sub-threshold drag guard, and pointercancel commits like pointerup.CanvasState's mutually-exclusive booleans (isMovingArrow/isMovingSource/isMovingCanvas/isDragSelecting/isPinching/isMovingLabel/isEditingName/editNameOnPointerUp/flowStillBeingCreated) and the loose pinch/label/deferred/dragPointerType fields collapse into a singleinteraction: InteractionState. The reducer owns the non-geometry mode transitions (empty-canvas press, creation tools, pinch enter/exit, label-drag start); element/arrowhead/source press resolution and pointer-up resolution intentionally stay in the shell, which composes the module's pure helpers and constructs union variants directly. The reducer's never-shell-drivenelementPointerDownbranch was deleted rather than kept as a divergence-prone parallel model -- that dual source of truth was the core of the build(deps): bump follow-redirects from 1.14.6 to 1.14.7 #65 complaint.React.memofunction component. Former state fields are per-fielduseState(matching the class's batched-merge semantics); instance fields become refs; alatestref refreshed each render gives escaped callbacks (native wheel/gesture listeners, momentum rAF loop, ResizeObserver, deferred tool-change commit) current-value reads exactly asthis.props/this.statedid. SSR stays byte-identical (the Rust-vs-TS SVG parity suite gatesrenderToString).Process
Each piece was implemented by a fresh sub-agent and adversarially reviewed by another (line-by-line semantic-equivalence proof against the pre-change code), iterating to SHIP. The piece-1 review caught one real regression before it could ship -- the staged-creation drag wrongly showing the name editor and hiding the element label (the old
isEditingNamevseditNameOnPointerUpdistinction, noweditingName.onPointerUp) -- which is fixed and pinned by new gesture assertions.grep -c 'isMovingArrow\|...\|isMovingLabel' Canvas.tsxdrops to comments and two Flow prop names; diagram suite 75 files / 1055 tests green; svg byte-parity green; lint/tsc clean.