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): place a new group frame on the grid, with a full cell of clearance

Bas Milius977f475f50ce
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 2b4c090a8..b576df6d5 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -516,6 +516,17 @@ const isMac = /Mac/i.test(navigator.platform || navigator.userAgent)
const GRID = 24
+/**
+ * The grid a structural edit should snap to right now, 0 when snapping is off. Read through
+ * `getState()` rather than the component's `settings`, so a callback that is not re-created per
+ * settings change cannot act on a stale value. `gridSize: 0` reads as "use the default", exactly
+ * as it does everywhere else on this canvas.
+ */
+function snapGridNow(): number {
+ const settings = useSettings.getState().settings
+ return settings.snapToGrid ? settings.gridSize || GRID : 0
+}
+
/** The empty opaque set (glyphgrid), shared so the render-time compute allocates nothing on the
* overwhelmingly common "nothing overlaps / layer off" path. */
const EMPTY_OPAQUE: string[] = []
@@ -4975,7 +4986,7 @@ export function Canvas() {
const groupSelection = useCallback(
(ids: string[]) => {
const groupCount = nodesRef.current.filter((n) => n.type === 'group').length
- setNodes((ns) => groupSelectedNodes(ns as CanvasNode[], ids, groupCount))
+ setNodes((ns) => groupSelectedNodes(ns as CanvasNode[], ids, groupCount, snapGridNow()))
markDirty()
},
[setNodes, markDirty]
@@ -4985,7 +4996,7 @@ export function Canvas() {
// always makes a new one). Only subtree roots move — see addSelectionToGroup.
const addToExistingGroup = useCallback(
(ids: string[], groupId: string) => {
- setNodes((nodes) => addSelectionToGroup(nodes as CanvasNode[], ids, groupId))
+ setNodes((nodes) => addSelectionToGroup(nodes as CanvasNode[], ids, groupId, snapGridNow()))
markDirty()
},
[setNodes, markDirty]
@@ -9385,7 +9396,7 @@ export function Canvas() {
return
}
const groupCount = live.filter((nd) => nd.type === 'group').length
- let grouped = groupSelectedNodes(live, resolvable, groupCount)
+ let grouped = groupSelectedNodes(live, resolvable, groupCount, snapGridNow())
// The new frame is no longer guaranteed to be first (it is emitted in tree order),
// and a refused set returns the array unchanged — find it by id instead.
const oldIds = new Set(live.map((node) => node.id))
@@ -9460,7 +9471,7 @@ export function Canvas() {
if (was?.parentId) affected.add(was.parentId)
}
for (const g of affected) {
- if (next.some((n) => n.parentId === g)) next = fitGroupToChildren(next, g)
+ if (next.some((n) => n.parentId === g)) next = fitGroupToChildren(next, g, snapGridNow())
}
setNodes(next)
markDirty()
@@ -9498,7 +9509,7 @@ export function Canvas() {
: alignNodes(live, ids, edge!)
// Tidying a frame's children usually leaves the frame oversized (it was sized to their
// old scattered spots) — shrink it to hug the new layout. Top-level sets have no frame.
- if (container) next = fitGroupToChildren(next, container)
+ if (container) next = fitGroupToChildren(next, container, snapGridNow())
setNodes(next)
markDirty()
const how = verb === 'arrange' ? `as ${layout}` : `to ${edge}`
@@ -9638,7 +9649,7 @@ export function Canvas() {
const existingGroupIds = new Set(
next.filter((node) => node.type === 'group').map((node) => node.id)
)
- next = groupSelectedNodes(next, panelIds, vGroupCount)
+ next = groupSelectedNodes(next, panelIds, vGroupCount, snapGridNow())
const vGroup = next.find(
(node) => node.type === 'group' && !existingGroupIds.has(node.id)
)!
@@ -9766,7 +9777,7 @@ export function Canvas() {
const existingGroupIds = new Set(
next.filter((node) => node.type === 'group').map((node) => node.id)
)
- next = groupSelectedNodes(next, memberIds, groupCount)
+ next = groupSelectedNodes(next, memberIds, groupCount, snapGridNow())
const teamGroup = next.find(
(node) => node.type === 'group' && !existingGroupIds.has(node.id)
)!
diff --git a/src/renderer/lib/gridSnap.ts b/src/renderer/lib/gridSnap.ts
index fb19d1626..37ac78127 100644
--- a/src/renderer/lib/gridSnap.ts
+++ b/src/renderer/lib/gridSnap.ts
@@ -1,6 +1,4 @@
import type { NodeKind } from '@shared/types'
-import type { CanvasNode } from '../state/workspace'
-import { rootPosition } from '../state/workspace'
import { snapNodeToGrid, type Rect } from './nodeSizing'
export interface Point {
@@ -8,19 +6,9 @@ export interface Point {
y: number
}
-const ROOT_ORIGIN: Point = { x: 0, y: 0 }
-
-/**
- * Root-space origin of the container `parentId` names: (0, 0) for a top-level object, else the
- * frame's own root position. A missing frame resolves to the root rather than throwing, matching
- * how the rest of the canvas treats a dangling parentId.
- */
-export function containerOrigin(parentId: string | undefined, nodes: CanvasNode[]): Point {
- if (!parentId) return ROOT_ORIGIN
- const frame = nodes.find((node) => node.id === parentId)
- if (!frame) return ROOT_ORIGIN
- return rootPosition(frame, nodes)
-}
+// One home, in the module that owns `rootPosition`; re-exported so this stays the import site
+// every snap caller already uses.
+export { containerOrigin } from '../state/workspace'
/**
* Snap a CONTAINER-relative point onto the canvas grid.
@@ -28,9 +16,12 @@ export function containerOrigin(parentId: string | undefined, nodes: CanvasNode[
* React Flow snaps a drag in flow (root) coordinates and only converts to parent-relative
* afterwards: `XYDrag` runs `snapPosition(nextPosition, snapGrid)` and `calculateNodePosition`
* subtracts the parent origin after that. Rounding a parent-relative value directly instead puts
- * the object on the FRAME's grid, and `groupSelectedNodes` creates frames at
- * `(minX - 28, minY - 62)`, so an off-grid frame origin is the normal case — the two grids then
- * differ by the frame's own fractional offset and the first drag moves the object again.
+ * the object on the FRAME's grid, and the two grids then differ by the frame's own fractional
+ * offset, so the first drag moves the object again.
+ *
+ * `groupSelectedNodes` now places a frame on the grid when snapping is on, but this stays
+ * load-bearing: a frame created with snapping off, or moved while it was off, keeps a fractional
+ * origin for the rest of its life.
*/
export function snapPointInRootSpace(point: Point, origin: Point, grid: number): Point {
if (grid <= 0) return point
diff --git a/src/renderer/lib/nodeSizing.test.ts b/src/renderer/lib/nodeSizing.test.ts
index 11230c28e..1f31b34f5 100644
--- a/src/renderer/lib/nodeSizing.test.ts
+++ b/src/renderer/lib/nodeSizing.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { NODE_MIN_SIZES, snapNodeToGrid } from './nodeSizing'
+import { NODE_MIN_SIZES, expandRectToGrid, snapNodeToGrid } from './nodeSizing'
import type { NodeKind } from '@shared/types'
const G = 24
@@ -80,3 +80,46 @@ describe('snapNodeToGrid', () => {
}
})
})
+
+describe('expandRectToGrid', () => {
+ it('grows the rect outward: left/top floor, right/bottom ceil', () => {
+ // x=10 -> 0 (not the nearer 24), right=210 -> 216, so the rect only ever gains area.
+ const r = expandRectToGrid(G, 'sticky', { x: 10, y: 10, width: 200, height: 200 })
+ expect(r).toEqual({ x: 0, y: 0, width: 216, height: 216 })
+ })
+
+ it('never pulls an edge inward, where nearest-rounding would', () => {
+ // x=20 is nearer to 24 than to 0, so snapNodeToGrid moves the left edge RIGHT by 4,
+ // eating 4px of whatever clearance the caller put there.
+ const rect = { x: 20, y: 20, width: 400, height: 400 }
+ expect(snapNodeToGrid(G, 'group', rect).x).toBe(24)
+ const grown = expandRectToGrid(G, 'group', rect)
+ expect(grown.x).toBe(0)
+ expect(grown.y).toBeLessThanOrEqual(rect.y)
+ expect(grown.x + grown.width).toBeGreaterThanOrEqual(rect.x + rect.width)
+ expect(grown.y + grown.height).toBeGreaterThanOrEqual(rect.y + rect.height)
+ })
+
+ it('lands every corner on a grid intersection, negative origins included', () => {
+ const r = expandRectToGrid(G, 'sticky', { x: -13, y: -47, width: 190, height: 205 })
+ // Math.abs: a negative multiple modulo the grid is -0, which toBe distinguishes from 0.
+ expect(Math.abs(r.x % G)).toBe(0)
+ expect(Math.abs(r.y % G)).toBe(0)
+ expect(Math.abs((r.x + r.width) % G)).toBe(0)
+ expect(Math.abs((r.y + r.height) % G)).toBe(0)
+ })
+
+ it('raises a small rect to the kind grid-aligned minimum, extending right/bottom only', () => {
+ const r = expandRectToGrid(G, 'group', { x: 0, y: 0, width: 10, height: 10 })
+ expect(r.x).toBe(0)
+ expect(r.y).toBe(0)
+ expect(r.width).toBeGreaterThanOrEqual(NODE_MIN_SIZES.group.width)
+ expect(r.height).toBeGreaterThanOrEqual(NODE_MIN_SIZES.group.height)
+ })
+
+ it('normalizes -0 so it cannot ride into a persisted position', () => {
+ const r = expandRectToGrid(G, 'sticky', { x: -0, y: -0, width: 240, height: 240 })
+ expect(Object.is(r.x, -0)).toBe(false)
+ expect(Object.is(r.y, -0)).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/nodeSizing.ts b/src/renderer/lib/nodeSizing.ts
index ba26b8abd..274bbac69 100644
--- a/src/renderer/lib/nodeSizing.ts
+++ b/src/renderer/lib/nodeSizing.ts
@@ -52,3 +52,25 @@ export function snapNodeToGrid(g: number, kind: NodeKind, r: Rect): Rect {
if (height < minH) height = minH
return { x, y, width, height }
}
+
+/**
+ * Snap a rectangle onto the grid by growing it: left/top round DOWN, right/bottom round UP, so
+ * every edge lands on a grid line and the rect never loses area. `snapNodeToGrid` rounds each
+ * edge to the nearest line instead, which is right for a resize (the user is aiming an edge) and
+ * wrong for a frame that has to keep a minimum clearance around what it wraps — nearest-rounding
+ * pulls an edge inward by up to half a grid and eats the padding.
+ */
+export function expandRectToGrid(g: number, kind: NodeKind, r: Rect): Rect {
+ // `+ 0` normalizes the -0 that flooring a small negative coordinate produces, which would
+ // otherwise ride into node positions and out to project.json.
+ const x = Math.floor(r.x / g) * g + 0
+ const y = Math.floor(r.y / g) * g + 0
+ let width = Math.ceil((r.x + r.width) / g) * g - x
+ let height = Math.ceil((r.y + r.height) / g) * g - y
+ const min = NODE_MIN_SIZES[kind] ?? { width: 0, height: 0 }
+ const minW = Math.ceil(min.width / g) * g
+ const minH = Math.ceil(min.height / g) * g
+ if (width < minW) width = minW
+ if (height < minH) height = minH
+ return { x, y, width, height }
+}
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index 65e4c6d0f..a891c4948 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -363,6 +363,93 @@ describe('groupSelectedNodes', () => {
})
})
+describe('groupSelectedNodes with snapping on', () => {
+ const GRID = 20
+ const GROUP_PAD = 28
+ const GROUP_HEADER = 34
+
+ it('places the frame on the grid, all four edges', () => {
+ const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]
+ const group = groupSelectedNodes(nodes, ['t1', 't2'], 0, GRID)[0]
+ expect(group.position.x % GRID).toBe(0)
+ expect(group.position.y % GRID).toBe(0)
+ expect((group.position.x + (group.width as number)) % GRID).toBe(0)
+ expect((group.position.y + (group.height as number)) % GRID).toBe(0)
+ })
+
+ it('keeps at least the unsnapped clearance on every side', () => {
+ // Snapping may only push the frame outward. The members span (100,100)-(820,540).
+ const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]
+ const group = groupSelectedNodes(nodes, ['t1', 't2'], 0, GRID)[0]
+ const pad = Math.max(GROUP_PAD, GRID)
+ expect(group.position.x).toBeLessThanOrEqual(100 - pad)
+ expect(group.position.y).toBeLessThanOrEqual(100 - pad - GROUP_HEADER)
+ expect(group.position.x + (group.width as number)).toBeGreaterThanOrEqual(820 + pad)
+ expect(group.position.y + (group.height as number)).toBeGreaterThanOrEqual(540 + pad)
+ })
+
+ it('honours a grid coarser than the fixed padding', () => {
+ const coarse = 64
+ const nodes = [term('t1', { x: 200, y: 200 })]
+ const group = groupSelectedNodes(nodes, ['t1'], 0, coarse)[0]
+ expect(group.position.x).toBeLessThanOrEqual(200 - coarse)
+ expect(group.position.x % coarse).toBe(0)
+ })
+
+ it('leaves every member where it was on canvas', () => {
+ const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]
+ const out = groupSelectedNodes(nodes, ['t1', 't2'], 0, GRID)
+ const group = out[0]
+ for (const [id, pos] of [['t1', { x: 100, y: 100 }], ['t2', { x: 500, y: 300 }]] as const) {
+ const child = out.find((n) => n.id === id)!
+ expect(group.position.x + child.position.x).toBe(pos.x)
+ expect(group.position.y + child.position.y).toBe(pos.y)
+ }
+ })
+
+ it('snaps a nested frame onto the CANVAS grid, not its parent frame grid', () => {
+ // An off-grid frame origin is the normal case, so a parent-relative snap would land the
+ // wrapper on a grid offset by (-28, -62) from the one React Flow drags against.
+ const nodes = [
+ grp('outer', { x: -28, y: -62 }),
+ term('a', { x: 100, y: 100 }, 'outer'),
+ term('b', { x: 400, y: 260 }, 'outer')
+ ]
+ const out = groupSelectedNodes(nodes, ['a', 'b'], 1, GRID)
+ const outer = out.find((n) => n.id === 'outer')!
+ const wrapper = out.find((n) => !nodes.some((old) => old.id === n.id))!
+ expect(wrapper.parentId).toBe('outer')
+ // Math.abs: a negative multiple modulo the grid is -0, which toBe distinguishes from 0.
+ expect(Math.abs((outer.position.x + wrapper.position.x) % GRID)).toBe(0)
+ expect(Math.abs((outer.position.y + wrapper.position.y) % GRID)).toBe(0)
+ })
+
+ it('is byte-identical to the unsnapped box when snapping is off', () => {
+ const nodes = [term('t1', { x: 103, y: 107 }), term('t2', { x: 511, y: 313 })]
+ const group = groupSelectedNodes(nodes, ['t1', 't2'], 0, 0)[0]
+ expect(group.position).toEqual({ x: 103 - GROUP_PAD, y: 107 - GROUP_PAD - GROUP_HEADER })
+ expect(group.width).toBe(511 + 320 - 103 + GROUP_PAD * 2)
+ expect(group.height).toBe(313 + 240 - 107 + GROUP_PAD * 2 + GROUP_HEADER)
+ expect(groupSelectedNodes(nodes, ['t1', 't2'], 0)[0].position).toEqual(group.position)
+ })
+
+ it('keeps a re-fit frame on the grid, so a later fit cannot undo the placement', () => {
+ const nodes = [
+ grp('g1', { x: 100, y: 100 }),
+ term('a', { x: 23, y: 41 }, 'g1'),
+ term('b', { x: 61, y: 19 }, 'g1')
+ ]
+ const out = fitGroupToChildren(nodes, 'g1', GRID)
+ const g = out.find((n) => n.id === 'g1')!
+ expect(g.position.x % GRID).toBe(0)
+ expect(g.position.y % GRID).toBe(0)
+ // Children still sit where they were on canvas.
+ const a = out.find((n) => n.id === 'a')!
+ expect(g.position.x + a.position.x).toBe(123)
+ expect(g.position.y + a.position.y).toBe(141)
+ })
+})
+
describe('ungroupNodes', () => {
it('removes the frame and restores children to absolute positions', () => {
const nodes = [grp('g1', { x: 50, y: 50 }), term('t1', { x: 10, y: 10 }, 'g1')]
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index c0f0cf8da..fdb036f5b 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -15,7 +15,7 @@ import { assembleLaunchCommand } from '@shared/agents/launch'
import { agentAccountColor } from '@shared/agents/account-color'
import { agentEnvSnapshot } from '../lib/agentEnv'
import { uuid } from '@renderer/lib/uuid'
-import { snapNodeToGrid } from '../lib/nodeSizing'
+import { expandRectToGrid, snapNodeToGrid, type Rect } from '../lib/nodeSizing'
import { claudeCliCapsNow } from './permissionMode'
import { projectLaunchInfoNow } from './projectLaunchInfo'
import { isAgentEnabled, launchableDefaultAgent } from './agentAvailability'
@@ -1131,6 +1131,48 @@ const GROUP_HEADER = 34
const nodeW = (n: CanvasNode) => n.measured?.width ?? (n.width as number) ?? 0
const nodeH = (n: CanvasNode) => n.measured?.height ?? (n.height as number) ?? 0
+/**
+ * Geometry for a frame that has to wrap `bounds`, with its label header above. `bounds` and the
+ * result are both in the space of the frame's own container, which is where `parentId` points.
+ *
+ * With `grid` on, the frame is placed on the grid AT CREATION instead of being left off-grid for
+ * every later resize to compensate: the padding is raised to at least one cell and the box then
+ * grows OUTWARD to the surrounding grid lines, so all four edges land on the grid and the
+ * clearance around the children can only increase. Snapping runs in ROOT space, because React
+ * Flow snaps a drag there too — rounding this container-relative box directly would put a nested
+ * frame on its parent's grid, which is the defect the rest of this change removes.
+ *
+ * `grid <= 0` (snapping off) reproduces the original fixed-padding box exactly.
+ */
+function groupBox(
+ nodes: CanvasNode[],
+ parentId: string | undefined,
+ bounds: { minX: number; minY: number; maxX: number; maxY: number },
+ grid: number
+): Rect {
+ const pad = grid > 0 ? Math.max(GROUP_PAD, grid) : GROUP_PAD
+ const rect: Rect = {
+ x: bounds.minX - pad,
+ y: bounds.minY - pad - GROUP_HEADER,
+ width: bounds.maxX - bounds.minX + pad * 2,
+ height: bounds.maxY - bounds.minY + pad * 2 + GROUP_HEADER
+ }
+ if (grid <= 0) return rect
+ const origin = containerOrigin(parentId, nodes)
+ const snapped = expandRectToGrid(grid, 'group', {
+ x: rect.x + origin.x,
+ y: rect.y + origin.y,
+ width: rect.width,
+ height: rect.height
+ })
+ return {
+ x: snapped.x - origin.x + 0,
+ y: snapped.y - origin.y + 0,
+ width: snapped.width,
+ height: snapped.height
+ }
+}
+
export type ArrangeLayout = 'grid' | 'row' | 'column'
/**
@@ -1278,6 +1320,24 @@ export function rootPosition(node: CanvasNode, nodes: CanvasNode[]): { x: number
return { x, y }
}
+/**
+ * Root-space origin of the container `parentId` names: (0, 0) for a top-level object, else the
+ * frame's own root position. A missing frame resolves to the root rather than throwing, matching
+ * how the rest of the canvas treats a dangling parentId.
+ *
+ * Lives here rather than in `lib/gridSnap` (which re-exports it) because it is `rootPosition`
+ * with one branch in front, and two homes for that would drift.
+ */
+export function containerOrigin(
+ parentId: string | undefined,
+ nodes: CanvasNode[]
+): { x: number; y: number } {
+ if (!parentId) return { x: 0, y: 0 }
+ const frame = nodes.find((node) => node.id === parentId)
+ if (!frame) return { x: 0, y: 0 }
+ return rootPosition(frame, nodes)
+}
+
function isDescendant(nodes: CanvasNode[], candidateId: string, ancestorId: string): boolean {
const byId = new Map(nodes.map((node) => [node.id, node]))
const seen = new Set<string>()
@@ -1318,13 +1378,17 @@ export function selectedRootIds(nodes: CanvasNode[], ids: string[]): string[] {
* that gained a child bigger than itself must be re-fitted BEFORE its own parent is, or the
* parent is fitted around a size that is about to change.
*/
-function fitAncestorChain(nodes: CanvasNode[], groupId: string | undefined): CanvasNode[] {
+function fitAncestorChain(
+ nodes: CanvasNode[],
+ groupId: string | undefined,
+ grid = 0
+): CanvasNode[] {
let next = nodes
const seen = new Set<string>()
let currentId = groupId
while (currentId && !seen.has(currentId)) {
seen.add(currentId)
- next = fitGroupToChildren(next, currentId)
+ next = fitGroupToChildren(next, currentId, grid)
currentId = next.find((n) => n.id === currentId)?.parentId
}
return next
@@ -1478,15 +1542,18 @@ export function restoreMaximizedNode(nodes: CanvasNode[], nodeId: string): Canva
* descendant would be torn out of the ancestor being wrapped).
*
* When the members live inside a parent frame, that parent (and its own ancestors) are re-fitted
- * around the new wrapper. Without this the wrapper is created at `(minX - 28, minY - 62)` — often
- * NEGATIVE — inside a parent that is by construction too small to hold it, and `extent: 'parent'`
+ * around the new wrapper. Without this the wrapper is created at a negative offset from its
+ * members inside a parent that is by construction too small to hold it, and `extent: 'parent'`
* makes React Flow clamp it to `parentSize - wrapperSize`, i.e. hundreds of px off, dragging the
* whole wrapped subtree with it. Same trap `addGrouped` documents in Canvas.
+ *
+ * `grid` (0 = snapping off) puts the frame on the grid immediately — see `groupBox`.
*/
export function groupSelectedNodes(
nodes: CanvasNode[],
ids: string[],
- groupIndex: number
+ groupIndex: number,
+ grid = 0
): CanvasNode[] {
const set = new Set(ids)
const members = nodes.filter((n) => set.has(n.id))
@@ -1506,14 +1573,13 @@ export function groupSelectedNodes(
const maxX = Math.max(...members.map((n) => n.position.x + nodeW(n)))
const maxY = Math.max(...members.map((n) => n.position.y + nodeH(n)))
- const gx = minX - GROUP_PAD
- const gy = minY - GROUP_PAD - GROUP_HEADER
+ const parentId = members[0].parentId
+ const box = groupBox(nodes, parentId, { minX, minY, maxX, maxY }, grid)
const group = createGroupNode(
- { x: gx, y: gy },
- { width: maxX - minX + GROUP_PAD * 2, height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER },
+ { x: box.x, y: box.y },
+ { width: box.width, height: box.height },
groupIndex
)
- const parentId = members[0].parentId
if (parentId) {
group.parentId = parentId
group.extent = 'parent'
@@ -1525,12 +1591,12 @@ export function groupSelectedNodes(
...n,
parentId: group.id,
extent: 'parent' as const,
- position: { x: n.position.x - gx, y: n.position.y - gy },
+ position: { x: n.position.x - box.x, y: n.position.y - box.y },
selected: false
}
: n
)
- return fitAncestorChain(groupsFirst([group, ...updated]), parentId)
+ return fitAncestorChain(groupsFirst([group, ...updated]), parentId, grid)
}
/** Returns a copy of a node with a fresh id, offset position, and top-level placement. */
@@ -1555,7 +1621,11 @@ export function duplicateNode(node: CanvasNode, offset = 28): CanvasNode {
* to sit when they were grouped, so a tidy inner layout still leaves an oversized box. No-op for a
* missing/non-group id or a frame with no children. Pure.
*/
-export function fitGroupToChildren(nodes: CanvasNode[], groupId: string): CanvasNode[] {
+export function fitGroupToChildren(
+ nodes: CanvasNode[],
+ groupId: string,
+ grid = 0
+): CanvasNode[] {
const group = nodes.find((n) => n.id === groupId)
if (!group || group.type !== 'group') return nodes
const children = nodes.filter((n) => n.parentId === groupId)
@@ -1567,10 +1637,10 @@ export function fitGroupToChildren(nodes: CanvasNode[], groupId: string): Canvas
const minY = Math.min(...children.map(absY))
const maxX = Math.max(...children.map((c) => absX(c) + nodeW(c)))
const maxY = Math.max(...children.map((c) => absY(c) + nodeH(c)))
- const gx = minX - GROUP_PAD
- const gy = minY - GROUP_PAD - GROUP_HEADER
- const width = maxX - minX + GROUP_PAD * 2
- const height = maxY - minY + GROUP_PAD * 2 + GROUP_HEADER
+ // Same box as a fresh grouping, so a re-fit cannot pull a frame off the grid that
+ // `groupSelectedNodes` just put on it.
+ const box = groupBox(nodes, group.parentId, { minX, minY, maxX, maxY }, grid)
+ const { x: gx, y: gy, width, height } = box
return nodes.map((n) => {
if (n.id === groupId) {
return { ...n, position: { x: gx, y: gy }, width, height, style: { ...n.style, width, height } }
@@ -1654,7 +1724,8 @@ export function reparentNode(
export function addSelectionToGroup(
nodes: CanvasNode[],
selectedIds: string[],
- groupId: string
+ groupId: string,
+ grid = 0
): CanvasNode[] {
if (!nodes.some((node) => node.id === groupId && node.type === 'group')) return nodes
const selected = new Set(selectedIds)
@@ -1672,7 +1743,7 @@ export function addSelectionToGroup(
})
let next = nodes
for (const root of roots) next = reparentNode(next, root.id, groupId)
- return next === nodes ? nodes : fitAncestorChain(next, groupId)
+ return next === nodes ? nodes : fitAncestorChain(next, groupId, grid)
}
/**