@appulsauce/snap-guides 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +40 -3
  2. package/dist/core/draw.d.ts +22 -0
  3. package/dist/core/draw.js +16 -0
  4. package/dist/core/gaps.d.ts +22 -6
  5. package/dist/core/gaps.js +201 -50
  6. package/dist/core/index.d.ts +3 -3
  7. package/dist/core/index.js +2 -2
  8. package/dist/core/snap.d.ts +16 -1
  9. package/dist/core/snap.js +138 -36
  10. package/dist/core/types.d.ts +13 -0
  11. package/dist/flow/boxes.d.ts +40 -0
  12. package/dist/flow/boxes.js +45 -0
  13. package/dist/flow/gestures.d.ts +52 -0
  14. package/dist/flow/gestures.js +80 -0
  15. package/dist/flow/index.d.ts +4 -0
  16. package/dist/flow/index.js +4 -0
  17. package/dist/flow/xyflow.d.ts +70 -0
  18. package/dist/flow/xyflow.js +52 -0
  19. package/dist/vue-flow/guide-state.d.ts +14 -0
  20. package/dist/vue-flow/guide-state.js +16 -0
  21. package/dist/vue-flow/index.d.ts +4 -0
  22. package/dist/vue-flow/index.js +4 -0
  23. package/dist/vue-flow/nodes.d.ts +29 -0
  24. package/dist/vue-flow/nodes.js +28 -0
  25. package/dist/vue-flow/snap-guides.d.ts +25 -0
  26. package/dist/vue-flow/snap-guides.js +54 -0
  27. package/dist/vue-flow/use-node-resize-snap.d.ts +23 -0
  28. package/dist/vue-flow/use-node-resize-snap.js +83 -0
  29. package/dist/vue-flow/use-node-snap.d.ts +15 -0
  30. package/dist/vue-flow/use-node-snap.js +67 -0
  31. package/dist/xyflow-react/index.d.ts +4 -0
  32. package/dist/xyflow-react/index.js +4 -0
  33. package/dist/xyflow-react/snap-guides.d.ts +10 -0
  34. package/dist/xyflow-react/snap-guides.js +43 -0
  35. package/dist/xyflow-react/use-node-resize-snap.d.ts +26 -0
  36. package/dist/xyflow-react/use-node-resize-snap.js +78 -0
  37. package/dist/xyflow-react/use-node-snap.d.ts +23 -0
  38. package/dist/xyflow-react/use-node-snap.js +62 -0
  39. package/dist/xyflow-svelte/SnapGuides.svelte +6 -11
  40. package/dist/xyflow-svelte/index.d.ts +2 -1
  41. package/dist/xyflow-svelte/index.js +2 -1
  42. package/dist/xyflow-svelte/node-resize-snap.svelte.d.ts +34 -0
  43. package/dist/xyflow-svelte/node-resize-snap.svelte.js +71 -0
  44. package/dist/xyflow-svelte/node-snap.svelte.d.ts +4 -7
  45. package/dist/xyflow-svelte/node-snap.svelte.js +15 -71
  46. package/package.json +56 -15
@@ -0,0 +1,4 @@
1
+ /** Vue Flow adapter: `useNodeSnap` and `useNodeResizeSnap` for node drags and resizes, `SnapGuides` to draw. */
2
+ export { SnapGuides } from "./snap-guides.js";
3
+ export { useNodeSnap, type NodeSnap, type NodeSnapOptions } from "./use-node-snap.js";
4
+ export { useNodeResizeSnap, type NodeResizeSnap, type NodeResizeSnapOptions } from "./use-node-resize-snap.js";
@@ -0,0 +1,4 @@
1
+ /** Vue Flow adapter: `useNodeSnap` and `useNodeResizeSnap` for node drags and resizes, `SnapGuides` to draw. */
2
+ export { SnapGuides } from "./snap-guides.js";
3
+ export { useNodeSnap } from "./use-node-snap.js";
4
+ export { useNodeResizeSnap } from "./use-node-resize-snap.js";
@@ -0,0 +1,29 @@
1
+ import type { Box, Vec } from "../core/index.js";
2
+ /** The part of a Vue Flow `GraphNode` the adapter reads. */
3
+ export interface PlacedNode {
4
+ readonly id: string;
5
+ readonly hidden?: boolean | undefined;
6
+ /** Relative to the parent node, or to the flow without one. */
7
+ readonly position: Vec;
8
+ /** Absolute; lags `position` until Vue's next post-flush. */
9
+ readonly computedPosition: Vec;
10
+ readonly dimensions: {
11
+ readonly width: number;
12
+ readonly height: number;
13
+ };
14
+ readonly parentNode?: string | undefined;
15
+ }
16
+ /** The origin of a node's coordinate space: its parent's absolute top-left, or the flow's. */
17
+ export declare const parentOrigin: (parent: PlacedNode | undefined) => Vec;
18
+ /** A node's settled absolute box, `null` while unmeasured (a size of 0) or hidden. */
19
+ export declare const vueFlowBox: (node: PlacedNode) => Box | null;
20
+ /** The absolute box of a node a gesture just moved, from its up-to-date relative `position`. */
21
+ export declare const vueFlowLiveBox: (node: PlacedNode, parent: PlacedNode | undefined) => Box | null;
22
+ /** The reference boxes of `nodes`: measured, visible, not in `exclude`, and accepted by `snapTo`. */
23
+ export declare const vueFlowReferences: <Node extends PlacedNode>(nodes: Iterable<Node>, exclude: readonly string[], snapTo: (node: Node) => boolean) => Box[];
24
+ /**
25
+ * The pointer event under a d3-drag event (its `sourceEvent` is typed `any`),
26
+ * `null` when it is not one. Checked by shape (`altKey` is a boolean, as on every
27
+ * mouse and touch event), so it does not depend on a `TouchEvent` global.
28
+ */
29
+ export declare const pointerEventOf: (sourceEvent: unknown) => MouseEvent | TouchEvent | null;
@@ -0,0 +1,28 @@
1
+ import { referenceBoxes } from "../flow/index.js";
2
+ /** The origin of a node's coordinate space: its parent's absolute top-left, or the flow's. */
3
+ export const parentOrigin = (parent) => parent?.computedPosition ?? { x: 0, y: 0 };
4
+ /** A node's settled absolute box, `null` while unmeasured (a size of 0) or hidden. */
5
+ export const vueFlowBox = (node) => {
6
+ const { width, height } = node.dimensions;
7
+ return width === 0 || height === 0 || node.hidden
8
+ ? null
9
+ : { x: node.computedPosition.x, y: node.computedPosition.y, width, height, id: node.id };
10
+ };
11
+ /** The absolute box of a node a gesture just moved, from its up-to-date relative `position`. */
12
+ export const vueFlowLiveBox = (node, parent) => {
13
+ const box = vueFlowBox(node);
14
+ if (!box)
15
+ return null;
16
+ const origin = parentOrigin(parent);
17
+ return { ...box, x: origin.x + node.position.x, y: origin.y + node.position.y };
18
+ };
19
+ /** The reference boxes of `nodes`: measured, visible, not in `exclude`, and accepted by `snapTo`. */
20
+ export const vueFlowReferences = (nodes, exclude, snapTo) => referenceBoxes(nodes, vueFlowBox, exclude, snapTo);
21
+ /**
22
+ * The pointer event under a d3-drag event (its `sourceEvent` is typed `any`),
23
+ * `null` when it is not one. Checked by shape (`altKey` is a boolean, as on every
24
+ * mouse and touch event), so it does not depend on a `TouchEvent` global.
25
+ */
26
+ export const pointerEventOf = (sourceEvent) => typeof sourceEvent === "object" && sourceEvent !== null && "altKey" in sourceEvent && typeof sourceEvent.altKey === "boolean"
27
+ ? sourceEvent
28
+ : null;
@@ -0,0 +1,25 @@
1
+ import { type PropType } from "vue";
2
+ import { type GapGuide, type Guide } from "../core/index.js";
3
+ export declare const SnapGuides: import("vue").DefineComponent<import("vue").ExtractPropTypes<{
4
+ guides: {
5
+ type: PropType<readonly Guide[]>;
6
+ required: true;
7
+ };
8
+ gaps: {
9
+ type: PropType<readonly GapGuide[]>;
10
+ default: () => never[];
11
+ };
12
+ }>, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
13
+ [key: string]: any;
14
+ }>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<import("vue").ExtractPropTypes<{
15
+ guides: {
16
+ type: PropType<readonly Guide[]>;
17
+ required: true;
18
+ };
19
+ gaps: {
20
+ type: PropType<readonly GapGuide[]>;
21
+ default: () => never[];
22
+ };
23
+ }>> & Readonly<{}>, {
24
+ gaps: readonly GapGuide[];
25
+ }, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
@@ -0,0 +1,54 @@
1
+ /*
2
+ * Draws the guides from `useNodeSnap` and `useNodeResizeSnap` on a Vue Flow
3
+ * canvas, in flow coordinates, so they pan and zoom with the nodes. Lines stay
4
+ * one screen pixel wide at any zoom; each aligned point gets a small cross, as
5
+ * in Excalidraw; centre guides are dashed. Equal gaps (`gaps`) are drawn as
6
+ * lines with a tick across each end.
7
+ *
8
+ * Vue Flow has no portal into its viewport, so this draws its own SVG and
9
+ * applies the viewport transform to it, the same `translate(x, y) scale(zoom)`
10
+ * the transformation pane gets (vue-flow-core.mjs:8397-8412). Put it in the
11
+ * default slot of `<VueFlow>`, like `<MiniMap>`: it then sits above the
12
+ * viewport (z-index 4 in Vue Flow's stylesheet) and ignores the pointer. Plain
13
+ * `h()` instead of an SFC, because the package is built without a Vue
14
+ * compiler.
15
+ *
16
+ * Colour: set `--snap-guide-color` on any ancestor (default a magenta that
17
+ * reads on light and dark canvases). Stacking: `--snap-guide-z` (default 5,
18
+ * the level of Vue Flow's panels).
19
+ */
20
+ import { useVueFlow } from "@vue-flow/core";
21
+ import { defineComponent, h } from "vue";
22
+ import { guideMarks } from "../core/index.js";
23
+ const SVG_STYLE = {
24
+ position: "absolute",
25
+ insetBlockStart: 0,
26
+ insetInlineStart: 0,
27
+ inlineSize: "1px",
28
+ blockSize: "1px",
29
+ overflow: "visible",
30
+ pointerEvents: "none",
31
+ fill: "none",
32
+ stroke: "var(--snap-guide-color, #e0447c)",
33
+ strokeWidth: "1px",
34
+ transformOrigin: "0 0",
35
+ zIndex: "var(--snap-guide-z, 5)",
36
+ };
37
+ const STROKE = { vectorEffect: "non-scaling-stroke" };
38
+ export const SnapGuides = defineComponent({
39
+ name: "SnapGuides",
40
+ props: {
41
+ guides: { type: Array, required: true },
42
+ gaps: { type: Array, default: () => [] },
43
+ },
44
+ setup(props) {
45
+ // Injected from the enclosing <VueFlow>.
46
+ const { viewport } = useVueFlow();
47
+ return () => {
48
+ const { x, y, zoom } = viewport.value;
49
+ return h("svg", { class: "snap-guides", "aria-hidden": "true", style: { ...SVG_STYLE, transform: `translate(${String(x)}px, ${String(y)}px) scale(${String(zoom)})` } }, guideMarks(props.guides, props.gaps, zoom).map((mark) => mark.kind === "line"
50
+ ? h("line", { key: mark.key, x1: mark.from.x, y1: mark.from.y, x2: mark.to.x, y2: mark.to.y, "stroke-dasharray": mark.dash?.join(" "), style: STROKE })
51
+ : h("path", { key: mark.key, d: mark.d, style: STROKE })));
52
+ };
53
+ },
54
+ });
@@ -0,0 +1,23 @@
1
+ import { type GraphNode } from "@vue-flow/core";
2
+ import type { OnResize, OnResizeEnd, OnResizeStart } from "@vue-flow/node-resizer";
3
+ import { type AdapterOptions } from "../flow/index.js";
4
+ import { type GuideRefs } from "./guide-state.js";
5
+ export interface NodeResizeSnapOptions extends AdapterOptions<GraphNode, MouseEvent | TouchEvent> {
6
+ /** The id of the flow the nodes are in, as for `useVueFlow(id)`. Default: the flow the calling component belongs to. */
7
+ readonly flowId?: string;
8
+ }
9
+ export interface NodeResizeSnap extends GuideRefs {
10
+ /** Pass to `<NodeResizer @resize-start>`. */
11
+ readonly onResizeStart: (event: OnResizeStart) => void;
12
+ /** Pass to `<NodeResizer @resize>`. */
13
+ readonly onResize: (event: OnResize) => void;
14
+ /** Pass to `<NodeResizer @resize-end>`. */
15
+ readonly onResizeEnd: (event: OnResizeEnd) => void;
16
+ }
17
+ /**
18
+ * Create the resize handlers and the live guides. Call it in the setup of a
19
+ * component inside `<VueFlow>`, or the one that renders it, as for
20
+ * `useVueFlow()`. Pass the same `<SnapGuides>` the drag guides go to, e.g.
21
+ * `:guides="[...drag.guides.value, ...resize.guides.value]"`.
22
+ */
23
+ export declare const useNodeResizeSnap: (options?: NodeResizeSnapOptions) => NodeResizeSnap;
@@ -0,0 +1,83 @@
1
+ /*
2
+ * Snapping for Vue Flow nodes resized with `<NodeResizer>`, built on the
3
+ * shared resize gesture.
4
+ *
5
+ * The resizer (@vue-flow/node-resizer 1.5.1, vue-flow-node-resizer.mjs) keeps
6
+ * its own state from the pointer (`startValues`, `prevValues`, lines 1053-1054
7
+ * and 1072-1083) and on every move emits `resize` with the unsnapped box
8
+ * (line 1184) and then triggers the `nodesChange` hook with it (line 1185),
9
+ * which Vue Flow applies at once. A change triggered from `onResize` would
10
+ * therefore be overwritten by the one that follows it in the same task, so the
11
+ * snapped box is triggered in a microtask instead: it runs after that task's
12
+ * unsnapped write and before the browser renders, so the DOM is never painted
13
+ * unsnapped; Vue Flow's ResizeObserver then measures the node from the DOM, at
14
+ * the snapped size (vue-flow-core.mjs:9782-9791). The resizer
15
+ * diffs against its own `prevValues` (lines 1131-1132), not against the node,
16
+ * so what is written over the node does not change what it writes next frame.
17
+ * The snapped change carries `updateStyle`, as the resizer's own does (line
18
+ * 1157), because the node's width and height come from its inline style.
19
+ *
20
+ * When the resize ends the resizer triggers a dimension change with only
21
+ * `resizing: false` (lines 1190-1195), which `applyChanges` reads as "leave the
22
+ * size alone" (vue-flow-core.mjs:4014-4020). The last snapped box stays, and
23
+ * `onResizeEnd` only resets the gesture and clears the guides. (Svelte Flow
24
+ * writes the unsnapped size again at the end, so its adapter writes the
25
+ * snapped one again.)
26
+ *
27
+ * The callbacks are shared by every `<NodeResizer>` they are given to and
28
+ * say neither which node nor which edges are dragged, so `onResizeStart`
29
+ * reads both from the DOM element the gesture began on. Assumes the default
30
+ * node origin; `keepAspectRatio` and min/max sizes can be overridden, since the
31
+ * snapped box is written over the resizer's.
32
+ */
33
+ import { useVueFlow } from "@vue-flow/core";
34
+ import { createResizeGesture, resizeTarget } from "../flow/index.js";
35
+ import { createGuideRefs } from "./guide-state.js";
36
+ import { pointerEventOf, parentOrigin, vueFlowReferences } from "./nodes.js";
37
+ /**
38
+ * Create the resize handlers and the live guides. Call it in the setup of a
39
+ * component inside `<VueFlow>`, or the one that renders it, as for
40
+ * `useVueFlow()`. Pass the same `<SnapGuides>` the drag guides go to, e.g.
41
+ * `:guides="[...drag.guides.value, ...resize.guides.value]"`.
42
+ */
43
+ export const useNodeResizeSnap = (options = {}) => {
44
+ const flow = useVueFlow(options.flowId);
45
+ const snapTo = options.snapTo ?? (() => true);
46
+ const { set, ...refs } = createGuideRefs();
47
+ const gesture = createResizeGesture(options, set);
48
+ const parentOf = (node) => (node.parentNode === undefined ? undefined : flow.findNode(node.parentNode));
49
+ /** Trigger `box` (absolute) as the node's position and size, after the resizer's own change. */
50
+ const place = (box) => {
51
+ queueMicrotask(() => {
52
+ const node = box.id === undefined ? undefined : flow.findNode(box.id);
53
+ if (!node)
54
+ return;
55
+ const origin = parentOrigin(parentOf(node));
56
+ void flow.emits.nodesChange([
57
+ { id: node.id, type: "position", from: { x: node.position.x, y: node.position.y }, position: { x: box.x - origin.x, y: box.y - origin.y } },
58
+ { id: node.id, type: "dimensions", resizing: true, updateStyle: true, dimensions: { width: box.width, height: box.height } },
59
+ ]);
60
+ });
61
+ };
62
+ return {
63
+ ...refs,
64
+ onResizeStart: ({ event }) => {
65
+ gesture.start(resizeTarget(pointerEventOf(event.sourceEvent)?.target ?? null, "vue-flow"));
66
+ },
67
+ onResize: ({ event, params }) => {
68
+ const id = gesture.target?.id;
69
+ const source = pointerEventOf(event.sourceEvent);
70
+ const node = id === undefined ? undefined : flow.findNode(id);
71
+ if (id === undefined || !source || !node)
72
+ return;
73
+ const origin = parentOrigin(parentOf(node));
74
+ const box = { x: origin.x + params.x, y: origin.y + params.y, width: params.width, height: params.height, id };
75
+ const snapped = gesture.move(source, box, () => vueFlowReferences(flow.nodes.value, [id], snapTo), flow.viewport.value.zoom);
76
+ if (snapped)
77
+ place(snapped);
78
+ },
79
+ onResizeEnd: () => {
80
+ gesture.end();
81
+ },
82
+ };
83
+ };
@@ -0,0 +1,15 @@
1
+ import { type GraphNode, type MouseTouchEvent } from "@vue-flow/core";
2
+ import { type AdapterOptions } from "../flow/index.js";
3
+ import { type GuideRefs } from "./guide-state.js";
4
+ export interface NodeSnapOptions extends AdapterOptions<GraphNode, MouseTouchEvent> {
5
+ /** The id of the flow to hook into, as for `useVueFlow(id)`. Default: the flow the calling component belongs to. */
6
+ readonly flowId?: string;
7
+ }
8
+ export type NodeSnap = GuideRefs;
9
+ /**
10
+ * Hook snapping into a flow's node drags and return the live guides. Call it
11
+ * in the setup of the component that renders `<VueFlow>` (or one inside it),
12
+ * as for `useVueFlow()`; the hooks go away with that component. Hand the
13
+ * guides to `<SnapGuides>`.
14
+ */
15
+ export declare const useNodeSnap: (options?: NodeSnapOptions) => NodeSnap;
@@ -0,0 +1,67 @@
1
+ /*
2
+ * Snapping for dragged Vue Flow nodes, built on the shared drag gesture.
3
+ *
4
+ * Vue Flow's own drag (useDrag, vue-flow-core.mjs, v1.48.2) recomputes every
5
+ * dragged node's position from the pointer on each move. `updateNodes` first
6
+ * triggers the `nodesChange` hook with the unsnapped positions (line 4940),
7
+ * which the default handler applies to the nodes at once (the hook calls its
8
+ * listeners synchronously, line 4132; `applyChanges` writes `node.position`,
9
+ * lines 3998-4001), and only then calls `onDrag` (line 4948), which is the
10
+ * `nodeDrag` hook. So a handler on `nodeDrag` runs after the unsnapped write,
11
+ * in the same task and before anything is rendered: the snapped position it
12
+ * triggers is the last write of the frame and wins. Vue Flow keeps its own
13
+ * pointer-derived position in its drag items (`n.position`, line 4933), not in
14
+ * the node, so the next frame starts from the pointer again and the offset
15
+ * never accumulates.
16
+ *
17
+ * When the drag ends Vue Flow does not write the unsnapped positions again:
18
+ * it triggers a position change with no `position` (`changed` is false, lines
19
+ * 5046 and 6283-6297), which `applyChanges` reads as "only clear `dragging`"
20
+ * (lines 3998-4004). The last snapped position therefore stays, and
21
+ * `nodeDragStop` only resets the gesture and clears the guides. (Svelte Flow
22
+ * does write the unsnapped positions at the end, so its adapter writes the
23
+ * snapped ones again.)
24
+ *
25
+ * The handlers are registered through `useVueFlow()`'s `onNodeDrag` and
26
+ * `onNodeDragStop` hooks, which run for a single node's drag and for a drag of
27
+ * the selection box alike (NodesSelection emits `nodeDrag` as well, line
28
+ * 8130), and which a `@node-drag` listener on `<VueFlow>` does not replace.
29
+ *
30
+ * Assumes Vue Flow applies its changes itself (the default `applyDefault`),
31
+ * so `node.position` is current inside `nodeDrag`; the snapped position is
32
+ * written over `extent` and `snapToGrid`, which are not applied again.
33
+ */
34
+ import { useVueFlow } from "@vue-flow/core";
35
+ import { createDragGesture } from "../flow/index.js";
36
+ import { createGuideRefs } from "./guide-state.js";
37
+ import { vueFlowLiveBox, vueFlowReferences } from "./nodes.js";
38
+ /**
39
+ * Hook snapping into a flow's node drags and return the live guides. Call it
40
+ * in the setup of the component that renders `<VueFlow>` (or one inside it),
41
+ * as for `useVueFlow()`; the hooks go away with that component. Hand the
42
+ * guides to `<SnapGuides>`.
43
+ */
44
+ export const useNodeSnap = (options = {}) => {
45
+ const flow = useVueFlow(options.flowId);
46
+ const snapTo = options.snapTo ?? (() => true);
47
+ const { set, ...refs } = createGuideRefs();
48
+ const gesture = createDragGesture(options, set);
49
+ flow.onNodeDrag(({ event, nodes }) => {
50
+ const ids = nodes.map((node) => node.id);
51
+ const moving = nodes.flatMap((node) => vueFlowLiveBox(node, node.parentNode === undefined ? undefined : flow.findNode(node.parentNode)) ?? []);
52
+ const offset = gesture.move(event, moving, () => vueFlowReferences(flow.nodes.value, ids, snapTo), flow.viewport.value.zoom);
53
+ if (!offset)
54
+ return;
55
+ void flow.emits.nodesChange(nodes.map((node) => ({
56
+ id: node.id,
57
+ type: "position",
58
+ dragging: true,
59
+ from: { x: node.computedPosition.x, y: node.computedPosition.y },
60
+ position: { x: node.position.x + offset.x, y: node.position.y + offset.y },
61
+ })));
62
+ });
63
+ flow.onNodeDragStop(() => {
64
+ gesture.end();
65
+ });
66
+ return refs;
67
+ };
@@ -0,0 +1,4 @@
1
+ /** React Flow (xyflow) adapter: `useNodeSnap` and `useNodeResizeSnap` for the drag and resize handlers, `<SnapGuides>` to draw. */
2
+ export { SnapGuides, type SnapGuidesProps } from "./snap-guides.js";
3
+ export { useNodeSnap, type NodeSnap, type NodeSnapOptions } from "./use-node-snap.js";
4
+ export { useNodeResizeSnap, type NodeResizeSnap, type NodeResizeSnapOptions } from "./use-node-resize-snap.js";
@@ -0,0 +1,4 @@
1
+ /** React Flow (xyflow) adapter: `useNodeSnap` and `useNodeResizeSnap` for the drag and resize handlers, `<SnapGuides>` to draw. */
2
+ export { SnapGuides } from "./snap-guides.js";
3
+ export { useNodeSnap } from "./use-node-snap.js";
4
+ export { useNodeResizeSnap } from "./use-node-resize-snap.js";
@@ -0,0 +1,10 @@
1
+ import { type ReactElement } from "react";
2
+ import { type GapGuide, type Guide } from "../core/index.js";
3
+ export interface SnapGuidesProps {
4
+ readonly guides: readonly Guide[];
5
+ readonly gaps?: readonly GapGuide[];
6
+ }
7
+ /** The SVG elements for `guides` and `gaps` at `zoom`: lines, crosses and gap ticks. */
8
+ export declare const snapGuideMarks: (guides: readonly Guide[], gaps: readonly GapGuide[], zoom: number) => ReactElement[];
9
+ /** The guides and equal gaps of a gesture, drawn in front of the nodes. Render it as a child of `<ReactFlow>`. */
10
+ export declare const SnapGuides: ({ guides, gaps }: SnapGuidesProps) => ReactElement;
@@ -0,0 +1,43 @@
1
+ /*
2
+ * Draws the guides from `useNodeSnap` and `useNodeResizeSnap` on the React Flow
3
+ * canvas, in flow coordinates (a ViewportPortal), so they pan and zoom with the
4
+ * nodes. Lines stay one screen pixel wide at any zoom; each aligned point gets
5
+ * a small cross, as in Excalidraw; centre guides are dashed. Equal gaps are
6
+ * drawn as lines with a tick across each end.
7
+ *
8
+ * Colour: set `--snap-guide-color` on any ancestor (default a magenta that
9
+ * reads on light and dark canvases). Stacking: ViewportPortal's container
10
+ * comes after the nodes and has no z-index, and xyflow lifts a selected node
11
+ * to z-index 1000 (@xyflow/system 1.0.1 src/utils/store.ts:34), so the drawing
12
+ * sits at `--snap-guide-z`, default 1001, to stay in front of the dragged node.
13
+ *
14
+ * Written with `createElement` in a `.ts` file: the library is built by
15
+ * svelte-package, which copies `.tsx` files without compiling them. The
16
+ * styles are inline, so there is no stylesheet to import.
17
+ */
18
+ import { useViewportStore, ViewportPortal } from "@xyflow/react";
19
+ import { createElement } from "react";
20
+ import { guideMarks } from "../core/index.js";
21
+ const SVG_STYLE = {
22
+ position: "absolute",
23
+ insetBlockStart: 0,
24
+ insetInlineStart: 0,
25
+ inlineSize: 1,
26
+ blockSize: 1,
27
+ overflow: "visible",
28
+ pointerEvents: "none",
29
+ zIndex: "var(--snap-guide-z, 1001)",
30
+ fill: "none",
31
+ stroke: "var(--snap-guide-color, #e0447c)",
32
+ strokeWidth: 1,
33
+ };
34
+ const STROKE = { vectorEffect: "non-scaling-stroke" };
35
+ /** The SVG elements for `guides` and `gaps` at `zoom`: lines, crosses and gap ticks. */
36
+ export const snapGuideMarks = (guides, gaps, zoom) => guideMarks(guides, gaps, zoom).map((mark) => mark.kind === "line"
37
+ ? createElement("line", { key: mark.key, x1: mark.from.x, y1: mark.from.y, x2: mark.to.x, y2: mark.to.y, strokeDasharray: mark.dash?.join(" "), ...STROKE })
38
+ : createElement("path", { key: mark.key, d: mark.d, ...STROKE }));
39
+ /** The guides and equal gaps of a gesture, drawn in front of the nodes. Render it as a child of `<ReactFlow>`. */
40
+ export const SnapGuides = ({ guides, gaps = [] }) => {
41
+ const zoom = useViewportStore((state) => state.transform[2]);
42
+ return createElement(ViewportPortal, null, createElement("svg", { "aria-hidden": true, style: SVG_STYLE }, snapGuideMarks(guides, gaps, zoom)));
43
+ };
@@ -0,0 +1,26 @@
1
+ import { type Node, type OnResize, type OnResizeEnd, type OnResizeStart } from "@xyflow/react";
2
+ import type { GapGuide, Guide } from "../core/index.js";
3
+ import { type AdapterOptions } from "../flow/index.js";
4
+ type ResizeEvent = MouseEvent | TouchEvent;
5
+ /** The options of `useNodeResizeSnap`: the snapping options, `snapTo` and `suspend`. */
6
+ export type NodeResizeSnapOptions<NodeType extends Node = Node> = AdapterOptions<NodeType, ResizeEvent>;
7
+ export interface NodeResizeSnap {
8
+ /** The guides to draw now; hand them to `<SnapGuides>`. Empty between resizes. */
9
+ readonly guides: readonly Guide[];
10
+ /** The equal gaps to draw now; hand them to `<SnapGuides gaps>`. Empty between resizes. */
11
+ readonly gaps: readonly GapGuide[];
12
+ /** Pass to `<NodeResizer onResizeStart>`. Keeps its identity between renders. */
13
+ readonly onResizeStart: OnResizeStart;
14
+ /** Pass to `<NodeResizer onResize>`. Keeps its identity between renders. */
15
+ readonly onResize: OnResize;
16
+ /** Pass to `<NodeResizer onResizeEnd>`. Keeps its identity between renders. */
17
+ readonly onResizeEnd: OnResizeEnd;
18
+ }
19
+ /**
20
+ * Create the resize handlers and the live guides. Call it in a component
21
+ * inside `<ReactFlow>` or a `<ReactFlowProvider>`, as for `useNodeSnap`. Pass
22
+ * the same `<SnapGuides>` the drag guides go to, e.g.
23
+ * `guides={[...drag.guides, ...resize.guides]}`.
24
+ */
25
+ export declare const useNodeResizeSnap: <NodeType extends Node = Node>(options?: NodeResizeSnapOptions<NodeType>) => NodeResizeSnap;
26
+ export {};
@@ -0,0 +1,78 @@
1
+ /*
2
+ * Snapping for React Flow nodes resized with `<NodeResizer>`, built on the
3
+ * shared resize gesture.
4
+ *
5
+ * xyflow's resizer keeps its own state from the pointer. On every move it
6
+ * calls `onResize` with the unsnapped box and then, in the same task, emits
7
+ * that box as position and dimension changes (@xyflow/system 1.0.1
8
+ * src/xyresizer/XYResizer.ts:353-354; the emit is @xyflow/react 13.0.3
9
+ * src/additional-components/NodeResizer/NodeResizeControl.tsx:84-155). A
10
+ * change emitted from `onResize` would therefore reach `onNodesChange` before
11
+ * xyflow's own and be overwritten, since `useNodesState` applies changes as
12
+ * functional `setNodes` updates, in the order they were emitted
13
+ * (src/hooks/useNodesEdgesState.ts:59). So the snapped box is emitted in a
14
+ * microtask: it runs after the synchronous emit, and its update comes last.
15
+ * When the resize ends, `onResizeEnd` runs before the resizer emits the
16
+ * unsnapped size once more (XYResizer.ts:357-358, NodeResizeControl.tsx:157-167),
17
+ * so the last snapped box is emitted the same way.
18
+ *
19
+ * `<NodeResizeControl>` sets up its drag handler in an effect that depends on
20
+ * `onResizeStart`, `onResize` and `onResizeEnd`, and the effect's cleanup
21
+ * destroys the handler (NodeResizeControl.tsx:191-203). A handler that
22
+ * changed identity during a resize would end it, so the three handlers
23
+ * returned here keep their identity for the life of the component.
24
+ *
25
+ * The callbacks are shared by every handle of a `<NodeResizer>` and say neither
26
+ * which node nor which handle is dragged, so `onResizeStart` reads both from
27
+ * the DOM element the gesture began on. Assumes the default node origin
28
+ * [0, 0]; a node with children, `keepAspectRatio` or min/max sizes can be
29
+ * pushed past what xyflow would allow, since the snapped box is written over
30
+ * xyflow's.
31
+ */
32
+ import { useReactFlowStoreApi } from "@xyflow/react";
33
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
34
+ import { createResizeGesture, NO_GUIDES, resizeTarget, xyflowParentOrigin, xyflowReferences, xyflowResizeChanges, } from "../flow/index.js";
35
+ /**
36
+ * Create the resize handlers and the live guides. Call it in a component
37
+ * inside `<ReactFlow>` or a `<ReactFlowProvider>`, as for `useNodeSnap`. Pass
38
+ * the same `<SnapGuides>` the drag guides go to, e.g.
39
+ * `guides={[...drag.guides, ...resize.guides]}`.
40
+ */
41
+ export const useNodeResizeSnap = (options = {}) => {
42
+ const stores = useReactFlowStoreApi();
43
+ const latest = useRef(options);
44
+ useEffect(() => {
45
+ latest.current = options;
46
+ });
47
+ const [state, setState] = useState(NO_GUIDES);
48
+ const [gesture] = useState(() => createResizeGesture({ ...options, suspend: (event) => (latest.current.suspend ?? ((e) => e.altKey))(event) }, setState));
49
+ const snapTo = useCallback((node) => (latest.current.snapTo ?? (() => true))(node), []);
50
+ /** Emit `box` as the node's position and size, after xyflow's own change. */
51
+ const place = useCallback((id, box, resizing) => {
52
+ const changes = xyflowResizeChanges(stores.nodesStore.getState().nodeLookup, id, box, resizing);
53
+ queueMicrotask(() => {
54
+ stores.optionsStore.getState().emitNodeChanges(changes);
55
+ });
56
+ }, [stores]);
57
+ const onResizeStart = useCallback(({ sourceEvent }) => {
58
+ gesture.start(resizeTarget(sourceEvent.target, "react-flow"));
59
+ }, [gesture]);
60
+ const onResize = useCallback(({ sourceEvent }, params) => {
61
+ const id = gesture.target?.id;
62
+ if (id === undefined)
63
+ return;
64
+ const { nodeLookup } = stores.nodesStore.getState();
65
+ const origin = xyflowParentOrigin(nodeLookup, id);
66
+ const box = { x: origin.x + params.x, y: origin.y + params.y, width: params.width, height: params.height, id };
67
+ const zoom = stores.viewportStore.getState().transform[2];
68
+ const snapped = gesture.move(sourceEvent, box, () => xyflowReferences(nodeLookup, [id], snapTo), zoom);
69
+ if (snapped)
70
+ place(id, snapped, true);
71
+ }, [stores, gesture, snapTo, place]);
72
+ const onResizeEnd = useCallback(() => {
73
+ const last = gesture.end();
74
+ if (last)
75
+ place(last.id, last.box, false);
76
+ }, [gesture, place]);
77
+ return useMemo(() => ({ guides: state.guides, gaps: state.gaps, onResizeStart, onResize, onResizeEnd }), [state, onResizeStart, onResize, onResizeEnd]);
78
+ };
@@ -0,0 +1,23 @@
1
+ import { type Node, type OnNodeDrag } from "@xyflow/react";
2
+ import type { GapGuide, Guide } from "../core/index.js";
3
+ import { type AdapterOptions } from "../flow/index.js";
4
+ type DragEvent = MouseEvent | TouchEvent;
5
+ /** The options of `useNodeSnap`: the snapping options, `snapTo` and `suspend`. */
6
+ export type NodeSnapOptions<NodeType extends Node = Node> = AdapterOptions<NodeType, DragEvent>;
7
+ export interface NodeSnap<NodeType extends Node = Node> {
8
+ /** The guides to draw now; hand them to `<SnapGuides>`. Empty between drags. */
9
+ readonly guides: readonly Guide[];
10
+ /** The equal gaps to draw now; hand them to `<SnapGuides gaps>`. Empty between drags. */
11
+ readonly gaps: readonly GapGuide[];
12
+ /** Pass to `<ReactFlow onNodeDrag>`. */
13
+ readonly onNodeDrag: OnNodeDrag<NodeType>;
14
+ /** Pass to `<ReactFlow onNodeDragStop>`. */
15
+ readonly onNodeDragStop: OnNodeDrag<NodeType>;
16
+ }
17
+ /**
18
+ * Create the drag handlers and the live guides. Call it in a component inside
19
+ * `<ReactFlow>` or a `<ReactFlowProvider>`, as for `useReactFlow`. When the
20
+ * same component renders `<ReactFlow>`, wrap it in a provider one level up.
21
+ */
22
+ export declare const useNodeSnap: <NodeType extends Node = Node>(options?: NodeSnapOptions<NodeType>) => NodeSnap<NodeType>;
23
+ export {};
@@ -0,0 +1,62 @@
1
+ /*
2
+ * Snapping for dragged React Flow nodes, built on the shared drag gesture.
3
+ *
4
+ * On every pointer move xyflow's drag helper computes the nodes' positions,
5
+ * emits them as position changes through `updateNodePositions` and only then
6
+ * calls `onNodeDrag` (@xyflow/system 1.0.1 src/xydrag/XYDrag.ts:228 and :238).
7
+ * `emitNodeChanges` hands the changes to `onNodesChange` synchronously
8
+ * (@xyflow/react 13.0.3 src/store/index.ts:268-287), and `useNodesState`
9
+ * applies them as a functional `setNodes` update
10
+ * (src/hooks/useNodesEdgesState.ts:59). React runs queued updaters in order,
11
+ * so the snapped position emitted from `onNodeDrag` is applied after the
12
+ * unsnapped one and is the state that renders. A held snap often leaves the
13
+ * position as it was a frame ago, but xyflow compares each frame with its own
14
+ * drag item, never with the nodes state, so nothing is skipped as unchanged.
15
+ * When the drag ends xyflow emits its own unsnapped positions once more
16
+ * (XYDrag.ts:411) before `onNodeDragStop` (:424); that handler emits the
17
+ * snapped ones again after them.
18
+ *
19
+ * The position given to `onNodeDrag` is the drag item's, not the one in
20
+ * `nodeLookup`: in a controlled flow the lookup only follows the `nodes` prop
21
+ * after React has rendered it, so it lags by a frame. Reference boxes come
22
+ * from the lookup, which holds the other nodes where they are drawn.
23
+ *
24
+ * Assumes the default node origin [0, 0] (a node's position is its top-left).
25
+ * Handlers and the gesture are created once, and the options are read through
26
+ * a ref at event time, so an inline `options` object is fine; the snapping
27
+ * options themselves (`threshold`, `centers`, ...) are read once, at the
28
+ * first render.
29
+ */
30
+ import { useReactFlowStoreApi } from "@xyflow/react";
31
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
32
+ import { createDragGesture, NO_GUIDES, xyflowDraggedBox, xyflowDragItems, xyflowReferences } from "../flow/index.js";
33
+ /**
34
+ * Create the drag handlers and the live guides. Call it in a component inside
35
+ * `<ReactFlow>` or a `<ReactFlowProvider>`, as for `useReactFlow`. When the
36
+ * same component renders `<ReactFlow>`, wrap it in a provider one level up.
37
+ */
38
+ export const useNodeSnap = (options = {}) => {
39
+ const stores = useReactFlowStoreApi();
40
+ const latest = useRef(options);
41
+ useEffect(() => {
42
+ latest.current = options;
43
+ });
44
+ const [state, setState] = useState(NO_GUIDES);
45
+ const [gesture] = useState(() => createDragGesture({ ...options, suspend: (event) => (latest.current.suspend ?? ((e) => e.altKey))(event) }, setState));
46
+ const snapTo = useCallback((node) => (latest.current.snapTo ?? (() => true))(node), []);
47
+ const onNodeDrag = useCallback((event, _node, nodes) => {
48
+ const { nodeLookup } = stores.nodesStore.getState();
49
+ const moving = nodes.map((node) => xyflowDraggedBox(nodeLookup, node)).filter((box) => box !== null);
50
+ const ids = nodes.map((node) => node.id);
51
+ const zoom = stores.viewportStore.getState().transform[2];
52
+ const offset = gesture.move(event, moving, () => xyflowReferences(nodeLookup, ids, snapTo), zoom);
53
+ if (offset)
54
+ stores.optionsStore.getState().updateNodePositions(xyflowDragItems(nodeLookup, nodes, offset), true);
55
+ }, [stores, gesture, snapTo]);
56
+ const onNodeDragStop = useCallback((_event, _node, nodes) => {
57
+ const offset = gesture.end();
58
+ if (offset)
59
+ stores.optionsStore.getState().updateNodePositions(xyflowDragItems(stores.nodesStore.getState().nodeLookup, nodes, offset), false);
60
+ }, [stores, gesture]);
61
+ return useMemo(() => ({ guides: state.guides, gaps: state.gaps, onNodeDrag, onNodeDragStop }), [state, onNodeDrag, onNodeDragStop]);
62
+ };
@@ -10,7 +10,7 @@
10
10
  -->
11
11
  <script lang="ts">
12
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";
13
+ import { guideMarks, type GapGuide, type Guide } from "../core/index.js";
14
14
 
15
15
  interface Props {
16
16
  guides: readonly Guide[];
@@ -24,17 +24,12 @@
24
24
 
25
25
  <ViewportPortal target="front">
26
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)} />
27
+ {#each guideMarks(guides, gaps, zoom) as mark (mark.key)}
28
+ {#if mark.kind === "line"}
29
+ <line x1={mark.from.x} y1={mark.from.y} x2={mark.to.x} y2={mark.to.y} stroke-dasharray={mark.dash?.join(" ")} />
30
+ {:else}
31
+ <path d={mark.d} />
31
32
  {/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
33
  {/each}
39
34
  </svg>
40
35
  </ViewportPortal>
@@ -1,3 +1,4 @@
1
- /** Svelte Flow (xyflow) adapter: `useNodeSnap` for the drag handlers, `<SnapGuides>` to draw. */
1
+ /** Svelte Flow (xyflow) adapter: `useNodeSnap` and `useNodeResizeSnap` for the drag and resize handlers, `<SnapGuides>` to draw. */
2
2
  export { default as SnapGuides } from "./SnapGuides.svelte";
3
3
  export { useNodeSnap, type NodeSnap, type NodeSnapOptions } from "./node-snap.svelte.js";
4
+ export { useNodeResizeSnap, type NodeResizeSnap, type NodeResizeSnapOptions } from "./node-resize-snap.svelte.js";