@pixerate/editor-svelte 0.3.11 → 0.4.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/dist/canvas/index.d.ts +345 -0
- package/dist/canvas/index.js +672 -0
- package/dist/canvas/index.js.map +1 -0
- package/dist/index.js +11 -19
- package/dist/index.js.map +1 -1
- package/package.json +24 -1
- package/src/EditableTextNodeEditor.svelte +4 -7
- package/src/canvas/README.md +167 -0
- package/src/canvas/__tests__/canvas-clipboard.test.ts +154 -0
- package/src/canvas/__tests__/canvas-docking.test.ts +136 -0
- package/src/canvas/__tests__/canvas-graph.test.ts +159 -0
- package/src/canvas/__tests__/canvas-interactions.test.ts +86 -0
- package/src/canvas/__tests__/canvas-layout.test.ts +75 -0
- package/src/canvas/__tests__/canvas-shortcuts.test.ts +59 -0
- package/src/canvas/createCanvasClipboard.svelte.ts +219 -0
- package/src/canvas/createCanvasDocking.svelte.ts +145 -0
- package/src/canvas/createCanvasGraph.svelte.ts +330 -0
- package/src/canvas/createCanvasInteractions.svelte.ts +112 -0
- package/src/canvas/createCanvasLayout.ts +120 -0
- package/src/canvas/createCanvasShortcuts.ts +99 -0
- package/src/canvas/index.d.ts +345 -0
- package/src/canvas/index.ts +46 -0
- package/src/canvas/types.ts +96 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# @pixerate/editor-svelte/canvas
|
|
2
|
+
|
|
3
|
+
A headless, unstyled Svelte 5 runes architecture for building interactive graph, flow, and diagramming canvas experiences on top of SvelteFlow (`@xyflow/svelte`).
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Philosophy & Core Principles
|
|
8
|
+
|
|
9
|
+
1. **Headless & UI-Agnostic**: Contains zero assumptions about styles, colors, DOM presentation, or application-specific AI pipelines. Pure business logic, coordinate mathematics, and interaction controllers.
|
|
10
|
+
2. **Svelte 5 Runes First**: Implemented using `$state.raw`, `$derived`, and modern functional runes instead of `.svelte` component-as-controller wrappers.
|
|
11
|
+
3. **High Performance**: Eliminates expensive per-frame array clones during animations and node dragging, avoiding requestAnimationFrame memory churn.
|
|
12
|
+
4. **Decoupled Architecture**: Independent modules for graph state, clipboard serialization, Dagre auto-layout, docking/intersections, and hotkeys that can be used together or individually.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Module Overview
|
|
17
|
+
|
|
18
|
+
| Module | Purpose |
|
|
19
|
+
| :--- | :--- |
|
|
20
|
+
| [`createCanvasGraph.svelte.ts`](./createCanvasGraph.svelte.ts) | Reactive graph state management, node deduplication, edge-preserving replacement, and diff calculation. |
|
|
21
|
+
| [`createCanvasClipboard.svelte.ts`](./createCanvasClipboard.svelte.ts) | Serialized JSON clipboard management, UUID remapping, position offset, URL and text pasting. |
|
|
22
|
+
| [`createCanvasDocking.svelte.ts`](./createCanvasDocking.svelte.ts) | Drag-to-dock intersection tracking, dock target hover/leave/drop lifecycle, and connection state. |
|
|
23
|
+
| [`createCanvasLayout.ts`](./createCanvasLayout.ts) | Dagre hierarchical auto-layout, viewport centering, and bounding box math. |
|
|
24
|
+
| [`createCanvasShortcuts.ts`](./createCanvasShortcuts.ts) | Global keyboard shortcut binding with automatic suppression during active text editing. |
|
|
25
|
+
| [`createCanvasInteractions.svelte.ts`](./createCanvasInteractions.svelte.ts) | Spacebar panning toggle, trackpad pinch detection, and SvelteFlow interaction presets. |
|
|
26
|
+
| [`types.ts`](./types.ts) | Shared generic types (`CanvasNode`, `CanvasEdge`, `GraphDifferences`, `CanvasLayoutOptions`, etc.). |
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Quickstart & Usage
|
|
31
|
+
|
|
32
|
+
### 1. Basic Setup
|
|
33
|
+
|
|
34
|
+
```svelte
|
|
35
|
+
<script lang="ts">
|
|
36
|
+
import { SvelteFlow, useSvelteFlow } from '@xyflow/svelte';
|
|
37
|
+
import '@xyflow/svelte/dist/style.css';
|
|
38
|
+
import {
|
|
39
|
+
createCanvasGraph,
|
|
40
|
+
createCanvasClipboard,
|
|
41
|
+
createCanvasShortcuts,
|
|
42
|
+
createCanvasInteractions,
|
|
43
|
+
defaultSvelteFlowPreset
|
|
44
|
+
} from '@pixerate/editor-svelte/canvas';
|
|
45
|
+
|
|
46
|
+
// 1. Initialize reactive graph controller
|
|
47
|
+
const graph = createCanvasGraph({
|
|
48
|
+
initialNodes: [
|
|
49
|
+
{ id: '1', position: { x: 100, y: 100 }, data: { label: 'Start' } }
|
|
50
|
+
],
|
|
51
|
+
initialEdges: [],
|
|
52
|
+
onSave: () => console.log('Graph changed, autosaving...')
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// 2. Setup clipboard handler
|
|
56
|
+
const clipboard = createCanvasClipboard({
|
|
57
|
+
onPasteNodes: (nodes, edges) => {
|
|
58
|
+
graph.addNodeOrNodes(nodes);
|
|
59
|
+
if (edges) graph.addEdges(edges);
|
|
60
|
+
},
|
|
61
|
+
onPasteUrl: (url) => {
|
|
62
|
+
console.log('Pasted URL:', url);
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// 3. Attach keyboard shortcuts
|
|
67
|
+
$effect(() => {
|
|
68
|
+
return createCanvasShortcuts({
|
|
69
|
+
getSelectedNodes: () => graph.nodes.filter((n) => n.selected),
|
|
70
|
+
onDelete: (selected) => graph.removeNodes(selected),
|
|
71
|
+
onDuplicate: (selected) => {
|
|
72
|
+
const clones = selected.map((n) => ({
|
|
73
|
+
...n,
|
|
74
|
+
id: crypto.randomUUID(),
|
|
75
|
+
position: { x: n.position.x + 40, y: n.position.y + 40 }
|
|
76
|
+
}));
|
|
77
|
+
graph.addNodeOrNodes(clones);
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
</script>
|
|
82
|
+
|
|
83
|
+
<div class="w-full h-screen" onpaste={(e) => clipboard.handlePasteEvent(e)}>
|
|
84
|
+
<SvelteFlow
|
|
85
|
+
bind:nodes={graph.nodes}
|
|
86
|
+
bind:edges={graph.edges}
|
|
87
|
+
{...defaultSvelteFlowPreset}
|
|
88
|
+
/>
|
|
89
|
+
</div>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## API Reference
|
|
95
|
+
|
|
96
|
+
### `createCanvasGraph<TNode, TEdge>(options?)`
|
|
97
|
+
|
|
98
|
+
Creates a reactive graph controller managing nodes and edges.
|
|
99
|
+
|
|
100
|
+
#### Parameters (`options`):
|
|
101
|
+
- `initialNodes?: TNode[]`: Initial node list.
|
|
102
|
+
- `initialEdges?: TEdge[]`: Initial edge list.
|
|
103
|
+
- `onNodesChange?: (nodes: TNode[]) => void`: Callback fired when nodes change.
|
|
104
|
+
- `onEdgesChange?: (edges: TEdge[]) => void`: Callback fired when edges change.
|
|
105
|
+
- `onSave?: () => void`: Optional persistence trigger.
|
|
106
|
+
- `createEdge?: (sourceId, targetId, options?) => TEdge`: Edge factory function.
|
|
107
|
+
|
|
108
|
+
#### Returns:
|
|
109
|
+
- `nodes`: Getter/setter for active nodes array.
|
|
110
|
+
- `edges`: Getter/setter for active edges array.
|
|
111
|
+
- `addNodeOrNodes(nodeOrNodes, animateFromPosition?, options?)`: Adds nodes with deduplication and optional positioning animation.
|
|
112
|
+
- `addEdge(edge, options?)` / `addEdges(edges, options?)`: Adds edges.
|
|
113
|
+
- `removeNodes(nodesToRemove, options?)` / `removeEdges(edgesToRemove, options?)`: Removes entities by ID.
|
|
114
|
+
- `replaceNode(oldNode, newNode, save?, keepEdges?)`: Replaces a node, optionally updating connected edge endpoints.
|
|
115
|
+
- `addConnectedNodes(params)`: Connects incoming and outgoing nodes to a batch of added nodes.
|
|
116
|
+
- `getDifferences(baseline)`: Returns `{ changedNodes, changedEdges, removedNodes, removedEdges }`.
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### `createCanvasLayout`
|
|
121
|
+
|
|
122
|
+
Pure geometry and Dagre layout calculations:
|
|
123
|
+
|
|
124
|
+
- `getLayoutedNodes(nodes, edges, getNodesBounds, options?)`: Automatically lays out graph nodes hierarchically (`'LR'`, `'TB'`, `'RL'`, or `'BT'`).
|
|
125
|
+
- `getCenteredNodePosition(width, height, screenToFlowPosition, screenDimensions?)`: Computes top-left coordinate to center an element in view.
|
|
126
|
+
- `centerNodes(nodes, screenToFlowPosition, getNodesBounds, screenDimensions?)`: Translates a collection of nodes so their bounding box is centered in the current viewport.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
### `createCanvasClipboard(options?)`
|
|
131
|
+
|
|
132
|
+
Headless clipboard interaction:
|
|
133
|
+
|
|
134
|
+
- `copySelectedNodes(nodes, edges?, event?)`: Serializes nodes to clipboard as JSON.
|
|
135
|
+
- `cutSelectedNodes(nodes, edges?, onRemove?, event?)`: Copies and calls deletion callback.
|
|
136
|
+
- `handlePasteEvent(event)`: Intelligently handles paste events, disambiguating images, serialized nodes, URLs, and plain text.
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
### `createCanvasDocking(options?)`
|
|
141
|
+
|
|
142
|
+
Drag-and-dock interaction tracking:
|
|
143
|
+
|
|
144
|
+
- `handleNodeDragStart({ targetNode, event })`: Starts drag tracking.
|
|
145
|
+
- `handleNodeDrag({ targetNode, event }, getIntersectingNodes)`: Computes intersections, firing `onDockHover` and `onDockLeave`.
|
|
146
|
+
- `handleNodeDragStop({ targetNode, event }, getIntersectingNodes, updatePosition?)`: Fires `onDockDrop` and cleans up state.
|
|
147
|
+
- `handleConnectStart` / `handleConnectEnd`: Tracks connection handle dragging.
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
### `createCanvasShortcuts(options)`
|
|
152
|
+
|
|
153
|
+
Attaches standard canvas hotkeys (`Meta/Ctrl+C`, `Meta/Ctrl+X`, `Meta/Ctrl+V`, `Delete`, `Meta/Ctrl+D`, `Meta/Ctrl+A`, `Meta/Ctrl+G`, zoom controls):
|
|
154
|
+
|
|
155
|
+
- Automatically respects active text inputs (`input`, `textarea`, `select`, `contenteditable`, and `.ProseMirror`).
|
|
156
|
+
- Returns a cleanup function `() => void`.
|
|
157
|
+
|
|
158
|
+
---
|
|
159
|
+
|
|
160
|
+
### `createCanvasInteractions(options?)`
|
|
161
|
+
|
|
162
|
+
Manages viewport interaction modes:
|
|
163
|
+
|
|
164
|
+
- `isSpacebarPanning`: Reactive flag active while Spacebar is held down.
|
|
165
|
+
- `trackpadDetected`: Reactive flag set when trackpad pinch-to-zoom is detected.
|
|
166
|
+
- Presets: `defaultSvelteFlowPreset`, `miroCompatiblePreset`.
|
|
167
|
+
- Helper: `restorePanelPointerEvents()` restores panel clickability after drag-selection.
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
createCanvasClipboard,
|
|
4
|
+
isValidCanvasNode,
|
|
5
|
+
isValidUrl,
|
|
6
|
+
isEventFromTextInput
|
|
7
|
+
} from '../createCanvasClipboard.svelte.js';
|
|
8
|
+
import type { CanvasNode, CanvasEdge } from '../types.js';
|
|
9
|
+
|
|
10
|
+
describe('createCanvasClipboard & Clipboard Utilities', () => {
|
|
11
|
+
it('validates canvas nodes with isValidCanvasNode', () => {
|
|
12
|
+
expect(isValidCanvasNode({ id: '1', position: { x: 10, y: 20 } })).toBe(true);
|
|
13
|
+
expect(isValidCanvasNode({ id: 123, position: { x: 10, y: 20 } })).toBe(false);
|
|
14
|
+
expect(isValidCanvasNode({ id: '1' })).toBe(false);
|
|
15
|
+
expect(isValidCanvasNode(null)).toBe(false);
|
|
16
|
+
expect(isValidCanvasNode('not a node')).toBe(false);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it('validates URLs with isValidUrl', () => {
|
|
20
|
+
expect(isValidUrl('https://example.com')).toBe(true);
|
|
21
|
+
expect(isValidUrl('http://localhost:5173/canvas')).toBe(true);
|
|
22
|
+
expect(isValidUrl('not a url')).toBe(false);
|
|
23
|
+
expect(isValidUrl('ftp://example.com')).toBe(false);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('detects text input targets with isEventFromTextInput', () => {
|
|
27
|
+
const inputEl = { tagName: 'INPUT' } as unknown as HTMLElement;
|
|
28
|
+
const textareaEl = { tagName: 'TEXTAREA' } as unknown as HTMLElement;
|
|
29
|
+
const contentEditableEl = { isContentEditable: true, tagName: 'DIV' } as unknown as HTMLElement;
|
|
30
|
+
const canvasEl = { tagName: 'DIV', isContentEditable: false } as unknown as HTMLElement;
|
|
31
|
+
|
|
32
|
+
expect(isEventFromTextInput({ target: inputEl })).toBe(true);
|
|
33
|
+
expect(isEventFromTextInput({ target: textareaEl })).toBe(true);
|
|
34
|
+
expect(isEventFromTextInput({ target: contentEditableEl })).toBe(true);
|
|
35
|
+
expect(isEventFromTextInput({ target: canvasEl })).toBe(false);
|
|
36
|
+
expect(isEventFromTextInput({ target: null })).toBe(false);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('copies selected nodes into clipboardData JSON payload', () => {
|
|
40
|
+
const clipboard = createCanvasClipboard();
|
|
41
|
+
const mockClipboardData = {
|
|
42
|
+
setData: vi.fn()
|
|
43
|
+
};
|
|
44
|
+
const mockEvent = {
|
|
45
|
+
target: { tagName: 'DIV' },
|
|
46
|
+
clipboardData: mockClipboardData,
|
|
47
|
+
preventDefault: vi.fn()
|
|
48
|
+
} as unknown as ClipboardEvent;
|
|
49
|
+
|
|
50
|
+
const selectedNodes: CanvasNode[] = [{ id: 'n1', position: { x: 10, y: 20 }, data: {} }];
|
|
51
|
+
const connectedEdges: CanvasEdge[] = [{ id: 'e1', source: 'n1', target: 'n2' }];
|
|
52
|
+
|
|
53
|
+
const copied = clipboard.copySelectedNodes(selectedNodes, connectedEdges, mockEvent);
|
|
54
|
+
expect(copied).toBe(true);
|
|
55
|
+
expect(mockClipboardData.setData).toHaveBeenCalledWith(
|
|
56
|
+
'application/json',
|
|
57
|
+
expect.stringContaining('"id":"n1"')
|
|
58
|
+
);
|
|
59
|
+
expect(mockEvent.preventDefault).toHaveBeenCalled();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
it('cuts selected nodes by calling onRemove callback', () => {
|
|
63
|
+
const clipboard = createCanvasClipboard();
|
|
64
|
+
const onRemove = vi.fn();
|
|
65
|
+
const mockEvent = {
|
|
66
|
+
target: { tagName: 'DIV' },
|
|
67
|
+
clipboardData: { setData: vi.fn() },
|
|
68
|
+
preventDefault: vi.fn()
|
|
69
|
+
} as unknown as ClipboardEvent;
|
|
70
|
+
|
|
71
|
+
const selectedNodes: CanvasNode[] = [{ id: 'n1', position: { x: 0, y: 0 }, data: {} }];
|
|
72
|
+
|
|
73
|
+
const cut = clipboard.cutSelectedNodes(selectedNodes, undefined, onRemove, mockEvent);
|
|
74
|
+
expect(cut).toBe(true);
|
|
75
|
+
expect(onRemove).toHaveBeenCalledWith(selectedNodes);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('handles paste of serialized node JSON with UUID remapping and offset', async () => {
|
|
79
|
+
const onPasteNodes = vi.fn();
|
|
80
|
+
const clipboard = createCanvasClipboard({ onPasteNodes });
|
|
81
|
+
|
|
82
|
+
const originalNodes: CanvasNode[] = [
|
|
83
|
+
{ id: 'orig-1', position: { x: 100, y: 100 }, data: { label: 'Node 1' } },
|
|
84
|
+
{ id: 'orig-2', position: { x: 200, y: 200 }, data: { label: 'Node 2' } }
|
|
85
|
+
];
|
|
86
|
+
const originalEdges: CanvasEdge[] = [{ id: 'e-orig', source: 'orig-1', target: 'orig-2' }];
|
|
87
|
+
|
|
88
|
+
const serializedPayload = JSON.stringify({
|
|
89
|
+
version: 1,
|
|
90
|
+
nodes: originalNodes,
|
|
91
|
+
edges: originalEdges
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
const mockEvent = {
|
|
95
|
+
target: { tagName: 'DIV' },
|
|
96
|
+
clipboardData: {
|
|
97
|
+
getData: (format: string) => (format === 'application/json' ? serializedPayload : ''),
|
|
98
|
+
files: []
|
|
99
|
+
},
|
|
100
|
+
preventDefault: vi.fn()
|
|
101
|
+
} as unknown as ClipboardEvent;
|
|
102
|
+
|
|
103
|
+
const handled = await clipboard.handlePasteEvent(mockEvent);
|
|
104
|
+
expect(handled).toBe(true);
|
|
105
|
+
expect(onPasteNodes).toHaveBeenCalledTimes(1);
|
|
106
|
+
|
|
107
|
+
const [pastedNodes, pastedEdges] = onPasteNodes.mock.calls[0];
|
|
108
|
+
expect(pastedNodes).toHaveLength(2);
|
|
109
|
+
expect(pastedNodes[0].id).not.toBe('orig-1');
|
|
110
|
+
expect(pastedNodes[0].position.x).toBe(140); // 100 + 40
|
|
111
|
+
expect(pastedNodes[0].position.y).toBe(140); // 100 + 40
|
|
112
|
+
|
|
113
|
+
// Check edge remapping
|
|
114
|
+
expect(pastedEdges).toHaveLength(1);
|
|
115
|
+
expect(pastedEdges[0].source).toBe(pastedNodes[0].id);
|
|
116
|
+
expect(pastedEdges[0].target).toBe(pastedNodes[1].id);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('handles paste of plain text URLs', async () => {
|
|
120
|
+
const onPasteUrl = vi.fn();
|
|
121
|
+
const clipboard = createCanvasClipboard({ onPasteUrl });
|
|
122
|
+
|
|
123
|
+
const mockEvent = {
|
|
124
|
+
target: { tagName: 'DIV' },
|
|
125
|
+
clipboardData: {
|
|
126
|
+
getData: (format: string) => (format === 'text/plain' ? 'https://example.com/asset' : ''),
|
|
127
|
+
files: []
|
|
128
|
+
},
|
|
129
|
+
preventDefault: vi.fn()
|
|
130
|
+
} as unknown as ClipboardEvent;
|
|
131
|
+
|
|
132
|
+
const handled = await clipboard.handlePasteEvent(mockEvent);
|
|
133
|
+
expect(handled).toBe(true);
|
|
134
|
+
expect(onPasteUrl).toHaveBeenCalledWith('https://example.com/asset');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('handles paste of plain text', async () => {
|
|
138
|
+
const onPasteText = vi.fn();
|
|
139
|
+
const clipboard = createCanvasClipboard({ onPasteText });
|
|
140
|
+
|
|
141
|
+
const mockEvent = {
|
|
142
|
+
target: { tagName: 'DIV' },
|
|
143
|
+
clipboardData: {
|
|
144
|
+
getData: (format: string) => (format === 'text/plain' ? 'Sample text content' : ''),
|
|
145
|
+
files: []
|
|
146
|
+
},
|
|
147
|
+
preventDefault: vi.fn()
|
|
148
|
+
} as unknown as ClipboardEvent;
|
|
149
|
+
|
|
150
|
+
const handled = await clipboard.handlePasteEvent(mockEvent);
|
|
151
|
+
expect(handled).toBe(true);
|
|
152
|
+
expect(onPasteText).toHaveBeenCalledWith('Sample text content');
|
|
153
|
+
});
|
|
154
|
+
});
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import { createCanvasDocking } from '../createCanvasDocking.svelte.js';
|
|
3
|
+
import type { CanvasNode } from '../types.js';
|
|
4
|
+
|
|
5
|
+
describe('createCanvasDocking', () => {
|
|
6
|
+
const createSampleNode = (id: string, type = 'default', x = 0, y = 0): CanvasNode => ({
|
|
7
|
+
id,
|
|
8
|
+
type,
|
|
9
|
+
position: { x, y },
|
|
10
|
+
data: {}
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('initializes with null drag and connect states', () => {
|
|
14
|
+
const docking = createCanvasDocking();
|
|
15
|
+
|
|
16
|
+
expect(docking.isDragging).toBe(false);
|
|
17
|
+
expect(docking.draggedNode).toBeNull();
|
|
18
|
+
expect(docking.draggedInitialPosition).toBeNull();
|
|
19
|
+
expect(docking.connectingHandle).toBe('');
|
|
20
|
+
expect(docking.connectingNode).toBeNull();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
it('tracks drag start, records initial position, and sets isDragging', () => {
|
|
24
|
+
const docking = createCanvasDocking();
|
|
25
|
+
const node = createSampleNode('n1', 'default', 100, 200);
|
|
26
|
+
|
|
27
|
+
docking.handleNodeDragStart({ targetNode: node });
|
|
28
|
+
|
|
29
|
+
expect(docking.isDragging).toBe(true);
|
|
30
|
+
expect(docking.draggedNode).toBe(node);
|
|
31
|
+
expect(docking.draggedInitialPosition).toEqual({ x: 100, y: 200 });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('fires onDockHover and onDockLeave as intersecting dock targets change', () => {
|
|
35
|
+
const onDockHover = vi.fn();
|
|
36
|
+
const onDockLeave = vi.fn();
|
|
37
|
+
const docking = createCanvasDocking({
|
|
38
|
+
isDockTarget: (n) => n.type === 'dockArea',
|
|
39
|
+
onDockHover,
|
|
40
|
+
onDockLeave
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const draggedNode = createSampleNode('dragged', 'item', 50, 50);
|
|
44
|
+
const dockNode1 = createSampleNode('dock-1', 'dockArea', 0, 0);
|
|
45
|
+
const dockNode2 = createSampleNode('dock-2', 'dockArea', 200, 200);
|
|
46
|
+
const normalNode = createSampleNode('normal', 'item', 50, 50);
|
|
47
|
+
|
|
48
|
+
docking.handleNodeDragStart({ targetNode: draggedNode });
|
|
49
|
+
|
|
50
|
+
// Drag intersecting with dockNode1 and a non-dock normalNode
|
|
51
|
+
docking.handleNodeDrag(
|
|
52
|
+
{ targetNode: draggedNode },
|
|
53
|
+
() => [dockNode1, normalNode]
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
expect(onDockHover).toHaveBeenCalledTimes(1);
|
|
57
|
+
expect(onDockHover).toHaveBeenCalledWith(dockNode1, draggedNode);
|
|
58
|
+
expect(onDockLeave).not.toHaveBeenCalled();
|
|
59
|
+
|
|
60
|
+
// Drag moves over dockNode2, leaving dockNode1
|
|
61
|
+
docking.handleNodeDrag(
|
|
62
|
+
{ targetNode: draggedNode },
|
|
63
|
+
() => [dockNode2]
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
expect(onDockLeave).toHaveBeenCalledTimes(1);
|
|
67
|
+
expect(onDockLeave).toHaveBeenCalledWith(expect.objectContaining({ id: 'dock-1' }), draggedNode);
|
|
68
|
+
expect(onDockHover).toHaveBeenCalledTimes(2);
|
|
69
|
+
expect(onDockHover).toHaveBeenLastCalledWith(dockNode2, draggedNode);
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
it('fires onDockDrop and restores position on dock stop', () => {
|
|
73
|
+
const onDockDrop = vi.fn();
|
|
74
|
+
const onSave = vi.fn();
|
|
75
|
+
const updateNodePosition = vi.fn();
|
|
76
|
+
|
|
77
|
+
const docking = createCanvasDocking({
|
|
78
|
+
isDockTarget: (n) => n.type === 'dockArea',
|
|
79
|
+
restorePositionOnDock: true,
|
|
80
|
+
onDockDrop,
|
|
81
|
+
onSave
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
const draggedNode = createSampleNode('dragged', 'item', 100, 100);
|
|
85
|
+
const dockNode = createSampleNode('dock', 'dockArea', 0, 0);
|
|
86
|
+
|
|
87
|
+
docking.handleNodeDragStart({ targetNode: draggedNode });
|
|
88
|
+
|
|
89
|
+
// Node was dragged to new position
|
|
90
|
+
draggedNode.position = { x: 300, y: 300 };
|
|
91
|
+
|
|
92
|
+
docking.handleNodeDragStop(
|
|
93
|
+
{ targetNode: draggedNode },
|
|
94
|
+
() => [dockNode],
|
|
95
|
+
updateNodePosition
|
|
96
|
+
);
|
|
97
|
+
|
|
98
|
+
expect(onDockDrop).toHaveBeenCalledWith(dockNode, draggedNode);
|
|
99
|
+
expect(updateNodePosition).toHaveBeenCalledWith('dragged', { x: 100, y: 100 });
|
|
100
|
+
expect(onSave).toHaveBeenCalled();
|
|
101
|
+
expect(docking.isDragging).toBe(false);
|
|
102
|
+
expect(docking.draggedNode).toBeNull();
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
it('tracks handle connect start and end', () => {
|
|
106
|
+
const docking = createCanvasDocking();
|
|
107
|
+
const node = createSampleNode('source-node');
|
|
108
|
+
const getNode = (id: string) => (id === 'source-node' ? node : undefined);
|
|
109
|
+
|
|
110
|
+
docking.handleConnectStart(
|
|
111
|
+
{ nodeId: 'source-node', handleId: 'h1', handleType: 'source' },
|
|
112
|
+
getNode
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
expect(docking.connectingHandle).toBe('source');
|
|
116
|
+
expect(docking.connectingNode).toBe(node);
|
|
117
|
+
|
|
118
|
+
docking.handleConnectEnd();
|
|
119
|
+
|
|
120
|
+
expect(docking.connectingHandle).toBe('');
|
|
121
|
+
expect(docking.connectingNode).toBeNull();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('resets all state cleanly', () => {
|
|
125
|
+
const docking = createCanvasDocking();
|
|
126
|
+
const node = createSampleNode('test');
|
|
127
|
+
|
|
128
|
+
docking.handleNodeDragStart({ targetNode: node });
|
|
129
|
+
expect(docking.isDragging).toBe(true);
|
|
130
|
+
|
|
131
|
+
docking.reset();
|
|
132
|
+
expect(docking.isDragging).toBe(false);
|
|
133
|
+
expect(docking.draggedNode).toBeNull();
|
|
134
|
+
expect(docking.draggedInitialPosition).toBeNull();
|
|
135
|
+
});
|
|
136
|
+
});
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
createCanvasGraph,
|
|
4
|
+
calculateGraphDifferences,
|
|
5
|
+
replaceNodeInGraph
|
|
6
|
+
} from '../createCanvasGraph.svelte.js';
|
|
7
|
+
import type { CanvasNode, CanvasEdge } from '../types.js';
|
|
8
|
+
|
|
9
|
+
describe('createCanvasGraph & Graph Operations', () => {
|
|
10
|
+
const createSampleNode = (id: string, x = 0, y = 0): CanvasNode => ({
|
|
11
|
+
id,
|
|
12
|
+
position: { x, y },
|
|
13
|
+
data: { label: `Node ${id}` }
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const createSampleEdge = (id: string, source: string, target: string): CanvasEdge => ({
|
|
17
|
+
id,
|
|
18
|
+
source,
|
|
19
|
+
target
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('initializes with default empty or provided nodes and edges', () => {
|
|
23
|
+
const graph = createCanvasGraph({
|
|
24
|
+
initialNodes: [createSampleNode('1')],
|
|
25
|
+
initialEdges: [createSampleEdge('e1', '1', '2')]
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
expect(graph.nodes).toHaveLength(1);
|
|
29
|
+
expect(graph.edges).toHaveLength(1);
|
|
30
|
+
expect(graph.nodes[0].id).toBe('1');
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('adds nodes and ignores duplicates', () => {
|
|
34
|
+
const onNodesChange = vi.fn();
|
|
35
|
+
const graph = createCanvasGraph({ onNodesChange });
|
|
36
|
+
|
|
37
|
+
graph.addNodeOrNodes(createSampleNode('1'));
|
|
38
|
+
expect(graph.nodes).toHaveLength(1);
|
|
39
|
+
expect(onNodesChange).toHaveBeenCalledTimes(1);
|
|
40
|
+
|
|
41
|
+
// Adding existing node does not duplicate
|
|
42
|
+
graph.addNodeOrNodes(createSampleNode('1'));
|
|
43
|
+
expect(graph.nodes).toHaveLength(1);
|
|
44
|
+
|
|
45
|
+
// Adding multiple nodes
|
|
46
|
+
graph.addNodeOrNodes([createSampleNode('2'), createSampleNode('3')]);
|
|
47
|
+
expect(graph.nodes).toHaveLength(3);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('adds and removes edges cleanly', () => {
|
|
51
|
+
const onEdgesChange = vi.fn();
|
|
52
|
+
const graph = createCanvasGraph({ onEdgesChange });
|
|
53
|
+
|
|
54
|
+
const e1 = createSampleEdge('e1', '1', '2');
|
|
55
|
+
const e2 = createSampleEdge('e2', '2', '3');
|
|
56
|
+
|
|
57
|
+
graph.addEdge(e1);
|
|
58
|
+
expect(graph.edges).toHaveLength(1);
|
|
59
|
+
|
|
60
|
+
graph.addEdges([e2]);
|
|
61
|
+
expect(graph.edges).toHaveLength(2);
|
|
62
|
+
|
|
63
|
+
graph.removeEdges([e1]);
|
|
64
|
+
expect(graph.edges).toHaveLength(1);
|
|
65
|
+
expect(graph.edges[0].id).toBe('e2');
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('removes nodes by reference or ID matching', () => {
|
|
69
|
+
const n1 = createSampleNode('1');
|
|
70
|
+
const n2 = createSampleNode('2');
|
|
71
|
+
const graph = createCanvasGraph({ initialNodes: [n1, n2] });
|
|
72
|
+
|
|
73
|
+
graph.removeNodes([n1]);
|
|
74
|
+
expect(graph.nodes).toHaveLength(1);
|
|
75
|
+
expect(graph.nodes[0].id).toBe('2');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('replaces a node and preserves connected edges when keepEdges is true', () => {
|
|
79
|
+
const n1 = createSampleNode('1');
|
|
80
|
+
const n2 = createSampleNode('2');
|
|
81
|
+
const e1 = createSampleEdge('e1', '1', '2');
|
|
82
|
+
const n1Replacement = createSampleNode('new-1', 10, 10);
|
|
83
|
+
|
|
84
|
+
const result = replaceNodeInGraph([n1, n2], [e1], n1, n1Replacement, true);
|
|
85
|
+
expect(result.nodes.some((n) => n.id === 'new-1')).toBe(true);
|
|
86
|
+
expect(result.nodes.some((n) => n.id === '1')).toBe(false);
|
|
87
|
+
|
|
88
|
+
// Edge should have updated source to new-1
|
|
89
|
+
expect(result.edges).toHaveLength(1);
|
|
90
|
+
expect(result.edges[0].source).toBe('new-1');
|
|
91
|
+
expect(result.edges[0].target).toBe('2');
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
it('replaces a node without preserving edges when keepEdges is false', () => {
|
|
95
|
+
const n1 = createSampleNode('1');
|
|
96
|
+
const n2 = createSampleNode('2');
|
|
97
|
+
const e1 = createSampleEdge('e1', '1', '2');
|
|
98
|
+
const n1Replacement = createSampleNode('new-1', 10, 10);
|
|
99
|
+
|
|
100
|
+
const result = replaceNodeInGraph([n1, n2], [e1], n1, n1Replacement, false);
|
|
101
|
+
expect(result.nodes.some((n) => n.id === 'new-1')).toBe(true);
|
|
102
|
+
expect(result.edges).toHaveLength(1);
|
|
103
|
+
expect(result.edges[0].source).toBe('1'); // Unchanged
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('adds connected nodes connecting inbound and outbound targets', () => {
|
|
107
|
+
const graph = createCanvasGraph();
|
|
108
|
+
const inNode = createSampleNode('in');
|
|
109
|
+
const outNode = createSampleNode('out');
|
|
110
|
+
const midNode = createSampleNode('mid');
|
|
111
|
+
|
|
112
|
+
graph.addNodeOrNodes([inNode, outNode]);
|
|
113
|
+
|
|
114
|
+
graph.addConnectedNodes({
|
|
115
|
+
nodesToAdd: [midNode],
|
|
116
|
+
inboundNodes: [inNode],
|
|
117
|
+
outboundNodes: [outNode],
|
|
118
|
+
getEdgeLabel: (src, tgt) => `${src.id}->${tgt.id}`
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
expect(graph.nodes).toHaveLength(3);
|
|
122
|
+
expect(graph.edges).toHaveLength(2);
|
|
123
|
+
expect(graph.edges.find((e) => e.source === 'in' && e.target === 'mid')?.label).toBe('in->mid');
|
|
124
|
+
expect(graph.edges.find((e) => e.source === 'mid' && e.target === 'out')?.label).toBe('mid->out');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it('accurately calculates graph differences against a baseline', () => {
|
|
128
|
+
const n1 = createSampleNode('1', 0, 0);
|
|
129
|
+
const n2 = createSampleNode('2', 50, 50);
|
|
130
|
+
const e1 = createSampleEdge('e1', '1', '2');
|
|
131
|
+
|
|
132
|
+
const baseline = {
|
|
133
|
+
nodes: [n1, n2],
|
|
134
|
+
edges: [e1]
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// Node 2 position changed, node 3 added, edge 1 removed, edge 2 added
|
|
138
|
+
const n2Changed = createSampleNode('2', 100, 100);
|
|
139
|
+
const n3Added = createSampleNode('3', 200, 200);
|
|
140
|
+
const e2Added = createSampleEdge('e2', '2', '3');
|
|
141
|
+
|
|
142
|
+
const current = {
|
|
143
|
+
nodes: [n1, n2Changed, n3Added],
|
|
144
|
+
edges: [e2Added]
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
const diff = calculateGraphDifferences(current, baseline);
|
|
148
|
+
|
|
149
|
+
expect(diff.changedNodes).toHaveLength(2); // n2 changed + n3 newly added
|
|
150
|
+
expect(diff.changedNodes.map((n) => n.id)).toContain('2');
|
|
151
|
+
expect(diff.changedNodes.map((n) => n.id)).toContain('3');
|
|
152
|
+
expect(diff.removedNodes).toHaveLength(0);
|
|
153
|
+
|
|
154
|
+
expect(diff.removedEdges).toHaveLength(1);
|
|
155
|
+
expect(diff.removedEdges[0].id).toBe('e1');
|
|
156
|
+
expect(diff.changedEdges).toHaveLength(1);
|
|
157
|
+
expect(diff.changedEdges[0].id).toBe('e2');
|
|
158
|
+
});
|
|
159
|
+
});
|