@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
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,100 @@
|
|
|
1
|
-
#
|
|
1
|
+
# snap-guides
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@appulsauce/snap-guides) [](https://github.com/KaiErikNiermann/snap-guides/actions/workflows/ci.yml) [](https://kaierikniermann.github.io/snap-guides/)
|
|
4
|
+
|
|
5
|
+
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.
|
|
6
|
+
|
|
7
|
+
The core works on plain boxes and has no framework or DOM dependency. Adapters for [Svelte Flow](https://svelteflow.dev), [React Flow](https://reactflow.dev) and [Vue Flow](https://vueflow.dev) feed it the dragged and resized nodes and draw the guides on the canvas.
|
|
8
|
+
|
|
9
|
+
## What it does
|
|
10
|
+
|
|
11
|
+
- 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.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- Snaps to equal spacing too (`gaps`, on by default): a box repeats the gap between the two boxes nearest to it on one side, or sits midway between its nearest box on each side. Boxes that overlap or nest count as one, and a run of equal gaps is drawn whole.
|
|
17
|
+
- Snaps while resizing (`snapper.resize`, and `useNodeResizeSnap` for each adapter's `NodeResizer`): only the dragged edges move, to other boxes' edges and centres or to equal spacing, and never past the opposite edge.
|
|
18
|
+
|
|
19
|
+
Not yet: rotated boxes.
|
|
20
|
+
|
|
21
|
+
The documentation is at https://kaierikniermann.github.io/snap-guides/, and also as plain text for language models: [llms.txt](https://kaierikniermann.github.io/snap-guides/llms.txt), an index of the pages, and [llms-full.txt](https://kaierikniermann.github.io/snap-guides/llms-full.txt), every page and the API reference in one file.
|
|
22
|
+
|
|
23
|
+
## Core
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createSnapper } from "@appulsauce/snap-guides";
|
|
27
|
+
|
|
28
|
+
const snapper = createSnapper(); // one per gesture; it remembers the held snap
|
|
29
|
+
|
|
30
|
+
// on every pointer move, with the unsnapped position:
|
|
31
|
+
const { offset, guides } = snapper.snap(movingBox, otherBoxes, zoom);
|
|
32
|
+
moveTo(movingBox.x + offset.x, movingBox.y + offset.y);
|
|
33
|
+
draw(guides);
|
|
34
|
+
|
|
35
|
+
// when the gesture ends:
|
|
36
|
+
snapper.reset();
|
|
37
|
+
|
|
38
|
+
// resizing from the right edge, on every pointer move:
|
|
39
|
+
const { box } = snapper.resize(resizedBox, { x: "high" }, otherBoxes, zoom);
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
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, and `snapResize(box, handle, others, options)` the same for a resize. A resize handle names the dragged edge on each axis, `"low"` (left, top) or `"high"` (right, bottom): `{ x: "high", y: "high" }` is the bottom-right corner.
|
|
43
|
+
|
|
44
|
+
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.
|
|
45
|
+
|
|
46
|
+
Options (distances in screen pixels): `threshold` (8), `centers` (true), `roles` (`"any"`), `clusterBreak` (200), `release` (1.5, a multiple of the threshold), `switchAdvantage` (2).
|
|
47
|
+
|
|
48
|
+
## Svelte Flow
|
|
49
|
+
|
|
50
|
+
```svelte
|
|
51
|
+
<script lang="ts">
|
|
52
|
+
import { SvelteFlow } from "@xyflow/svelte";
|
|
53
|
+
import { SnapGuides, useNodeSnap } from "@appulsauce/snap-guides/xyflow-svelte";
|
|
54
|
+
|
|
55
|
+
// In a component inside <SvelteFlow> or a <SvelteFlowProvider>.
|
|
56
|
+
const snap = useNodeSnap();
|
|
57
|
+
</script>
|
|
58
|
+
|
|
59
|
+
<SvelteFlow bind:nodes bind:edges onnodedrag={snap.onnodedrag} onnodedragstop={snap.onnodedragstop}>
|
|
60
|
+
<SnapGuides guides={snap.guides} />
|
|
61
|
+
</SvelteFlow>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
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]`.
|
|
65
|
+
|
|
66
|
+
## React Flow
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { ReactFlow } from "@xyflow/react";
|
|
70
|
+
import { createElement } from "react";
|
|
71
|
+
import { SnapGuides, useNodeSnap } from "@appulsauce/snap-guides/xyflow-react";
|
|
72
|
+
|
|
73
|
+
// In a component inside <ReactFlow> or a <ReactFlowProvider>.
|
|
74
|
+
const snap = useNodeSnap();
|
|
75
|
+
createElement(ReactFlow, { nodes, onNodesChange, onNodeDrag: snap.onNodeDrag, onNodeDragStop: snap.onNodeDragStop }, createElement(SnapGuides, { guides: snap.guides, gaps: snap.gaps }));
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
For `@xyflow/react` 13 and React 19. `useNodeResizeSnap` returns `onResizeStart`, `onResize` and `onResizeEnd` for `<NodeResizer>`; they keep their identity between renders, which the resizer needs. `<SnapGuides>` draws in the flow's `ViewportPortal`, with no stylesheet to import. The options are the Svelte adapter's.
|
|
79
|
+
|
|
80
|
+
## Vue Flow
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { useNodeSnap, useNodeResizeSnap, SnapGuides } from "@appulsauce/snap-guides/vue-flow";
|
|
84
|
+
|
|
85
|
+
// In the setup of the component that renders <VueFlow>, or one inside it.
|
|
86
|
+
const drag = useNodeSnap(); // hooks into the flow's node drags itself
|
|
87
|
+
const resize = useNodeResizeSnap(); // @resize-start, @resize, @resize-end on <NodeResizer>
|
|
88
|
+
// In <VueFlow>'s default slot:
|
|
89
|
+
// <SnapGuides :guides="[...drag.guides.value, ...resize.guides.value]" :gaps="[...drag.gaps.value, ...resize.gaps.value]" />
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
For `@vue-flow/core` 1.48 and `@vue-flow/node-resizer` 1.5. `guides` and `gaps` are refs. `flowId` picks the flow when there is more than one. The options are otherwise the Svelte adapter's.
|
|
93
|
+
|
|
94
|
+
## Credits
|
|
95
|
+
|
|
96
|
+
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`.
|
|
97
|
+
|
|
98
|
+
## Development
|
|
99
|
+
|
|
100
|
+
`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,60 @@
|
|
|
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;
|
|
39
|
+
/**
|
|
40
|
+
* One mark to draw: a guide's line (`dash` in world units, undefined when
|
|
41
|
+
* solid) or a path (a cross or a gap with its ticks). `key` is stable within
|
|
42
|
+
* one frame's list, for keyed rendering.
|
|
43
|
+
*/
|
|
44
|
+
export type GuideMark = {
|
|
45
|
+
readonly kind: "line";
|
|
46
|
+
readonly key: string;
|
|
47
|
+
readonly from: Vec;
|
|
48
|
+
readonly to: Vec;
|
|
49
|
+
readonly dash: readonly number[] | undefined;
|
|
50
|
+
} | {
|
|
51
|
+
readonly kind: "path";
|
|
52
|
+
readonly key: string;
|
|
53
|
+
readonly d: string;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Every mark for `guides` and `gaps` at `zoom`, in world units, in drawing
|
|
57
|
+
* order: each guide's line and the crosses on its points, then the gaps.
|
|
58
|
+
* Sizes are divided by `zoom` so they come out the same on screen at any zoom.
|
|
59
|
+
*/
|
|
60
|
+
export declare const guideMarks: (guides: readonly Guide[], gaps: readonly GapGuide[], zoom: number) => GuideMark[];
|
|
@@ -0,0 +1,57 @@
|
|
|
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("");
|
|
42
|
+
/**
|
|
43
|
+
* Every mark for `guides` and `gaps` at `zoom`, in world units, in drawing
|
|
44
|
+
* order: each guide's line and the crosses on its points, then the gaps.
|
|
45
|
+
* Sizes are divided by `zoom` so they come out the same on screen at any zoom.
|
|
46
|
+
*/
|
|
47
|
+
export const guideMarks = (guides, gaps, zoom) => [
|
|
48
|
+
...guides.flatMap((guide) => {
|
|
49
|
+
const key = guideKey(guide);
|
|
50
|
+
const ends = guideEnds(guide);
|
|
51
|
+
return [
|
|
52
|
+
...(ends ? [{ kind: "line", key: `${key}:line`, from: ends[0], to: ends[1], dash: guideDashArray(guide, zoom) }] : []),
|
|
53
|
+
...guide.points.map((p) => ({ kind: "path", key: `${key}:${String(p.x)},${String(p.y)}`, d: crossPath(p, GUIDE_MARKS.cross / zoom) })),
|
|
54
|
+
];
|
|
55
|
+
}),
|
|
56
|
+
...gaps.map((gap) => ({ kind: "path", key: gapKey(gap), d: gapPath(gap, GUIDE_MARKS.tick / zoom) })),
|
|
57
|
+
];
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Axis, Box, GapGuide } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* References that intersect or nest, as one box: their bounding box and the
|
|
4
|
+
* ids of those that have one, sorted.
|
|
5
|
+
*/
|
|
6
|
+
export interface Block extends Box {
|
|
7
|
+
readonly ids: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
/** Which edge of the moving box a gap target places. */
|
|
10
|
+
export type GapEdge = "low" | "high";
|
|
11
|
+
/**
|
|
12
|
+
* Where one edge of the moving box should go on `axis` for one gap rule.
|
|
13
|
+
* `distance` is how far the moving box is from the nearest box the rule
|
|
14
|
+
* spaces it against, for the nearest-cluster filter.
|
|
15
|
+
*/
|
|
16
|
+
export interface GapTarget {
|
|
17
|
+
readonly axis: Axis;
|
|
18
|
+
readonly edge: GapEdge;
|
|
19
|
+
readonly at: number;
|
|
20
|
+
readonly distance: number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The blocks gaps are measured between for `moving` at its current place: the
|
|
24
|
+
* references (normalised) that do not overlap it, merged where they intersect
|
|
25
|
+
* or nest.
|
|
26
|
+
*/
|
|
27
|
+
export declare const blocksAround: (moving: Box, references: readonly Box[], tolerance: number) => Block[];
|
|
28
|
+
/**
|
|
29
|
+
* Where the gap rules would place the moving box's edges on `axis`; with
|
|
30
|
+
* `stretch`, where they would place that one edge of a box being resized.
|
|
31
|
+
*/
|
|
32
|
+
export declare const gapTargets: (moving: Box, blocks: readonly Block[], axis: Axis, tolerance: number, stretch?: GapEdge) => GapTarget[];
|
|
33
|
+
/**
|
|
34
|
+
* The equal gaps the (already snapped) moving box takes part in: every rule
|
|
35
|
+
* whose target its edge is on, within `tolerance`, with the run of equal gaps
|
|
36
|
+
* it belongs to.
|
|
37
|
+
*/
|
|
38
|
+
export declare const gapGuides: (moving: Box, blocks: readonly Block[], tolerance: number) => GapGuide[];
|
|
@@ -0,0 +1,261 @@
|
|
|
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
|
+
/** The root of `i` in a union-find forest, halving the path on the way. */
|
|
5
|
+
const root = (parent, i) => {
|
|
6
|
+
let at = i;
|
|
7
|
+
while (parent[at] !== at) {
|
|
8
|
+
const up = parent[at] ?? at;
|
|
9
|
+
parent[at] = parent[up] ?? up;
|
|
10
|
+
at = up;
|
|
11
|
+
}
|
|
12
|
+
return at;
|
|
13
|
+
};
|
|
14
|
+
const intersects = (a, b, tolerance) => overlaps(extent(a, "x"), extent(b, "x"), tolerance) && overlaps(extent(a, "y"), extent(b, "y"), tolerance);
|
|
15
|
+
/**
|
|
16
|
+
* One pass of merging: every set of `blocks` that intersect, directly or
|
|
17
|
+
* through others, as one block. A sweep along x compares each block only with
|
|
18
|
+
* those whose x extent it can still overlap.
|
|
19
|
+
*/
|
|
20
|
+
const mergeOnce = (blocks, tolerance) => {
|
|
21
|
+
const order = blocks.map((_, i) => i).toSorted((a, b) => (blocks[a]?.x ?? 0) - (blocks[b]?.x ?? 0));
|
|
22
|
+
const parent = blocks.map((_, i) => i);
|
|
23
|
+
let active = [];
|
|
24
|
+
for (const i of order) {
|
|
25
|
+
const b = blocks[i];
|
|
26
|
+
if (!b)
|
|
27
|
+
continue;
|
|
28
|
+
active = active.filter((j) => {
|
|
29
|
+
const a = blocks[j];
|
|
30
|
+
return a !== undefined && a.x + a.width - b.x > tolerance;
|
|
31
|
+
});
|
|
32
|
+
for (const j of active) {
|
|
33
|
+
const a = blocks[j];
|
|
34
|
+
if (a && intersects(a, b, tolerance))
|
|
35
|
+
parent[root(parent, j)] = root(parent, i);
|
|
36
|
+
}
|
|
37
|
+
active.push(i);
|
|
38
|
+
}
|
|
39
|
+
const groups = new Map();
|
|
40
|
+
for (const [i, b] of blocks.entries()) {
|
|
41
|
+
const r = root(parent, i);
|
|
42
|
+
const g = groups.get(r);
|
|
43
|
+
if (g) {
|
|
44
|
+
g.low = { x: Math.min(g.low.x, b.x), y: Math.min(g.low.y, b.y) };
|
|
45
|
+
g.high = { x: Math.max(g.high.x, b.x + b.width), y: Math.max(g.high.y, b.y + b.height) };
|
|
46
|
+
g.ids.push(...b.ids);
|
|
47
|
+
}
|
|
48
|
+
else
|
|
49
|
+
groups.set(r, { low: { x: b.x, y: b.y }, high: { x: b.x + b.width, y: b.y + b.height }, ids: [...b.ids] });
|
|
50
|
+
}
|
|
51
|
+
return [...groups.values()].map(({ low, high, ids }) => ({
|
|
52
|
+
x: low.x,
|
|
53
|
+
y: low.y,
|
|
54
|
+
width: high.x - low.x,
|
|
55
|
+
height: high.y - low.y,
|
|
56
|
+
ids: ids.toSorted((a, b) => a.localeCompare(b)),
|
|
57
|
+
}));
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* `boxes` (normalised) with every set that intersects or nests merged into one
|
|
61
|
+
* block, again until no two blocks intersect: the bounding box of two boxes
|
|
62
|
+
* can cover a third that touches neither. Boxes that only touch stay apart:
|
|
63
|
+
* their gap is zero, which edge snapping already handles.
|
|
64
|
+
*/
|
|
65
|
+
const mergeOverlapping = (boxes, tolerance) => {
|
|
66
|
+
let blocks = boxes.map((b) => ({ x: b.x, y: b.y, width: b.width, height: b.height, ids: b.id === undefined ? [] : [b.id] }));
|
|
67
|
+
for (;;) {
|
|
68
|
+
const merged = mergeOnce(blocks, tolerance);
|
|
69
|
+
if (merged.length === blocks.length)
|
|
70
|
+
return merged;
|
|
71
|
+
blocks = merged;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* The blocks gaps are measured between for `moving` at its current place: the
|
|
76
|
+
* references (normalised) that do not overlap it, merged where they intersect
|
|
77
|
+
* or nest.
|
|
78
|
+
*/
|
|
79
|
+
export const blocksAround = (moving, references, tolerance) => mergeOverlapping(references.filter((r) => !intersects(r, moving, tolerance)), tolerance);
|
|
80
|
+
/**
|
|
81
|
+
* A total order on neighbours by coordinates alone (then id), so the choice
|
|
82
|
+
* never depends on the order the references came in. `key` maps a neighbour
|
|
83
|
+
* to its nearness: larger is nearer.
|
|
84
|
+
*/
|
|
85
|
+
const nearestBy = (key) => (a, b) => key(b) - key(a) ||
|
|
86
|
+
b.along.low + b.along.high - (a.along.low + a.along.high) ||
|
|
87
|
+
a.across.low - b.across.low ||
|
|
88
|
+
a.across.high - b.across.high ||
|
|
89
|
+
a.ids.join(",").localeCompare(b.ids.join(","));
|
|
90
|
+
/** The nearest of `side` by `key`, independent of the order it came in. */
|
|
91
|
+
const nearestOf = (side, key) => {
|
|
92
|
+
const order = nearestBy(key);
|
|
93
|
+
let winner;
|
|
94
|
+
for (const n of side)
|
|
95
|
+
if (!winner || order(n, winner) < 0)
|
|
96
|
+
winner = n;
|
|
97
|
+
return winner;
|
|
98
|
+
};
|
|
99
|
+
/** The nearest of `beside` wholly below `n` along the axis. */
|
|
100
|
+
const nextLow = (beside, n, tolerance) => nearestOf(beside.filter((m) => m !== n && m.along.high <= n.along.low + tolerance), (m) => m.along.high);
|
|
101
|
+
/** The nearest of `beside` wholly above `n` along the axis. */
|
|
102
|
+
const nextHigh = (beside, n, tolerance) => nearestOf(beside.filter((m) => m !== n && m.along.low >= n.along.high - tolerance), (m) => -m.along.low);
|
|
103
|
+
/** The first neighbour from `next(from)` on, and the one after it. */
|
|
104
|
+
const nearestTwo = (from, next) => {
|
|
105
|
+
const first = next(from);
|
|
106
|
+
const second = first && next(first);
|
|
107
|
+
return [first, second].filter((n) => n !== undefined);
|
|
108
|
+
};
|
|
109
|
+
/** The moving box's neighbours on each side along `axis` (blocks normalised). */
|
|
110
|
+
const neighbours = (self, blocks, axis, tolerance) => {
|
|
111
|
+
const beside = blocks
|
|
112
|
+
.map((r) => ({ along: extent(r, axis), across: extent(r, other(axis)), ids: r.ids }))
|
|
113
|
+
.filter((n) => overlaps(n.across, self.across, tolerance));
|
|
114
|
+
return {
|
|
115
|
+
low: nearestTwo(self, (n) => nextLow(beside, n, tolerance)),
|
|
116
|
+
high: nearestTwo(self, (n) => nextHigh(beside, n, tolerance)),
|
|
117
|
+
beside,
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
const selfOf = (moving, axis) => ({ along: extent(moving, axis), across: extent(moving, other(axis)), ids: [] });
|
|
121
|
+
/**
|
|
122
|
+
* The spacings the rules offer for a moving box with extent `along` on `axis`:
|
|
123
|
+
* continuing the gap of the two nearest boxes on either side, and centring
|
|
124
|
+
* between the nearest on each side. Gaps no wider than `tolerance` are left to
|
|
125
|
+
* edge snapping, which already lines touching boxes up.
|
|
126
|
+
*
|
|
127
|
+
* With `stretch`, only that edge of the box moves (a resize), as in Graphite's
|
|
128
|
+
* spacing rules: a gap continues only from the moving side, and centring
|
|
129
|
+
* places the moving edge so its gap matches the one on the fixed side. A
|
|
130
|
+
* place that would turn the box inside out is not offered.
|
|
131
|
+
*/
|
|
132
|
+
const spacings = (along, sides, tolerance, stretch) => {
|
|
133
|
+
const result = [];
|
|
134
|
+
const width = along.high - along.low;
|
|
135
|
+
const [lowFirst, lowSecond] = sides.low;
|
|
136
|
+
const [highFirst, highSecond] = sides.high;
|
|
137
|
+
const moves = (edge) => stretch === undefined || stretch === edge;
|
|
138
|
+
// A stretched edge stays on its own side of the fixed one.
|
|
139
|
+
const fits = (edge, at) => stretch === undefined || (edge === "low" ? at <= along.high + tolerance : at >= along.low - tolerance);
|
|
140
|
+
if (lowFirst && lowSecond && moves("low")) {
|
|
141
|
+
const length = lowFirst.along.low - lowSecond.along.high;
|
|
142
|
+
const at = lowFirst.along.high + length;
|
|
143
|
+
if (length > tolerance && fits("low", at))
|
|
144
|
+
result.push({ kind: "continue", edge: "low", at, length, near: along.low - lowFirst.along.high, pairs: [[lowSecond, lowFirst], [lowFirst, "moving"]] });
|
|
145
|
+
}
|
|
146
|
+
if (highFirst && highSecond && moves("high")) {
|
|
147
|
+
const length = highSecond.along.low - highFirst.along.high;
|
|
148
|
+
const at = highFirst.along.low - length;
|
|
149
|
+
if (length > tolerance && fits("high", at))
|
|
150
|
+
result.push({ kind: "continue", edge: "high", at, length, near: highFirst.along.low - along.high, pairs: [["moving", highFirst], [highFirst, highSecond]] });
|
|
151
|
+
}
|
|
152
|
+
if (lowFirst && highFirst) {
|
|
153
|
+
const centre = centring(along, width, lowFirst, highFirst, stretch);
|
|
154
|
+
if (centre.length > tolerance && fits(centre.edge, centre.at))
|
|
155
|
+
result.push({ kind: "center", ...centre, pairs: [[lowFirst, "moving"], ["moving", highFirst]] });
|
|
156
|
+
}
|
|
157
|
+
return result;
|
|
158
|
+
};
|
|
159
|
+
/** Where centring between `before` and `after` puts the moving edge, and the gap it makes on each side. */
|
|
160
|
+
const centring = (along, width, before, after, stretch) => {
|
|
161
|
+
switch (stretch) {
|
|
162
|
+
case undefined: {
|
|
163
|
+
const length = (after.along.low - before.along.high - width) / 2;
|
|
164
|
+
return { edge: "low", at: before.along.high + length, length, near: Math.min(along.low - before.along.high, after.along.low - along.high) };
|
|
165
|
+
}
|
|
166
|
+
case "high": {
|
|
167
|
+
const length = along.low - before.along.high;
|
|
168
|
+
return { edge: "high", at: after.along.low - length, length, near: after.along.low - along.high };
|
|
169
|
+
}
|
|
170
|
+
case "low": {
|
|
171
|
+
const length = after.along.low - along.high;
|
|
172
|
+
return { edge: "low", at: before.along.high + length, length, near: along.low - before.along.high };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Where the gap rules would place the moving box's edges on `axis`; with
|
|
178
|
+
* `stretch`, where they would place that one edge of a box being resized.
|
|
179
|
+
*/
|
|
180
|
+
export const gapTargets = (moving, blocks, axis, tolerance, stretch) => spacings(extent(moving, axis), neighbours(selfOf(moving, axis), blocks, axis, tolerance), tolerance, stretch).map((s) => ({
|
|
181
|
+
axis,
|
|
182
|
+
edge: s.edge,
|
|
183
|
+
at: s.at,
|
|
184
|
+
distance: Math.abs(s.near),
|
|
185
|
+
}));
|
|
186
|
+
/**
|
|
187
|
+
* A segment across the gap between two extents along `axis`, drawn at the
|
|
188
|
+
* middle of where they overlap across it: from `a`'s high end to `b`'s low end.
|
|
189
|
+
*/
|
|
190
|
+
const span = (axis, a, b) => {
|
|
191
|
+
const c = (Math.max(a.across.low, b.across.low) + Math.min(a.across.high, b.across.high)) / 2;
|
|
192
|
+
return axis === "x"
|
|
193
|
+
? [
|
|
194
|
+
{ x: a.along.high, y: c },
|
|
195
|
+
{ x: b.along.low, y: c },
|
|
196
|
+
]
|
|
197
|
+
: [
|
|
198
|
+
{ x: c, y: a.along.high },
|
|
199
|
+
{ x: c, y: b.along.low },
|
|
200
|
+
];
|
|
201
|
+
};
|
|
202
|
+
const resolveMoving = (n, self) => (n === "moving" ? self : n);
|
|
203
|
+
/**
|
|
204
|
+
* `pairs`, a run of gaps of `length`, extended on both ends over every further
|
|
205
|
+
* neighbour whose gap to the run's end is the same length within `tolerance`.
|
|
206
|
+
*/
|
|
207
|
+
const chain = (pairs, beside, length, tolerance) => {
|
|
208
|
+
const run = [...pairs];
|
|
209
|
+
const same = (gap) => Math.abs(gap - length) <= tolerance;
|
|
210
|
+
let first = run[0]?.[0];
|
|
211
|
+
let before = first && nextLow(beside, first, tolerance);
|
|
212
|
+
while (first && before && same(first.along.low - before.along.high)) {
|
|
213
|
+
run.unshift([before, first]);
|
|
214
|
+
first = before;
|
|
215
|
+
before = nextLow(beside, before, tolerance);
|
|
216
|
+
}
|
|
217
|
+
let last = run.at(-1)?.[1];
|
|
218
|
+
let after = last && nextHigh(beside, last, tolerance);
|
|
219
|
+
while (last && after && same(after.along.low - last.along.high)) {
|
|
220
|
+
run.push([last, after]);
|
|
221
|
+
last = after;
|
|
222
|
+
after = nextHigh(beside, after, tolerance);
|
|
223
|
+
}
|
|
224
|
+
return run;
|
|
225
|
+
};
|
|
226
|
+
/**
|
|
227
|
+
* One guide per run: rules that fire on the same run of equal gaps (continuing
|
|
228
|
+
* it from either end, or centring in it) draw the same segments. A run that
|
|
229
|
+
* the box is centred in is drawn as `"center"`.
|
|
230
|
+
*/
|
|
231
|
+
const onePerRun = (guides) => {
|
|
232
|
+
const runs = new Map();
|
|
233
|
+
for (const g of guides) {
|
|
234
|
+
const key = [g.axis, ...g.segments.flatMap(([a, b]) => [a.x, a.y, b.x, b.y].map(String))].join(":");
|
|
235
|
+
const seen = runs.get(key);
|
|
236
|
+
if (!seen || (g.kind === "center" && seen.kind !== "center"))
|
|
237
|
+
runs.set(key, g);
|
|
238
|
+
}
|
|
239
|
+
return [...runs.values()];
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* The equal gaps the (already snapped) moving box takes part in: every rule
|
|
243
|
+
* whose target its edge is on, within `tolerance`, with the run of equal gaps
|
|
244
|
+
* it belongs to.
|
|
245
|
+
*/
|
|
246
|
+
export const gapGuides = (moving, blocks, tolerance) => onePerRun(["x", "y"].flatMap((axis) => {
|
|
247
|
+
const self = selfOf(moving, axis);
|
|
248
|
+
const sides = neighbours(self, blocks, axis, tolerance);
|
|
249
|
+
return spacings(self.along, sides, tolerance)
|
|
250
|
+
.filter((s) => Math.abs((s.edge === "low" ? self.along.low : self.along.high) - s.at) <= tolerance)
|
|
251
|
+
.map((s) => {
|
|
252
|
+
const pairs = chain(s.pairs.map(([a, b]) => [resolveMoving(a, self), resolveMoving(b, self)]), sides.beside, s.length, tolerance);
|
|
253
|
+
return {
|
|
254
|
+
axis,
|
|
255
|
+
kind: s.kind,
|
|
256
|
+
length: s.length,
|
|
257
|
+
segments: pairs.map(([a, b]) => span(axis, a, b)),
|
|
258
|
+
ids: [...new Set(pairs.flatMap(([a, b]) => [...a.ids, ...b.ids]))],
|
|
259
|
+
};
|
|
260
|
+
});
|
|
261
|
+
}));
|
|
@@ -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, snapResize, unionBox, type Snapper } from "./snap.js";
|
|
7
|
+
export { GUIDE_MARKS, crossPath, gapKey, gapPath, guideDash, guideDashArray, guideEnds, guideKey, guideMarks, type GuideMark } from "./draw.js";
|
|
8
|
+
export type { Axis, Box, GapGuide, Guide, ResizeHandle, ResizeResult, 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, snapResize, unionBox } from "./snap.js";
|
|
7
|
+
export { GUIDE_MARKS, crossPath, gapKey, gapPath, guideDash, guideDashArray, guideEnds, guideKey, guideMarks } from "./draw.js";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Box, ResizeHandle, ResizeResult, 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
|
+
/**
|
|
27
|
+
* Snap the edges `handle` drags of `box`, which is being resized, to
|
|
28
|
+
* `references`: only those edges move, by alignment with the references'
|
|
29
|
+
* points and by the gap rules, and never past the opposite edge. Call it on
|
|
30
|
+
* every move of one resize gesture with the unsnapped box, as with `snap`.
|
|
31
|
+
*
|
|
32
|
+
* Throws a RangeError for a non-finite `box`, a `zoom` that is not a
|
|
33
|
+
* positive finite number, or a `handle` that names no edge or names one
|
|
34
|
+
* other than `"low"` or `"high"`.
|
|
35
|
+
*/
|
|
36
|
+
resize: (box: Box, handle: ResizeHandle, references: readonly Box[], zoom?: number) => ResizeResult;
|
|
37
|
+
/** Forget the held snap; call it when the gesture ends. */
|
|
38
|
+
reset: () => void;
|
|
39
|
+
}
|
|
40
|
+
/** A snapper for one gesture at a time, with hysteresis between calls. */
|
|
41
|
+
export declare const createSnapper: (options?: SnapOptions) => Snapper;
|
|
42
|
+
/** One-off snap with no memory between calls; use `createSnapper` during a drag. */
|
|
43
|
+
export declare const snapBoxes: (moving: Box | readonly Box[], references: readonly Box[], options?: SnapOptions & {
|
|
44
|
+
readonly zoom?: number;
|
|
45
|
+
}) => SnapResult;
|
|
46
|
+
/** One-off resize snap with no memory between calls; use `createSnapper` during a resize gesture. */
|
|
47
|
+
export declare const snapResize: (box: Box, handle: ResizeHandle, references: readonly Box[], options?: SnapOptions & {
|
|
48
|
+
readonly zoom?: number;
|
|
49
|
+
}) => ResizeResult;
|