@pixerate/editor-svelte 0.3.12 → 0.5.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.
@@ -0,0 +1,75 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ getCenteredNodePosition,
4
+ centerNodes,
5
+ getLayoutedNodes
6
+ } from '../createCanvasLayout.js';
7
+ import type { CanvasNode, CanvasEdge } from '../types.js';
8
+
9
+ describe('createCanvasLayout & Geometry Helpers', () => {
10
+ it('calculates centered node position correctly', () => {
11
+ const screenDimensions = { width: 1000, height: 800 };
12
+ const screenToFlowPosition = (pos: { x: number; y: number }) => ({ x: pos.x, y: pos.y });
13
+
14
+ const pos = getCenteredNodePosition(200, 100, screenToFlowPosition, screenDimensions);
15
+ // Center of 1000x800 is (500, 400). Top-left of 200x100 is (500 - 100, 400 - 50) = (400, 350)
16
+ expect(pos.x).toBe(400);
17
+ expect(pos.y).toBe(350);
18
+ });
19
+
20
+ it('centers multiple nodes using centerNodes', () => {
21
+ const screenDimensions = { width: 1000, height: 800 };
22
+ const screenToFlowPosition = (pos: { x: number; y: number }) => pos;
23
+
24
+ const nodes: CanvasNode[] = [
25
+ { id: '1', position: { x: 0, y: 0 }, data: {} },
26
+ { id: '2', position: { x: 200, y: 100 }, data: {} }
27
+ ];
28
+
29
+ const getNodesBounds = () => ({ x: 0, y: 0, width: 300, height: 200 });
30
+
31
+ const centered = centerNodes(nodes, screenToFlowPosition, getNodesBounds, screenDimensions);
32
+
33
+ // Center of viewport is (500, 400). Upper left for 300x200 bounding box is (350, 300).
34
+ // DeltaX = 350 - 0 = 350, DeltaY = 300 - 0 = 300.
35
+ expect(centered[0].position.x).toBe(350);
36
+ expect(centered[0].position.y).toBe(300);
37
+ expect(centered[1].position.x).toBe(550);
38
+ expect(centered[1].position.y).toBe(400);
39
+ });
40
+
41
+ it('computes Dagre hierarchical layout positions for nodes and edges', () => {
42
+ const nodes: CanvasNode[] = [
43
+ { id: 'root', position: { x: 0, y: 0 }, data: {}, measured: { width: 100, height: 100 } },
44
+ { id: 'child1', position: { x: 0, y: 0 }, data: {}, measured: { width: 100, height: 100 } },
45
+ { id: 'child2', position: { x: 0, y: 0 }, data: {}, measured: { width: 100, height: 100 } }
46
+ ];
47
+
48
+ const edges: CanvasEdge[] = [
49
+ { id: 'e1', source: 'root', target: 'child1' },
50
+ { id: 'e2', source: 'root', target: 'child2' }
51
+ ];
52
+
53
+ const getNodesBounds = () => ({ x: 100, y: 100, width: 400, height: 400 });
54
+
55
+ const layouted = getLayoutedNodes(nodes, edges, getNodesBounds, {
56
+ direction: 'LR',
57
+ ranksep: 80,
58
+ nodesep: 40
59
+ });
60
+
61
+ expect(layouted).toHaveLength(3);
62
+
63
+ const root = layouted.find((n) => n.id === 'root')!;
64
+ const child1 = layouted.find((n) => n.id === 'child1')!;
65
+ const child2 = layouted.find((n) => n.id === 'child2')!;
66
+
67
+ // Root should be to the left of child nodes in 'LR' layout
68
+ expect(root.position.x).toBeLessThan(child1.position.x);
69
+ expect(root.position.x).toBeLessThan(child2.position.x);
70
+
71
+ // Target and source positions should be configured for horizontal layout
72
+ expect(root.sourcePosition).toBe('right');
73
+ expect(child1.targetPosition).toBe('left');
74
+ });
75
+ });
@@ -0,0 +1,59 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { createCanvasShortcuts } from '../createCanvasShortcuts.js';
3
+ import type { CanvasNode } from '../types.js';
4
+
5
+ describe('createCanvasShortcuts', () => {
6
+ it('attaches listener, handles hotkeys, and cleans up', () => {
7
+ const target = new EventTarget();
8
+ const onDelete = vi.fn();
9
+ const onDuplicate = vi.fn();
10
+ const onSelectAll = vi.fn();
11
+
12
+ const selectedNodes: CanvasNode[] = [{ id: 'node-1', position: { x: 0, y: 0 }, data: {} }];
13
+
14
+ const destroy = createCanvasShortcuts({
15
+ targetElement: target as unknown as HTMLElement,
16
+ getSelectedNodes: () => selectedNodes,
17
+ onDelete,
18
+ onDuplicate,
19
+ onSelectAll
20
+ });
21
+
22
+ // Trigger Backspace -> onDelete
23
+ const deleteEvent = new CustomEvent('keydown', { cancelable: true });
24
+ Object.assign(deleteEvent, { key: 'Backspace' });
25
+ target.dispatchEvent(deleteEvent);
26
+
27
+ expect(onDelete).toHaveBeenCalledWith(selectedNodes);
28
+
29
+ // Trigger Meta + D -> onDuplicate
30
+ const dupEvent = new CustomEvent('keydown', { cancelable: true });
31
+ Object.assign(dupEvent, { key: 'd', metaKey: true });
32
+ target.dispatchEvent(dupEvent);
33
+
34
+ expect(onDuplicate).toHaveBeenCalledWith(selectedNodes);
35
+
36
+ // Trigger Meta + A -> onSelectAll
37
+ const allEvent = new CustomEvent('keydown', { cancelable: true });
38
+ Object.assign(allEvent, { key: 'a', metaKey: true });
39
+ target.dispatchEvent(allEvent);
40
+
41
+ expect(onSelectAll).toHaveBeenCalledTimes(1);
42
+
43
+ // Trigger shortcut while targeting an input -> should be ignored
44
+ const inputEl = { tagName: 'INPUT' } as unknown as HTMLElement;
45
+ const ignoredEvent = new CustomEvent('keydown', { cancelable: true });
46
+ Object.defineProperty(ignoredEvent, 'target', { value: inputEl });
47
+ Object.assign(ignoredEvent, { key: 'Backspace' });
48
+ target.dispatchEvent(ignoredEvent);
49
+
50
+ expect(onDelete).toHaveBeenCalledTimes(1); // Not called again
51
+
52
+ // Destroy listeners
53
+ destroy();
54
+
55
+ // Dispatching after destroy should do nothing
56
+ target.dispatchEvent(deleteEvent);
57
+ expect(onDelete).toHaveBeenCalledTimes(1);
58
+ });
59
+ });
@@ -0,0 +1,219 @@
1
+ import { tick } from 'svelte';
2
+ import type { XYPosition } from '@xyflow/svelte';
3
+ import type { CanvasNode, CanvasEdge, CanvasClipboardPayload } from './types.js';
4
+
5
+ /**
6
+ * Checks if an event originated from a text input, textarea, contenteditable element, or rich editor.
7
+ */
8
+ export function isEventFromTextInput(event: Event | { target: EventTarget | null }): boolean {
9
+ const target = event.target as HTMLElement | null;
10
+ if (!target) return false;
11
+ if (
12
+ target.tagName === 'INPUT' ||
13
+ target.tagName === 'TEXTAREA' ||
14
+ target.tagName === 'SELECT' ||
15
+ target.isContentEditable ||
16
+ target.closest?.('[contenteditable="true"]') ||
17
+ target.closest?.('.ProseMirror')
18
+ ) {
19
+ return true;
20
+ }
21
+ return false;
22
+ }
23
+
24
+ /**
25
+ * Validates that an object conforms to minimal CanvasNode shape.
26
+ */
27
+ export function isValidCanvasNode(obj: unknown): obj is CanvasNode {
28
+ return (
29
+ typeof obj === 'object' &&
30
+ obj !== null &&
31
+ 'id' in obj &&
32
+ typeof (obj as any).id === 'string' &&
33
+ 'position' in obj &&
34
+ typeof (obj as any).position === 'object' &&
35
+ (obj as any).position !== null &&
36
+ 'x' in (obj as any).position &&
37
+ 'y' in (obj as any).position
38
+ );
39
+ }
40
+
41
+ /**
42
+ * Checks if a string is a valid HTTP/HTTPS URL.
43
+ */
44
+ export function isValidUrl(url: string): boolean {
45
+ try {
46
+ const parsed = new URL(url);
47
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+
53
+ export interface CreateCanvasClipboardOptions<
54
+ TNode extends CanvasNode = CanvasNode,
55
+ TEdge extends CanvasEdge = CanvasEdge
56
+ > {
57
+ onPasteNodes?: (nodes: TNode[], edges?: TEdge[]) => void | Promise<void>;
58
+ onPasteUrl?: (url: string, position?: XYPosition) => void;
59
+ onPasteText?: (text: string, position?: XYPosition) => void;
60
+ onPasteImage?: (blob: File) => void | Promise<void>;
61
+ screenToFlowPosition?: (position: XYPosition) => XYPosition;
62
+ }
63
+
64
+ /**
65
+ * Headless Svelte 5 rune managing canvas copy, cut, and paste interactions.
66
+ */
67
+ export function createCanvasClipboard<
68
+ TNode extends CanvasNode = CanvasNode,
69
+ TEdge extends CanvasEdge = CanvasEdge
70
+ >(options: CreateCanvasClipboardOptions<TNode, TEdge> = {}) {
71
+ function copySelectedNodes(
72
+ selectedNodes: TNode[],
73
+ connectedEdges?: TEdge[],
74
+ event?: ClipboardEvent
75
+ ): boolean {
76
+ if (event && isEventFromTextInput(event)) {
77
+ return false;
78
+ }
79
+
80
+ if (selectedNodes.length === 0) return false;
81
+
82
+ const payload: CanvasClipboardPayload<TNode, TEdge> = {
83
+ version: 1,
84
+ nodes: selectedNodes,
85
+ edges: connectedEdges
86
+ };
87
+
88
+ const serialized = JSON.stringify(payload);
89
+
90
+ if (event?.clipboardData) {
91
+ event.clipboardData.setData('application/json', serialized);
92
+ event.clipboardData.setData('text/plain', serialized);
93
+ event.preventDefault();
94
+ } else if (typeof navigator !== 'undefined' && navigator.clipboard) {
95
+ navigator.clipboard.writeText(serialized).catch(() => {});
96
+ }
97
+
98
+ return true;
99
+ }
100
+
101
+ function cutSelectedNodes(
102
+ selectedNodes: TNode[],
103
+ connectedEdges?: TEdge[],
104
+ onRemove?: (nodes: TNode[]) => void,
105
+ event?: ClipboardEvent
106
+ ): boolean {
107
+ if (event && isEventFromTextInput(event)) {
108
+ return false;
109
+ }
110
+
111
+ const copied = copySelectedNodes(selectedNodes, connectedEdges, event);
112
+ if (copied && onRemove) {
113
+ onRemove(selectedNodes);
114
+ }
115
+ return copied;
116
+ }
117
+
118
+ async function handlePasteEvent(event: ClipboardEvent): Promise<boolean> {
119
+ if (isEventFromTextInput(event)) {
120
+ return false;
121
+ }
122
+
123
+ const clipboardData = event.clipboardData;
124
+ if (!clipboardData) return false;
125
+
126
+ // 1. Check for files (images)
127
+ const files = clipboardData.files;
128
+ if (files && files.length > 0) {
129
+ const imageFile = Array.from(files).find((f) => f.type.startsWith('image/'));
130
+ if (imageFile && options.onPasteImage) {
131
+ event.preventDefault();
132
+ await options.onPasteImage(imageFile);
133
+ return true;
134
+ }
135
+ }
136
+
137
+ // 2. Check for serialized nodes (application/json or json in text/plain)
138
+ const rawJson =
139
+ clipboardData.getData('application/json') || clipboardData.getData('text/plain');
140
+
141
+ if (rawJson) {
142
+ try {
143
+ const parsed = JSON.parse(rawJson);
144
+ let rawNodes: TNode[] | undefined;
145
+ let rawEdges: TEdge[] | undefined;
146
+
147
+ if (Array.isArray(parsed) && parsed.every(isValidCanvasNode)) {
148
+ rawNodes = parsed as TNode[];
149
+ } else if (
150
+ typeof parsed === 'object' &&
151
+ parsed !== null &&
152
+ Array.isArray((parsed as any).nodes) &&
153
+ (parsed as any).nodes.every(isValidCanvasNode)
154
+ ) {
155
+ rawNodes = (parsed as any).nodes;
156
+ rawEdges = (parsed as any).edges;
157
+ }
158
+
159
+ if (rawNodes && rawNodes.length > 0) {
160
+ event.preventDefault();
161
+
162
+ // Create ID mapping for cloned nodes
163
+ const idMap = new Map<string, string>();
164
+ const newNodes: TNode[] = rawNodes.map((node) => {
165
+ const newId = crypto.randomUUID();
166
+ idMap.set(node.id, newId);
167
+ return {
168
+ ...node,
169
+ id: newId,
170
+ selected: true,
171
+ position: {
172
+ x: node.position.x + 40,
173
+ y: node.position.y + 40
174
+ }
175
+ };
176
+ });
177
+
178
+ // Clone edges mapping them to the newly generated node IDs
179
+ const newEdges: TEdge[] | undefined = rawEdges?.map((edge) => ({
180
+ ...edge,
181
+ id: crypto.randomUUID(),
182
+ source: idMap.get(edge.source) ?? edge.source,
183
+ target: idMap.get(edge.target) ?? edge.target
184
+ }));
185
+
186
+ if (options.onPasteNodes) {
187
+ await options.onPasteNodes(newNodes, newEdges);
188
+ await tick();
189
+ }
190
+ return true;
191
+ }
192
+ } catch {
193
+ // Not JSON, fall through to text/URL processing
194
+ }
195
+ }
196
+
197
+ // 3. Check for URLs or plain text
198
+ const text = clipboardData.getData('text/plain')?.trim();
199
+ if (text) {
200
+ if (isValidUrl(text) && options.onPasteUrl) {
201
+ event.preventDefault();
202
+ options.onPasteUrl(text);
203
+ return true;
204
+ } else if (options.onPasteText) {
205
+ event.preventDefault();
206
+ options.onPasteText(text);
207
+ return true;
208
+ }
209
+ }
210
+
211
+ return false;
212
+ }
213
+
214
+ return {
215
+ copySelectedNodes,
216
+ cutSelectedNodes,
217
+ handlePasteEvent
218
+ };
219
+ }
@@ -0,0 +1,226 @@
1
+ import dagre from '@dagrejs/dagre';
2
+ import type { Rect, XYPosition } from '@xyflow/svelte';
3
+ import type {
4
+ CanvasEdge,
5
+ CanvasLayoutOptions,
6
+ CanvasNode,
7
+ DirectionalDisplacementOptions
8
+ } from './types.js';
9
+
10
+ /**
11
+ * Calculates a bounding rectangle for a set of nodes if not provided by getNodesBounds.
12
+ */
13
+ export function computeNodesBoundingBox<TNode extends CanvasNode = CanvasNode>(
14
+ nodes: TNode[],
15
+ defaultWidth = 200,
16
+ defaultHeight = 60
17
+ ): Rect {
18
+ if (nodes.length === 0) {
19
+ return { x: 0, y: 0, width: 0, height: 0 };
20
+ }
21
+
22
+ let minX = Infinity;
23
+ let minY = Infinity;
24
+ let maxX = -Infinity;
25
+ let maxY = -Infinity;
26
+
27
+ for (const node of nodes) {
28
+ const width = node.measured?.width ?? (node as any).width ?? defaultWidth;
29
+ const height = node.measured?.height ?? (node as any).height ?? defaultHeight;
30
+
31
+ minX = Math.min(minX, node.position.x);
32
+ minY = Math.min(minY, node.position.y);
33
+ maxX = Math.max(maxX, node.position.x + width);
34
+ maxY = Math.max(maxY, node.position.y + height);
35
+ }
36
+
37
+ return {
38
+ x: minX,
39
+ y: minY,
40
+ width: maxX - minX,
41
+ height: maxY - minY
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Pure directional displacement calculation.
47
+ * Shifts downstream or surrounding nodes along an axis to clear space for newly inserted child nodes.
48
+ */
49
+ export function calculateDirectionalDisplacement<TNode extends CanvasNode = CanvasNode>(params: {
50
+ existingNodes: TNode[];
51
+ originNode: TNode;
52
+ childNodes: TNode[];
53
+ getNodesBounds?: (nodes: TNode[]) => Rect;
54
+ options?: DirectionalDisplacementOptions;
55
+ }): Map<string, XYPosition> {
56
+ const {
57
+ existingNodes,
58
+ originNode,
59
+ childNodes,
60
+ getNodesBounds,
61
+ options = {}
62
+ } = params;
63
+
64
+ const {
65
+ direction = 'right',
66
+ gap = 40,
67
+ spreadSiblingLanes = false,
68
+ siblingTolerance = 50
69
+ } = options;
70
+
71
+ const displacedMap = new Map<string, XYPosition>();
72
+ if (childNodes.length === 0 || existingNodes.length === 0) {
73
+ return displacedMap;
74
+ }
75
+
76
+ const childBounds = getNodesBounds
77
+ ? getNodesBounds(childNodes)
78
+ : computeNodesBoundingBox(childNodes);
79
+
80
+ const originWidth = originNode.measured?.width ?? (originNode as any).width ?? 200;
81
+ const originHeight = originNode.measured?.height ?? (originNode as any).height ?? 60;
82
+
83
+ // The delta space required along primary axis
84
+ const deltaPrimary = (direction === 'right' || direction === 'left')
85
+ ? childBounds.width + gap
86
+ : childBounds.height + gap;
87
+
88
+ for (const node of existingNodes) {
89
+ if (node.id === originNode.id) continue;
90
+
91
+ let newX = node.position.x;
92
+ let newY = node.position.y;
93
+ let moved = false;
94
+
95
+ if (direction === 'right') {
96
+ // Downstream nodes strictly to the right of the origin
97
+ if (node.position.x >= originNode.position.x + originWidth * 0.5) {
98
+ newX += deltaPrimary;
99
+ moved = true;
100
+ } else if (spreadSiblingLanes) {
101
+ // Sibling nodes occupying the same vertical space as the exploded cluster
102
+ const isVerticallyOverlapping =
103
+ node.position.y + ((node as any).height ?? 60) >= childBounds.y - gap &&
104
+ node.position.y <= childBounds.y + childBounds.height + gap;
105
+
106
+ if (isVerticallyOverlapping && Math.abs(node.position.x - originNode.position.x) <= siblingTolerance) {
107
+ const pushDirection = node.position.y >= originNode.position.y ? 1 : -1;
108
+ newY += pushDirection * (childBounds.height * 0.5 + gap);
109
+ moved = true;
110
+ }
111
+ }
112
+ } else if (direction === 'left') {
113
+ if (node.position.x <= originNode.position.x) {
114
+ newX -= deltaPrimary;
115
+ moved = true;
116
+ }
117
+ } else if (direction === 'down') {
118
+ if (node.position.y >= originNode.position.y + originHeight * 0.5) {
119
+ newY += deltaPrimary;
120
+ moved = true;
121
+ }
122
+ } else if (direction === 'up') {
123
+ if (node.position.y <= originNode.position.y) {
124
+ newY -= deltaPrimary;
125
+ moved = true;
126
+ }
127
+ }
128
+
129
+ if (moved) {
130
+ displacedMap.set(node.id, { x: newX, y: newY });
131
+ }
132
+ }
133
+
134
+ return displacedMap;
135
+ }
136
+
137
+ /**
138
+ * Pure hierarchical Dagre reflow displacement calculation.
139
+ * Calculates new coordinates for surrounding nodes using Dagre hierarchical layout,
140
+ * anchoring the origin node at its current position to eliminate layout jumping.
141
+ */
142
+ export function calculateReflowDisplacement<
143
+ TNode extends CanvasNode = CanvasNode,
144
+ TEdge extends CanvasEdge = CanvasEdge
145
+ >(params: {
146
+ existingNodes: TNode[];
147
+ existingEdges: TEdge[];
148
+ originNode: TNode;
149
+ childNodes: TNode[];
150
+ childEdges?: TEdge[];
151
+ getNodesBounds?: (nodes: TNode[]) => Rect;
152
+ options?: CanvasLayoutOptions;
153
+ }): Map<string, XYPosition> {
154
+ const {
155
+ existingNodes,
156
+ existingEdges,
157
+ originNode,
158
+ childNodes,
159
+ childEdges = [],
160
+ options = {}
161
+ } = params;
162
+
163
+ const {
164
+ direction = 'LR',
165
+ ranksep = 80,
166
+ nodesep = 30,
167
+ defaultNodeWidth = 200,
168
+ defaultNodeHeight = 60
169
+ } = options;
170
+
171
+ const displacedMap = new Map<string, XYPosition>();
172
+ if (existingNodes.length === 0) return displacedMap;
173
+
174
+ const allNodes = [...existingNodes, ...childNodes];
175
+ const allEdges = [...existingEdges, ...childEdges];
176
+
177
+ const dagreGraph = new dagre.graphlib.Graph();
178
+ dagreGraph.setDefaultEdgeLabel(() => ({}));
179
+ dagreGraph.setGraph({ rankdir: direction, ranksep, nodesep });
180
+
181
+ const allNodeIds = new Set(allNodes.map((n) => n.id));
182
+
183
+ allNodes.forEach((node) => {
184
+ const nodeWidth = node.measured?.width ?? (node as any).width ?? defaultNodeWidth;
185
+ const nodeHeight = node.measured?.height ?? (node as any).height ?? defaultNodeHeight;
186
+ dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
187
+ });
188
+
189
+ allEdges.forEach((edge) => {
190
+ if (allNodeIds.has(edge.source) && allNodeIds.has(edge.target)) {
191
+ dagreGraph.setEdge(edge.source, edge.target);
192
+ }
193
+ });
194
+
195
+ dagre.layout(dagreGraph);
196
+
197
+ const dagreOrigin = dagreGraph.node(originNode.id);
198
+ if (!dagreOrigin) return displacedMap;
199
+
200
+ const originWidth = originNode.measured?.width ?? (originNode as any).width ?? defaultNodeWidth;
201
+ const originHeight = originNode.measured?.height ?? (originNode as any).height ?? defaultNodeHeight;
202
+
203
+ // Calculate offset so origin node remains anchored at its exact initial coordinates
204
+ const anchorOffsetX = originNode.position.x - (dagreOrigin.x - originWidth / 2);
205
+ const anchorOffsetY = originNode.position.y - (dagreOrigin.y - originHeight / 2);
206
+
207
+ existingNodes.forEach((node) => {
208
+ if (node.id === originNode.id) return;
209
+
210
+ const dagreNode = dagreGraph.node(node.id);
211
+ if (!dagreNode) return;
212
+
213
+ const nodeWidth = node.measured?.width ?? (node as any).width ?? defaultNodeWidth;
214
+ const nodeHeight = node.measured?.height ?? (node as any).height ?? defaultNodeHeight;
215
+
216
+ const targetX = dagreNode.x - nodeWidth / 2 + anchorOffsetX;
217
+ const targetY = dagreNode.y - nodeHeight / 2 + anchorOffsetY;
218
+
219
+ // Only include if position actually shifted
220
+ if (Math.abs(targetX - node.position.x) > 0.5 || Math.abs(targetY - node.position.y) > 0.5) {
221
+ displacedMap.set(node.id, { x: targetX, y: targetY });
222
+ }
223
+ });
224
+
225
+ return displacedMap;
226
+ }