@appulsauce/snap-guides 0.0.0-stage → 0.1.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 +62 -2
- package/dist/core/draw.d.ts +38 -0
- package/dist/core/draw.js +41 -0
- package/dist/core/gaps.d.ts +22 -0
- package/dist/core/gaps.js +110 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.js +7 -0
- package/dist/core/snap.d.ts +34 -0
- package/dist/core/snap.js +260 -0
- package/dist/core/types.d.ts +108 -0
- package/dist/core/types.js +1 -0
- package/dist/xyflow-svelte/SnapGuides.svelte +59 -0
- package/dist/xyflow-svelte/SnapGuides.svelte.d.ts +8 -0
- package/dist/xyflow-svelte/index.d.ts +3 -0
- package/dist/xyflow-svelte/index.js +3 -0
- package/dist/xyflow-svelte/node-snap.svelte.d.ts +26 -0
- package/dist/xyflow-svelte/node-snap.svelte.js +115 -0
- package/package.json +88 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kai Erik Niermann
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
src/core/snap.ts follows the snapping algorithm of Excalidraw
|
|
26
|
+
(https://github.com/excalidraw/excalidraw, packages/excalidraw/snapping.ts)
|
|
27
|
+
and design decisions of tikz-editor
|
|
28
|
+
(https://github.com/DominikPeters/tikz-editor, design/snapping-redesign.md),
|
|
29
|
+
both under the MIT License:
|
|
30
|
+
|
|
31
|
+
Copyright (c) 2020 Excalidraw
|
|
32
|
+
Copyright (c) 2026 Dominik Peters
|
|
33
|
+
|
|
34
|
+
The permission notice above applies to those portions as well.
|
package/README.md
CHANGED
|
@@ -1,3 +1,63 @@
|
|
|
1
|
-
#
|
|
1
|
+
# snap-guides
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Alignment snapping with guide lines for node editors and canvases, as in Excalidraw, Figma or PowerPoint: drag a box near another and its edges or centre lock onto the other's, with a line showing what it lined up with.
|
|
4
|
+
|
|
5
|
+
The core works on plain boxes and has no framework or DOM dependency. An adapter for [Svelte Flow](https://svelteflow.dev) (xyflow) feeds it the dragged nodes and draws the guides on the canvas.
|
|
6
|
+
|
|
7
|
+
## What it does
|
|
8
|
+
|
|
9
|
+
- Snaps the moving box's left, centre and right to other boxes' lefts, centres and rights, and the same for top, middle and bottom, within 8 screen pixels at any zoom.
|
|
10
|
+
- Any of these may meet any other, as in Excalidraw: one box's middle can line up with another's top. `roles: "same"` restricts it to edges with edges and centres with centres.
|
|
11
|
+
- When several boxes are in reach, it prefers the nearest group of them over a far box that is a hair closer on one axis.
|
|
12
|
+
- A snap holds until the pointer is 1.5 times the threshold away, and a new target takes over only when it is clearly nearer, so the box does not flicker between targets.
|
|
13
|
+
- Guides run across every box that shares the coordinate, with a cross on each aligned point; a centre guide that edge guides on both sides already explain is left out.
|
|
14
|
+
|
|
15
|
+
Not yet: equal-spacing ("gap") snapping, snapping while resizing, rotated boxes.
|
|
16
|
+
|
|
17
|
+
## Core
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { createSnapper } from "@appulsauce/snap-guides";
|
|
21
|
+
|
|
22
|
+
const snapper = createSnapper(); // one per gesture; it remembers the held snap
|
|
23
|
+
|
|
24
|
+
// on every pointer move, with the unsnapped position:
|
|
25
|
+
const { offset, guides } = snapper.snap(movingBox, otherBoxes, zoom);
|
|
26
|
+
moveTo(movingBox.x + offset.x, movingBox.y + offset.y);
|
|
27
|
+
draw(guides);
|
|
28
|
+
|
|
29
|
+
// when the gesture ends:
|
|
30
|
+
snapper.reset();
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
A box is `{ x, y, width, height, id? }` with `x`/`y` its top-left corner, in your world units. `zoom` is screen pixels per world unit. Pass an array as the first argument to move several boxes as one. `snapBoxes(moving, others, options)` is a one-off snap with no memory between calls.
|
|
34
|
+
|
|
35
|
+
A guide is `{ axis, at, role, points, ids }`: for `axis: "x"` the vertical line `x = at`, for `"y"` the horizontal line `y = at`; `points` are sorted along it, so the first and last are its ends; `ids` are the reference boxes it passes through.
|
|
36
|
+
|
|
37
|
+
Options (distances in screen pixels): `threshold` (8), `centers` (true), `roles` (`"any"`), `clusterBreak` (200), `release` (1.5, a multiple of the threshold), `switchAdvantage` (2).
|
|
38
|
+
|
|
39
|
+
## Svelte Flow
|
|
40
|
+
|
|
41
|
+
```svelte
|
|
42
|
+
<script lang="ts">
|
|
43
|
+
import { SvelteFlow } from "@xyflow/svelte";
|
|
44
|
+
import { SnapGuides, useNodeSnap } from "@appulsauce/snap-guides/xyflow-svelte";
|
|
45
|
+
|
|
46
|
+
// In a component inside <SvelteFlow> or a <SvelteFlowProvider>.
|
|
47
|
+
const snap = useNodeSnap();
|
|
48
|
+
</script>
|
|
49
|
+
|
|
50
|
+
<SvelteFlow bind:nodes bind:edges onnodedrag={snap.onnodedrag} onnodedragstop={snap.onnodedragstop}>
|
|
51
|
+
<SnapGuides guides={snap.guides} />
|
|
52
|
+
</SvelteFlow>
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Holding Alt during a drag turns snapping off (`suspend` changes the key). `snapTo: (node) => boolean` limits which nodes are targets. Set `--snap-guide-color` on an ancestor to colour the guides. The adapter assumes the default node origin `[0, 0]`.
|
|
56
|
+
|
|
57
|
+
## Credits
|
|
58
|
+
|
|
59
|
+
The algorithm follows Excalidraw's `packages/excalidraw/snapping.ts`. The optional like-with-like roles, the nearest-cluster preference, hysteresis and dropping explained centre guides follow the tikz-editor's redesign of its port (`design/snapping-redesign.md` in [DominikPeters/tikz-editor](https://github.com/DominikPeters/tikz-editor)), which in turn takes the cluster rule from Excalidraw PR #11316. Both are MIT; see `LICENSE`.
|
|
60
|
+
|
|
61
|
+
## Development
|
|
62
|
+
|
|
63
|
+
`just check` runs lint, type-check, tests and the package build; the pre-push hook runs it too. `just --list` shows the rest.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Geometry for drawing guides, shared by every renderer so they draw the same
|
|
3
|
+
* marks: a line between a guide's outermost points, a small cross on each
|
|
4
|
+
* aligned point, and dashes for centre guides, as in Excalidraw; for equal
|
|
5
|
+
* gaps, each gap as a line with a short tick across either end.
|
|
6
|
+
*/
|
|
7
|
+
import type { GapGuide, Guide, Vec } from "./types.js";
|
|
8
|
+
/** Half the cross size, the centre-guide dash pattern and half a gap's end tick, in screen pixels. */
|
|
9
|
+
export declare const GUIDE_MARKS: {
|
|
10
|
+
readonly cross: 3;
|
|
11
|
+
readonly dash: readonly [4, 3];
|
|
12
|
+
readonly tick: 4;
|
|
13
|
+
};
|
|
14
|
+
/** A stable key for a guide within one frame's list, for keyed rendering. */
|
|
15
|
+
export declare const guideKey: (guide: Guide) => string;
|
|
16
|
+
/** The two ends of a guide's line: its first and last points, or null if it has none. */
|
|
17
|
+
export declare const guideEnds: (guide: Guide) => readonly [Vec, Vec] | null;
|
|
18
|
+
/**
|
|
19
|
+
* SVG path data for a cross on `p` whose arms reach `half` world units along
|
|
20
|
+
* each axis: $\overline{(p_x - h, p_y - h)(p_x + h, p_y + h)}$ and
|
|
21
|
+
* $\overline{(p_x - h, p_y + h)(p_x + h, p_y - h)}$ with $h = $ `half`.
|
|
22
|
+
*/
|
|
23
|
+
export declare const crossPath: (p: Vec, half: number) => string;
|
|
24
|
+
/**
|
|
25
|
+
* The dash pattern for a guide at `zoom` as lengths in world units, for a
|
|
26
|
+
* canvas `setLineDash` or Konva's `dash`; undefined for a solid edge guide.
|
|
27
|
+
*/
|
|
28
|
+
export declare const guideDashArray: (guide: Guide, zoom: number) => readonly number[] | undefined;
|
|
29
|
+
/** The dash pattern for a guide at `zoom`, as an SVG `stroke-dasharray`, or undefined for a solid edge guide. */
|
|
30
|
+
export declare const guideDash: (guide: Guide, zoom: number) => string | undefined;
|
|
31
|
+
/** A stable key for a gap guide within one frame's list, for keyed rendering. */
|
|
32
|
+
export declare const gapKey: (gap: GapGuide) => string;
|
|
33
|
+
/**
|
|
34
|
+
* SVG path data for a gap guide: each gap a line from its start to its end,
|
|
35
|
+
* with a tick across either end reaching `half` world units each way (for a
|
|
36
|
+
* gap along x, from $(x, c - h)$ to $(x, c + h)$ with $h = $ `half`).
|
|
37
|
+
*/
|
|
38
|
+
export declare const gapPath: (gap: GapGuide, half: number) => string;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** Half the cross size, the centre-guide dash pattern and half a gap's end tick, in screen pixels. */
|
|
2
|
+
export const GUIDE_MARKS = { cross: 3, dash: [4, 3], tick: 4 };
|
|
3
|
+
/** A stable key for a guide within one frame's list, for keyed rendering. */
|
|
4
|
+
export const guideKey = (guide) => `${guide.axis}:${String(guide.at)}:${guide.role}`;
|
|
5
|
+
/** The two ends of a guide's line: its first and last points, or null if it has none. */
|
|
6
|
+
export const guideEnds = (guide) => {
|
|
7
|
+
const first = guide.points[0];
|
|
8
|
+
const last = guide.points.at(-1);
|
|
9
|
+
return first && last ? [first, last] : null;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* SVG path data for a cross on `p` whose arms reach `half` world units along
|
|
13
|
+
* each axis: $\overline{(p_x - h, p_y - h)(p_x + h, p_y + h)}$ and
|
|
14
|
+
* $\overline{(p_x - h, p_y + h)(p_x + h, p_y - h)}$ with $h = $ `half`.
|
|
15
|
+
*/
|
|
16
|
+
export const crossPath = (p, half) => {
|
|
17
|
+
const [x0, x1, y0, y1] = [String(p.x - half), String(p.x + half), String(p.y - half), String(p.y + half)];
|
|
18
|
+
return `M${x0} ${y0}L${x1} ${y1}M${x0} ${y1}L${x1} ${y0}`;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The dash pattern for a guide at `zoom` as lengths in world units, for a
|
|
22
|
+
* canvas `setLineDash` or Konva's `dash`; undefined for a solid edge guide.
|
|
23
|
+
*/
|
|
24
|
+
export const guideDashArray = (guide, zoom) => guide.role === "center" ? GUIDE_MARKS.dash.map((d) => d / zoom) : undefined;
|
|
25
|
+
/** The dash pattern for a guide at `zoom`, as an SVG `stroke-dasharray`, or undefined for a solid edge guide. */
|
|
26
|
+
export const guideDash = (guide, zoom) => guideDashArray(guide, zoom)?.join(" ");
|
|
27
|
+
/** A stable key for a gap guide within one frame's list, for keyed rendering. */
|
|
28
|
+
export const gapKey = (gap) => [gap.axis, gap.kind, ...gap.segments.flatMap(([a, b]) => [a.x, a.y, b.x, b.y].map(String))].join(":");
|
|
29
|
+
/**
|
|
30
|
+
* SVG path data for a gap guide: each gap a line from its start to its end,
|
|
31
|
+
* with a tick across either end reaching `half` world units each way (for a
|
|
32
|
+
* gap along x, from $(x, c - h)$ to $(x, c + h)$ with $h = $ `half`).
|
|
33
|
+
*/
|
|
34
|
+
export const gapPath = (gap, half) => gap.segments
|
|
35
|
+
.map(([a, b]) => {
|
|
36
|
+
const tick = (p) => gap.axis === "x"
|
|
37
|
+
? `M${String(p.x)} ${String(p.y - half)}L${String(p.x)} ${String(p.y + half)}`
|
|
38
|
+
: `M${String(p.x - half)} ${String(p.y)}L${String(p.x + half)} ${String(p.y)}`;
|
|
39
|
+
return `M${String(a.x)} ${String(a.y)}L${String(b.x)} ${String(b.y)}${tick(a)}${tick(b)}`;
|
|
40
|
+
})
|
|
41
|
+
.join("");
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Axis, Box, GapGuide } from "./types.js";
|
|
2
|
+
/** Which edge of the moving box a gap target places. */
|
|
3
|
+
type GapEdge = "low" | "high";
|
|
4
|
+
/**
|
|
5
|
+
* Where one edge of the moving box should go on `axis` for one gap rule.
|
|
6
|
+
* `distance` is how far the moving box is from the nearest box the rule
|
|
7
|
+
* spaces it against, for the nearest-cluster filter.
|
|
8
|
+
*/
|
|
9
|
+
export interface GapTarget {
|
|
10
|
+
readonly axis: Axis;
|
|
11
|
+
readonly edge: GapEdge;
|
|
12
|
+
readonly at: number;
|
|
13
|
+
readonly distance: number;
|
|
14
|
+
}
|
|
15
|
+
/** Where the gap rules would place the moving box's edges on `axis`. */
|
|
16
|
+
export declare const gapTargets: (moving: Box, references: readonly Box[], axis: Axis, tolerance: number) => GapTarget[];
|
|
17
|
+
/**
|
|
18
|
+
* The equal gaps the (already snapped) moving box takes part in: every rule
|
|
19
|
+
* whose target its edge is on, within `tolerance`.
|
|
20
|
+
*/
|
|
21
|
+
export declare const gapGuides: (moving: Box, references: readonly Box[], tolerance: number) => GapGuide[];
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
const other = (axis) => (axis === "x" ? "y" : "x");
|
|
2
|
+
const extent = (box, axis) => axis === "x" ? { low: box.x, high: box.x + box.width } : { low: box.y, high: box.y + box.height };
|
|
3
|
+
const overlaps = (a, b, tolerance) => Math.min(a.high, b.high) - Math.max(a.low, b.low) > tolerance;
|
|
4
|
+
/**
|
|
5
|
+
* A total order on neighbours by coordinates alone (then id), so the choice
|
|
6
|
+
* never depends on the order the references came in. `key` maps a neighbour
|
|
7
|
+
* to its nearness: larger is nearer.
|
|
8
|
+
*/
|
|
9
|
+
const nearestBy = (key) => (a, b) => key(b) - key(a) ||
|
|
10
|
+
b.along.low + b.along.high - (a.along.low + a.along.high) ||
|
|
11
|
+
a.across.low - b.across.low ||
|
|
12
|
+
a.across.high - b.across.high ||
|
|
13
|
+
(a.id ?? "").localeCompare(b.id ?? "");
|
|
14
|
+
/** The nearest neighbour and, if there is one, the nearest wholly beyond it. */
|
|
15
|
+
const nearestTwo = (side, key, beyond) => {
|
|
16
|
+
const order = nearestBy(key);
|
|
17
|
+
const first = side.toSorted(order)[0];
|
|
18
|
+
if (!first)
|
|
19
|
+
return [];
|
|
20
|
+
const second = side.filter((n) => beyond(n, first)).toSorted(order)[0];
|
|
21
|
+
return second ? [first, second] : [first];
|
|
22
|
+
};
|
|
23
|
+
/** The moving box's nearest neighbours on each side along `axis` (boxes normalised). */
|
|
24
|
+
const neighbours = (moving, references, axis, tolerance) => {
|
|
25
|
+
const along = extent(moving, axis);
|
|
26
|
+
const across = extent(moving, other(axis));
|
|
27
|
+
const beside = references
|
|
28
|
+
.map((r) => ({ along: extent(r, axis), across: extent(r, other(axis)), id: r.id }))
|
|
29
|
+
.filter((n) => overlaps(n.across, across, tolerance));
|
|
30
|
+
return {
|
|
31
|
+
low: nearestTwo(beside.filter((n) => n.along.high <= along.low + tolerance), (n) => n.along.high, (n, first) => n.along.high <= first.along.low + tolerance),
|
|
32
|
+
high: nearestTwo(beside.filter((n) => n.along.low >= along.high - tolerance), (n) => -n.along.low, (n, first) => n.along.low >= first.along.high - tolerance),
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* The spacings the rules offer for a moving box with extent `along` on `axis`:
|
|
37
|
+
* continuing the gap of the two nearest boxes on either side, and centring
|
|
38
|
+
* between the nearest on each side. Gaps no wider than `tolerance` are left to
|
|
39
|
+
* edge snapping, which already lines touching boxes up.
|
|
40
|
+
*/
|
|
41
|
+
const spacings = (along, sides, tolerance) => {
|
|
42
|
+
const result = [];
|
|
43
|
+
const width = along.high - along.low;
|
|
44
|
+
const [lowFirst, lowSecond] = sides.low;
|
|
45
|
+
const [highFirst, highSecond] = sides.high;
|
|
46
|
+
if (lowFirst && lowSecond) {
|
|
47
|
+
const length = lowFirst.along.low - lowSecond.along.high;
|
|
48
|
+
if (length > tolerance)
|
|
49
|
+
result.push({ kind: "continue", edge: "low", at: lowFirst.along.high + length, length, near: along.low - lowFirst.along.high, pairs: [[lowSecond, lowFirst], [lowFirst, "moving"]] });
|
|
50
|
+
}
|
|
51
|
+
if (highFirst && highSecond) {
|
|
52
|
+
const length = highSecond.along.low - highFirst.along.high;
|
|
53
|
+
if (length > tolerance)
|
|
54
|
+
result.push({ kind: "continue", edge: "high", at: highFirst.along.low - length, length, near: highFirst.along.low - along.high, pairs: [["moving", highFirst], [highFirst, highSecond]] });
|
|
55
|
+
}
|
|
56
|
+
if (lowFirst && highFirst) {
|
|
57
|
+
const length = (highFirst.along.low - lowFirst.along.high - width) / 2;
|
|
58
|
+
if (length > tolerance)
|
|
59
|
+
result.push({
|
|
60
|
+
kind: "center",
|
|
61
|
+
edge: "low",
|
|
62
|
+
at: lowFirst.along.high + length,
|
|
63
|
+
length,
|
|
64
|
+
near: Math.min(along.low - lowFirst.along.high, highFirst.along.low - along.high),
|
|
65
|
+
pairs: [[lowFirst, "moving"], ["moving", highFirst]],
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
return result;
|
|
69
|
+
};
|
|
70
|
+
/** Where the gap rules would place the moving box's edges on `axis`. */
|
|
71
|
+
export const gapTargets = (moving, references, axis, tolerance) => spacings(extent(moving, axis), neighbours(moving, references, axis, tolerance), tolerance).map((s) => ({
|
|
72
|
+
axis,
|
|
73
|
+
edge: s.edge,
|
|
74
|
+
at: s.at,
|
|
75
|
+
distance: Math.abs(s.near),
|
|
76
|
+
}));
|
|
77
|
+
/**
|
|
78
|
+
* A segment across the gap between two extents along `axis`, drawn at the
|
|
79
|
+
* middle of where they overlap across it: from `a`'s high end to `b`'s low end.
|
|
80
|
+
*/
|
|
81
|
+
const span = (axis, a, b) => {
|
|
82
|
+
const c = (Math.max(a.across.low, b.across.low) + Math.min(a.across.high, b.across.high)) / 2;
|
|
83
|
+
return axis === "x"
|
|
84
|
+
? [
|
|
85
|
+
{ x: a.along.high, y: c },
|
|
86
|
+
{ x: b.along.low, y: c },
|
|
87
|
+
]
|
|
88
|
+
: [
|
|
89
|
+
{ x: c, y: a.along.high },
|
|
90
|
+
{ x: c, y: b.along.low },
|
|
91
|
+
];
|
|
92
|
+
};
|
|
93
|
+
const resolveMoving = (n, self) => (n === "moving" ? self : n);
|
|
94
|
+
/**
|
|
95
|
+
* The equal gaps the (already snapped) moving box takes part in: every rule
|
|
96
|
+
* whose target its edge is on, within `tolerance`.
|
|
97
|
+
*/
|
|
98
|
+
export const gapGuides = (moving, references, tolerance) => ["x", "y"].flatMap((axis) => {
|
|
99
|
+
const along = extent(moving, axis);
|
|
100
|
+
const self = { along, across: extent(moving, other(axis)), id: undefined };
|
|
101
|
+
return spacings(along, neighbours(moving, references, axis, tolerance), tolerance)
|
|
102
|
+
.filter((s) => Math.abs((s.edge === "low" ? along.low : along.high) - s.at) <= tolerance)
|
|
103
|
+
.map((s) => ({
|
|
104
|
+
axis,
|
|
105
|
+
kind: s.kind,
|
|
106
|
+
length: s.length,
|
|
107
|
+
segments: s.pairs.map(([a, b]) => span(axis, resolveMoving(a, self), resolveMoving(b, self))),
|
|
108
|
+
ids: [...new Set(s.pairs.flat().map((n) => (n === "moving" ? undefined : n.id)))].filter((id) => id !== undefined),
|
|
109
|
+
}));
|
|
110
|
+
});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @appulsauce/snap-guides: alignment snapping over plain boxes, with no
|
|
3
|
+
* framework or DOM. Adapters (`@appulsauce/snap-guides/xyflow-svelte`) feed it
|
|
4
|
+
* the boxes of a particular editor and draw its guides.
|
|
5
|
+
*/
|
|
6
|
+
export { EPSILON, boxPoints, createSnapper, roundCoordinate, snapBoxes, unionBox, type Snapper } from "./snap.js";
|
|
7
|
+
export { GUIDE_MARKS, crossPath, gapKey, gapPath, guideDash, guideDashArray, guideEnds, guideKey } from "./draw.js";
|
|
8
|
+
export type { Axis, Box, GapGuide, Guide, Role, SnapOptions, SnapPoint, SnapResult, Vec } from "./types.js";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @appulsauce/snap-guides: alignment snapping over plain boxes, with no
|
|
3
|
+
* framework or DOM. Adapters (`@appulsauce/snap-guides/xyflow-svelte`) feed it
|
|
4
|
+
* the boxes of a particular editor and draw its guides.
|
|
5
|
+
*/
|
|
6
|
+
export { EPSILON, boxPoints, createSnapper, roundCoordinate, snapBoxes, unionBox } from "./snap.js";
|
|
7
|
+
export { GUIDE_MARKS, crossPath, gapKey, gapPath, guideDash, guideDashArray, guideEnds, guideKey } from "./draw.js";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Box, SnapOptions, SnapPoint, SnapResult } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Coordinates closer than this many screen pixels are the same coordinate: the
|
|
4
|
+
* tolerance in world units is `EPSILON / zoom`, so it means the same on screen
|
|
5
|
+
* at any zoom and in any world unit.
|
|
6
|
+
*/
|
|
7
|
+
export declare const EPSILON = 0.000001;
|
|
8
|
+
/** Rounds away float noise at 1e-6 world units (kept for callers; the core compares in screen pixels). */
|
|
9
|
+
export declare const roundCoordinate: (value: number) => number;
|
|
10
|
+
/** The four corners (edge role) and, with `centers`, the centre of a box. */
|
|
11
|
+
export declare const boxPoints: (box: Box, centers?: boolean) => SnapPoint[];
|
|
12
|
+
/** The smallest box holding all of `boxes`, which move together (negative sizes are normalised). */
|
|
13
|
+
export declare const unionBox: (boxes: readonly Box[]) => Box;
|
|
14
|
+
export interface Snapper {
|
|
15
|
+
/**
|
|
16
|
+
* Snap `moving` (one box, or several that move as one) to `references`.
|
|
17
|
+
* `zoom` is screen pixels per world unit, so the options' pixel distances
|
|
18
|
+
* stay the same on screen at any zoom. Call it on every move of one gesture,
|
|
19
|
+
* with the unsnapped position; the snapper remembers what it held.
|
|
20
|
+
*
|
|
21
|
+
* Throws a RangeError for an empty or non-finite `moving`, or a `zoom` that
|
|
22
|
+
* is not a positive finite number. References that are not finite, or that
|
|
23
|
+
* share an `id` with a moving box, are ignored.
|
|
24
|
+
*/
|
|
25
|
+
snap: (moving: Box | readonly Box[], references: readonly Box[], zoom?: number) => SnapResult;
|
|
26
|
+
/** Forget the held snap; call it when the gesture ends. */
|
|
27
|
+
reset: () => void;
|
|
28
|
+
}
|
|
29
|
+
/** A snapper for one gesture at a time, with hysteresis between calls. */
|
|
30
|
+
export declare const createSnapper: (options?: SnapOptions) => Snapper;
|
|
31
|
+
/** One-off snap with no memory between calls; use `createSnapper` during a drag. */
|
|
32
|
+
export declare const snapBoxes: (moving: Box | readonly Box[], references: readonly Box[], options?: SnapOptions & {
|
|
33
|
+
readonly zoom?: number;
|
|
34
|
+
}) => SnapResult;
|
|
@@ -0,0 +1,260 @@
|
|
|
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 { 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 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];
|
|
111
|
+
const from = points[index];
|
|
112
|
+
if (!from)
|
|
113
|
+
return [];
|
|
114
|
+
const to = { ...from, [t.axis]: t.at, role: "edge" };
|
|
115
|
+
return [{ index, from, to, offset: t.at - from[t.axis], distance: t.distance, gap: true }];
|
|
116
|
+
};
|
|
117
|
+
const isBox = (value) => "width" in value;
|
|
118
|
+
const translate = (box, by) => ({ ...box, x: box.x + by.x, y: box.y + by.y });
|
|
119
|
+
const other = (axis) => (axis === "x" ? "y" : "x");
|
|
120
|
+
/** A key equal for coordinates within `tolerance` of a grid point (for grouping). */
|
|
121
|
+
const keyOf = (value, tolerance) => String(Math.round(value / tolerance));
|
|
122
|
+
/** Points deduplicated and sorted along the guide (by the other axis). */
|
|
123
|
+
const alongGuide = (axis, points, tolerance) => {
|
|
124
|
+
const seen = new Map();
|
|
125
|
+
for (const p of points)
|
|
126
|
+
seen.set(`${keyOf(p.x, tolerance)},${keyOf(p.y, tolerance)}`, p);
|
|
127
|
+
const across = other(axis);
|
|
128
|
+
return [...seen.values()].toSorted((a, b) => a[across] - b[across]);
|
|
129
|
+
};
|
|
130
|
+
/** Guides through every exact alignment of the (already snapped) moving points. */
|
|
131
|
+
const buildGuides = (moving, references, clusterBreak, sameRole, tolerance) => {
|
|
132
|
+
const guides = [];
|
|
133
|
+
for (const axis of AXES) {
|
|
134
|
+
// One guide per line: an edge and a centre that meet on the same
|
|
135
|
+
// coordinate share it, drawn as an edge guide.
|
|
136
|
+
const groups = new Map();
|
|
137
|
+
// The nearest cluster decides which reference boxes take part; every
|
|
138
|
+
// aligned point of those boxes then goes on the guide, so it spans them
|
|
139
|
+
// whole rather than stopping at the nearest corners.
|
|
140
|
+
const exact = collect(moving, references, axis, tolerance, sameRole);
|
|
141
|
+
const near = nearestCluster(exact, clusterBreak);
|
|
142
|
+
const boxes = new Set(near.map((c) => c.to.id).filter((id) => id !== undefined));
|
|
143
|
+
const aligned = exact.filter((c) => near.includes(c) || (c.to.id !== undefined && boxes.has(c.to.id)));
|
|
144
|
+
for (const c of aligned) {
|
|
145
|
+
const key = keyOf(c.to[axis], tolerance);
|
|
146
|
+
// The line is the reference's own coordinate, exactly.
|
|
147
|
+
const group = groups.get(key) ?? { at: c.to[axis], center: true, points: [], ids: new Set() };
|
|
148
|
+
groups.set(key, group);
|
|
149
|
+
group.center &&= c.from.role === "center" && c.to.role === "center";
|
|
150
|
+
// The moving point sits on the line up to float noise; put it exactly on.
|
|
151
|
+
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 });
|
|
152
|
+
if (c.to.id !== undefined)
|
|
153
|
+
group.ids.add(c.to.id);
|
|
154
|
+
}
|
|
155
|
+
for (const g of groups.values()) {
|
|
156
|
+
const role = g.center ? "center" : "edge";
|
|
157
|
+
guides.push({ axis, at: g.at, role, points: alongGuide(axis, g.points, tolerance), ids: [...g.ids] });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return withoutBracketedCenters(guides);
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* When edge guides on both sides of a centre guide on the same axis already
|
|
164
|
+
* pass through the boxes it does (two boxes of equal size, aligned), the
|
|
165
|
+
* centre guide says nothing new: drop it. A centre guide through a box the
|
|
166
|
+
* edge guides miss stays, so every aligned box appears in some guide.
|
|
167
|
+
*/
|
|
168
|
+
const withoutBracketedCenters = (guides) => guides.filter((g) => {
|
|
169
|
+
if (g.role !== "center")
|
|
170
|
+
return true;
|
|
171
|
+
const explains = (e) => e.axis === g.axis && e.role === "edge" && g.ids.every((id) => e.ids.includes(id));
|
|
172
|
+
return !(guides.some((e) => explains(e) && e.at < g.at) && guides.some((e) => explains(e) && e.at > g.at));
|
|
173
|
+
});
|
|
174
|
+
/** A snapper for one gesture at a time, with hysteresis between calls. */
|
|
175
|
+
export const createSnapper = (options = {}) => {
|
|
176
|
+
const opts = { ...DEFAULTS, ...options };
|
|
177
|
+
const sameRole = opts.roles === "same";
|
|
178
|
+
const none = { x: undefined, y: undefined };
|
|
179
|
+
let held = none;
|
|
180
|
+
const offsetOn = (axis, points, references, gaps, scale) => {
|
|
181
|
+
const tolerance = EPSILON / scale;
|
|
182
|
+
const reach = opts.threshold / scale + tolerance;
|
|
183
|
+
const candidates = [...collect(points, references, axis, reach, sameRole), ...gaps.filter((c) => Math.abs(c.offset) <= reach)];
|
|
184
|
+
// An axis already exactly aligned stays put (snapping is idempotent);
|
|
185
|
+
// otherwise the nearest cluster's smallest offset wins.
|
|
186
|
+
const aligned = candidates.filter((c) => Math.abs(c.offset) <= tolerance);
|
|
187
|
+
const pick = best(aligned.length > 0 ? aligned : nearestCluster(candidates, opts.clusterBreak / scale));
|
|
188
|
+
const fresh = pick ? { offset: pick.offset, held: { index: pick.index, at: pick.to[axis], role: pick.to.role, gap: pick.gap === true } } : null;
|
|
189
|
+
// Keep the held target while it is within the release distance and still
|
|
190
|
+
// there, unless a fresh one is nearer by a clear margin.
|
|
191
|
+
const previous = held[axis];
|
|
192
|
+
const from = previous ? points[previous.index] : undefined;
|
|
193
|
+
const stillThere = previous &&
|
|
194
|
+
(previous.gap
|
|
195
|
+
? gaps.some((c) => c.index === previous.index && Math.abs(c.to[axis] - previous.at) <= tolerance)
|
|
196
|
+
: references.some((r) => r.role === previous.role && Math.abs(r[axis] - previous.at) <= tolerance));
|
|
197
|
+
if (previous && from && stillThere) {
|
|
198
|
+
const kept = previous.at - from[axis];
|
|
199
|
+
const beaten = fresh && Math.abs(fresh.offset) + opts.switchAdvantage / scale < Math.abs(kept) - tolerance;
|
|
200
|
+
if (!beaten && Math.abs(kept) <= (opts.threshold / scale) * opts.release + tolerance)
|
|
201
|
+
return kept;
|
|
202
|
+
}
|
|
203
|
+
if (fresh) {
|
|
204
|
+
held = { ...held, [axis]: fresh.held };
|
|
205
|
+
return fresh.offset;
|
|
206
|
+
}
|
|
207
|
+
held = { ...held, [axis]: undefined };
|
|
208
|
+
return null;
|
|
209
|
+
};
|
|
210
|
+
return {
|
|
211
|
+
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)}`);
|
|
214
|
+
const movingBoxes = isBox(moving) ? [moving] : moving;
|
|
215
|
+
if (movingBoxes.some((b) => !isFiniteBox(b)))
|
|
216
|
+
throw new RangeError("snap-guides: a moving box has a non-finite coordinate or size");
|
|
217
|
+
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));
|
|
221
|
+
const points = boxPoints(box, opts.centers);
|
|
222
|
+
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
|
+
const before = held;
|
|
230
|
+
const solve = (withGaps, at) => {
|
|
231
|
+
held = before;
|
|
232
|
+
const gapsOn = (axis) => withGaps ? gapTargets(at, others, axis, tolerance).flatMap((t) => gapCandidate(points, t)) : [];
|
|
233
|
+
return {
|
|
234
|
+
x: offsetOn("x", points, targets, gapsOn("x"), zoom) ?? 0,
|
|
235
|
+
y: offsetOn("y", points, targets, gapsOn("y"), zoom) ?? 0,
|
|
236
|
+
};
|
|
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
|
+
}
|
|
247
|
+
const moved = translate(box, offset);
|
|
248
|
+
return {
|
|
249
|
+
offset,
|
|
250
|
+
guides: buildGuides(boxPoints(moved, opts.centers), targets, opts.clusterBreak / zoom, sameRole, tolerance),
|
|
251
|
+
gaps: opts.gaps ? gapGuides(moved, others, tolerance) : [],
|
|
252
|
+
};
|
|
253
|
+
},
|
|
254
|
+
reset: () => {
|
|
255
|
+
held = none;
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
};
|
|
259
|
+
/** One-off snap with no memory between calls; use `createSnapper` during a drag. */
|
|
260
|
+
export const snapBoxes = (moving, references, options = {}) => createSnapper(options).snap(moving, references, options.zoom);
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
/** Every distance here is in screen pixels; `snap` divides by the zoom it is given. */
|
|
72
|
+
export interface SnapOptions {
|
|
73
|
+
/** How close a point must come to snap. Default 8 (as in Excalidraw). */
|
|
74
|
+
readonly threshold?: number;
|
|
75
|
+
/** Snap and draw centres as well as edges. Default true. */
|
|
76
|
+
readonly centers?: boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Which snap points may line up. `"any"` (default, as in Excalidraw) lets a
|
|
79
|
+
* centre meet an edge, such as one box's middle on another's top. `"same"`
|
|
80
|
+
* matches edges only with edges and centres only with centres, as the
|
|
81
|
+
* tikz-editor's redesign does to keep every guide obvious.
|
|
82
|
+
*/
|
|
83
|
+
readonly roles?: "any" | "same";
|
|
84
|
+
/**
|
|
85
|
+
* Among targets within reach, keep only the nearest cluster: candidates are
|
|
86
|
+
* taken in order of distance and the list is cut where the distance jumps by
|
|
87
|
+
* more than this. A far box that wins on offset by a hair then loses to the
|
|
88
|
+
* near one. Default 200 (Excalidraw PR #11316). `Infinity` turns it off.
|
|
89
|
+
*/
|
|
90
|
+
readonly clusterBreak?: number;
|
|
91
|
+
/**
|
|
92
|
+
* A held snap is let go only past `release` times the threshold, so it does
|
|
93
|
+
* not flicker at the edge of its reach. Default 1.5. 1 removes the extra
|
|
94
|
+
* reach; a held target is still kept while it is in reach, even when the
|
|
95
|
+
* nearest-cluster rule would now pass it over, and while any reference
|
|
96
|
+
* point of its role stays on its line.
|
|
97
|
+
*/
|
|
98
|
+
readonly release?: number;
|
|
99
|
+
/** A new target replaces a held one only when it is this much nearer. Default 2. */
|
|
100
|
+
readonly switchAdvantage?: number;
|
|
101
|
+
/**
|
|
102
|
+
* Snap to equal spacing as well as to alignment: continue the gap between
|
|
103
|
+
* the two boxes nearest on one side, or centre between the nearest box on
|
|
104
|
+
* each side. Only boxes that overlap the moving box across the axis count.
|
|
105
|
+
* Default true.
|
|
106
|
+
*/
|
|
107
|
+
readonly gaps?: boolean;
|
|
108
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
Draws the guides from `useNodeSnap` on the Svelte Flow canvas, in flow
|
|
3
|
+
coordinates (a ViewportPortal), so they pan and zoom with the nodes. Lines
|
|
4
|
+
stay one screen pixel wide at any zoom; each aligned point gets a small cross,
|
|
5
|
+
as in Excalidraw; centre guides are dashed. Equal gaps (`gaps`) are drawn as
|
|
6
|
+
lines with a tick across each end.
|
|
7
|
+
|
|
8
|
+
Colour: set `--snap-guide-color` on any ancestor (default a magenta that reads
|
|
9
|
+
on light and dark canvases).
|
|
10
|
+
-->
|
|
11
|
+
<script lang="ts">
|
|
12
|
+
import { useSvelteFlowStore, ViewportPortal } from "@xyflow/svelte";
|
|
13
|
+
import { crossPath, gapKey, gapPath, GUIDE_MARKS, guideDash, guideEnds, guideKey, type GapGuide, type Guide } from "../core/index.js";
|
|
14
|
+
|
|
15
|
+
interface Props {
|
|
16
|
+
guides: readonly Guide[];
|
|
17
|
+
gaps?: readonly GapGuide[];
|
|
18
|
+
}
|
|
19
|
+
const { guides, gaps = [] }: Props = $props();
|
|
20
|
+
// Derived, so it follows the store a <SvelteFlowProvider> swaps in (see node-snap.svelte.ts).
|
|
21
|
+
const store = $derived(useSvelteFlowStore());
|
|
22
|
+
const zoom = $derived(store.viewport.zoom);
|
|
23
|
+
</script>
|
|
24
|
+
|
|
25
|
+
<ViewportPortal target="front">
|
|
26
|
+
<svg class="snap-guides" aria-hidden="true">
|
|
27
|
+
{#each guides as guide (guideKey(guide))}
|
|
28
|
+
{@const line = guideEnds(guide)}
|
|
29
|
+
{#if line}
|
|
30
|
+
<line x1={line[0].x} y1={line[0].y} x2={line[1].x} y2={line[1].y} stroke-dasharray={guideDash(guide, zoom)} />
|
|
31
|
+
{/if}
|
|
32
|
+
{#each guide.points as p (`${String(p.x)},${String(p.y)}`)}
|
|
33
|
+
<path d={crossPath(p, GUIDE_MARKS.cross / zoom)} />
|
|
34
|
+
{/each}
|
|
35
|
+
{/each}
|
|
36
|
+
{#each gaps as gap (gapKey(gap))}
|
|
37
|
+
<path d={gapPath(gap, GUIDE_MARKS.tick / zoom)} />
|
|
38
|
+
{/each}
|
|
39
|
+
</svg>
|
|
40
|
+
</ViewportPortal>
|
|
41
|
+
|
|
42
|
+
<style>
|
|
43
|
+
.snap-guides {
|
|
44
|
+
position: absolute;
|
|
45
|
+
inset-block-start: 0;
|
|
46
|
+
inset-inline-start: 0;
|
|
47
|
+
inline-size: 1px;
|
|
48
|
+
block-size: 1px;
|
|
49
|
+
overflow: visible;
|
|
50
|
+
pointer-events: none;
|
|
51
|
+
fill: none;
|
|
52
|
+
stroke: var(--snap-guide-color, #e0447c);
|
|
53
|
+
stroke-width: 1px;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
.snap-guides :is(line, path) {
|
|
57
|
+
vector-effect: non-scaling-stroke;
|
|
58
|
+
}
|
|
59
|
+
</style>
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type GapGuide, type Guide } from "../core/index.js";
|
|
2
|
+
interface Props {
|
|
3
|
+
guides: readonly Guide[];
|
|
4
|
+
gaps?: readonly GapGuide[];
|
|
5
|
+
}
|
|
6
|
+
declare const SnapGuides: import("svelte").Component<Props, {}, "">;
|
|
7
|
+
type SnapGuides = ReturnType<typeof SnapGuides>;
|
|
8
|
+
export default SnapGuides;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type Node, type NodeTargetEventWithPointer } from "@xyflow/svelte";
|
|
2
|
+
import { type GapGuide, type Guide, type SnapOptions } from "../core/index.js";
|
|
3
|
+
type DragEvent = MouseEvent | TouchEvent;
|
|
4
|
+
export interface NodeSnapOptions<NodeType extends Node = Node> extends SnapOptions {
|
|
5
|
+
/** The nodes a dragged node may snap to. Default: every node not being dragged and not hidden. */
|
|
6
|
+
readonly snapTo?: (node: NodeType) => boolean;
|
|
7
|
+
/** While this holds for the drag's pointer event, snapping is off. Default: Alt is held. */
|
|
8
|
+
readonly suspend?: (event: DragEvent) => boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface NodeSnap<NodeType extends Node = Node> {
|
|
11
|
+
/** The guides to draw now; hand them to `<SnapGuides>`. Empty between drags. */
|
|
12
|
+
readonly guides: readonly Guide[];
|
|
13
|
+
/** The equal gaps to draw now; hand them to `<SnapGuides gaps>`. Empty between drags. */
|
|
14
|
+
readonly gaps: readonly GapGuide[];
|
|
15
|
+
/** Pass to `<SvelteFlow onnodedrag>`. */
|
|
16
|
+
readonly onnodedrag: NodeTargetEventWithPointer<DragEvent, NodeType>;
|
|
17
|
+
/** Pass to `<SvelteFlow onnodedragstop>`. */
|
|
18
|
+
readonly onnodedragstop: NodeTargetEventWithPointer<DragEvent, NodeType>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Create the drag handlers and the live guides. Call it during the init of a
|
|
22
|
+
* component inside `<SvelteFlow>` or a `<SvelteFlowProvider>`, as for
|
|
23
|
+
* `useSvelteFlow`.
|
|
24
|
+
*/
|
|
25
|
+
export declare const useNodeSnap: <NodeType extends Node = Node>(options?: NodeSnapOptions<NodeType>) => NodeSnap<NodeType>;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Snapping for dragged Svelte Flow nodes, built on the core snapper.
|
|
3
|
+
*
|
|
4
|
+
* xyflow recomputes a dragged node's position from the pointer on every move
|
|
5
|
+
* and queues it as a change; `onnodedrag` runs after that, so a snapped
|
|
6
|
+
* position queued here lands later in the same batch and wins. A held snap
|
|
7
|
+
* often leaves the position unchanged from the last frame, which
|
|
8
|
+
* `useSvelteFlow().updateNode` would skip as a no-op, so this writes through
|
|
9
|
+
* the store's `updateNodePositions`, which always queues. When the drag ends
|
|
10
|
+
* xyflow queues its own unsnapped positions once more, before
|
|
11
|
+
* `onnodedragstop`; that handler queues the snapped ones again after them.
|
|
12
|
+
*
|
|
13
|
+
* Assumes the default node origin [0, 0] (a node's position is its top-left).
|
|
14
|
+
* The guides component reads the zoom the same way, through a derived store.
|
|
15
|
+
*/
|
|
16
|
+
import { useSvelteFlowStore, } from "@xyflow/svelte";
|
|
17
|
+
import { createSnapper } from "../core/index.js";
|
|
18
|
+
const ZERO = { x: 0, y: 0 };
|
|
19
|
+
/**
|
|
20
|
+
* Create the drag handlers and the live guides. Call it during the init of a
|
|
21
|
+
* component inside `<SvelteFlow>` or a `<SvelteFlowProvider>`, as for
|
|
22
|
+
* `useSvelteFlow`.
|
|
23
|
+
*/
|
|
24
|
+
export const useNodeSnap = (options = {}) => {
|
|
25
|
+
// Under a <SvelteFlowProvider> the context first holds a placeholder store,
|
|
26
|
+
// replaced when <SvelteFlow> mounts; a plain call here would keep the empty
|
|
27
|
+
// placeholder. Deriving it re-reads the current one, as useSvelteFlow does.
|
|
28
|
+
const store = $derived(useSvelteFlowStore());
|
|
29
|
+
const snapper = createSnapper(options);
|
|
30
|
+
const snapTo = options.snapTo ?? (() => true);
|
|
31
|
+
const suspend = options.suspend ?? ((event) => event.altKey);
|
|
32
|
+
let guides = $state.raw([]);
|
|
33
|
+
let gaps = $state.raw([]);
|
|
34
|
+
/** The offset the last drag frame applied, re-applied when the drag ends. */
|
|
35
|
+
let last = ZERO;
|
|
36
|
+
const size = (internal) => {
|
|
37
|
+
const width = internal.measured.width ?? internal.width;
|
|
38
|
+
const height = internal.measured.height ?? internal.height;
|
|
39
|
+
return width === undefined || height === undefined ? null : { width, height };
|
|
40
|
+
};
|
|
41
|
+
/** A dragged node's box, from the position xyflow just computed for it. */
|
|
42
|
+
const draggedBox = (node) => {
|
|
43
|
+
const internal = store.nodeLookup.get(node.id);
|
|
44
|
+
const dims = internal ? size(internal) : null;
|
|
45
|
+
if (!dims)
|
|
46
|
+
return null;
|
|
47
|
+
const parent = node.parentId === undefined ? undefined : store.nodeLookup.get(node.parentId);
|
|
48
|
+
const origin = parent?.internals.positionAbsolute ?? ZERO;
|
|
49
|
+
return { x: origin.x + node.position.x, y: origin.y + node.position.y, ...dims, id: node.id };
|
|
50
|
+
};
|
|
51
|
+
const referenceBoxes = (dragged) => {
|
|
52
|
+
const boxes = [];
|
|
53
|
+
for (const internal of store.nodeLookup.values()) {
|
|
54
|
+
const dims = size(internal);
|
|
55
|
+
if (!dims || dragged.includes(internal.id) || internal.hidden || !snapTo(internal.internals.userNode))
|
|
56
|
+
continue;
|
|
57
|
+
const { x, y } = internal.internals.positionAbsolute;
|
|
58
|
+
boxes.push({ x, y, ...dims, id: internal.id });
|
|
59
|
+
}
|
|
60
|
+
return boxes;
|
|
61
|
+
};
|
|
62
|
+
/** Queue `nodes` at their positions plus `offset`, after xyflow's own change. */
|
|
63
|
+
const place = (nodes, offset, dragging) => {
|
|
64
|
+
const entries = [];
|
|
65
|
+
for (const node of nodes) {
|
|
66
|
+
const internal = store.nodeLookup.get(node.id);
|
|
67
|
+
const dims = internal ? size(internal) : null;
|
|
68
|
+
if (!internal || !dims)
|
|
69
|
+
continue;
|
|
70
|
+
const position = { x: node.position.x + offset.x, y: node.position.y + offset.y };
|
|
71
|
+
entries.push([
|
|
72
|
+
node.id,
|
|
73
|
+
{ id: node.id, position, distance: ZERO, measured: dims, internals: { positionAbsolute: internal.internals.positionAbsolute } },
|
|
74
|
+
]);
|
|
75
|
+
}
|
|
76
|
+
// A throwaway argument, never read reactively; SvelteMap would only add cost.
|
|
77
|
+
// eslint-disable-next-line svelte/prefer-svelte-reactivity
|
|
78
|
+
store.updateNodePositions(new Map(entries), dragging);
|
|
79
|
+
};
|
|
80
|
+
const stop = () => {
|
|
81
|
+
snapper.reset();
|
|
82
|
+
guides = [];
|
|
83
|
+
gaps = [];
|
|
84
|
+
last = ZERO;
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
get guides() {
|
|
88
|
+
return guides;
|
|
89
|
+
},
|
|
90
|
+
get gaps() {
|
|
91
|
+
return gaps;
|
|
92
|
+
},
|
|
93
|
+
onnodedrag: ({ nodes, event }) => {
|
|
94
|
+
if (suspend(event)) {
|
|
95
|
+
stop();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const moving = nodes.flatMap((n) => draggedBox(n) ?? []);
|
|
99
|
+
if (moving.length === 0)
|
|
100
|
+
return;
|
|
101
|
+
const ids = nodes.map((n) => n.id);
|
|
102
|
+
const result = snapper.snap(moving, referenceBoxes(ids), store.viewport.zoom);
|
|
103
|
+
guides = result.guides;
|
|
104
|
+
gaps = result.gaps;
|
|
105
|
+
last = result.offset;
|
|
106
|
+
if (last.x !== 0 || last.y !== 0)
|
|
107
|
+
place(nodes, last, true);
|
|
108
|
+
},
|
|
109
|
+
onnodedragstop: ({ nodes }) => {
|
|
110
|
+
if (last.x !== 0 || last.y !== 0)
|
|
111
|
+
place(nodes, last, false);
|
|
112
|
+
stop();
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,91 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@appulsauce/snap-guides",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Alignment snapping with guide lines for node editors and canvases: a framework-free core over plain boxes, and an adapter for Svelte Flow (xyflow).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Kai Erik Niermann",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/KaiErikNiermann/snap-guides.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://kaierikniermann.github.io/snap-guides/",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/KaiErikNiermann/snap-guides/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/core/index.d.ts",
|
|
22
|
+
"default": "./dist/core/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./xyflow-svelte": {
|
|
25
|
+
"types": "./dist/xyflow-svelte/index.d.ts",
|
|
26
|
+
"svelte": "./dist/xyflow-svelte/index.js",
|
|
27
|
+
"default": "./dist/xyflow-svelte/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./package.json": "./package.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"!dist/**/*.test.*"
|
|
34
|
+
],
|
|
35
|
+
"sideEffects": [
|
|
36
|
+
"**/*.svelte"
|
|
37
|
+
],
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@xyflow/svelte": "^2.0.0",
|
|
40
|
+
"svelte": "^5.15.0"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"@xyflow/svelte": {
|
|
44
|
+
"optional": true
|
|
45
|
+
},
|
|
46
|
+
"svelte": {
|
|
47
|
+
"optional": true
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"keywords": [
|
|
51
|
+
"snapping",
|
|
52
|
+
"alignment",
|
|
53
|
+
"guides",
|
|
54
|
+
"smart-guides",
|
|
55
|
+
"node-editor",
|
|
56
|
+
"xyflow",
|
|
57
|
+
"svelte-flow"
|
|
58
|
+
],
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@antithesishq/bombadil": "0.8.0",
|
|
61
|
+
"@eslint/js": "^10.0.1",
|
|
62
|
+
"@sveltejs/package": "^3.0.3",
|
|
63
|
+
"@xyflow/svelte": "^2.0.3",
|
|
64
|
+
"eslint": "^10.15.0",
|
|
65
|
+
"eslint-plugin-security": "^4.2.1",
|
|
66
|
+
"eslint-plugin-sonarjs": "^4.2.3",
|
|
67
|
+
"eslint-plugin-svelte": "^3.24.1",
|
|
68
|
+
"eslint-plugin-unicorn": "^80.0.0",
|
|
69
|
+
"fast-check": "^4.11.0",
|
|
70
|
+
"globals": "^17.14.0",
|
|
71
|
+
"husky": "^9.1.7",
|
|
72
|
+
"jscpd": "^5.4.3",
|
|
73
|
+
"knip": "^6.50.0",
|
|
74
|
+
"konva": "^10.12.0",
|
|
75
|
+
"publint": "^0.3.25",
|
|
76
|
+
"svelte": "^5.59.2",
|
|
77
|
+
"svelte-check": "^4.7.8",
|
|
78
|
+
"typescript": "^6.0.3",
|
|
79
|
+
"typescript-eslint": "^8.74.0",
|
|
80
|
+
"vitest": "^5.1.2"
|
|
81
|
+
},
|
|
82
|
+
"scripts": {
|
|
83
|
+
"build": "svelte-package -i src -o dist && publint",
|
|
84
|
+
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
|
85
|
+
"lint": "eslint . --max-warnings=0",
|
|
86
|
+
"lint:fix": "eslint . --fix",
|
|
87
|
+
"test": "vitest run",
|
|
88
|
+
"test:watch": "vitest",
|
|
89
|
+
"verify": "pnpm lint && pnpm check && pnpm test && pnpm build"
|
|
90
|
+
}
|
|
6
91
|
}
|