@appulsauce/snap-guides 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +40 -3
  2. package/dist/core/draw.d.ts +22 -0
  3. package/dist/core/draw.js +16 -0
  4. package/dist/core/gaps.d.ts +22 -6
  5. package/dist/core/gaps.js +201 -50
  6. package/dist/core/index.d.ts +3 -3
  7. package/dist/core/index.js +2 -2
  8. package/dist/core/snap.d.ts +16 -1
  9. package/dist/core/snap.js +138 -36
  10. package/dist/core/types.d.ts +13 -0
  11. package/dist/flow/boxes.d.ts +40 -0
  12. package/dist/flow/boxes.js +45 -0
  13. package/dist/flow/gestures.d.ts +52 -0
  14. package/dist/flow/gestures.js +80 -0
  15. package/dist/flow/index.d.ts +4 -0
  16. package/dist/flow/index.js +4 -0
  17. package/dist/flow/xyflow.d.ts +70 -0
  18. package/dist/flow/xyflow.js +52 -0
  19. package/dist/vue-flow/guide-state.d.ts +14 -0
  20. package/dist/vue-flow/guide-state.js +16 -0
  21. package/dist/vue-flow/index.d.ts +4 -0
  22. package/dist/vue-flow/index.js +4 -0
  23. package/dist/vue-flow/nodes.d.ts +29 -0
  24. package/dist/vue-flow/nodes.js +28 -0
  25. package/dist/vue-flow/snap-guides.d.ts +25 -0
  26. package/dist/vue-flow/snap-guides.js +54 -0
  27. package/dist/vue-flow/use-node-resize-snap.d.ts +23 -0
  28. package/dist/vue-flow/use-node-resize-snap.js +83 -0
  29. package/dist/vue-flow/use-node-snap.d.ts +15 -0
  30. package/dist/vue-flow/use-node-snap.js +67 -0
  31. package/dist/xyflow-react/index.d.ts +4 -0
  32. package/dist/xyflow-react/index.js +4 -0
  33. package/dist/xyflow-react/snap-guides.d.ts +10 -0
  34. package/dist/xyflow-react/snap-guides.js +43 -0
  35. package/dist/xyflow-react/use-node-resize-snap.d.ts +26 -0
  36. package/dist/xyflow-react/use-node-resize-snap.js +78 -0
  37. package/dist/xyflow-react/use-node-snap.d.ts +23 -0
  38. package/dist/xyflow-react/use-node-snap.js +62 -0
  39. package/dist/xyflow-svelte/SnapGuides.svelte +6 -11
  40. package/dist/xyflow-svelte/index.d.ts +2 -1
  41. package/dist/xyflow-svelte/index.js +2 -1
  42. package/dist/xyflow-svelte/node-resize-snap.svelte.d.ts +34 -0
  43. package/dist/xyflow-svelte/node-resize-snap.svelte.js +71 -0
  44. package/dist/xyflow-svelte/node-snap.svelte.d.ts +4 -7
  45. package/dist/xyflow-svelte/node-snap.svelte.js +15 -71
  46. package/package.json +56 -15
package/dist/core/snap.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * filter, hysteresis for a held snap, and dropping a centre guide that edge
13
13
  * guides on both sides already explain.
14
14
  */
15
- import { gapGuides, gapTargets } from "./gaps.js";
15
+ import { blocksAround, gapGuides, gapTargets } from "./gaps.js";
16
16
  /**
17
17
  * Coordinates closer than this many screen pixels are the same coordinate: the
18
18
  * tolerance in world units is `EPSILON / zoom`, so it means the same on screen
@@ -103,11 +103,15 @@ const best = (candidates) => {
103
103
  winner = c;
104
104
  return winner;
105
105
  };
106
- /** `boxPoints` indices of the corner on a box's low and high edge along each axis. */
107
- const EDGE_POINT = { x: { low: 0, high: 1 }, y: { low: 0, high: 2 } };
108
- /** A gap target as a candidate: the moving edge's corner to the target coordinate. */
109
- const gapCandidate = (points, t) => {
110
- const index = EDGE_POINT[t.axis][t.edge];
106
+ /** `boxPoints` indices of the two corners on a box's low and high edge along each axis. */
107
+ const EDGE_POINTS = {
108
+ x: { low: [0, 2], high: [1, 3] },
109
+ y: { low: [0, 1], high: [2, 3] },
110
+ };
111
+ /** The two corners of `points` (a box's `boxPoints`) on its `edge` along `axis`. */
112
+ const edgePoints = (points, axis, edge) => EDGE_POINTS[axis][edge].flatMap((i) => points[i] ?? []);
113
+ /** A gap target as a candidate: the point at `index` of `points` (on the target's edge) to the target coordinate. */
114
+ const gapCandidate = (points, t, index) => {
111
115
  const from = points[index];
112
116
  if (!from)
113
117
  return [];
@@ -127,8 +131,8 @@ const alongGuide = (axis, points, tolerance) => {
127
131
  const across = other(axis);
128
132
  return [...seen.values()].toSorted((a, b) => a[across] - b[across]);
129
133
  };
130
- /** Guides through every exact alignment of the (already snapped) moving points. */
131
- const buildGuides = (moving, references, clusterBreak, sameRole, tolerance) => {
134
+ /** Guides through every exact alignment of the (already snapped) moving points on each axis. */
135
+ const buildGuides = (movingOn, references, clusterBreak, sameRole, tolerance) => {
132
136
  const guides = [];
133
137
  for (const axis of AXES) {
134
138
  // One guide per line: an edge and a centre that meet on the same
@@ -137,7 +141,7 @@ const buildGuides = (moving, references, clusterBreak, sameRole, tolerance) => {
137
141
  // The nearest cluster decides which reference boxes take part; every
138
142
  // aligned point of those boxes then goes on the guide, so it spans them
139
143
  // whole rather than stopping at the nearest corners.
140
- const exact = collect(moving, references, axis, tolerance, sameRole);
144
+ const exact = collect(movingOn(axis), references, axis, tolerance, sameRole);
141
145
  const near = nearestCluster(exact, clusterBreak);
142
146
  const boxes = new Set(near.map((c) => c.to.id).filter((id) => id !== undefined));
143
147
  const aligned = exact.filter((c) => near.includes(c) || (c.to.id !== undefined && boxes.has(c.to.id)));
@@ -171,16 +175,78 @@ const withoutBracketedCenters = (guides) => guides.filter((g) => {
171
175
  const explains = (e) => e.axis === g.axis && e.role === "edge" && g.ids.every((id) => e.ids.includes(id));
172
176
  return !(guides.some((e) => explains(e) && e.at < g.at) && guides.some((e) => explains(e) && e.at > g.at));
173
177
  });
178
+ const isEdge = (value) => value === "low" || value === "high";
179
+ /** Checks a resize handle and returns its edge on each axis (`undefined` where it drags none). */
180
+ const handleEdges = (handle) => {
181
+ const edges = { x: handle.x, y: handle.y };
182
+ for (const axis of AXES) {
183
+ const edge = edges[axis];
184
+ if (edge !== undefined && !isEdge(edge))
185
+ throw new RangeError(`snap-guides: a resize handle's ${axis} must be "low" or "high", got ${JSON.stringify(edge)}`);
186
+ }
187
+ if (edges.x === undefined && edges.y === undefined)
188
+ throw new RangeError("snap-guides: a resize handle must drag an edge on x, y or both");
189
+ return edges;
190
+ };
191
+ /** `box` with the edges `edges` names moved by `by` (never past the opposite edge) and the others kept. */
192
+ const stretch = (box, edges, by) => {
193
+ const along = (low, size, edge, d) => {
194
+ switch (edge) {
195
+ case undefined: {
196
+ return [low, size];
197
+ }
198
+ // Float rounding can put a target an ulp past the fixed edge; the
199
+ // dragged edge stops at it rather than turning the box inside out.
200
+ case "low": {
201
+ const moved = Math.min(low + d, low + size);
202
+ return [moved, low + size - moved];
203
+ }
204
+ case "high": {
205
+ return [low, Math.max(size + d, 0)];
206
+ }
207
+ }
208
+ };
209
+ const [x, width] = along(box.x, box.width, edges.x, by.x);
210
+ const [y, height] = along(box.y, box.height, edges.y, by.y);
211
+ return { ...box, x, y, width, height };
212
+ };
213
+ const checkZoom = (zoom) => {
214
+ if (!(Number.isFinite(zoom) && zoom > 0))
215
+ throw new RangeError(`snap-guides: zoom must be a positive finite number, got ${String(zoom)}`);
216
+ };
217
+ /**
218
+ * Gap targets come from the boxes beside the moving one, and which boxes
219
+ * those are depends on where it ends up, on both axes. So the offset is
220
+ * solved again from the neighbours at the snapped position until it stops
221
+ * changing: then snapping the result again finds the same neighbours and
222
+ * every axis already exact (idempotence). A scene that has not settled after
223
+ * a few rounds snaps by alignment alone.
224
+ */
225
+ const settle = (gaps, solve) => {
226
+ let offset = { x: 0, y: 0 };
227
+ for (let round = 0;; round++) {
228
+ const withGaps = gaps && round < GAP_ROUNDS;
229
+ const next = solve(withGaps, offset);
230
+ const settled = next.x === offset.x && next.y === offset.y;
231
+ offset = next;
232
+ if (!withGaps || settled)
233
+ return offset;
234
+ }
235
+ };
174
236
  /** A snapper for one gesture at a time, with hysteresis between calls. */
175
237
  export const createSnapper = (options = {}) => {
176
238
  const opts = { ...DEFAULTS, ...options };
177
239
  const sameRole = opts.roles === "same";
178
240
  const none = { x: undefined, y: undefined };
179
241
  let held = none;
180
- const offsetOn = (axis, points, references, gaps, scale) => {
242
+ /**
243
+ * The offset on `axis` for `points`. With `keep`, only targets whose
244
+ * coordinate it accepts count (a resized edge stays on its side).
245
+ */
246
+ const offsetOn = (axis, points, references, gaps, scale, keep = () => true) => {
181
247
  const tolerance = EPSILON / scale;
182
248
  const reach = opts.threshold / scale + tolerance;
183
- const candidates = [...collect(points, references, axis, reach, sameRole), ...gaps.filter((c) => Math.abs(c.offset) <= reach)];
249
+ const candidates = [...collect(points, references, axis, reach, sameRole), ...gaps.filter((c) => Math.abs(c.offset) <= reach)].filter((c) => keep(c.to[axis]));
184
250
  // An axis already exactly aligned stays put (snapping is idempotent);
185
251
  // otherwise the nearest cluster's smallest offset wins.
186
252
  const aligned = candidates.filter((c) => Math.abs(c.offset) <= tolerance);
@@ -191,6 +257,7 @@ export const createSnapper = (options = {}) => {
191
257
  const previous = held[axis];
192
258
  const from = previous ? points[previous.index] : undefined;
193
259
  const stillThere = previous &&
260
+ keep(previous.at) &&
194
261
  (previous.gap
195
262
  ? gaps.some((c) => c.index === previous.index && Math.abs(c.to[axis] - previous.at) <= tolerance)
196
263
  : references.some((r) => r.role === previous.role && Math.abs(r[axis] - previous.at) <= tolerance));
@@ -207,48 +274,81 @@ export const createSnapper = (options = {}) => {
207
274
  held = { ...held, [axis]: undefined };
208
275
  return null;
209
276
  };
277
+ /** The finite references other than the moving boxes, normalised, and their points. */
278
+ const scene = (moving, references) => {
279
+ const movingIds = new Set(moving.map((b) => b.id).filter((id) => id !== undefined));
280
+ const others = references.filter((r) => isFiniteBox(r) && (r.id === undefined || !movingIds.has(r.id))).map((r) => normalize(r));
281
+ return { others, targets: others.flatMap((r) => boxPoints(r, opts.centers)) };
282
+ };
210
283
  return {
211
284
  snap: (moving, references, zoom = 1) => {
212
- if (!(Number.isFinite(zoom) && zoom > 0))
213
- throw new RangeError(`snap-guides: zoom must be a positive finite number, got ${String(zoom)}`);
285
+ checkZoom(zoom);
214
286
  const movingBoxes = isBox(moving) ? [moving] : moving;
215
287
  if (movingBoxes.some((b) => !isFiniteBox(b)))
216
288
  throw new RangeError("snap-guides: a moving box has a non-finite coordinate or size");
217
289
  const box = unionBox(movingBoxes);
218
- const movingIds = new Set(movingBoxes.map((b) => b.id).filter((id) => id !== undefined));
219
- const others = references.filter((r) => isFiniteBox(r) && (r.id === undefined || !movingIds.has(r.id))).map((r) => normalize(r));
220
- const targets = others.flatMap((r) => boxPoints(r, opts.centers));
290
+ const { others, targets } = scene(movingBoxes, references);
221
291
  const points = boxPoints(box, opts.centers);
222
292
  const tolerance = EPSILON / zoom;
223
- // Gap targets come from the boxes beside the moving one, and which
224
- // boxes those are depends on where it ends up, on both axes. So the
225
- // offset is solved again from the neighbours at the snapped position
226
- // until it stops changing: then snapping the result again finds the
227
- // same neighbours and every axis already exact (idempotence). A scene
228
- // that has not settled after a few rounds snaps by alignment alone.
229
293
  const before = held;
230
- const solve = (withGaps, at) => {
294
+ const offset = settle(opts.gaps, (withGaps, by) => {
231
295
  held = before;
232
- const gapsOn = (axis) => withGaps ? gapTargets(at, others, axis, tolerance).flatMap((t) => gapCandidate(points, t)) : [];
296
+ const at = translate(box, by);
297
+ const blocks = withGaps ? blocksAround(at, others, tolerance) : [];
298
+ const gapsOn = (axis) => gapTargets(at, blocks, axis, tolerance).flatMap((t) => gapCandidate(points, t, EDGE_POINTS[axis][t.edge][0]));
233
299
  return {
234
300
  x: offsetOn("x", points, targets, gapsOn("x"), zoom) ?? 0,
235
301
  y: offsetOn("y", points, targets, gapsOn("y"), zoom) ?? 0,
236
302
  };
237
- };
238
- let offset = { x: 0, y: 0 };
239
- for (let round = 0;; round++) {
240
- const withGaps = opts.gaps && round < GAP_ROUNDS;
241
- const next = solve(withGaps, translate(box, offset));
242
- const settled = next.x === offset.x && next.y === offset.y;
243
- offset = next;
244
- if (!withGaps || settled)
245
- break;
246
- }
303
+ });
247
304
  const moved = translate(box, offset);
305
+ const movedPoints = boxPoints(moved, opts.centers);
306
+ return {
307
+ offset,
308
+ guides: buildGuides(() => movedPoints, targets, opts.clusterBreak / zoom, sameRole, tolerance),
309
+ gaps: opts.gaps ? gapGuides(moved, blocksAround(moved, others, tolerance), tolerance) : [],
310
+ };
311
+ },
312
+ resize: (input, handle, references, zoom = 1) => {
313
+ checkZoom(zoom);
314
+ if (!isFiniteBox(input))
315
+ throw new RangeError("snap-guides: the resized box has a non-finite coordinate or size");
316
+ const edges = handleEdges(handle);
317
+ const box = normalize(input);
318
+ const { others, targets } = scene([box], references);
319
+ // Only the corners on a dragged edge move; the centre moves by half and
320
+ // is left out, as in Excalidraw's resize snapping.
321
+ const points = boxPoints(box, false);
322
+ const tolerance = EPSILON / zoom;
323
+ const before = held;
324
+ const offset = settle(opts.gaps, (withGaps, by) => {
325
+ held = before;
326
+ const at = stretch(box, edges, by);
327
+ const blocks = withGaps ? blocksAround(at, others, tolerance) : [];
328
+ const on = (axis) => {
329
+ const edge = edges[axis];
330
+ if (edge === undefined)
331
+ return 0;
332
+ const moving = edgePoints(points, axis, edge);
333
+ // The opposite edge stays put, so the dragged one may meet it but not cross it.
334
+ const fixed = edgePoints(points, axis, edge === "high" ? "low" : "high")[0]?.[axis] ?? 0;
335
+ const keep = (target) => (edge === "high" ? target >= fixed : target <= fixed);
336
+ const gaps = gapTargets(at, blocks, axis, tolerance, edge).flatMap((t) => gapCandidate(moving, t, 0));
337
+ return offsetOn(axis, moving, targets, gaps, zoom, keep) ?? 0;
338
+ };
339
+ return { x: on("x"), y: on("y") };
340
+ });
341
+ const resized = stretch(box, edges, offset);
342
+ const resizedPoints = boxPoints(resized, false);
343
+ const movingOn = (axis) => {
344
+ const edge = edges[axis];
345
+ return edge === undefined ? [] : edgePoints(resizedPoints, axis, edge);
346
+ };
248
347
  return {
348
+ box: normalize(resized),
249
349
  offset,
250
- guides: buildGuides(boxPoints(moved, opts.centers), targets, opts.clusterBreak / zoom, sameRole, tolerance),
251
- gaps: opts.gaps ? gapGuides(moved, others, tolerance) : [],
350
+ guides: buildGuides(movingOn, targets, opts.clusterBreak / zoom, sameRole, tolerance),
351
+ gaps: opts.gaps ? gapGuides(resized, blocksAround(resized, others, tolerance), tolerance) : [],
252
352
  };
253
353
  },
254
354
  reset: () => {
@@ -258,3 +358,5 @@ export const createSnapper = (options = {}) => {
258
358
  };
259
359
  /** One-off snap with no memory between calls; use `createSnapper` during a drag. */
260
360
  export const snapBoxes = (moving, references, options = {}) => createSnapper(options).snap(moving, references, options.zoom);
361
+ /** One-off resize snap with no memory between calls; use `createSnapper` during a resize gesture. */
362
+ export const snapResize = (box, handle, references, options = {}) => createSnapper(options).resize(box, handle, references, options.zoom);
@@ -68,6 +68,19 @@ export interface SnapResult {
68
68
  /** The equal gaps the snapped boxes now make, to draw while they move (empty with `gaps: false`). */
69
69
  readonly gaps: readonly GapGuide[];
70
70
  }
71
+ /**
72
+ * The edges a resize handle drags: on each axis it names, the box's low edge
73
+ * (left, top) or high edge (right, bottom), of the box with its sizes made
74
+ * non-negative. A corner handle names both axes, a side handle one.
75
+ */
76
+ export interface ResizeHandle {
77
+ readonly x?: "low" | "high";
78
+ readonly y?: "low" | "high";
79
+ }
80
+ export interface ResizeResult extends SnapResult {
81
+ /** The box with its dragged edges snapped (sizes non-negative); `offset` is how far each dragged edge moved. */
82
+ readonly box: Box;
83
+ }
71
84
  /** Every distance here is in screen pixels; `snap` divides by the zoom it is given. */
72
85
  export interface SnapOptions {
73
86
  /** How close a point must come to snap. Default 8 (as in Excalidraw). */
@@ -0,0 +1,40 @@
1
+ import type { Box, ResizeHandle } from "../core/index.js";
2
+ /** A node's size: the measured one, else the one it was given. */
3
+ export interface SizedNode {
4
+ readonly measured?: {
5
+ readonly width?: number | undefined;
6
+ readonly height?: number | undefined;
7
+ } | undefined;
8
+ readonly width?: number | undefined;
9
+ readonly height?: number | undefined;
10
+ }
11
+ /** A node's measured size, or `null` before it is measured. */
12
+ export declare const nodeSize: (node: SizedNode) => {
13
+ width: number;
14
+ height: number;
15
+ } | null;
16
+ /**
17
+ * The boxes of every node `boxOf` can measure, that is not in `exclude` and
18
+ * that `snapTo` accepts. `boxOf` returns `null` for a node that has no box
19
+ * yet or is hidden.
20
+ */
21
+ export declare const referenceBoxes: <Node>(nodes: Iterable<Node>, boxOf: (node: Node) => Box | null, exclude: readonly string[], snapTo: (node: Node) => boolean) => Box[];
22
+ /**
23
+ * The edges a resize control drags, from its class list: xyflow and Vue Flow
24
+ * put the control's position (`top`, `bottom-left`, ...) on it as classes.
25
+ * `null` when it names no edge.
26
+ */
27
+ export declare const handleOfClasses: (classes: Iterable<string>) => ResizeHandle | null;
28
+ /** The node a resize gesture is on and the edges it drags. */
29
+ export interface ResizeTarget {
30
+ readonly id: string;
31
+ readonly handle: ResizeHandle;
32
+ }
33
+ /**
34
+ * The node and handle of a resize gesture that began on `target`, found
35
+ * through the DOM: the control has the class `<prefix>__resize-control` and
36
+ * sits inside the node's element, `<prefix>__node` with a `data-id`. The
37
+ * prefix is `svelte-flow`, `react-flow` or `vue-flow`. `null` when `target` is
38
+ * not inside such a control.
39
+ */
40
+ export declare const resizeTarget: (target: EventTarget | null, prefix: string) => ResizeTarget | null;
@@ -0,0 +1,45 @@
1
+ /** A node's measured size, or `null` before it is measured. */
2
+ export const nodeSize = (node) => {
3
+ const width = node.measured?.width ?? node.width;
4
+ const height = node.measured?.height ?? node.height;
5
+ return width === undefined || height === undefined ? null : { width, height };
6
+ };
7
+ /**
8
+ * The boxes of every node `boxOf` can measure, that is not in `exclude` and
9
+ * that `snapTo` accepts. `boxOf` returns `null` for a node that has no box
10
+ * yet or is hidden.
11
+ */
12
+ export const referenceBoxes = (nodes, boxOf, exclude, snapTo) => {
13
+ const boxes = [];
14
+ for (const node of nodes) {
15
+ const box = boxOf(node);
16
+ if (box?.id !== undefined && !exclude.includes(box.id) && snapTo(node))
17
+ boxes.push(box);
18
+ }
19
+ return boxes;
20
+ };
21
+ /**
22
+ * The edges a resize control drags, from its class list: xyflow and Vue Flow
23
+ * put the control's position (`top`, `bottom-left`, ...) on it as classes.
24
+ * `null` when it names no edge.
25
+ */
26
+ export const handleOfClasses = (classes) => {
27
+ const set = new Set(classes);
28
+ const x = [["left", "low"], ["right", "high"]].find(([name]) => set.has(name))?.[1];
29
+ const y = [["top", "low"], ["bottom", "high"]].find(([name]) => set.has(name))?.[1];
30
+ return x === undefined && y === undefined ? null : { ...(x && { x }), ...(y && { y }) };
31
+ };
32
+ /**
33
+ * The node and handle of a resize gesture that began on `target`, found
34
+ * through the DOM: the control has the class `<prefix>__resize-control` and
35
+ * sits inside the node's element, `<prefix>__node` with a `data-id`. The
36
+ * prefix is `svelte-flow`, `react-flow` or `vue-flow`. `null` when `target` is
37
+ * not inside such a control.
38
+ */
39
+ export const resizeTarget = (target, prefix) => {
40
+ const element = target instanceof Element ? target : null;
41
+ const control = element?.closest(`.${prefix}__resize-control`);
42
+ const id = control?.closest(`.${prefix}__node`)?.dataset["id"];
43
+ const handle = control ? handleOfClasses(control.classList) : null;
44
+ return id !== undefined && handle ? { id, handle } : null;
45
+ };
@@ -0,0 +1,52 @@
1
+ import { type Box, type GapGuide, type Guide, type SnapOptions, type Vec } from "../core/index.js";
2
+ import type { ResizeTarget } from "./boxes.js";
3
+ /** The pointer event of a gesture, as far as the default `suspend` reads it. */
4
+ export interface ModifierEvent {
5
+ readonly altKey: boolean;
6
+ }
7
+ export interface GestureOptions<Event extends ModifierEvent = ModifierEvent> extends SnapOptions {
8
+ /** While this holds for the gesture's pointer event, snapping is off. Default: Alt is held. */
9
+ readonly suspend?: (event: Event) => boolean;
10
+ }
11
+ /** The options every adapter's drag and resize hooks take: the snapping options, `suspend`, and which nodes to snap to. */
12
+ export interface AdapterOptions<Node, Event extends ModifierEvent = ModifierEvent> extends GestureOptions<Event> {
13
+ /** The nodes a dragged or resized node may snap to. Default: every node not being moved and not hidden. */
14
+ readonly snapTo?: (node: Node) => boolean;
15
+ }
16
+ /** What to draw now. Both are empty between gestures. */
17
+ export interface GuideState {
18
+ readonly guides: readonly Guide[];
19
+ readonly gaps: readonly GapGuide[];
20
+ }
21
+ /** The guide state with no gesture going. */
22
+ export declare const NO_GUIDES: GuideState;
23
+ export interface DragGesture<Event extends ModifierEvent = ModifierEvent> {
24
+ /**
25
+ * Snap one drag frame of the `moving` boxes (absolute, as the editor just
26
+ * placed them). Returns the offset to add to every dragged node's position,
27
+ * or `null` when there is nothing to write. `references` is called only when
28
+ * something is snapped.
29
+ */
30
+ move(event: Event, moving: readonly Box[], references: () => readonly Box[], zoom: number): Vec | null;
31
+ /** End the drag: the offset to write once more (the editor writes its own unsnapped positions last), or `null`. */
32
+ end(): Vec | null;
33
+ }
34
+ export declare const createDragGesture: <Event extends ModifierEvent = ModifierEvent>(options: GestureOptions<Event>, onGuides: (state: GuideState) => void) => DragGesture<Event>;
35
+ export interface ResizeGesture<Event extends ModifierEvent = ModifierEvent> {
36
+ /** The node and handle being resized, `null` between resizes or when the start named none. */
37
+ readonly target: ResizeTarget | null;
38
+ /** Begin a resize on `target` (`null` when the gesture is not on a known control: later moves do nothing). */
39
+ start(target: ResizeTarget | null): void;
40
+ /**
41
+ * Snap one resize frame of `box` (absolute, as the editor just sized it).
42
+ * Returns the snapped box to write over the editor's, or `null` when there
43
+ * is nothing to write.
44
+ */
45
+ move(event: Event, box: Box, references: () => readonly Box[], zoom: number): Box | null;
46
+ /** End the resize: the node and box to write once more, or `null`. */
47
+ end(): {
48
+ readonly id: string;
49
+ readonly box: Box;
50
+ } | null;
51
+ }
52
+ export declare const createResizeGesture: <Event extends ModifierEvent = ModifierEvent>(options: GestureOptions<Event>, onGuides: (state: GuideState) => void) => ResizeGesture<Event>;
@@ -0,0 +1,80 @@
1
+ /*
2
+ * The state of one drag or resize gesture in a node editor, shared by the
3
+ * framework adapters. A gesture owns a snapper and the guides it last
4
+ * produced; the adapter reads boxes out of its editor, passes them in, and
5
+ * writes back what the gesture says to write. Guides go out through
6
+ * `onGuides`, so each adapter can keep them in its own reactive state.
7
+ */
8
+ import { createSnapper } from "../core/index.js";
9
+ /** The guide state with no gesture going. */
10
+ export const NO_GUIDES = { guides: [], gaps: [] };
11
+ const ZERO = { x: 0, y: 0 };
12
+ const moved = (offset) => offset.x !== 0 || offset.y !== 0;
13
+ export const createDragGesture = (options, onGuides) => {
14
+ const snapper = createSnapper(options);
15
+ const suspend = options.suspend ?? ((event) => event.altKey);
16
+ let last = ZERO;
17
+ const stop = () => {
18
+ snapper.reset();
19
+ onGuides(NO_GUIDES);
20
+ last = ZERO;
21
+ };
22
+ return {
23
+ move: (event, moving, references, zoom) => {
24
+ if (suspend(event)) {
25
+ stop();
26
+ return null;
27
+ }
28
+ if (moving.length === 0)
29
+ return null;
30
+ const result = snapper.snap(moving, references(), zoom);
31
+ onGuides({ guides: result.guides, gaps: result.gaps });
32
+ last = result.offset;
33
+ return moved(last) ? last : null;
34
+ },
35
+ end: () => {
36
+ const offset = moved(last) ? last : null;
37
+ stop();
38
+ return offset;
39
+ },
40
+ };
41
+ };
42
+ export const createResizeGesture = (options, onGuides) => {
43
+ const snapper = createSnapper(options);
44
+ const suspend = options.suspend ?? ((event) => event.altKey);
45
+ let target = null;
46
+ /** The last snapped box, `null` while snapping is off or nothing snapped. */
47
+ let snapped = null;
48
+ const stop = () => {
49
+ snapper.reset();
50
+ onGuides(NO_GUIDES);
51
+ snapped = null;
52
+ };
53
+ return {
54
+ get target() {
55
+ return target;
56
+ },
57
+ start: (next) => {
58
+ stop();
59
+ target = next;
60
+ },
61
+ move: (event, box, references, zoom) => {
62
+ if (!target)
63
+ return null;
64
+ if (suspend(event)) {
65
+ stop();
66
+ return null;
67
+ }
68
+ const result = snapper.resize(box, target.handle, references(), zoom);
69
+ onGuides({ guides: result.guides, gaps: result.gaps });
70
+ snapped = moved(result.offset) ? result.box : null;
71
+ return snapped;
72
+ },
73
+ end: () => {
74
+ const last = target && snapped ? { id: target.id, box: snapped } : null;
75
+ stop();
76
+ target = null;
77
+ return last;
78
+ },
79
+ };
80
+ };
@@ -0,0 +1,4 @@
1
+ /** Framework-free pieces of the node-editor adapters: reading boxes and resize handles, the drag and resize gesture state, and the xyflow reads and writes. */
2
+ export { handleOfClasses, referenceBoxes, resizeTarget } from "./boxes.js";
3
+ export { createDragGesture, createResizeGesture, NO_GUIDES, type AdapterOptions, type GuideState } from "./gestures.js";
4
+ export { xyflowDraggedBox, xyflowDragItems, xyflowParentOrigin, xyflowReferences, xyflowResizeChanges, type XyInternalNode, } from "./xyflow.js";
@@ -0,0 +1,4 @@
1
+ /** Framework-free pieces of the node-editor adapters: reading boxes and resize handles, the drag and resize gesture state, and the xyflow reads and writes. */
2
+ export { handleOfClasses, referenceBoxes, resizeTarget } from "./boxes.js";
3
+ export { createDragGesture, createResizeGesture, NO_GUIDES } from "./gestures.js";
4
+ export { xyflowDraggedBox, xyflowDragItems, xyflowParentOrigin, xyflowReferences, xyflowResizeChanges, } from "./xyflow.js";
@@ -0,0 +1,70 @@
1
+ import type { Box, Vec } from "../core/index.js";
2
+ import { type SizedNode } from "./boxes.js";
3
+ /** The part of an xyflow internal node (`nodeLookup` entry) the adapters read. */
4
+ export interface XyInternalNode<UserNode> extends SizedNode {
5
+ readonly id: string;
6
+ readonly hidden?: boolean | undefined;
7
+ readonly parentId?: string | undefined;
8
+ readonly internals: {
9
+ readonly positionAbsolute: {
10
+ readonly x: number;
11
+ readonly y: number;
12
+ };
13
+ readonly userNode: UserNode;
14
+ };
15
+ }
16
+ /** The reference boxes of an xyflow `nodeLookup`, with `snapTo` asked about the user's node. */
17
+ export declare const xyflowReferences: <UserNode>(lookup: ReadonlyMap<string, XyInternalNode<UserNode>>, exclude: readonly string[], snapTo: (node: UserNode) => boolean) => Box[];
18
+ /** The absolute top-left of `id`'s parent in an xyflow `nodeLookup`, the origin when it has none. */
19
+ export declare const xyflowParentOrigin: <UserNode>(lookup: ReadonlyMap<string, XyInternalNode<UserNode>>, id: string) => {
20
+ x: number;
21
+ y: number;
22
+ };
23
+ /** The part of a user node a drag hands the adapters. */
24
+ export interface XyUserNode {
25
+ readonly id: string;
26
+ /** Relative to the parent node, or to the flow without one. */
27
+ readonly position: Vec;
28
+ }
29
+ /** A dragged node's absolute box, from the position xyflow just computed for it; `null` before it is measured. */
30
+ export declare const xyflowDraggedBox: <UserNode>(lookup: ReadonlyMap<string, XyInternalNode<UserNode>>, node: XyUserNode) => Box | null;
31
+ /** One entry of the map `updateNodePositions` takes, as far as xyflow reads it. */
32
+ export interface XyDragItem {
33
+ readonly id: string;
34
+ readonly position: Vec;
35
+ readonly distance: Vec;
36
+ readonly measured: {
37
+ readonly width: number;
38
+ readonly height: number;
39
+ };
40
+ readonly internals: {
41
+ readonly positionAbsolute: Vec;
42
+ };
43
+ }
44
+ /**
45
+ * The drag items for `nodes` moved by `offset`, in the shape the store's
46
+ * `updateNodePositions` takes. A node missing from `lookup` or not measured
47
+ * yet is left out.
48
+ */
49
+ export declare const xyflowDragItems: <UserNode>(lookup: ReadonlyMap<string, XyInternalNode<UserNode>>, nodes: readonly XyUserNode[], offset: Vec) => Map<string, XyDragItem>;
50
+ /** A node change of the kinds `xyflowResizeChanges` makes, as xyflow's `NodeChange` takes them. */
51
+ export type XyResizeChange = {
52
+ readonly id: string;
53
+ readonly type: "position";
54
+ readonly position: Vec;
55
+ } | {
56
+ readonly id: string;
57
+ readonly type: "dimensions";
58
+ readonly resizing: boolean;
59
+ readonly setAttributes: true;
60
+ readonly dimensions: {
61
+ readonly width: number;
62
+ readonly height: number;
63
+ };
64
+ };
65
+ /**
66
+ * The node changes that put node `id` at `box` (absolute), with its parent's
67
+ * absolute top-left read from `lookup`: a position and a dimensions change,
68
+ * the pair xyflow's own resizer emits.
69
+ */
70
+ export declare const xyflowResizeChanges: <UserNode>(lookup: ReadonlyMap<string, XyInternalNode<UserNode>>, id: string, box: Box, resizing: boolean) => XyResizeChange[];
@@ -0,0 +1,52 @@
1
+ import { nodeSize, referenceBoxes } from "./boxes.js";
2
+ /** The absolute box of an xyflow internal node, `null` while unmeasured or hidden. */
3
+ const xyflowBox = (internal) => {
4
+ const dims = nodeSize(internal);
5
+ if (!dims || internal.hidden)
6
+ return null;
7
+ const { x, y } = internal.internals.positionAbsolute;
8
+ return { x, y, ...dims, id: internal.id };
9
+ };
10
+ /** The reference boxes of an xyflow `nodeLookup`, with `snapTo` asked about the user's node. */
11
+ export const xyflowReferences = (lookup, exclude, snapTo) => referenceBoxes(lookup.values(), xyflowBox, exclude, (internal) => snapTo(internal.internals.userNode));
12
+ /** The absolute top-left of `id`'s parent in an xyflow `nodeLookup`, the origin when it has none. */
13
+ export const xyflowParentOrigin = (lookup, id) => {
14
+ const parentId = lookup.get(id)?.parentId;
15
+ return (parentId === undefined ? undefined : lookup.get(parentId)?.internals.positionAbsolute) ?? { x: 0, y: 0 };
16
+ };
17
+ const ZERO = { x: 0, y: 0 };
18
+ /** A dragged node's absolute box, from the position xyflow just computed for it; `null` before it is measured. */
19
+ export const xyflowDraggedBox = (lookup, node) => {
20
+ const measured = nodeSize(lookup.get(node.id) ?? {});
21
+ const origin = xyflowParentOrigin(lookup, node.id);
22
+ return measured ? { x: origin.x + node.position.x, y: origin.y + node.position.y, ...measured, id: node.id } : null;
23
+ };
24
+ /**
25
+ * The drag items for `nodes` moved by `offset`, in the shape the store's
26
+ * `updateNodePositions` takes. A node missing from `lookup` or not measured
27
+ * yet is left out.
28
+ */
29
+ export const xyflowDragItems = (lookup, nodes, offset) => {
30
+ const items = new Map();
31
+ for (const node of nodes) {
32
+ const measured = nodeSize(lookup.get(node.id) ?? {});
33
+ if (!measured)
34
+ continue;
35
+ const origin = xyflowParentOrigin(lookup, node.id);
36
+ const position = { x: node.position.x + offset.x, y: node.position.y + offset.y };
37
+ items.set(node.id, { id: node.id, position, distance: ZERO, measured, internals: { positionAbsolute: { x: origin.x + position.x, y: origin.y + position.y } } });
38
+ }
39
+ return items;
40
+ };
41
+ /**
42
+ * The node changes that put node `id` at `box` (absolute), with its parent's
43
+ * absolute top-left read from `lookup`: a position and a dimensions change,
44
+ * the pair xyflow's own resizer emits.
45
+ */
46
+ export const xyflowResizeChanges = (lookup, id, box, resizing) => {
47
+ const origin = xyflowParentOrigin(lookup, id);
48
+ return [
49
+ { id, type: "position", position: { x: box.x - origin.x, y: box.y - origin.y } },
50
+ { id, type: "dimensions", resizing, setAttributes: true, dimensions: { width: box.width, height: box.height } },
51
+ ];
52
+ };
@@ -0,0 +1,14 @@
1
+ /** The live guides of a gesture as refs, shared by the drag and resize composables. */
2
+ import { type ComputedRef } from "vue";
3
+ import type { GapGuide, Guide } from "../core/index.js";
4
+ import type { GuideState } from "../flow/index.js";
5
+ export interface GuideRefs {
6
+ /** The guides to draw now; empty between gestures. */
7
+ readonly guides: ComputedRef<readonly Guide[]>;
8
+ /** The equal gaps to draw now; empty between gestures. */
9
+ readonly gaps: ComputedRef<readonly GapGuide[]>;
10
+ }
11
+ /** Refs for the guides, and the setter to give a gesture as its `onGuides`. */
12
+ export declare const createGuideRefs: () => GuideRefs & {
13
+ readonly set: (state: GuideState) => void;
14
+ };
@@ -0,0 +1,16 @@
1
+ /** The live guides of a gesture as refs, shared by the drag and resize composables. */
2
+ import { computed, shallowRef } from "vue";
3
+ /** Refs for the guides, and the setter to give a gesture as its `onGuides`. */
4
+ export const createGuideRefs = () => {
5
+ // Shallow: the guide objects are replaced as a whole on every frame.
6
+ const guides = shallowRef([]);
7
+ const gaps = shallowRef([]);
8
+ return {
9
+ guides: computed(() => guides.value),
10
+ gaps: computed(() => gaps.value),
11
+ set: (state) => {
12
+ guides.value = state.guides;
13
+ gaps.value = state.gaps;
14
+ },
15
+ };
16
+ };