Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(canvas): snap to object (#8171)
Seamus459d684647ae
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.mdindex 268206d870..622e3d50f4 100644--- a/apps/web/src/features/block-canvas/README.md+++ b/apps/web/src/features/block-canvas/README.md@@ -42,14 +42,27 @@ Camera zoom limits still apply; padding decreases for small embedded viewports.Ctrl/Meta-wheel zoom is pointer-anchored, with a continuous 0.002 exponential rateper normalized wheel pixel and an exponent cap of 0.2 per event (about 22% zoom-in).Plain wheel input pans at its existing speed.-The Canvas panel's zoom menu offers **No snapping** (the default for each session),+The Canvas panel's zoom menu offers **No grid snapping** (the default grid mode for each session),**Snap to px** (1 canvas px at every zoom), and **Auto snapping** (the smallestcurrently visible dot-grid interval, including faint dots). Auto follows zoom;hiding the grid temporarily disables it. Drawing, moving, resizing, insertion, duplication, pasting, freeconnector endpoints and layout inspector values use the chosen interval; inspectorscrubs preview the same snapped values they commit. Freehand and rotation keeptheir own precision, and connector bindings and aspect-ratio constraints stay exact.-The preference is local editor state, not saved JSON or shared Loro data.+The preferences are local editor state, not saved JSON or shared Loro data.+**Snap to objects** is independently enabled by default. Moving selections snap+their combined world bounds' edges and centers to nearby objects; axis-aligned+resize handles snap their moving edges. Matching axes show dashed guides and+prefer object alignment over grid snapping. The tolerance is six screen pixels,+with a 160-screen-pixel perpendicular reach. Shift constraints and proportional /+centered resizing remain intact; rotated resize frames retain local-axis behavior.+The graphics engine caches sorted alignment anchors with perpendicular interval+trees per immutable scene snapshot (O(n log n) construction). Each pointer update+queries a constant number of selection anchors and prunes distant candidates,+including long rows and columns, instead of comparing every selected object with+every scene object. Selected objects, descendants, and ancestors are excluded.+Gesture telemetry records query, candidate, and visited-index-node counts; its+span measures the gesture, not cold index construction.The dot grid adapts to zoom, revealing 1, 4, 16, 64 px levels (andcoarser levels at extreme zoom-out). Coarse dots remain steady while finer dotsfade in gently; individual canvas pixels are faintly visible at 800%. Dots usediff --git a/apps/web/src/features/block-canvas/canvas-next.tsx b/apps/web/src/features/block-canvas/canvas-next.tsxindex 7486e6f377..79984c3e5b 100644--- a/apps/web/src/features/block-canvas/canvas-next.tsx+++ b/apps/web/src/features/block-canvas/canvas-next.tsx@@ -18,6 +18,7 @@ import { registerCanvasNextHotkeys } from './hotkeys';import { createAssetState } from './primitives/create-asset-state';import { createCanvasState } from './primitives/create-canvas-state';import { createCanvasInsertState } from './primitives/create-insert-state';+import { observeObjectSnapping } from './primitives/observe-object-snapping';import { importTextClipboard } from './primitives/text-lexical';import { canvasAssetSource } from './queries/assets';import { CanvasReadOnlyView } from './views/canvas-read-only-view';@@ -73,6 +74,7 @@ function EditableCanvasNext(props: {}) {const editor = props.editor;const state = createCanvasState(editor, props.measureText);+ observeObjectSnapping(editor, props.documentId);const assets = createAssetState(state, canvasAssetSource);const insert = createCanvasInsertState(editor.getCamera);const { openWithSplit } = useSplitLayout();diff --git a/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.ts b/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.tsindex db3e4cc3de..aec406f2a0 100644--- a/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.ts+++ b/apps/web/src/features/block-canvas/primitives/create-canvas-snapping.ts@@ -9,6 +9,8 @@ export function createCanvasSnapping() {const [snapMode, setMode] = createSignal<CanvasSnapMode>('none');const [grid, setGridVisible] = createSignal(true);+ const [snapToObjects, setObjects] = createSignal(true);+ editor.setObjectSnapping(true);const apply = () => {const unit = canvasSnapUnit(snapMode(), editor.getCamera().scale, grid());if (unit === editor.getSnapUnit()) return;@@ -20,6 +22,12 @@ export function createCanvasSnapping(return {snapMode,grid,+ snapToObjects,+ setSnapToObjects(enabled: boolean) {+ cancelPreviews();+ setObjects(enabled);+ editor.setObjectSnapping(enabled);+ },setSnapMode(mode: CanvasSnapMode) {batch(() => {setMode(mode);diff --git a/apps/web/src/features/block-canvas/primitives/observe-object-snapping.ts b/apps/web/src/features/block-canvas/primitives/observe-object-snapping.tsnew file mode 100644index 0000000000..a1bbd6148e--- /dev/null+++ b/apps/web/src/features/block-canvas/primitives/observe-object-snapping.ts@@ -0,0 +1,47 @@+import type { GraphicsEditor, ObjectSnapStats } from '@macro-inc/graphics';+import { Telemetry } from '@macro-inc/observability';+import { onCleanup } from 'solid-js';++/** One trace per gesture, with aggregate query work rather than per-pointer spans. */+export function observeObjectSnapping(+ editor: GraphicsEditor,+ documentId: string+) {+ let span: ReturnType<typeof Telemetry.span> | undefined;+ let stats: ObjectSnapStats | undefined;+ let snappedUpdates = 0;+ let initial = editor.document;+ const finish = () => {+ if (!span) return;+ span.setAttr('snap.targets', stats?.targets ?? 0);+ span.setAttr('snap.queries', stats?.queries ?? 0);+ span.setAttr('snap.candidates', stats?.candidates ?? 0);+ span.setAttr('snap.index_nodes_visited', stats?.visited ?? 0);+ span.setAttr('snap.snapped_updates', snappedUpdates);+ span.setAttr(+ 'outcome',+ editor.document === initial ? 'cancelled' : 'committed'+ );+ span.end();+ span = undefined;+ };+ onCleanup(+ editor.subscribeSession((session) => {+ const transform = session.transform;+ if (!transform?.snapStats) {+ finish();+ return;+ }+ if (!span) {+ span = Telemetry.span('canvas.object_snap');+ span.setAttr('document.id', documentId);+ span.setAttr('transform.kind', transform.kind);+ initial = editor.document;+ snappedUpdates = 0;+ }+ stats = transform.snapStats;+ if (transform.snapGuides.length) snappedUpdates++;+ })+ );+ onCleanup(finish);+}diff --git a/apps/web/src/features/block-canvas/views/canvas-toolbars.tsx b/apps/web/src/features/block-canvas/views/canvas-toolbars.tsxindex 740f26676f..f32985dbe7 100644--- a/apps/web/src/features/block-canvas/views/canvas-toolbars.tsx+++ b/apps/web/src/features/block-canvas/views/canvas-toolbars.tsx@@ -241,6 +241,8 @@ export function CanvasViewControls(onGrid: (visible: boolean) => void;snapMode: CanvasSnapMode;onSnapMode: (mode: CanvasSnapMode) => void;+ snapToObjects: boolean;+ onSnapToObjects: (enabled: boolean) => void;}) {return (@@ -256,11 +258,19 @@ export function CanvasViewControls(Toggle dot grid</CanvasViewCheckboxItem></Dropdown.Group>+ <Dropdown.Group>+ <CanvasViewCheckboxItem+ checked={props.snapToObjects}+ onChange={props.onSnapToObjects}+ >+ Snap to objects+ </CanvasViewCheckboxItem>+ </Dropdown.Group><Dropdown.Group><Foreach={[- { mode: 'none', label: 'No snapping' },+ { mode: 'none', label: 'No grid snapping' },{ mode: 'pixel', label: 'Snap to px' },{ mode: 'auto', label: 'Auto snapping' },] as constdiff --git a/apps/web/src/features/block-canvas/views/canvas-view.tsx b/apps/web/src/features/block-canvas/views/canvas-view.tsxindex 7453f1f742..e2cdd7e21c 100644--- a/apps/web/src/features/block-canvas/views/canvas-view.tsx+++ b/apps/web/src/features/block-canvas/views/canvas-view.tsx@@ -287,6 +287,8 @@ export function CanvasView(props: {onFitSelection={fitSelection}snapMode={state.snapMode()}onSnapMode={state.setSnapMode}+ snapToObjects={state.snapToObjects()}+ onSnapToObjects={state.setSnapToObjects}/></header><Show when={state.selection().length > 0}>diff --git a/docs/agent-guide/documents.md b/docs/agent-guide/documents.mdindex 5b3da31337..b79b8cfa8a 100644--- a/docs/agent-guide/documents.md+++ b/docs/agent-guide/documents.md@@ -141,6 +141,16 @@ must never enter the saved scene. When opening a canvas, image nodes show aloads; this also applies to read-only embeds. Failed image requests display“Media unavailable” instead of an indefinite skeleton.+Canvas object snapping is enabled by default. Drag a shape or selection near+another object's edge or center to align it; dashed guides show the matched axes.+Axis-aligned resize handles also snap. The tolerance stays six screen pixels at+any zoom, and objects more than 160 screen pixels away on the perpendicular axis+are ignored. In **Zoom options**, toggle **Snap to objects** independently of+**No grid snapping**, **Snap to px**, or **Auto snapping**. Object alignment takes+priority over grid snapping on the matched axis. Verify dragging with snapping+on/off, resizing, Shift-constrained movement, zoom changes, and undo. Rotated+resize frames retain their existing local-axis resizing behavior.+Canvas embeds are read-only: **Select** selects shapes without moving them,and **Hand** pans the canvas. The toolbar contains only those two tools; propertyinspector details and drawing/editing controls are absent. Check toolbar clicks,diff --git a/packages/graphics/README.md b/packages/graphics/README.mdindex f496421975..3a33ef674d 100644--- a/packages/graphics/README.md+++ b/packages/graphics/README.md@@ -85,7 +85,7 @@ individual shapes. This does not change hit testing for unselected shapes.Editors accept `snapUnit` in their options, with `getSnapUnit()` and`setSnapUnit(unit)` for local configuration. Any positive finite scene-unit-interval is supported, including fractions; `undefined` disables snapping.+interval is supported, including fractions; `undefined` disables grid snapping.It is independent of camera zoom, document serialization and backend choice.Changing the unit cancels active drawing/transform previews without adding history.`CommandContext.snapUnit` and the pure `snapValue`, `snapPoint`, and@@ -101,6 +101,20 @@ bindings and angle/axis constraints take priority over the grid. Freehand samplerotation, equal distribution and exact alignment retain their own semantics.Snapping does not round existing documents on load or remote updates.+Object snapping is a separate opt-in editor option (`objectSnapping`, default+`false`) controlled by `setObjectSnapping(enabled)` and exposed in the session.+Canvas enables it by default. Moves align the selection's combined world bounds'+edges and centers; axis-aligned resize handles align their moving edges. Rotated+resize frames keep local-axis behavior, and image surfaces do not object-snap.+The index caches sorted anchors and perpendicular interval trees per immutable+scene snapshot, with O(n log n) construction and a constant number of spatially+pruned anchor queries per pointer update. Selected objects and their ancestors /+descendants are excluded. Tolerance is six screen pixels; perpendicular reach is+160 screen pixels. Object matches override grid values on matched axes without+breaking axis or aspect constraints. `transform.snapGuides` drives the Solid+overlay and `transform.snapStats` exposes aggregate query work to host telemetry.+Changing the setting cancels active transforms without adding history.+The Solid surface's dot grid is camera-aware presentation: scene-unit intervals1, 4, 16, 64, 256, etc. appear progressively as zoom increases. Fine dots fade infrom invisible at 4 screen pixels apart to full strength at 36; coarser dots staydiff --git a/packages/graphics/src/core/editor.ts b/packages/graphics/src/core/editor.tsindex 7640be5c7d..4032be0263 100644--- a/packages/graphics/src/core/editor.ts+++ b/packages/graphics/src/core/editor.ts@@ -51,12 +51,15 @@ export type EditingSession = SelectionState &canUndo: boolean;canRedo: boolean;snapUnit?: number;+ objectSnapping: boolean;}>;export type GraphicsEditorOptions = Readonly<{measureText?: TextMeasurer;/** Any positive finite scene-unit interval; omitted disables snapping. */snapUnit?: number;+ /** Align nearby edges and centers during selection transforms. Off by default. */+ objectSnapping?: boolean;}>;export type GraphicsEditor = ReturnType<typeof createGraphicsEditor>;@@ -83,6 +86,7 @@ function createEditor() {validateSnapUnit(options.snapUnit);let snapUnit = options.snapUnit;+ let objectSnapping = options.objectSnapping ?? false;let document: GraphicsDocument = Array.isArray(seed)? createScene(seed): freezeDocument(seed as GraphicsDocument);@@ -98,6 +102,7 @@ function createEditor(Object.freeze({...selection.getState(),snapUnit,+ objectSnapping,canUndo: backend ? backend.getHistory().canUndo : undoStack.length > 0,canRedo: backend ? backend.getHistory().canRedo : redoStack.length > 0,});@@ -108,6 +113,8 @@ function createEditor(const selection = createSelection({measureText: options.measureText,getSnapUnit: () => snapUnit,+ getObjectSnapping: () => objectSnapping,+ getScale: () => camera.scale,getDocument: () => document,commitDocument,cancelDrawing: cancelShape,@@ -332,6 +339,11 @@ function createEditor(},getSession,getSnapUnit: () => snapUnit,+ setObjectSnapping(enabled: boolean) {+ if (disposed || objectSnapping === enabled) return;+ objectSnapping = enabled;+ cancelTransform();+ },setSnapUnit(unit: number | undefined) {validateSnapUnit(unit);if (disposed || unit === snapUnit) return;diff --git a/packages/graphics/src/core/index.ts b/packages/graphics/src/core/index.tsindex 0ee4424678..646c30c053 100644--- a/packages/graphics/src/core/index.ts+++ b/packages/graphics/src/core/index.ts@@ -48,6 +48,7 @@ export type {ShapeKind,SurfaceItem,} from './model';+export type { ObjectSnapStats, SnapGuide } from './object-snapping';export {isSortKey,type LayerPosition,diff --git a/packages/graphics/src/core/object-snap-resize.ts b/packages/graphics/src/core/object-snap-resize.tsnew file mode 100644index 0000000000..3c00df6990--- /dev/null+++ b/packages/graphics/src/core/object-snap-resize.ts@@ -0,0 +1,113 @@+import {+ corners,+ enclosing,+ inverse,+ type Matrix,+ multiply,+ transformPoint,+} from './affine';+import type { Bounds, Point } from './model';+import type { ObjectSnapper, SnapGuide } from './object-snapping';+import { type ResizeHandle, resizeBox } from './resize';++/** Snap axis-aligned resize handles after grid/proportion constraints. Rotated+ * resize frames keep their local-axis behavior instead of jumping off-axis. */+export function snapObjectResize(+ bounds: Bounds,+ handle: ResizeHandle,+ delta: Point,+ modifiers: Parameters<typeof resizeBox>[3],+ world: Matrix,+ snapper: ObjectSnapper | undefined,+ scale: number+) {+ const fallback = resizeBox(bounds, handle, delta, modifiers);+ const guides: SnapGuide[] = [];+ if (!snapper || Math.abs(world[1]) > 1e-8 || Math.abs(world[2]) > 1e-8)+ return { resized: fallback, guides };+ const initial = resizeBox(bounds, handle, delta, {+ ...modifiers,+ snap: undefined,+ });+ const horizontal = handle.includes('w') || handle.includes('e');+ const vertical = handle.includes('n') || handle.includes('s');+ const moving = {+ x:+ bounds.x ++ bounds.width * (horizontal ? (handle.includes('w') ? 0 : 1) : 0.5),+ y:+ bounds.y ++ bounds.height * (vertical ? (handle.includes('n') ? 0 : 1) : 0.5),+ };+ const local = transformPoint(initial.transform, moving);+ const end = transformPoint(world, local);+ const projected = enclosing(+ corners(bounds).map((p) =>+ transformPoint(multiply(world, initial.transform), p)+ )+ );+ const match = snapper.snap(projected, scale, {+ x: horizontal ? [end.x] : [],+ y: vertical ? [end.y] : [],+ });+ if (!match.guides.length) return { resized: fallback, guides };+ let desired = transformPoint(inverse(world), {+ x: end.x + match.offset.x,+ y: end.y + match.offset.y,+ });+ if (modifiers.proportional) {+ const anchor = {+ x:+ bounds.x ++ bounds.width *+ (modifiers.fromCenter || !horizontal+ ? 0.5+ : handle.includes('w')+ ? 1+ : 0),+ y:+ bounds.y ++ bounds.height *+ (modifiers.fromCenter || !vertical+ ? 0.5+ : handle.includes('n')+ ? 1+ : 0),+ };+ const useX =+ match.guides.some((guide) => guide.axis === 'x') &&+ (!match.guides.some((guide) => guide.axis === 'y') ||+ Math.abs(match.offset.x) <= Math.abs(match.offset.y));+ const axis = useX ? 'x' : 'y';+ const distance = local[axis] - anchor[axis];+ if (Math.abs(distance) < 1e-8) return { resized: fallback, guides };+ const factor = (desired[axis] - anchor[axis]) / distance;+ desired = {+ x: anchor.x + (local.x - anchor.x) * factor,+ y: anchor.y + (local.y - anchor.y) * factor,+ };+ } else {+ const gridEnd = transformPoint(fallback.transform, moving);+ desired = {+ x: match.guides.some((guide) => guide.axis === 'x')+ ? desired.x+ : gridEnd.x,+ y: match.guides.some((guide) => guide.axis === 'y')+ ? desired.y+ : gridEnd.y,+ };+ }+ const resized = resizeBox(+ bounds,+ handle,+ { x: desired.x - moving.x, y: desired.y - moving.y },+ { ...modifiers, snap: undefined }+ );+ const final = transformPoint(multiply(world, resized.transform), moving);+ return {+ resized,+ guides: match.guides.filter(+ (guide) => Math.abs(final[guide.axis] - guide.value) * scale < 1e-5+ ),+ };+}diff --git a/packages/graphics/src/core/object-snapping.ts b/packages/graphics/src/core/object-snapping.tsnew file mode 100644index 0000000000..b38f8c09fb--- /dev/null+++ b/packages/graphics/src/core/object-snapping.ts@@ -0,0 +1,263 @@+import {+ corners,+ enclosing,+ IDENTITY,+ type Matrix,+ multiply,+ transformPoint,+} from './affine';+import type { Bounds, GraphicsDocument, Point } from './model';+import { children } from './ordering';+import { isShape, shapeDefinition } from './shapes/registry';++export type SnapGuide = Readonly<{+ axis: 'x' | 'y';+ value: number;+ start: number;+ end: number;+}>;+export type ObjectSnapStats = Readonly<{+ targets: number;+ queries: number;+ candidates: number;+ visited: number;+}>;+type Anchor = { value: number; bounds: Bounds; id: string };+type RangeNode = {+ from: number;+ to: number;+ min: number;+ max: number;+ left?: RangeNode;+ right?: RangeNode;+};+type AxisIndex = { entries: Anchor[]; tree?: RangeNode };+type SnapIndex = { x: AxisIndex; y: AxisIndex; targets: number };++function indexAxis(entries: Anchor[], other: 'x' | 'y'): AxisIndex {+ const size = other === 'x' ? 'width' : 'height';+ entries.sort(+ (a, b) => a.value - b.value || a.bounds[other] - b.bounds[other]+ );+ function build(from: number, to: number): RangeNode {+ if (to - from === 1) {+ const bounds = entries[from]!.bounds;+ return {+ from,+ to,+ min: bounds[other],+ max: bounds[other] + bounds[size],+ };+ }+ const mid = (from + to) >>> 1;+ const left = build(from, mid),+ right = build(mid, to);+ return {+ from,+ to,+ min: Math.min(left.min, right.min),+ max: Math.max(left.max, right.max),+ left,+ right,+ };+ }+ return {+ entries,+ tree: entries.length ? build(0, entries.length) : undefined,+ };+}+const indexes = new WeakMap<GraphicsDocument['items'], SnapIndex>();+const positions = (start: number, size: number) => [+ start,+ start + size / 2,+ start + size,+];++function union(a: Bounds, b: Bounds): Bounds {+ const x = Math.min(a.x, b.x),+ y = Math.min(a.y, b.y);+ return {+ x,+ y,+ width: Math.max(a.x + a.width, b.x + b.width) - x,+ height: Math.max(a.y + a.height, b.y + b.height) - y,+ };+}++/** Build world bounds in one hierarchy traversal, then sort three anchors per axis.+ * Immutable document snapshots share the O(n log n) index across gestures. */+function indexScene(document: GraphicsDocument): SnapIndex {+ const cached = indexes.get(document.items);+ if (cached) return cached;+ const anchors: { x: Anchor[]; y: Anchor[]; targets: number } = {+ x: [],+ y: [],+ targets: 0,+ };+ function visit(id: string, parent: Matrix): Bounds | undefined {+ const item = document.items[id];+ if (!item || item.type === 'surface') return;+ const world = multiply(parent, item.transform);+ let bounds: Bounds | undefined;+ if (isShape(item)) {+ // Connector bindings move independently; their attachment snapping has its own policy.+ if (item.type === 'connector' || item.appearance.opacity === 0) return;+ const definition = shapeDefinition(item.type);+ bounds =+ definition.transformedBounds?.(item, world) ??+ enclosing(+ corners(definition.bounds(item)).map((p) => transformPoint(world, p))+ );+ } else {+ let complete = true;+ for (const child of children(document, id)) {+ const childBounds = visit(child, world);+ if (!childBounds) complete = false;+ else bounds = bounds ? union(bounds, childBounds) : childBounds;+ }+ // Do not advertise a group box that omits a connector or hidden child.+ if (!complete) return;+ }+ if (!bounds) return;+ anchors.targets++;+ for (const value of positions(bounds.x, bounds.width))+ anchors.x.push({ value, bounds, id });+ for (const value of positions(bounds.y, bounds.height))+ anchors.y.push({ value, bounds, id });+ return bounds;+ }+ for (const id of children(document)) visit(id, IDENTITY);+ const index: SnapIndex = {+ x: indexAxis(anchors.x, 'y'),+ y: indexAxis(anchors.y, 'x'),+ targets: anchors.targets,+ };+ if (Object.isFrozen(document.items)) indexes.set(document.items, index);+ return index;+}++/** Selection size does not multiply query work: query the combined moving box,+ * using a constant number of indexed alignment-band searches per update. The+ * orthogonal interval tree also prunes distant objects sharing a row/column. */+export function createObjectSnapper(+ document: GraphicsDocument,+ selection: readonly string[]+) {+ const index = indexScene(document);+ const excluded = new Set<string>();+ const descendants = (id: string) => {+ if (excluded.has(id)) return;+ excluded.add(id);+ for (const child of children(document, id)) descendants(child);+ };+ for (const id of selection) descendants(id);+ for (const id of selection) {+ let item = document.items[id];+ while (item && item.type !== 'surface') {+ const parent = item.placement.parentId;+ if (excluded.has(parent)) break;+ excluded.add(parent);+ item = document.items[parent];+ }+ }+ let queries = 0,+ candidates = 0,+ visited = 0;+ function find(+ axis: 'x' | 'y',+ anchors: readonly number[],+ bounds: Bounds,+ scale: number+ ) {+ const tolerance = 6 / scale,+ reach = 160 / scale;+ const other = axis === 'x' ? 'y' : 'x';+ const size = axis === 'x' ? 'height' : 'width';+ let best: { offset: number; anchor: Anchor; distance: number } | undefined;+ for (const value of anchors) {+ queries++;+ const { entries, tree } = index[axis];+ function visit(node: RangeNode | undefined) {+ if (!node) return;+ visited++;+ if (+ entries[node.from]!.value > value + tolerance ||+ entries[node.to - 1]!.value < value - tolerance ||+ node.min > bounds[other] + bounds[size] + reach ||+ node.max < bounds[other] - reach+ )+ return;+ if (node.left || node.right) {+ visit(node.left);+ visit(node.right);+ return;+ }+ const entry = entries[node.from]!;+ candidates++;+ if (excluded.has(entry.id)) return;+ const gap = Math.max(+ 0,+ entry.bounds[other] - bounds[other] - bounds[size],+ bounds[other] - entry.bounds[other] - entry.bounds[size]+ );+ if (gap > reach) return;+ const offset = entry.value - value;+ if (+ !best ||+ Math.abs(offset) < Math.abs(best.offset) ||+ (Math.abs(offset) === Math.abs(best.offset) && gap < best.distance)+ )+ best = { offset, anchor: entry, distance: gap };+ }+ visit(tree);+ }+ return best;+ }+ return {+ stats: (): ObjectSnapStats => ({+ targets: index.targets,+ queries,+ candidates,+ visited,+ }),+ snap(+ bounds: Bounds,+ scale: number,+ anchors = {+ x: positions(bounds.x, bounds.width),+ y: positions(bounds.y, bounds.height),+ }+ ) {+ const x = find('x', anchors.x, bounds, scale),+ y = find('y', anchors.y, bounds, scale);+ const offset: Point = { x: x?.offset ?? 0, y: y?.offset ?? 0 };+ const guides: SnapGuide[] = [];+ for (const [axis, match] of [+ ['x', x],+ ['y', y],+ ] as const) {+ if (!match) continue;+ const other = axis === 'x' ? 'y' : 'x',+ size = axis === 'x' ? 'height' : 'width';+ guides.push({+ axis,+ value: match.anchor.value,+ start:+ Math.min(+ bounds[other] + offset[other],+ match.anchor.bounds[other]+ ) -+ 8 / scale,+ end:+ Math.max(+ bounds[other] + offset[other] + bounds[size],+ match.anchor.bounds[other] + match.anchor.bounds[size]+ ) ++ 8 / scale,+ });+ }+ return { offset, guides };+ },+ };+}+export type ObjectSnapper = ReturnType<typeof createObjectSnapper>;diff --git a/packages/graphics/src/core/selection.ts b/packages/graphics/src/core/selection.tsindex 0ae08bdc69..6ffbe02bc3 100644--- a/packages/graphics/src/core/selection.ts+++ b/packages/graphics/src/core/selection.ts@@ -12,6 +12,13 @@ import {} from './affine';import { duplicateNodes, type IdFactory } from './fragments';import type { Bounds, GraphicsDocument, GraphicsItem, Point } from './model';+import { snapObjectResize } from './object-snap-resize';+import {+ createObjectSnapper,+ type ObjectSnapper,+ type ObjectSnapStats,+ type SnapGuide,+} from './object-snapping';import {dragRectangleRadius,isRadiusHandle,@@ -55,11 +62,15 @@ export type SelectionState = Readonly<{geometries: Readonly<Record<string, Bounds>>;nodes: SceneOverrides;document?: GraphicsDocument;+ snapGuides: readonly SnapGuide[];+ snapStats?: ObjectSnapStats;}>;}>;export type SelectionHost = Readonly<{measureText?: TextMeasurer;getSnapUnit?: () => number | undefined;+ getObjectSnapping?: () => boolean;+ getScale?: () => number;getDocument: () => GraphicsDocument;commitDocument: (document: GraphicsDocument) => void;cancelDrawing: () => void;@@ -88,6 +99,9 @@ export function createSelection(host: SelectionHost) {pivot: Point;nodes: SceneOverrides;originalSelection?: readonly string[];+ bounds: Bounds;+ snapper?: ObjectSnapper;+ snapGuides: readonly SnapGuide[];}| undefined;const emit = () => host.onChange();@@ -120,6 +134,8 @@ export function createSelection(host: SelectionHost) {geometries: Object.freeze(geometries),nodes: gesture.nodes,document: gesture.originalSelection ? gesture.base : undefined,+ snapGuides: gesture.snapGuides,+ snapStats: gesture.snapper?.stats(),}): undefined,});@@ -153,6 +169,8 @@ export function createSelection(host: SelectionHost) {const node = resolvedShape(base, id) ?? base.items[id];const nodes: Record<string, GraphicsItem> = Object.create(null);const unit = host.getSnapUnit?.();+ const scale = host.getScale?.() ?? 1;+ let snapGuides: readonly SnapGuide[] = [];if (isRadiusHandle(handle)) {if (node?.type !== 'rectangle') return;nodes[id] = dragRectangleRadius(@@ -175,7 +193,7 @@ export function createSelection(host: SelectionHost) {// Different child axes force uniform scaling for the entire selection,// including edge drags. This keeps the dragged box and content in sync.const proportional = modifiers.proportional || !frame.canDeform;- const resized = resizeBox(+ const snapped = snapObjectResize(bounds,handle,{@@ -186,8 +204,13 @@ export function createSelection(host: SelectionHost) {...modifiers,proportional,snap: unit === undefined ? undefined : { x: unit, y: unit },- }+ },+ frame.transform,+ gesture.snapper,+ scale);+ const resized = snapped.resized;+ snapGuides = snapped.guides;const delta = multiply(frame.transform,multiply(resized.transform, fromWorld)@@ -232,16 +255,26 @@ export function createSelection(host: SelectionHost) {? { proportional: true, proportionalFit: 'project' as const }: {}),};- let resized = resizeBox(localBounds, handle, delta, {- ...resizeModifiers,- snap:- unit === undefined- ? undefined- : {- x: unit / Math.hypot(world[0], world[1]),- y: unit / Math.hypot(world[2], world[3]),- },- });+ const snapped = snapObjectResize(+ localBounds,+ handle,+ delta,+ {+ ...resizeModifiers,+ snap:+ unit === undefined+ ? undefined+ : {+ x: unit / Math.hypot(world[0], world[1]),+ y: unit / Math.hypot(world[2], world[3]),+ },+ },+ world,+ surface ? undefined : gesture.snapper,+ scale+ );+ let resized = snapped.resized;+ snapGuides = snapped.guides;if (surface && unit !== undefined) {const matrix = multiply(world, resized.transform);const outside = corners(localBounds).some((point) => {@@ -271,32 +304,50 @@ export function createSelection(host: SelectionHost) {let dx = point.x - origin.x,dy = point.y - origin.y;const horizontal = Math.abs(dx) >= Math.abs(dy);- if (!handle && unit !== undefined) {- // A single shape's frame is local; moving always snaps in world space.- const anchor =- targets.length === 1 && isShape(base.items[targets[0]!])- ? worldBounds(base, targets[0]!)- : frame.bounds;- const snapped = snapTranslation(anchor, { x: dx, y: dy }, unit);- dx = snapped.x;- dy = snapped.y;- }- if (!handle && base.surface) {- const bounds = enclosing(- targets.flatMap((key) => nodeBoundsPoints(base, key))- );- dx = Math.max(- -bounds.x,- Math.min(base.surface.width - bounds.x - bounds.width, dx)- );- dy = Math.max(- -bounds.y,- Math.min(base.surface.height - bounds.y - bounds.height, dy)- );- }- if (!handle && modifiers.constrainAxis) {- if (horizontal) dy = 0;- else dx = 0;+ if (!handle) {+ if (modifiers.constrainAxis) {+ if (horizontal) dy = 0;+ else dx = 0;+ }+ const bounds = gesture.bounds;+ const moving = { ...bounds, x: bounds.x + dx, y: bounds.y + dy };+ const snapper = base.surface ? undefined : gesture.snapper;+ const snapped = snapper?.snap(moving, scale, {+ x:+ modifiers.constrainAxis && !horizontal+ ? []+ : [+ moving.x,+ moving.x + moving.width / 2,+ moving.x + moving.width,+ ],+ y:+ modifiers.constrainAxis && horizontal+ ? []+ : [+ moving.y,+ moving.y + moving.height / 2,+ moving.y + moving.height,+ ],+ });+ const grid = snapTranslation(bounds, { x: dx, y: dy }, unit);+ dx = snapped?.guides.some((g) => g.axis === 'x')+ ? dx + snapped.offset.x+ : grid.x;+ dy = snapped?.guides.some((g) => g.axis === 'y')+ ? dy + snapped.offset.y+ : grid.y;+ snapGuides = snapped?.guides ?? [];+ if (base.surface) {+ dx = Math.max(+ -bounds.x,+ Math.min(base.surface.width - bounds.x - bounds.width, dx)+ );+ dy = Math.max(+ -bounds.y,+ Math.min(base.surface.height - bounds.y - bounds.height, dy)+ );+ }}let delta = translation(dx, dy);if (handle === 'rotate') {@@ -347,7 +398,7 @@ export function createSelection(host: SelectionHost) {}): Object.freeze({ ...node, transform });}- gesture = { ...gesture, nodes: Object.freeze(nodes) };+ gesture = { ...gesture, nodes: Object.freeze(nodes), snapGuides };emit();}return {@@ -465,6 +516,17 @@ export function createSelection(host: SelectionHost) {targets,frame,pivot: frame.center,+ bounds: enclosing(+ targets.flatMap((key) => nodeBoundsPoints(base, key))+ ),+ snapper:+ host.getObjectSnapping?.() &&+ !base.surface &&+ handle !== 'rotate' &&+ !isRadiusHandle(handle)+ ? createObjectSnapper(base, targets)+ : undefined,+ snapGuides: [],nodes: Object.freeze({}),};emit();diff --git a/packages/graphics/src/solid/index.tsx b/packages/graphics/src/solid/index.tsxindex f19c1aa330..7f308c538c 100644--- a/packages/graphics/src/solid/index.tsx+++ b/packages/graphics/src/solid/index.tsx@@ -456,6 +456,21 @@ export function GraphicsSurface(props: {projection.camera().y,])}>+ <For each={projection.session().transform?.snapGuides}>+ {(guide) => (+ <line+ data-graphics-snap-guide={guide.axis}+ x1={guide.axis === 'x' ? guide.value : guide.start}+ y1={guide.axis === 'y' ? guide.value : guide.start}+ x2={guide.axis === 'x' ? guide.value : guide.end}+ y2={guide.axis === 'y' ? guide.value : guide.end}+ stroke={SELECTION_COLOR}+ stroke-width="1"+ stroke-dasharray="4 3"+ vector-effect="non-scaling-stroke"+ />+ )}+ </For><For each={indicatedShapes()}>{(id) => {const initial = scene().items[id];diff --git a/packages/graphics/tests/object-snapping.test.ts b/packages/graphics/tests/object-snapping.test.tsnew file mode 100644index 0000000000..2a79f3f153--- /dev/null+++ b/packages/graphics/tests/object-snapping.test.ts@@ -0,0 +1,279 @@+import { describe, expect, it } from 'vitest';+import {+ createGraphicsEditor,+ IDENTITY,+ rotation,+ sortKeysBetween,+ translation,+ worldBounds,+} from '../src/core';+import { createObjectSnapper } from '../src/core/object-snapping';++const moving = {+ id: 'moving',+ type: 'rectangle' as const,+ placement: { parentId: 'scene-root', sortKey: 'a0' },+ transform: IDENTITY,+ geometry: { width: 100, height: 100 },+ appearance: { fill: 'transparent', stroke: 'black' },+};+const target = {+ ...moving,+ id: 'target',+ placement: { parentId: 'scene-root', sortKey: 'a1' },+ transform: translation(300, 0),+};++describe('object snapping', () => {+ it('aligns edges, emits guides, and commits one undoable edit', () => {+ const editor = createGraphicsEditor([moving, target], {+ objectSnapping: true,+ });+ editor.beginTransform('moving', { x: 50, y: 50 });+ editor.updateTransform({ x: 248, y: 50 });+ expect(editor.getSession().transform?.geometry.x).toBe(200);+ expect(editor.getSession().transform?.snapGuides).toContainEqual({+ axis: 'x',+ value: 300,+ start: -8,+ end: 108,+ });+ expect(worldBounds(editor.document, 'moving').x).toBe(0);+ editor.commitTransform();+ expect(editor.getSession().transform).toBeUndefined();+ expect(worldBounds(editor.document, 'moving').x).toBe(200);+ editor.undo();+ expect(worldBounds(editor.document, 'moving').x).toBe(0);+ expect(editor.getSession().canUndo).toBe(false);+ });++ it('aligns centers and preserves off-center pointer grabs', () => {+ const editor = createGraphicsEditor(+ [moving, { ...target, geometry: { width: 200, height: 100 } }],+ { objectSnapping: true }+ );+ editor.beginTransform('moving', { x: 17, y: 21 });+ editor.updateTransform({ x: 365, y: 21 });+ expect(editor.getSession().transform?.geometry.x).toBe(350);+ expect(+ editor+ .getSession()+ .transform?.snapGuides.some((g) => g.axis === 'x' && g.value === 400)+ ).toBe(true);+ });++ it('uses screen-pixel tolerance and ignores distant parallel alignments', () => {+ const editor = createGraphicsEditor([moving, target], {+ objectSnapping: true,+ });+ editor.zoomAt({ x: 0, y: 0 }, 2);+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 196, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(196);+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(200);+ editor.updateTransform({ x: 198, y: 1000 });+ expect(editor.getSession().transform?.geometry.x).toBe(198);+ });++ it('does not snap to itself or violate a constrained axis; objects win over grid', () => {+ const solo = createGraphicsEditor([moving], { objectSnapping: true });+ solo.beginTransform('moving', { x: 0, y: 0 });+ solo.updateTransform({ x: 3, y: 4 });+ expect(solo.getSession().transform?.geometry).toEqual({+ x: 3,+ y: 4,+ width: 100,+ height: 100,+ });+ expect(solo.getSession().transform?.snapGuides).toEqual([]);+ const editor = createGraphicsEditor(+ [moving, { ...target, transform: translation(300, 3) }],+ { objectSnapping: true, snapUnit: 16 }+ );+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 201, y: 2 }, { constrainAxis: true });+ expect(editor.getSession().transform?.geometry).toEqual({+ x: 200,+ y: 0,+ width: 100,+ height: 100,+ });+ expect(+ editor.getSession().transform?.snapGuides.every((g) => g.axis === 'x')+ ).toBe(true);+ });++ it('snaps a group as one box and excludes its own descendants', () => {+ const editor = createGraphicsEditor(+ [+ moving,+ { ...target, transform: translation(200, 0) },+ {+ ...target,+ id: 'outside',+ placement: { parentId: 'scene-root', sortKey: 'a2' },+ transform: translation(500, 0),+ },+ ],+ { objectSnapping: true }+ );+ editor.select('moving');+ editor.toggleSelection('target');+ editor.groupSelection('group');+ editor.beginTransform('group', { x: 0, y: 0 });+ editor.updateTransform({ x: 3, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(3);+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(200);+ editor.commitTransform();+ expect(worldBounds(editor.document, 'moving').x).toBe(200);+ expect(worldBounds(editor.document, 'target').x).toBe(400);+ });++ it('handles transformed target geometry and invalidates the index after edits', () => {+ const editor = createGraphicsEditor(+ [moving, { ...target, transform: [0, 1, -1, 0, 400, 0] }],+ { objectSnapping: true }+ );+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(200);+ editor.cancelTransform();+ editor.select('target');+ editor.deleteSelection();+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(198);+ editor.cancelTransform();+ editor.undo();+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(200);+ });++ it('can be disabled and cancels the pending snap without changing the document', () => {+ const editor = createGraphicsEditor([moving, target], {+ objectSnapping: true,+ });+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 198, y: 0 });+ editor.setObjectSnapping(false);+ expect(editor.getSession().transform).toBeUndefined();+ expect(editor.getSession().objectSnapping).toBe(false);+ editor.beginTransform('moving', { x: 0, y: 0 });+ editor.updateTransform({ x: 198, y: 0 });+ expect(editor.getSession().transform?.geometry.x).toBe(198);+ });++ it('resizes a moving edge without translating its stationary edge', () => {+ const editor = createGraphicsEditor([moving, target], {+ objectSnapping: true,+ });+ editor.beginTransform('moving', { x: 102, y: 50 }, 'e');+ editor.updateTransform({ x: 300, y: 50 });+ expect(editor.getSession().transform?.geometry).toEqual({+ x: 0,+ y: 0,+ width: 300,+ height: 100,+ });+ expect(+ editor.getSession().transform?.snapGuides.some((g) => g.axis === 'x')+ ).toBe(true);+ });++ it('gives object alignment priority over a coarse resize grid', () => {+ const editor = createGraphicsEditor(+ [moving, { ...target, transform: translation(301, 0) }],+ { objectSnapping: true, snapUnit: 16 }+ );+ editor.beginTransform('moving', { x: 100, y: 50 }, 'e');+ editor.updateTransform({ x: 299, y: 50 });+ expect(editor.getSession().transform?.geometry.width).toBe(301);+ });++ it('keeps grid snapping on a resize axis without an object match', () => {+ const editor = createGraphicsEditor(+ [moving, { ...target, transform: translation(301, 0) }],+ { objectSnapping: true, snapUnit: 16 }+ );+ editor.beginTransform('moving', { x: 100, y: 100 }, 'se');+ editor.updateTransform({ x: 299, y: 147 });+ expect(editor.getSession().transform?.geometry.width).toBe(301);+ expect(editor.getSession().transform?.geometry.height).toBeCloseTo(144);+ });++ it('preserves proportional and centered resizing when snapping', () => {+ const editor = createGraphicsEditor([moving, target], {+ objectSnapping: true,+ });+ editor.beginTransform('moving', { x: 100, y: 100 }, 'se');+ editor.updateTransform({ x: 298, y: 250 }, { proportional: true });+ expect(editor.getSession().transform?.geometry).toEqual({+ x: 0,+ y: 0,+ width: 300,+ height: 300,+ });+ editor.updateTransform(+ { x: 298, y: 250 },+ { proportional: true, fromCenter: true }+ );+ expect(editor.getSession().transform?.geometry).toEqual({+ x: -200,+ y: -200,+ width: 500,+ height: 500,+ });+ });++ it('leaves rotated resize frames on their local axes', () => {+ const shape = { ...moving, transform: rotation(Math.PI / 4) };+ const snapping = createGraphicsEditor([shape, target], {+ objectSnapping: true,+ });+ const free = createGraphicsEditor([shape, target]);+ for (const editor of [snapping, free]) {+ editor.beginTransform('moving', { x: 0, y: 141.421 }, 'se');+ editor.updateTransform({ x: 298, y: 250 });+ }+ expect(snapping.getSession().transform?.geometry).toEqual(+ free.getSession().transform?.geometry+ );+ expect(snapping.getSession().transform?.snapGuides).toEqual([]);+ });++ it.each(['diagonal', 'row', 'column'])(+ 'prunes distant objects on a large %s scene',+ (layout) => {+ const keys = sortKeysBetween(null, null, 10001);+ const editor = createGraphicsEditor(+ Array.from({ length: 10001 }, (_, i) => ({+ ...moving,+ id: String(i),+ placement: { parentId: 'scene-root', sortKey: keys[i]! },+ transform: translation(+ layout === 'column' ? 0 : i * 1000,+ layout === 'row' ? 0 : i * 1000+ ),+ }))+ );+ const snapper = createObjectSnapper(editor.document, ['0']);+ const result = snapper.snap(+ {+ x: layout === 'column' ? 0 : 898,+ y: layout === 'row' ? 0 : 898,+ width: 100,+ height: 100,+ },+ 1+ );+ expect(result.offset[layout === 'column' ? 'y' : 'x']).toBe(2);+ expect(snapper.stats().targets).toBe(10001);+ expect(snapper.stats().queries).toBe(6);+ expect(snapper.stats().candidates).toBeLessThan(20);+ expect(snapper.stats().visited).toBeLessThan(400);+ }+ );+});