-
-
Notifications
You must be signed in to change notification settings - Fork 178
Expand file tree
/
Copy pathAnchor.svelte
More file actions
725 lines (630 loc) 路 21.4 KB
/
Copy pathAnchor.svelte
File metadata and controls
725 lines (630 loc) 路 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
<script context="module" lang="ts">
import DefaultAnchor from './DefaultAnchor.svelte';
import Edge from '../Edge/Edge.svelte';
import EdgeContext from '../Edge/EdgeContext.svelte';
import { onMount, getContext, onDestroy, afterUpdate } from 'svelte';
import { writable, get } from 'svelte/store';
import { createEdge, createAnchor, generateOutput } from '$lib/utils/creators';
import { createEventDispatcher } from 'svelte';
import type {
Graph,
Node,
Connections,
CSSColorString,
EdgeStyle,
EndStyle,
EdgeConfig
} from '$lib/types';
import type {
Anchor,
Direction,
AnchorKey,
CustomWritable,
AnchorConnectionEvent
} from '$lib/types';
import type { InputType, NodeKey, OutputStore, InputStore, ConnectingFrom } from '$lib/types';
import type { ComponentType } from 'svelte';
import type { Writable, Readable } from 'svelte/store';
let animationFrameId: number;
export const connectingFrom: Writable<ConnectingFrom | null> = writable(null);
export function changeAnchorSide(anchorElement: HTMLElement, newSide: Direction, node: Node) {
if (newSide === 'self') return;
const parentNode = anchorElement.parentNode;
if (!parentNode) return;
// Remove the anchor from its current container
parentNode.removeChild(anchorElement);
// Add the anchor to the new container
const newContainer = document.querySelector(`#anchors-${newSide}-${node.id}`);
if (!newContainer) return;
newContainer.appendChild(anchorElement);
if (anchorElement) node.recalculateAnchors();
}
</script>
<script lang="ts">
const nodeDynamic = getContext<boolean>('dynamic');
const node = getContext<Node>('node');
const edgeStore = getContext<Graph['edges']>('edgeStore');
const cursorAnchor = getContext<Anchor>('cursorAnchor');
const graphDirection = getContext<string>('direction');
const mounted = getContext<Writable<number | true>>('mounted');
const graph = getContext<Graph>('graph');
const nodeStore = getContext<Graph['nodes']>('nodeStore');
const graphEdge = getContext<ComponentType>('graphEdge');
const nodeConnectEvent = getContext<Writable<null | MouseEvent>>('nodeConnectEvent');
const anchorsMounted = getContext<Writable<number>>('anchorsMounted');
const flowChart = getContext<object>('flowchart') || undefined;
export let bgColor: CSSColorString | null = null;
export let id: string | number = 0;
export let input = false;
export let output = false;
export let dataType: string | string[] | undefined = undefined;
/**
* @default dependent on `input` and `output` props
* @description When `true`, the Anchor will accept multiple connections. This is set to true by default
* for output anchors or anchors that have not specified an input/output prop.
*/
export let multiple = output ? true : input ? false : true;
/**
* @default 'false'
* @description When `true`, the Anchor will dynamically change its direction
* based on the relative positioning of connected Nodes
*/
export let dynamic = nodeDynamic || false;
export let edge: ComponentType | null = null;
export let inputsStore: InputStore | null = null;
export let key: string | number | null = null;
export let outputStore: OutputStore | null = null;
export let connections: Connections = [];
export let edgeColor:
| Writable<CSSColorString | null>
| CustomWritable<CSSColorString>
| Readable<CSSColorString> = writable(null);
export let edgeLabel = '';
/**
* @default 'false'
* @description When `true`, connections and disconnections are not allowed. Updates the cursor on hover.
*/
export let locked = false;
/**
* @default 'false'
* @description When `true`, mouse up events on the parent Node will trigger connections to this Anchor. If this value
* is true for multiple Anchors, connections will be assigned in order, unless an Anchor is set to accept multiple connections.
*/
export let nodeConnect = false;
export let edgeStyle: EdgeStyle | null = null;
export let endStyles: Array<EndStyle> = [null, null];
/**
* @default 'false'
* @description When `true`, the default Anchor will not be rendered. It is not necessary to set this to true
* when passing custom Anchors as children. It likely only makes sense to use this
* in combination with the `nodeConnect` prop.
*/
export let invisible = false;
export let direction: Direction =
graphDirection === 'TD' ? (input ? 'north' : 'south') : input ? 'west' : 'east';
export let title = '';
const dispatchConnection = createEventDispatcher<{ connection: AnchorConnectionEvent }>();
const dispatchDisconnection = createEventDispatcher();
let anchorElement: HTMLDivElement;
let tracking = false;
let hovering = false;
let previousConnectionCount = 0;
let type: InputType = input === output ? null : input ? 'input' : 'output';
let assignedConnections: Connections = [];
const nodeEdge = node.edge;
const anchors = node.anchors;
const resizingWidth = node.resizingWidth;
const resizingHeight = node.resizingHeight;
const rotating = node.rotating;
const nodeLevelConnections = node.connections;
$: connecting = $connectingFrom?.anchor === anchor;
$: connectedAnchors = anchor && anchor.connected;
const anchorKey: AnchorKey = `A-${id || anchors.count() + 1}/${node.id}`;
const anchor = createAnchor(
graph,
node,
anchorKey,
{ x: 0, y: 0 },
{ width: 0, height: 0 },
inputsStore || outputStore || null,
edge || nodeEdge || graphEdge || null,
type,
direction,
dynamic,
key,
edgeColor,
dataType
);
anchors.add(anchor, anchor.id);
onMount(() => {
if (anchorElement) anchor.recalculatePosition();
// Need to add this to the Anchor store as a native property
const outputCount = Array.from(get(node.anchors)).reduce((acc, [, anchor]) => {
if (anchor.type === 'output') acc++;
return acc;
}, 0);
if ($nodeLevelConnections?.length && !input) {
const remainingConnections: Connections = [];
let first: number | null = null;
$nodeLevelConnections.forEach((connection, i) => {
if (!connection) return;
if (first === null) first = i;
if ((i - first) % outputCount === 0) {
assignedConnections.push(connection);
remainingConnections.push(null);
} else {
remainingConnections.push(connection);
}
});
$nodeLevelConnections = remainingConnections;
}
$anchorsMounted++;
});
afterUpdate(() => {
if (anchorElement) anchor.recalculatePosition();
});
// When the anchor is destroyed we remove the edge and cancel any animation
onDestroy(() => {
destroy();
cancelAnimationFrame(animationFrameId);
});
$: dynamicDirection = anchor?.direction;
$: if (dynamic && anchorElement) changeAnchorSide(anchorElement, $dynamicDirection, node);
// $: if (!input && $anchorsMounted && $anchorsMounted === node.anchors.count()) {
// console.log('Popping');
// const poppedConnections = $nodeLevelConnections?.pop();
// if (poppedConnections) connections.push(poppedConnections);
// connections = connections;
// }
$: if ($mounted === nodeStore.count() && connections.length) {
checkDirectConnections();
}
$: if (nodeConnect && $nodeConnectEvent) {
handleMouseUp($nodeConnectEvent);
}
// If the user has specifcied connections, we check once all nodes have mounted
$: if ($mounted === nodeStore.count() && assignedConnections.length) {
checkNodeLevelConnections();
}
// If an anchor is added to the store, we update all anchor positions
$: if (anchorElement) {
$anchors;
$connectedAnchors;
$dynamicDirection;
anchor.recalculatePosition();
}
// If the parent node is resizing, we actively track the position of the anchor
$: if (!tracking && ($resizingWidth || $resizingHeight || $rotating)) {
tracking = true;
trackPosition();
} else if (!$resizingWidth && !$resizingHeight && tracking && !$rotating) {
tracking = false;
cancelAnimationFrame(animationFrameId);
}
// This fires the connection/disconnection events
// We track previous connections and fire a correct event accordingly
$: if ($connectedAnchors) {
if ($connectedAnchors.size < previousConnectionCount) {
// Need to add additional detail for disconnections here
dispatchDisconnection('disconnection', { node, anchor });
} else if ($connectedAnchors.size > previousConnectionCount) {
const anchorArray = Array.from($connectedAnchors);
const lastConnection = anchorArray[anchorArray.length - 1];
dispatchConnection('connection', {
node,
anchor,
connectedNode: lastConnection.node,
connectedAnchor: lastConnection
});
}
previousConnectionCount = $connectedAnchors.size;
}
function touchBasedConnection(e: TouchEvent) {
edgeStore.delete('cursor');
const touchPosition = {
x: e.changedTouches[0].clientX,
y: e.changedTouches[0].clientY
};
// This retrieves the child element at the touch position
const otherAnchor = document.elementFromPoint(touchPosition.x, touchPosition.y);
if (!otherAnchor) return;
// This retrieves the parent element of the anchor, which has the ID
const parentElement = otherAnchor.parentElement;
if (!parentElement) return;
const compoundId: AnchorKey = parentElement.id as AnchorKey;
const nodeId = compoundId.split('/')[1] as NodeKey;
const connectingAnchor = nodeStore.get(nodeId)?.anchors.get(compoundId);
if (!connectingAnchor) return;
edgeStore.delete('cursor');
attemptConnection(anchor, connectingAnchor, e);
}
function attemptConnection(source: Anchor, target: Anchor, e: MouseEvent | TouchEvent) {
const success = connectAnchors(source, target);
if (success) {
connectStores();
}
if (!e.shiftKey) {
clearLinking(success);
}
}
function handleMouseUp(e: MouseEvent | TouchEvent) {
// Touchend events fire on the original element rather than the "curent one"
// So we need to check for this case and retieve the anchor to connect to
if ('changedTouches' in e && connecting) {
touchBasedConnection(e);
return;
}
if (connecting) return; // If the anchor initiated the connection, do nothing
// If the anchor receiving the event has connections
// And it can't have multiple connections
// Then this is an invalid connection
// Delete the cursor edge and clear the linking store
if ($connectedAnchors?.size && !multiple) {
edgeStore.delete('cursor');
if (!e.shiftKey) clearLinking(false);
return;
}
// Otherwise, proceed with connection logic
if ($connectingFrom) connectEdge(e);
}
function handleClick(e: MouseEvent | TouchEvent) {
if (locked) return; // Return if the anchor is locked
// If the Anchor being clicked has connections
// And it can't have multiple connections
// And there isn't an active connection being made
// Then this is a disconnection event
if ($connectedAnchors?.size && !multiple && !$connectingFrom) return disconnectEdge();
// If there isn't an active connection being made, start a new edge
if (!$connectingFrom) return startEdge();
// Otherwise, proceed with the edge connection logic
connectEdge(e);
}
// This can be condensed
function startEdge() {
if (input === output) {
$connectingFrom = { anchor, store: null, key: null };
createCursorEdge(anchor, cursorAnchor);
} else if (input) {
$connectingFrom = {
anchor,
store: inputsStore,
key
};
createCursorEdge(cursorAnchor, anchor);
} else if (output) {
$connectingFrom = {
anchor,
store: outputStore,
key: null
};
createCursorEdge(anchor, cursorAnchor);
}
}
function createCursorEdge(source: Anchor, target: Anchor, disconnect = false) {
const edgeConfig: EdgeConfig = {
color: edgeColor,
label: { text: edgeLabel }
};
if (disconnect) edgeConfig.disconnect = true;
if (edgeStyle) edgeConfig.type = edgeStyle;
if (endStyles[0]) edgeConfig.start = endStyles[0];
if (endStyles[1]) edgeConfig.start = endStyles[1];
// Create a temporary edge to track the cursor
const newEdge = createEdge({ source, target }, source?.edge || null, edgeConfig);
// Add the edge to the store
edgeStore.add(newEdge, 'cursor');
}
function connectEdge(e: MouseEvent | TouchEvent) {
// Delete the temporary edge
edgeStore.delete('cursor');
if (!$connectingFrom) return;
const connectingType = $connectingFrom.anchor.type;
if ($connectingFrom.anchor === anchor || (connectingType === anchor.type && connectingType)) {
clearLinking(false);
return;
}
anchor.recalculatePosition();
// Create edge
let source: Anchor;
let target: Anchor;
if (input === output) {
if (connectingType === 'input') {
source = anchor;
target = $connectingFrom.anchor;
} else {
source = $connectingFrom.anchor;
target = anchor;
}
} else if (input) {
source = $connectingFrom.anchor;
target = anchor;
} else {
source = anchor;
target = $connectingFrom.anchor;
}
attemptConnection(source, target, e);
}
// Check if the data types of the source and target anchors are compatible
function matchDataTypes(source: Anchor, target: Anchor): boolean {
if (!source.dataType || !target.dataType) return true;
const sourceDataType = Array.isArray(source.dataType) ? source.dataType : [source.dataType];
const targetDataType = Array.isArray(target.dataType) ? target.dataType : [target.dataType];
return sourceDataType.some((type) => targetDataType.includes(type));
}
// Updates the connected anchors set on source and target
// Creates the edge and add it to the store
function connectAnchors(source: Anchor, target: Anchor) {
// Don't connect an anchor to itself
if (source === target) return false;
// Don't connect if the anchors are already connected
if (get(source.connected).has(anchor)) return false;
// Don't connect if not compatible data types
if (!matchDataTypes(source, target)) return false;
const edgeConfig: EdgeConfig = {
color: edgeColor,
label: { text: edgeLabel }
};
// get edge style from flowchart if edge is defined in flowchart
if (flowChart) {
// check if source is in flowchart and target is a child of the source
const sourceId: string = source.node.id.slice(2);
const sourceInFlowchart = flowChart.nodeList[sourceId]; // type flowchart node obj
// if source is in flowchart
if (sourceInFlowchart) {
const targetId: string = target.node.id.slice(2);
const targetInSourceChildren = sourceInFlowchart.children.filter(
(child) => child.node.id === targetId
)[0];
// check to see if target is its child
if (targetInSourceChildren) {
// configure the edge with data defined in the flowchart
const edgeData = targetInSourceChildren;
edgeConfig.label = { text: edgeData.content };
}
}
}
if (edgeStyle) edgeConfig.type = edgeStyle;
if (endStyles[0]) edgeConfig.start = endStyles[0];
if (endStyles[1]) edgeConfig.start = endStyles[1];
const newEdge = createEdge({ source, target }, source?.edge || null, edgeConfig);
if (!source.node || !target.node) return false;
edgeStore.add(newEdge, new Set([source, target, source.node, target.node]));
return true;
}
// If both anchors have stores, we "link" them
function connectStores() {
if (input && $connectingFrom && $connectingFrom.store) {
if (
$inputsStore &&
key &&
inputsStore &&
typeof inputsStore.set === 'function' &&
typeof inputsStore.update === 'function'
)
$inputsStore[key] = $connectingFrom.store;
} else if (output && $connectingFrom && $connectingFrom.store) {
const { store, key } = $connectingFrom;
if (store && key && typeof store.update === 'function')
store.update((store) => {
if (!outputStore) return store;
store[key] = outputStore;
return store;
});
}
}
function disconnectStore() {
if ($inputsStore && key && $inputsStore[key])
$inputsStore[key] = writable(get($inputsStore[key]));
}
function clearLinking(connectionMade: boolean) {
if (connectionMade || !$nodeConnectEvent) {
$connectingFrom = null;
$nodeConnectEvent = null;
}
}
// This just repeatedly calls updatePosition until cancelled
function trackPosition() {
if (!tracking) return;
if (anchorElement) anchor.recalculatePosition();
animationFrameId = requestAnimationFrame(trackPosition);
}
// Destroy the edge and disconnect the anchors/stores
function destroy() {
// return;
edgeStore.delete('cursor');
// Get all edges connected to this anchor
const connections = edgeStore.match(anchor);
// Delete them from the store
connections.forEach((edge) => edgeStore.delete(edge));
clearLinking(false);
disconnectStore();
}
// Disconnect edge and create a new cursor edge
function disconnectEdge() {
if (get(anchor.connected).size > 1) return;
const source = Array.from(get(anchor.connected))[0];
if (source.type === 'input') return;
destroy();
if (source.type === 'output') {
createCursorEdge(source, cursorAnchor, true);
disconnectStore();
const store: ReturnType<typeof generateOutput> = source.store as ReturnType<
typeof generateOutput
>;
$connectingFrom = { anchor: source, store, key: null };
} else {
createCursorEdge(source, cursorAnchor, true);
$connectingFrom = { anchor: source, store: null, key: null };
}
}
function checkNodeLevelConnections() {
assignedConnections.forEach((connection, index) => {
if (!connection) return;
const connected = processConnection(connection);
if (connected) connections[index] = null;
});
assignedConnections = assignedConnections.filter((connection) => connection !== null);
}
function checkDirectConnections() {
connections.forEach((connection) => {
if (!connection) return;
processConnection(connection);
// if (connected) connections[index] = null;
});
// connections = connections.filter((connection) => connection !== null);
}
export function disconnect(target: [string | number, string | number]) {
const nodekey: NodeKey = `N-${target[0]}`;
const node = nodeStore.get(nodekey);
if (!node) return;
const targetAnchor = node.anchors.get(`A-${target[1]}/N-${target[0]}`);
if (!targetAnchor) return;
const edgeKey = edgeStore.match(anchor, targetAnchor);
if (!edgeKey) return;
edgeStore.delete(edgeKey[0]);
}
const processConnection = (connection: [string | number, string | number] | string | number) => {
let nodeId: string;
let anchorId: string | null;
let anchorToConnect: Anchor | null = null;
if (Array.isArray(connection)) {
nodeId = connection[0].toString();
anchorId = connection[1].toString();
} else {
nodeId = connection.toString();
anchorId = null;
}
//Convert to node key used in store/DOM
const nodekey: NodeKey = `N-${nodeId}`;
// Look up node in store
const nodeToConnect = nodeStore.get(nodekey);
if (!nodeToConnect) {
return false;
}
if (!anchorId) {
// Connect to the anchor with the fewest connections
const anchorStore = get(nodeToConnect.anchors);
const anchors = Array.from(anchorStore.values());
if (!anchors.length) {
return false;
}
anchorToConnect = anchors.reduce<Anchor | null>((a, b) => {
if (!a && b.type === 'output') return null;
if (b.type === 'output') return a;
if (!a) return b;
if (get(b.connected).size < get(a.connected).size) return b;
return a;
}, null);
} else {
// Create anchor key
const anchorKey: AnchorKey = `A-${anchorId}/${nodekey}`;
// Look up anchor in store
anchorToConnect = nodeToConnect.anchors.get(anchorKey) || null;
}
if (!anchorToConnect) {
return false;
}
connectAnchors(anchor, anchorToConnect);
if (anchorToConnect.store && (inputsStore || outputStore)) {
if (input && anchorToConnect.type === 'output') {
if (
$inputsStore &&
key &&
inputsStore &&
typeof inputsStore.set === 'function' &&
typeof inputsStore.update === 'function'
)
$inputsStore[key] = anchorToConnect.store;
} else if (output && anchorToConnect.type === 'input') {
const { store, inputKey } = anchorToConnect;
if (store && inputKey && typeof store.update === 'function')
store.update((store) => {
if (!outputStore) return store;
store[inputKey] = outputStore;
return store;
});
}
}
return true;
};
</script>
<div
id={anchor?.id}
class="anchor-wrapper"
role="button"
tabindex="0"
class:locked
title={title || ''}
on:mouseenter={() => (hovering = true)}
on:mouseleave={() => (hovering = false)}
on:mousedown|stopPropagation|preventDefault={handleClick}
on:mouseup|stopPropagation={handleMouseUp}
on:touchstart|stopPropagation|preventDefault={handleClick}
on:touchend|stopPropagation={handleMouseUp}
bind:this={anchorElement}
>
<slot linked={$connectedAnchors?.size >= 1} {hovering} {connecting}>
{#if !invisible}
<DefaultAnchor
{output}
{input}
{connecting}
{hovering}
{bgColor}
connected={$connectedAnchors?.size >= 1}
/>
{/if}
</slot>
</div>
{#each Array.from($connectedAnchors) as target (target.id)}
{@const edge = edgeStore.fetch(anchor, target)}
{#if edge && edge.source === anchor}
{@const CustomEdge = edge.component}
<EdgeContext {edge}>
<slot name="edge">
{#if CustomEdge}
<CustomEdge />
{:else}
<Edge />
{/if}
</slot>
</EdgeContext>
{/if}
{/each}
{#if connecting}
{@const edge = edgeStore.get('cursor')}
{#if edge}
{@const CustomEdge = edge.component}
<EdgeContext {edge}>
<slot name="edge">
{#if CustomEdge}
<CustomEdge />
{:else}
<Edge />
{/if}
</slot>
</EdgeContext>
{/if}
{/if}
<style>
* {
box-sizing: border-box;
}
.anchor-wrapper {
z-index: 10;
width: fit-content;
height: fit-content;
pointer-events: all;
}
.locked {
cursor: not-allowed !important;
}
div {
background: none;
border: none;
padding: 0;
font: inherit;
cursor: pointer;
outline: inherit;
}
</style>