Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(canvas): go to node lands on the node, not on the canvas origin

Bas Milius8b2ea6eb5e3d
diff --git a/CLAUDE.md b/CLAUDE.md
index 9ec130c8b..4d36c3779 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2687,20 +2687,32 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
`main/index.ts` intercepts it in `before-input-event` and forwards `app:zoom-actual-size`, which
re-asks the same refusals. Server Edition needs no intercept (no menu; Chrome/Firefox hand ⌘0 to
the page) and stubs the subscription.
-- **"Go to node" (`goToNode`)** — the one camera-travel path (notification click, sessions
- sidebar, ⌘K jump, presence travel, minimap double-click, double-click focus). It frames the node
- with `fitView({nodes:[{id}]})` **only when React Flow has MEASURED it**: `getFitViewNodes` filters
- the fit set by `measured` (no `width`/`height` fallback in there), so an unmeasured node leaves the
- set EMPTY, its bounds collapse to `{0,0,0,0}` and the camera lands on the canvas **ORIGIN** at max
- zoom — empty canvas, node off-screen. That is the state every node is in for the first tick after
- its project loads, which is why **cross-project** focus (the load and the focus happen in the same
- tick, and measuring can lose the race — heavier canvas = more likely) used to land on nothing and
- only work on a second try. `renderer/lib/nodeFocus.ts` computes the identical framing from the
- node's PERSISTED size for that window (`nodeFitRect` resolves the group-parent chain →
- `viewportForRect` → `setViewport`), and the measured check reads React Flow's **store**
- (`getInternalNode`), not our node object — `measured` reaches our state one render later (via
- `onNodesChange`), so our copy lies about nodes the store has long sized. Unknowable size ⇒ the
- camera **stands still**; never fall back to a bare `fitView` there, that IS the origin jump.
+- **"Go to node" (`goToNode` → `frameNode`)** — the one camera-travel path (notification click,
+ sessions sidebar, ⌘K jump, presence travel, minimap double-click, double-click focus).
+ **It computes the viewport itself and applies it with `setViewport`. It must never go through
+ `fitView`.** React Flow's `fitView` frames nothing when you call it: it sets `fitViewQueued` and
+ the fit is RESOLVED LATER — from a subsequent `setNodes` (and only once EVERY node is measured,
+ `nodesInitialized`) or from the next `updateNodeInternals` — against whatever `nodeLookup` holds
+ by then. Its fit set is also filtered by `measured` (no `width`/`height` fallback in
+ `getFitViewNodes`), so a set that comes out EMPTY collapses the bounds to `{0,0,0,0}` and
+ `getViewportForBounds` parks the canvas **ORIGIN** in the middle of the screen at max zoom. On a
+ canvas whose nodes sit thousands of px out that is the field report verbatim: right project,
+ empty stretch of canvas, *sometimes*. **Cross-project** focus lands in that window every time —
+ switch project → load its nodes → frame the target, all before the mount-time measuring has
+ settled — and the second click always works, which is what makes it read as intermittent.
+ The geometry is `renderer/lib/nodeFocus.ts`: the node's rect from React Flow's own measurement
+ when it has one (`getInternalNode` — `measured` reaches OUR node objects one render later via
+ `onNodesChange`, and `internals.positionAbsolute` also accounts for `extent:'parent'` clamping),
+ else `nodeFitRect` from the PERSISTED size, resolving the group-parent chain. Then the
+ chrome-free frame (`solveFitFrame`, pane-local — the same solve `fitAll`'s padding is expressed
+ through) → `viewportForRectInFrame`, which centres the node in the space it can actually be seen
+ in; no solvable frame ⇒ `viewportForRect` against the whole pane at the flat ratio. Unknowable
+ size or no pane ⇒ the camera **stands still**. Two rules a refactor must not undo: framing goes
+ through `frameNode` and nothing else (`canvas-wiring.test.tsx` pins that it contains no
+ `fitView(`), and a "stands still" branch must never be "helpfully" replaced by a bare `fitView` —
+ that IS the origin jump. `fitAll` still uses `fitView` deliberately: it is an explicit user
+ gesture on a settled canvas and its fit set is every node, but it carries the same deferral, so
+ do not reach for it from anything automatic.
- **Breadcrumb trail** (`renderer/lib/breadcrumbs.ts` — all the pure logic lives there) — every
deliberate `goToNode` landing records a `NavStop` ({nodeId, at, note}) for the ACTIVE project, and
**Cmd+[ / Cmd+]** (`canvas.goBack` / `canvas.goForward`, bound in `shared/keybindings.ts`) plus the
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5acc29586..de41049b6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -341,6 +341,14 @@ from the target's `pendingLaunch` (`renderer/lib/edgeModel.ts`), and the context
writes stays hidden underneath it. One `open-claude --after` used to land three edges on one node.
`src/renderer/canvas/edge-model.source.test.ts` pins both halves.
+**React Flow's `fitView` is queued, not immediate — never use it to frame something automatically.**
+Calling it sets `fitViewQueued` and the fit runs from a later `setNodes` (only once every node is
+measured) or the next `updateNodeInternals`, against whatever the node lookup holds by then; a fit
+set that comes out empty parks the canvas origin in the middle of the screen. Compute the viewport
+yourself and apply it with `setViewport` (`renderer/lib/nodeFocus.ts`, `canvas/fit-view.ts`), which
+lands now and against the canvas you meant. `fitAll` is the one deliberate exception: an explicit
+user gesture on a settled canvas.
+
## Testing
`npm test` must pass, and `npm run typecheck` is the fastest gate.
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 0528a1fa7..50f2bbfb3 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -36,7 +36,7 @@ import {
isSessionReady,
subscribeSessionReady
} from '../nodes/TerminalNode'
-import { solveFitPadding } from './fit-view'
+import { solveFitFrame, solveFitPadding } from './fit-view'
import { FloatingEdge } from './FloatingEdge'
import { MacWheelGestureRouter, trackpadRoutingEnabled } from './wheel-gesture'
import { isBrowserRuntime } from '@renderer/bridge/runtime'
@@ -265,11 +265,11 @@ import {
folderName
} from '../lib/projectOpen'
import {
- FIT_NODE_OPTIONS,
absolutePosition,
isMeasured,
nodeFitRect,
viewportForRect,
+ viewportForRectInFrame,
type FocusableNode
} from '../lib/nodeFocus'
import { NODE_MAXIMIZE_MARGIN_PX, maximizeTargetRect } from '../lib/nodeMaximize'
@@ -6634,54 +6634,53 @@ export function Canvas() {
* The ONE framing implementation behind both deliberate focus (`goToNode`) and breadcrumb
* back/forward (`stepAndFrame`) — extracted so CLAUDE.md's "Go to node" invariant has a single
* copy to regress. Fit the node in view instead of centering at a fixed zoom — `zoom:
- * max(current, 1)` overshot large terminals (their body never fit the viewport). fitView sizes
- * the zoom to the node and resolves group-relative positions itself; the clamp keeps a small
- * node from filling the whole screen and a huge one from being fit microscopic.
+ * max(current, 1)` overshot large terminals (their body never fit the viewport). The clamp keeps
+ * a small node from filling the whole screen and a huge one from being fit microscopic.
*
- * …but ONLY once React Flow has MEASURED the node. Its fit set is filtered by `measured`
- * (no width/height fallback in there), so an unmeasured node leaves the set EMPTY, the
- * bounds collapse to {0,0,0,0} and the camera flies to the canvas ORIGIN at max zoom —
- * empty canvas, node off-screen. That is precisely the state a node is in for the first
- * tick after its project loads, i.e. on every CROSS-PROJECT focus (OS-notification click,
- * sessions sidebar, ⌘K jump, presence travel): the load and the focus happen in the same
- * tick, so measuring can lose the race and only a second attempt would work. In that
- * window we frame the node ourselves from its persisted size — see lib/nodeFocus.
+ * **It computes the camera itself and applies it with `setViewport`. It must never go through
+ * `fitView`.** React Flow's `fitView` does not frame anything when you call it: it sets
+ * `fitViewQueued` and runs LATER, from `setNodes` (and only once EVERY node is measured) or from
+ * the next `updateNodeInternals`. So the fit is resolved against whatever `nodeLookup` holds by
+ * then, not against the canvas the user clicked on — and its fit set is filtered by `measured`
+ * with no width/height fallback, so a set that comes out EMPTY collapses the bounds to
+ * {0,0,0,0} and the camera flies to the canvas ORIGIN at max zoom. On a canvas whose nodes sit
+ * thousands of px out that reads exactly as the field report: right project, empty stretch of
+ * canvas, "sometimes". A cross-project focus lands in that window every time (switch project →
+ * load its nodes → frame the target, all before the mount-time measuring has settled), and a
+ * second click works because by then everything is measured.
*
- * The measured check must read React Flow's OWN store (`getInternalNode`), not our node
- * object: `measured` only reaches our state one render later, when `onNodesChange` applies
- * the dimensions change, so our copy says "unmeasured" for nodes the store has long sized.
+ * So the geometry is ours: the node's rect from React Flow's measurement when it has one (its
+ * `positionAbsolute` also accounts for `extent: 'parent'` clamping) and from the PERSISTED size
+ * otherwise — which needs no layout — then the chrome-free frame, then `setViewport`, which
+ * applies immediately. See lib/nodeFocus and canvas/fit-view.
*
- * The framing itself is solved against the CURRENT chrome layout, exactly like `fitAll`:
- * a flat 20% ratio has to reserve enough slack for the dock/minimap on EVERY side, which
- * is what kept a big node (a group frame most of all) further away than it needed to be.
- * The free-rect solver reclaims the space the chrome does not actually occupy, so the node
- * is framed tighter without sliding underneath anything. Falls back to the flat ratio when
- * there is nothing sensible to solve — the same ratio the unmeasured branch uses.
+ * The frame is solved against the CURRENT chrome layout, exactly like `fitAll`: a flat 20% ratio
+ * has to reserve enough slack for the dock/minimap on EVERY side, which is what kept a big node
+ * (a group frame most of all) further away than it needed to be. Falls back to the flat ratio
+ * against the whole pane when there is nothing sensible to solve.
*/
const frameNode = useCallback(
(node: Node) => {
const internal = getInternalNode(node.id)
- if (isMeasured(internal)) {
- const wrap = flowWrapRef.current
- const size = internal?.measured
- const solved =
- wrap && size?.width && size?.height ? solveFitPadding(wrap, size.width, size.height) : null
- void fitView({
- nodes: [{ id: node.id }],
- duration: 300,
- ...FIT_NODE_OPTIONS,
- padding: solved ?? FIT_NODE_OPTIONS.padding
- })
- return
- }
- const rect = nodeFitRect(node as FocusableNode, nodesRef.current as FocusableNode[])
- const wrap = flowWrapRef.current?.getBoundingClientRect()
- const viewport = rect && wrap ? viewportForRect(rect, wrap.width, wrap.height) : null
+ const rect = isMeasured(internal)
+ ? {
+ ...internal!.internals.positionAbsolute,
+ width: internal!.measured.width as number,
+ height: internal!.measured.height as number
+ }
+ : nodeFitRect(node as FocusableNode, nodesRef.current as FocusableNode[])
+ const wrap = flowWrapRef.current
// Size unknowable / no pane yet: leave the camera where it is. Standing still beats
- // teleporting the user to the origin, which is the bug this branch exists for.
+ // teleporting the user to the origin, which is the failure this whole path exists for.
+ if (!rect || !wrap) return
+ const frame = solveFitFrame(wrap, rect.width, rect.height)
+ const box = wrap.getBoundingClientRect()
+ const viewport = frame
+ ? viewportForRectInFrame(rect, frame)
+ : viewportForRect(rect, box.width, box.height)
if (viewport) void setViewport(viewport, { duration: 300 })
},
- [fitView, setViewport, getInternalNode]
+ [setViewport, getInternalNode]
)
const goToNode = useCallback(
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index 7eaaea6b5..0cabda1db 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -155,6 +155,21 @@ describe('breadcrumb wiring the CLAUDE.md bullet calls load-bearing', () => {
expect(CANVAS_SRC.match(/isMeasured\(internal\)/g) ?? []).toHaveLength(1)
})
+ it('frameNode computes the camera itself and never routes through fitView', () => {
+ // React Flow's fitView is QUEUED, not immediate: it runs from a later setNodes (and only once
+ // EVERY node is measured) or the next updateNodeInternals, so it frames whatever nodeLookup
+ // holds by then. Resolved after the node set moved on, its fit set comes out empty, the bounds
+ // collapse to {0,0,0,0} and the camera flies to the canvas ORIGIN — the "right project, empty
+ // canvas, sometimes" report. A cross-project focus lands in that window every time.
+ const frame = CANVAS_SRC.slice(
+ CANVAS_SRC.indexOf('const frameNode = useCallback'),
+ CANVAS_SRC.indexOf('const goToNode = useCallback')
+ )
+ expect(frame.length).toBeGreaterThan(0)
+ expect(frame).not.toContain('fitView(')
+ expect(frame).toContain('setViewport(viewport, { duration: 300 })')
+ })
+
it('the resume card slot is spent only on a card that can render, and only when opted in', () => {
// Gated on settings.showResumeCard (default off) FIRST — a disabled card must not spend the
// one-shot slot — then once per app run, only with a live stop, and never under the opaque
diff --git a/src/renderer/canvas/fit-view.test.ts b/src/renderer/canvas/fit-view.test.ts
index 071289921..bae97ddcf 100644
--- a/src/renderer/canvas/fit-view.test.ts
+++ b/src/renderer/canvas/fit-view.test.ts
@@ -1,5 +1,13 @@
-import { describe, expect, it } from 'vitest'
-import { largestFreeRect, rectToPadding, rectsOverlap, type FitRect } from './fit-view'
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ FIT_VIEW_GAP,
+ largestFreeRect,
+ rectToPadding,
+ rectsOverlap,
+ solveFitFrame,
+ type FitRect
+} from './fit-view'
/**
* Geometry measured from a real 1264x722 canvas (see docs/superpowers/specs) — the chrome rects
@@ -122,3 +130,48 @@ describe('rectToPadding', () => {
})
})
})
+
+describe('solveFitFrame answers in the pane\u2019s own coordinates', () => {
+ // The camera transform lives in pane space, so a caller that computes the viewport itself
+ // (`viewportForRectInFrame`) needs the frame there — converting per call site is how the two
+ // would drift. `solveFitPadding` is expressed through this, so both stay one solve.
+ function pane(rect: { left: number; top: number; width: number; height: number }): HTMLElement {
+ const el = document.createElement('div')
+ el.getBoundingClientRect = () =>
+ ({
+ left: rect.left,
+ top: rect.top,
+ right: rect.left + rect.width,
+ bottom: rect.top + rect.height,
+ width: rect.width,
+ height: rect.height,
+ x: rect.left,
+ y: rect.top
+ }) as DOMRect
+ return el
+ }
+
+ afterEach(() => {
+ document.body.innerHTML = ''
+ })
+
+ it('offsets the frame by the pane origin, so an inset pane does not shift the camera', () => {
+ const flush = pane({ left: 0, top: 0, width: 1200, height: 800 })
+ const inset = pane({ left: 300, top: 120, width: 1200, height: 800 })
+ expect(solveFitFrame(inset, 600, 400)).toEqual(solveFitFrame(flush, 600, 400))
+ })
+
+ it('keeps the frame clear of visible chrome', () => {
+ document.body.innerHTML = '<div class="dock"></div>'
+ const dock = document.querySelector('.dock')!
+ dock.getBoundingClientRect = () =>
+ ({ left: 0, top: 700, right: 1200, bottom: 800, width: 1200, height: 100, x: 0, y: 700 }) as DOMRect
+ const frame = solveFitFrame(pane({ left: 0, top: 0, width: 1200, height: 800 }), 600, 400)!
+ expect(frame.bottom).toBeLessThanOrEqual(700 - FIT_VIEW_GAP)
+ })
+
+ it('gives up rather than returning a degenerate frame', () => {
+ expect(solveFitFrame(pane({ left: 0, top: 0, width: 8, height: 8 }), 600, 400)).toBeNull()
+ expect(solveFitFrame(pane({ left: 0, top: 0, width: 1200, height: 800 }), 0, 400)).toBeNull()
+ })
+})
diff --git a/src/renderer/canvas/fit-view.ts b/src/renderer/canvas/fit-view.ts
index 30fc57b0f..8af6facc4 100644
--- a/src/renderer/canvas/fit-view.ts
+++ b/src/renderer/canvas/fit-view.ts
@@ -140,14 +140,18 @@ export function rectToPadding(outer: FitRect, rect: FitRect): FitPadding {
}
/**
- * Solve the fit-view padding for the current chrome layout and content shape.
- * Returns null when there is nothing sensible to solve, so callers can fall back to plain fitView.
+ * The chrome-free rectangle for this content, in the pane's OWN coordinates (0,0 = the pane's
+ * top-left) rather than the window's. Null when there is nothing sensible to solve.
+ *
+ * Pane-local because that is the space a viewport transform lives in: a caller that computes the
+ * camera itself (`viewportForRectInFrame`) needs the frame in the same coordinates as the
+ * transform, and converting at each call site is how the two would drift.
*/
-export function solveFitPadding(
+export function solveFitFrame(
wrap: HTMLElement,
contentW: number,
contentH: number
-): FitPadding | null {
+): FitRect | null {
if (contentW <= 0 || contentH <= 0) return null
const v = wrap.getBoundingClientRect()
const outer: FitRect = { left: v.left, top: v.top, right: v.right, bottom: v.bottom }
@@ -159,5 +163,28 @@ export function solveFitPadding(
}
if (width(viewport) < 1 || height(viewport) < 1) return null
const rect = largestFreeRect(viewport, chromeObstacles(viewport), contentW, contentH)
- return rect ? rectToPadding(outer, rect) : null
+ return rect
+ ? {
+ left: rect.left - outer.left,
+ top: rect.top - outer.top,
+ right: rect.right - outer.left,
+ bottom: rect.bottom - outer.top
+ }
+ : null
+}
+
+/**
+ * Solve the fit-view padding for the current chrome layout and content shape.
+ * Returns null when there is nothing sensible to solve, so callers can fall back to plain fitView.
+ */
+export function solveFitPadding(
+ wrap: HTMLElement,
+ contentW: number,
+ contentH: number
+): FitPadding | null {
+ const frame = solveFitFrame(wrap, contentW, contentH)
+ if (!frame) return null
+ const v = wrap.getBoundingClientRect()
+ // `frame` is pane-local, so the pane's own box IS the outer rect at the origin.
+ return rectToPadding({ left: 0, top: 0, right: v.width, bottom: v.height }, frame)
}
diff --git a/src/renderer/lib/nodeFocus.test.ts b/src/renderer/lib/nodeFocus.test.ts
index 9d58f569a..92f32c429 100644
--- a/src/renderer/lib/nodeFocus.test.ts
+++ b/src/renderer/lib/nodeFocus.test.ts
@@ -5,7 +5,8 @@ import {
absolutePosition,
isMeasured,
nodeFitRect,
- viewportForRect
+ viewportForRect,
+ viewportForRectInFrame
} from './nodeFocus'
import type { FocusableNode } from './nodeFocus'
@@ -148,6 +149,37 @@ describe('viewportForRect', () => {
})
})
+describe('viewportForRectInFrame', () => {
+ // 1280×900 pane with a 340px sessions sidebar on the left: the chrome-free frame the solver
+ // hands over, in pane-local coordinates.
+ const frame = { left: 352, top: 12, right: 1268, bottom: 888 }
+
+ it('puts the node in the middle of the free frame, not of the whole pane', () => {
+ const rect = { x: 5000, y: 4000, width: 600, height: 400 }
+ const vp = viewportForRectInFrame(rect, frame)!
+ expect(vp.x + 5300 * vp.zoom).toBeCloseTo((frame.left + frame.right) / 2, 0)
+ expect(vp.y + 4200 * vp.zoom).toBeCloseTo((frame.top + frame.bottom) / 2, 0)
+ // And emphatically not at the canvas origin, which is where an empty fitView set lands the
+ // camera — the failure this whole path exists to make impossible.
+ expect(vp.x).not.toBeCloseTo((frame.left + frame.right) / 2, 0)
+ })
+
+ it('applies the same zoom clamp as every other framing path', () => {
+ expect(viewportForRectInFrame({ x: 0, y: 0, width: 8, height: 8 }, frame)!.zoom).toBe(
+ FIT_NODE_OPTIONS.maxZoom
+ )
+ expect(viewportForRectInFrame({ x: 0, y: 0, width: 90000, height: 90000 }, frame)!.zoom).toBe(
+ FIT_NODE_OPTIONS.minZoom
+ )
+ })
+
+ it('refuses a frame or a node it cannot size, so the camera stands still', () => {
+ const rect = { x: 0, y: 0, width: 600, height: 400 }
+ expect(viewportForRectInFrame(rect, { left: 10, top: 10, right: 10, bottom: 900 })).toBeNull()
+ expect(viewportForRectInFrame({ x: 0, y: 0, width: 0, height: 400 }, frame)).toBeNull()
+ })
+})
+
describe('isMeasured', () => {
it('reads React Flow measurements from either node shape, and tolerates a missing node', () => {
expect(isMeasured({ measured: { width: 600, height: 400 } })).toBe(true)
diff --git a/src/renderer/lib/nodeFocus.ts b/src/renderer/lib/nodeFocus.ts
index 0b7b1ad9c..1a9a57ed4 100644
--- a/src/renderer/lib/nodeFocus.ts
+++ b/src/renderer/lib/nodeFocus.ts
@@ -1,21 +1,26 @@
import { getViewportForBounds, type Rect, type Viewport } from '@xyflow/system'
/**
- * "Zoom to this node" geometry, computed WITHOUT React Flow's measurements.
+ * "Zoom to this node" geometry, computed without React Flow's `fitView`.
*
* Why this exists: `fitView({ nodes: [{ id }] })` is the natural way to frame one node, and it is
- * what `Canvas.goToNode` uses — but React Flow filters the fit set down to nodes it has already
- * MEASURED (`getFitViewNodes` keys off `measured.width && measured.height`; there is no
- * `width`/`height` fallback there). A node that was handed to React Flow a tick ago has no
- * measurement yet, so the fit set comes out EMPTY, its bounds collapse to `{0,0,0,0}` and the
- * camera flies to the canvas ORIGIN at max zoom — an empty stretch of canvas, nowhere near the
- * node. That is exactly the window a cross-project focus lands in: switch project → load its nodes
- * → focus the target, all before React Flow's mount-time measuring has run. (Clicking an OS
- * notification for a session in another project is the everyday path into it; the same node focuses
- * correctly on a second try, once it is measured.)
+ * what `Canvas.goToNode` used to do — but it frames nothing when you call it. It sets
+ * `fitViewQueued` and the fit is RESOLVED LATER: from a subsequent `setNodes` (and only once EVERY
+ * node is measured) or from the next `updateNodeInternals`. Whatever `nodeLookup` holds by then is
+ * what gets framed. And the fit set is filtered down to nodes React Flow has already MEASURED
+ * (`getFitViewNodes` keys off `measured.width && measured.height`; there is no `width`/`height`
+ * fallback there), so a set that comes out EMPTY collapses the bounds to `{0,0,0,0}` and the camera
+ * flies to the canvas ORIGIN at max zoom — an empty stretch of canvas, nowhere near the node.
*
- * So for the unmeasured case we do the same maths ourselves from the size the node was persisted
- * with — which needs no layout — and drive the camera with `setViewport`.
+ * Both halves fire on the same everyday path. A cross-project focus (sessions sidebar, OS
+ * notification, ⌘K jump, presence travel) switches project → loads its nodes → frames the target,
+ * all before the mount-time measuring has settled: the queued fit then waits for a later node
+ * update, and by the time it runs the canvas may have moved on. The second click always works,
+ * because by then everything is measured — which is what makes it read as "sometimes".
+ *
+ * So the maths is ours, from React Flow's measurement when it has one and from the size the node
+ * was persisted with when it does not — neither needs layout — and the camera is driven with
+ * `setViewport`, which applies immediately.
*/
/** The subset of a React Flow node this module needs. Loose on purpose: it must accept both a
@@ -30,9 +35,9 @@ export interface FocusableNode {
style?: { width?: number | string | null; height?: number | string | null }
}
-/** Zoom/padding for framing a single node. Kept beside the maths so the fallback path and
- * `fitView` cannot drift apart: the clamp keeps a small node from filling the screen and a
- * huge one from being fit microscopic. */
+/** Zoom/padding for framing a single node, shared by both framing paths here so the whole-pane
+ * and chrome-free-frame answers cannot drift apart: the clamp keeps a small node from filling the
+ * screen and a huge one from being fit microscopic. */
export const FIT_NODE_OPTIONS = { padding: 0.2, minZoom: 0.25, maxZoom: 1.38 } as const
/** A `parentId` chain longer than this is a data bug (or a cycle) — stop walking. */
@@ -102,6 +107,36 @@ export function viewportForRect(
)
}
+/** A rectangle inside the flow pane, in the pane's OWN coordinates (0,0 = its top-left) — the
+ * chrome-free area a node should be framed into. Structurally the `FitRect` of `canvas/fit-view`,
+ * restated here so this module stays free of anything that touches the DOM. */
+export interface FitFrame {
+ left: number
+ top: number
+ right: number
+ bottom: number
+}
+
+/**
+ * The viewport that puts `rect` in the middle of `frame`, at the zoom that fits it there.
+ *
+ * The counterpart to `viewportForRect` for callers that solved a chrome-free frame first: the node
+ * is centred in the space it can actually be seen in, rather than in the whole pane and then
+ * nudged out from under a panel. Null when either box has no usable size.
+ */
+export function viewportForRectInFrame(rect: Rect, frame: FitFrame): Viewport | null {
+ const frameW = frame.right - frame.left
+ const frameH = frame.bottom - frame.top
+ if (!(frameW > 0) || !(frameH > 0) || !(rect.width > 0) || !(rect.height > 0)) return null
+ const fit = Math.min(frameW / rect.width, frameH / rect.height)
+ const zoom = Math.min(Math.max(fit, FIT_NODE_OPTIONS.minZoom), FIT_NODE_OPTIONS.maxZoom)
+ return {
+ x: (frame.left + frame.right) / 2 - (rect.x + rect.width / 2) * zoom,
+ y: (frame.top + frame.bottom) / 2 - (rect.y + rect.height / 2) * zoom,
+ zoom
+ }
+}
+
/** Whether React Flow already knows this node's on-screen size — i.e. whether `fitView` will
* actually include it in its fit set. Takes the minimal shape so it reads either a user-land
* node or React Flow's own internal node (the authoritative one; see Canvas.goToNode). */