@appulsauce/snap-guides 0.0.0-stage → 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.
- package/LICENSE +34 -0
- package/README.md +99 -2
- package/dist/core/draw.d.ts +60 -0
- package/dist/core/draw.js +57 -0
- package/dist/core/gaps.d.ts +38 -0
- package/dist/core/gaps.js +261 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.js +7 -0
- package/dist/core/snap.d.ts +49 -0
- package/dist/core/snap.js +362 -0
- package/dist/core/types.d.ts +121 -0
- package/dist/core/types.js +1 -0
- package/dist/flow/boxes.d.ts +40 -0
- package/dist/flow/boxes.js +45 -0
- package/dist/flow/gestures.d.ts +52 -0
- package/dist/flow/gestures.js +80 -0
- package/dist/flow/index.d.ts +4 -0
- package/dist/flow/index.js +4 -0
- package/dist/flow/xyflow.d.ts +70 -0
- package/dist/flow/xyflow.js +52 -0
- package/dist/vue-flow/guide-state.d.ts +14 -0
- package/dist/vue-flow/guide-state.js +16 -0
- package/dist/vue-flow/index.d.ts +4 -0
- package/dist/vue-flow/index.js +4 -0
- package/dist/vue-flow/nodes.d.ts +29 -0
- package/dist/vue-flow/nodes.js +28 -0
- package/dist/vue-flow/snap-guides.d.ts +25 -0
- package/dist/vue-flow/snap-guides.js +54 -0
- package/dist/vue-flow/use-node-resize-snap.d.ts +23 -0
- package/dist/vue-flow/use-node-resize-snap.js +83 -0
- package/dist/vue-flow/use-node-snap.d.ts +15 -0
- package/dist/vue-flow/use-node-snap.js +67 -0
- package/dist/xyflow-react/index.d.ts +4 -0
- package/dist/xyflow-react/index.js +4 -0
- package/dist/xyflow-react/snap-guides.d.ts +10 -0
- package/dist/xyflow-react/snap-guides.js +43 -0
- package/dist/xyflow-react/use-node-resize-snap.d.ts +26 -0
- package/dist/xyflow-react/use-node-resize-snap.js +78 -0
- package/dist/xyflow-react/use-node-snap.d.ts +23 -0
- package/dist/xyflow-react/use-node-snap.js +62 -0
- package/dist/xyflow-svelte/SnapGuides.svelte +54 -0
- package/dist/xyflow-svelte/SnapGuides.svelte.d.ts +8 -0
- package/dist/xyflow-svelte/index.d.ts +4 -0
- package/dist/xyflow-svelte/index.js +4 -0
- package/dist/xyflow-svelte/node-resize-snap.svelte.d.ts +34 -0
- package/dist/xyflow-svelte/node-resize-snap.svelte.js +71 -0
- package/dist/xyflow-svelte/node-snap.svelte.d.ts +23 -0
- package/dist/xyflow-svelte/node-snap.svelte.js +59 -0
- package/package.json +130 -4
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Point snapping for moving boxes, with the guide lines that explain it.
|
|
3
|
+
*
|
|
4
|
+
* The algorithm is Excalidraw's (packages/excalidraw/snapping.ts, MIT,
|
|
5
|
+
* Copyright (c) 2020 Excalidraw): each box contributes its four corners and its
|
|
6
|
+
* centre; per axis, the moving points' nearest reference points within the
|
|
7
|
+
* threshold decide the offset; a second pass over the snapped points at zero
|
|
8
|
+
* distance gives the lines to draw. On top of it, from the tikz-editor's
|
|
9
|
+
* redesign of that port (github.com/DominikPeters/tikz-editor,
|
|
10
|
+
* design/snapping-redesign.md, MIT): optional like-with-like roles (`roles:
|
|
11
|
+
* "same"`; the default is Excalidraw's any-to-any), the nearest-cluster
|
|
12
|
+
* filter, hysteresis for a held snap, and dropping a centre guide that edge
|
|
13
|
+
* guides on both sides already explain.
|
|
14
|
+
*/
|
|
15
|
+
import { blocksAround, gapGuides, gapTargets } from "./gaps.js";
|
|
16
|
+
/**
|
|
17
|
+
* Coordinates closer than this many screen pixels are the same coordinate: the
|
|
18
|
+
* tolerance in world units is `EPSILON / zoom`, so it means the same on screen
|
|
19
|
+
* at any zoom and in any world unit.
|
|
20
|
+
*/
|
|
21
|
+
export const EPSILON = 1e-6;
|
|
22
|
+
const DEFAULTS = {
|
|
23
|
+
threshold: 8,
|
|
24
|
+
centers: true,
|
|
25
|
+
roles: "any",
|
|
26
|
+
clusterBreak: 200,
|
|
27
|
+
release: 1.5,
|
|
28
|
+
switchAdvantage: 2,
|
|
29
|
+
gaps: true,
|
|
30
|
+
};
|
|
31
|
+
const AXES = ["x", "y"];
|
|
32
|
+
/** Rounds of solving from the neighbours at the snapped position before gaps are given up (see `snap`). */
|
|
33
|
+
const GAP_ROUNDS = 4;
|
|
34
|
+
/** Rounds away float noise at 1e-6 world units (kept for callers; the core compares in screen pixels). */
|
|
35
|
+
export const roundCoordinate = (value) => Math.round(value * 1e6) / 1e6;
|
|
36
|
+
const isFiniteBox = (b) => [b.x, b.y, b.width, b.height].every((v) => Number.isFinite(v));
|
|
37
|
+
/** The same rectangle with non-negative sizes: a negative width spans `x + width` to `x`. */
|
|
38
|
+
const normalize = (b) => b.width >= 0 && b.height >= 0
|
|
39
|
+
? b
|
|
40
|
+
: { ...b, x: Math.min(b.x, b.x + b.width), y: Math.min(b.y, b.y + b.height), width: Math.abs(b.width), height: Math.abs(b.height) };
|
|
41
|
+
/** The four corners (edge role) and, with `centers`, the centre of a box. */
|
|
42
|
+
export const boxPoints = (box, centers = true) => {
|
|
43
|
+
const { x, y, width, height, id } = normalize(box);
|
|
44
|
+
const named = id === undefined ? {} : { id };
|
|
45
|
+
const corners = [
|
|
46
|
+
{ x, y, role: "edge", ...named },
|
|
47
|
+
{ x: x + width, y, role: "edge", ...named },
|
|
48
|
+
{ x, y: y + height, role: "edge", ...named },
|
|
49
|
+
{ x: x + width, y: y + height, role: "edge", ...named },
|
|
50
|
+
];
|
|
51
|
+
return centers ? [...corners, { x: x + width / 2, y: y + height / 2, role: "center", ...named }] : corners;
|
|
52
|
+
};
|
|
53
|
+
/** The smallest box holding all of `boxes`, which move together (negative sizes are normalised). */
|
|
54
|
+
export const unionBox = (boxes) => {
|
|
55
|
+
const [first, ...rest] = boxes.map((b) => normalize(b));
|
|
56
|
+
if (!first)
|
|
57
|
+
throw new RangeError("snap-guides: no moving boxes");
|
|
58
|
+
let minX = first.x;
|
|
59
|
+
let minY = first.y;
|
|
60
|
+
let maxX = first.x + first.width;
|
|
61
|
+
let maxY = first.y + first.height;
|
|
62
|
+
for (const b of rest) {
|
|
63
|
+
minX = Math.min(minX, b.x);
|
|
64
|
+
minY = Math.min(minY, b.y);
|
|
65
|
+
maxX = Math.max(maxX, b.x + b.width);
|
|
66
|
+
maxY = Math.max(maxY, b.y + b.height);
|
|
67
|
+
}
|
|
68
|
+
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
69
|
+
};
|
|
70
|
+
/** Pairs of points (like-role only with `sameRole`) whose offset on `axis` is within `reach`. */
|
|
71
|
+
const collect = (moving, references, axis, reach, sameRole) => moving.flatMap((from, index) => references
|
|
72
|
+
.filter((to) => (!sameRole || to.role === from.role) && Math.abs(to[axis] - from[axis]) <= reach)
|
|
73
|
+
.map((to) => ({
|
|
74
|
+
index,
|
|
75
|
+
from,
|
|
76
|
+
to,
|
|
77
|
+
offset: to[axis] - from[axis],
|
|
78
|
+
distance: Math.hypot(to.x - from.x, to.y - from.y),
|
|
79
|
+
})));
|
|
80
|
+
/** Keeps the candidates up to the first jump in distance wider than `gap`. */
|
|
81
|
+
const nearestCluster = (candidates, gap) => {
|
|
82
|
+
const sorted = candidates.toSorted((a, b) => a.distance - b.distance);
|
|
83
|
+
const cut = sorted.findIndex((c, i) => i > 0 && c.distance - (sorted[i - 1]?.distance ?? 0) > gap);
|
|
84
|
+
return cut === -1 ? sorted : sorted.slice(0, cut);
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* A total order on candidates, so the winner never depends on the order the
|
|
88
|
+
* references came in: smallest offset, then nearest, then the reference point
|
|
89
|
+
* and moving point by coordinates.
|
|
90
|
+
*/
|
|
91
|
+
const byPreference = (a, b) => Math.abs(a.offset) - Math.abs(b.offset) ||
|
|
92
|
+
// On a tie, alignment wins over equal spacing, as in Excalidraw and Graphite.
|
|
93
|
+
(a.gap ? 1 : 0) - (b.gap ? 1 : 0) ||
|
|
94
|
+
a.distance - b.distance ||
|
|
95
|
+
a.to.x - b.to.x ||
|
|
96
|
+
a.to.y - b.to.y ||
|
|
97
|
+
a.index - b.index;
|
|
98
|
+
/** The preferred candidate (a loop, not `Math.min(...)`, which overflows the stack on large boards). */
|
|
99
|
+
const best = (candidates) => {
|
|
100
|
+
let winner;
|
|
101
|
+
for (const c of candidates)
|
|
102
|
+
if (!winner || byPreference(c, winner) < 0)
|
|
103
|
+
winner = c;
|
|
104
|
+
return winner;
|
|
105
|
+
};
|
|
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) => {
|
|
115
|
+
const from = points[index];
|
|
116
|
+
if (!from)
|
|
117
|
+
return [];
|
|
118
|
+
const to = { ...from, [t.axis]: t.at, role: "edge" };
|
|
119
|
+
return [{ index, from, to, offset: t.at - from[t.axis], distance: t.distance, gap: true }];
|
|
120
|
+
};
|
|
121
|
+
const isBox = (value) => "width" in value;
|
|
122
|
+
const translate = (box, by) => ({ ...box, x: box.x + by.x, y: box.y + by.y });
|
|
123
|
+
const other = (axis) => (axis === "x" ? "y" : "x");
|
|
124
|
+
/** A key equal for coordinates within `tolerance` of a grid point (for grouping). */
|
|
125
|
+
const keyOf = (value, tolerance) => String(Math.round(value / tolerance));
|
|
126
|
+
/** Points deduplicated and sorted along the guide (by the other axis). */
|
|
127
|
+
const alongGuide = (axis, points, tolerance) => {
|
|
128
|
+
const seen = new Map();
|
|
129
|
+
for (const p of points)
|
|
130
|
+
seen.set(`${keyOf(p.x, tolerance)},${keyOf(p.y, tolerance)}`, p);
|
|
131
|
+
const across = other(axis);
|
|
132
|
+
return [...seen.values()].toSorted((a, b) => a[across] - b[across]);
|
|
133
|
+
};
|
|
134
|
+
/** Guides through every exact alignment of the (already snapped) moving points on each axis. */
|
|
135
|
+
const buildGuides = (movingOn, references, clusterBreak, sameRole, tolerance) => {
|
|
136
|
+
const guides = [];
|
|
137
|
+
for (const axis of AXES) {
|
|
138
|
+
// One guide per line: an edge and a centre that meet on the same
|
|
139
|
+
// coordinate share it, drawn as an edge guide.
|
|
140
|
+
const groups = new Map();
|
|
141
|
+
// The nearest cluster decides which reference boxes take part; every
|
|
142
|
+
// aligned point of those boxes then goes on the guide, so it spans them
|
|
143
|
+
// whole rather than stopping at the nearest corners.
|
|
144
|
+
const exact = collect(movingOn(axis), references, axis, tolerance, sameRole);
|
|
145
|
+
const near = nearestCluster(exact, clusterBreak);
|
|
146
|
+
const boxes = new Set(near.map((c) => c.to.id).filter((id) => id !== undefined));
|
|
147
|
+
const aligned = exact.filter((c) => near.includes(c) || (c.to.id !== undefined && boxes.has(c.to.id)));
|
|
148
|
+
for (const c of aligned) {
|
|
149
|
+
const key = keyOf(c.to[axis], tolerance);
|
|
150
|
+
// The line is the reference's own coordinate, exactly.
|
|
151
|
+
const group = groups.get(key) ?? { at: c.to[axis], center: true, points: [], ids: new Set() };
|
|
152
|
+
groups.set(key, group);
|
|
153
|
+
group.center &&= c.from.role === "center" && c.to.role === "center";
|
|
154
|
+
// The moving point sits on the line up to float noise; put it exactly on.
|
|
155
|
+
group.points.push(axis === "x" ? { x: group.at, y: c.from.y } : { x: c.from.x, y: group.at }, { x: c.to.x, y: c.to.y });
|
|
156
|
+
if (c.to.id !== undefined)
|
|
157
|
+
group.ids.add(c.to.id);
|
|
158
|
+
}
|
|
159
|
+
for (const g of groups.values()) {
|
|
160
|
+
const role = g.center ? "center" : "edge";
|
|
161
|
+
guides.push({ axis, at: g.at, role, points: alongGuide(axis, g.points, tolerance), ids: [...g.ids] });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return withoutBracketedCenters(guides);
|
|
165
|
+
};
|
|
166
|
+
/**
|
|
167
|
+
* When edge guides on both sides of a centre guide on the same axis already
|
|
168
|
+
* pass through the boxes it does (two boxes of equal size, aligned), the
|
|
169
|
+
* centre guide says nothing new: drop it. A centre guide through a box the
|
|
170
|
+
* edge guides miss stays, so every aligned box appears in some guide.
|
|
171
|
+
*/
|
|
172
|
+
const withoutBracketedCenters = (guides) => guides.filter((g) => {
|
|
173
|
+
if (g.role !== "center")
|
|
174
|
+
return true;
|
|
175
|
+
const explains = (e) => e.axis === g.axis && e.role === "edge" && g.ids.every((id) => e.ids.includes(id));
|
|
176
|
+
return !(guides.some((e) => explains(e) && e.at < g.at) && guides.some((e) => explains(e) && e.at > g.at));
|
|
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
|
+
};
|
|
236
|
+
/** A snapper for one gesture at a time, with hysteresis between calls. */
|
|
237
|
+
export const createSnapper = (options = {}) => {
|
|
238
|
+
const opts = { ...DEFAULTS, ...options };
|
|
239
|
+
const sameRole = opts.roles === "same";
|
|
240
|
+
const none = { x: undefined, y: undefined };
|
|
241
|
+
let held = none;
|
|
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) => {
|
|
247
|
+
const tolerance = EPSILON / scale;
|
|
248
|
+
const reach = opts.threshold / scale + tolerance;
|
|
249
|
+
const candidates = [...collect(points, references, axis, reach, sameRole), ...gaps.filter((c) => Math.abs(c.offset) <= reach)].filter((c) => keep(c.to[axis]));
|
|
250
|
+
// An axis already exactly aligned stays put (snapping is idempotent);
|
|
251
|
+
// otherwise the nearest cluster's smallest offset wins.
|
|
252
|
+
const aligned = candidates.filter((c) => Math.abs(c.offset) <= tolerance);
|
|
253
|
+
const pick = best(aligned.length > 0 ? aligned : nearestCluster(candidates, opts.clusterBreak / scale));
|
|
254
|
+
const fresh = pick ? { offset: pick.offset, held: { index: pick.index, at: pick.to[axis], role: pick.to.role, gap: pick.gap === true } } : null;
|
|
255
|
+
// Keep the held target while it is within the release distance and still
|
|
256
|
+
// there, unless a fresh one is nearer by a clear margin.
|
|
257
|
+
const previous = held[axis];
|
|
258
|
+
const from = previous ? points[previous.index] : undefined;
|
|
259
|
+
const stillThere = previous &&
|
|
260
|
+
keep(previous.at) &&
|
|
261
|
+
(previous.gap
|
|
262
|
+
? gaps.some((c) => c.index === previous.index && Math.abs(c.to[axis] - previous.at) <= tolerance)
|
|
263
|
+
: references.some((r) => r.role === previous.role && Math.abs(r[axis] - previous.at) <= tolerance));
|
|
264
|
+
if (previous && from && stillThere) {
|
|
265
|
+
const kept = previous.at - from[axis];
|
|
266
|
+
const beaten = fresh && Math.abs(fresh.offset) + opts.switchAdvantage / scale < Math.abs(kept) - tolerance;
|
|
267
|
+
if (!beaten && Math.abs(kept) <= (opts.threshold / scale) * opts.release + tolerance)
|
|
268
|
+
return kept;
|
|
269
|
+
}
|
|
270
|
+
if (fresh) {
|
|
271
|
+
held = { ...held, [axis]: fresh.held };
|
|
272
|
+
return fresh.offset;
|
|
273
|
+
}
|
|
274
|
+
held = { ...held, [axis]: undefined };
|
|
275
|
+
return null;
|
|
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
|
+
};
|
|
283
|
+
return {
|
|
284
|
+
snap: (moving, references, zoom = 1) => {
|
|
285
|
+
checkZoom(zoom);
|
|
286
|
+
const movingBoxes = isBox(moving) ? [moving] : moving;
|
|
287
|
+
if (movingBoxes.some((b) => !isFiniteBox(b)))
|
|
288
|
+
throw new RangeError("snap-guides: a moving box has a non-finite coordinate or size");
|
|
289
|
+
const box = unionBox(movingBoxes);
|
|
290
|
+
const { others, targets } = scene(movingBoxes, references);
|
|
291
|
+
const points = boxPoints(box, opts.centers);
|
|
292
|
+
const tolerance = EPSILON / zoom;
|
|
293
|
+
const before = held;
|
|
294
|
+
const offset = settle(opts.gaps, (withGaps, by) => {
|
|
295
|
+
held = before;
|
|
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]));
|
|
299
|
+
return {
|
|
300
|
+
x: offsetOn("x", points, targets, gapsOn("x"), zoom) ?? 0,
|
|
301
|
+
y: offsetOn("y", points, targets, gapsOn("y"), zoom) ?? 0,
|
|
302
|
+
};
|
|
303
|
+
});
|
|
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
|
+
};
|
|
347
|
+
return {
|
|
348
|
+
box: normalize(resized),
|
|
349
|
+
offset,
|
|
350
|
+
guides: buildGuides(movingOn, targets, opts.clusterBreak / zoom, sameRole, tolerance),
|
|
351
|
+
gaps: opts.gaps ? gapGuides(resized, blocksAround(resized, others, tolerance), tolerance) : [],
|
|
352
|
+
};
|
|
353
|
+
},
|
|
354
|
+
reset: () => {
|
|
355
|
+
held = none;
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
};
|
|
359
|
+
/** One-off snap with no memory between calls; use `createSnapper` during a drag. */
|
|
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);
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/** A point or a translation, in the caller's world units. */
|
|
2
|
+
export interface Vec {
|
|
3
|
+
readonly x: number;
|
|
4
|
+
readonly y: number;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* An axis-aligned box: `x`/`y` is its top-left corner. `id` names it in the
|
|
8
|
+
* guides it takes part in, so a caller can highlight the boxes a guide passes
|
|
9
|
+
* through, and keeps a moving box from snapping to itself.
|
|
10
|
+
*
|
|
11
|
+
* It is the rectangle that should line up: for a DOM element, its border box
|
|
12
|
+
* (borders included, outlines and shadows not). A negative width or height
|
|
13
|
+
* spans from `x + width` to `x`. Coordinates are compared to 1e-6 screen
|
|
14
|
+
* pixels, which holds while they stay within about 1e9 screen pixels of the
|
|
15
|
+
* origin.
|
|
16
|
+
*/
|
|
17
|
+
export interface Box {
|
|
18
|
+
readonly x: number;
|
|
19
|
+
readonly y: number;
|
|
20
|
+
readonly width: number;
|
|
21
|
+
readonly height: number;
|
|
22
|
+
readonly id?: string;
|
|
23
|
+
}
|
|
24
|
+
/** `x` snaps horizontal positions (guides are vertical lines), `y` vertical ones. */
|
|
25
|
+
export type Axis = "x" | "y";
|
|
26
|
+
/** What a snap point is on its box: a corner (edge) or its centre. */
|
|
27
|
+
export type Role = "edge" | "center";
|
|
28
|
+
export interface SnapPoint extends Vec {
|
|
29
|
+
readonly role: Role;
|
|
30
|
+
readonly id?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One alignment to draw: a line across every point that shares a coordinate.
|
|
34
|
+
* For `axis: "x"` it is the vertical line `x = at`, for `axis: "y"` the
|
|
35
|
+
* horizontal line `y = at`; `points` are sorted along it, so the first and last
|
|
36
|
+
* are its ends. `role` is `"center"` only when centres meet centres; any
|
|
37
|
+
* alignment involving an edge is `"edge"`.
|
|
38
|
+
*/
|
|
39
|
+
export interface Guide {
|
|
40
|
+
readonly axis: Axis;
|
|
41
|
+
readonly at: number;
|
|
42
|
+
readonly role: Role;
|
|
43
|
+
readonly points: readonly Vec[];
|
|
44
|
+
/** The reference boxes the guide passes through (those that have an `id`). */
|
|
45
|
+
readonly ids: readonly string[];
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Equal spacing the moving box takes part in, measured along `axis`: for
|
|
49
|
+
* `axis: "x"` the gaps are horizontal, between boxes side by side. Every
|
|
50
|
+
* segment in `segments` spans one gap of `length` world units, from the box
|
|
51
|
+
* before it to the box after it, drawn across the middle of where the two
|
|
52
|
+
* overlap. `kind` is `"continue"` when the box repeats the gap between the two
|
|
53
|
+
* boxes beside it, `"center"` when it sits midway between its two neighbours.
|
|
54
|
+
*/
|
|
55
|
+
export interface GapGuide {
|
|
56
|
+
readonly axis: Axis;
|
|
57
|
+
readonly kind: "continue" | "center";
|
|
58
|
+
readonly length: number;
|
|
59
|
+
readonly segments: readonly (readonly [Vec, Vec])[];
|
|
60
|
+
/** The reference boxes the gaps run between (those that have an `id`). */
|
|
61
|
+
readonly ids: readonly string[];
|
|
62
|
+
}
|
|
63
|
+
export interface SnapResult {
|
|
64
|
+
/** Add this to the moving boxes' positions to snap them. Zero on an axis that did not snap. */
|
|
65
|
+
readonly offset: Vec;
|
|
66
|
+
/** The alignments the snapped boxes now have, to draw while they move. */
|
|
67
|
+
readonly guides: readonly Guide[];
|
|
68
|
+
/** The equal gaps the snapped boxes now make, to draw while they move (empty with `gaps: false`). */
|
|
69
|
+
readonly gaps: readonly GapGuide[];
|
|
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
|
+
}
|
|
84
|
+
/** Every distance here is in screen pixels; `snap` divides by the zoom it is given. */
|
|
85
|
+
export interface SnapOptions {
|
|
86
|
+
/** How close a point must come to snap. Default 8 (as in Excalidraw). */
|
|
87
|
+
readonly threshold?: number;
|
|
88
|
+
/** Snap and draw centres as well as edges. Default true. */
|
|
89
|
+
readonly centers?: boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Which snap points may line up. `"any"` (default, as in Excalidraw) lets a
|
|
92
|
+
* centre meet an edge, such as one box's middle on another's top. `"same"`
|
|
93
|
+
* matches edges only with edges and centres only with centres, as the
|
|
94
|
+
* tikz-editor's redesign does to keep every guide obvious.
|
|
95
|
+
*/
|
|
96
|
+
readonly roles?: "any" | "same";
|
|
97
|
+
/**
|
|
98
|
+
* Among targets within reach, keep only the nearest cluster: candidates are
|
|
99
|
+
* taken in order of distance and the list is cut where the distance jumps by
|
|
100
|
+
* more than this. A far box that wins on offset by a hair then loses to the
|
|
101
|
+
* near one. Default 200 (Excalidraw PR #11316). `Infinity` turns it off.
|
|
102
|
+
*/
|
|
103
|
+
readonly clusterBreak?: number;
|
|
104
|
+
/**
|
|
105
|
+
* A held snap is let go only past `release` times the threshold, so it does
|
|
106
|
+
* not flicker at the edge of its reach. Default 1.5. 1 removes the extra
|
|
107
|
+
* reach; a held target is still kept while it is in reach, even when the
|
|
108
|
+
* nearest-cluster rule would now pass it over, and while any reference
|
|
109
|
+
* point of its role stays on its line.
|
|
110
|
+
*/
|
|
111
|
+
readonly release?: number;
|
|
112
|
+
/** A new target replaces a held one only when it is this much nearer. Default 2. */
|
|
113
|
+
readonly switchAdvantage?: number;
|
|
114
|
+
/**
|
|
115
|
+
* Snap to equal spacing as well as to alignment: continue the gap between
|
|
116
|
+
* the two boxes nearest on one side, or centre between the nearest box on
|
|
117
|
+
* each side. Only boxes that overlap the moving box across the axis count.
|
|
118
|
+
* Default true.
|
|
119
|
+
*/
|
|
120
|
+
readonly gaps?: boolean;
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -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>;
|