-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
InternalNode.svelte
380 lines (331 loc) 路 10.8 KB
/
InternalNode.svelte
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
<script context="module" lang="ts">
import { initialClickPosition, tracking } from '$lib/stores';
import { captureGroup, calculateFitContentWidth } from '$lib/utils';
import { getContext, onDestroy, onMount, setContext } from 'svelte';
import { createEventDispatcher } from 'svelte';
import { get } from 'svelte/store';
import type { Writable } from 'svelte/store';
import type { Node, Graph } from '$lib/types';
import type { GroupKey, Group } from '$lib/types';
</script>
<script lang="ts">
// Context
const mounted = getContext<Writable<number>>('mounted');
const duplicate = getContext<Writable<boolean>>('duplicate');
const graphDOMElement = getContext<Writable<HTMLElement>>('graphDOMElement');
const dispatch = createEventDispatcher();
// Props
export let node: Node;
export let isDefault: boolean;
export let center: boolean;
export let nodeStore: Graph['nodes'];
export let locked: Graph['locked'];
export let groups: Graph['groups'];
export let maxZIndex: Graph['maxZIndex'];
export let centerPoint: Graph['center'];
export let cursor: Graph['cursor'];
export let initialNodePositions: Graph['initialNodePositions'];
export let activeGroup: Graph['activeGroup'];
export let editing: Graph['editing'];
// External stores
const id = node.id;
const position = node.position;
const widthStore = node.dimensions.width;
const heightStore = node.dimensions.height;
const selectionColor = node.selectionColor;
const editable = node.editable;
const nodeLock = node.locked;
const zIndex = node.zIndex;
const bgColor = node.bgColor;
const borderRadius = node.borderRadius;
const textColor = node.textColor;
const group = node.group;
const borderColor = node.borderColor;
const borderWidth = node.borderWidth;
const rotation = node.rotation;
const { selected: selectedNodeGroup, hidden: hiddenNodesGroup } = $groups;
const hiddenNodes = hiddenNodesGroup.nodes;
const selectedNodes = selectedNodeGroup.nodes;
// Reactive variables
let collapsed = false;
let minWidth = 200;
let minHeight = 100;
let DOMnode: HTMLElement;
// Subscriptions
$: actualPosition = $position;
// Reactive declarations
$: selected = $selectedNodes.has(node); // Used as class directive
$: hidden = $hiddenNodes.has(node); // Used as class directive
// If the node is selected and the duplicate key pair is pressed
// Dispatch the duplicate event
$: if (selected && $duplicate) {
dispatch('duplicate', node);
}
setContext<Node>('node', node);
// Lifecycle methods
onMount(() => {
// If the node dimensions got set in previous steps, we don't need to do anything
if (!$widthStore && !$heightStore) {
// This only runs when a width and height were not provided via props
// Set the wrapper to fit-content and grab the width and height
[minWidth, minHeight] = calculateFitContentWidth(DOMnode);
// Update the node dimensions in the store
$widthStore = minWidth;
$heightStore = minHeight;
}
if (center) {
const opticalCenter = {
x: $centerPoint.x - $widthStore / 2,
y: $centerPoint.y - $heightStore / 2
};
node.position.set(opticalCenter);
tracking.set(true);
tracking.set(false);
}
$mounted++;
});
onDestroy(() => {
// Remove the node from the selected nodes group
// If it is selected
if (selected) {
$selectedNodes.delete(node);
$selectedNodes = $selectedNodes;
}
// Decrement the store value for mounted nodes
$mounted--;
});
function toggleSelected() {
if (selected) {
if (node) $selectedNodes.delete(node);
$selectedNodes = $selectedNodes;
} else {
if (node) $selectedNodes.add(node);
$selectedNodes = $selectedNodes;
}
}
// This doesn't really do anything at the moment
function handleKeydown(e: KeyboardEvent) {
// If node is focused, hitting enter will toggle the selected state
if (e.key === 'Enter') {
toggleSelected();
} else if (e.key === 'Backspace') {
$nodeStore.delete(node.id);
$nodeStore = $nodeStore;
}
}
// Initial handler for a touch event on a node
function handleNodeTouch(e: TouchEvent) {
$graphDOMElement.focus();
e.stopPropagation();
e.preventDefault();
if (e.touches.length > 1) return; // If the user is using more than one finger, don't do anything
if ($locked || $nodeLock) return; // If the node is locked, don't do anything
// If the node is Node is not currently on top, bring it to the front
// Unless the zIndex prop has been set to infinity
if ($zIndex !== $maxZIndex && $zIndex !== Infinity) $zIndex = ++$maxZIndex;
// Dispatch our nodeClicked event for developer use
dispatch('nodeClicked', { node, e });
// Capture the initial touch position
$initialClickPosition = $cursor;
// Handle the node selection logic
nodeSelectLogic(e);
}
// Initial handler for a click event on a node
function handleNodeClicked(e: MouseEvent) {
$graphDOMElement.focus();
const targetElement = e.target as HTMLElement; // Cast e.target to HTMLElement
// Bring node to front regardless of event target
if ($zIndex !== $maxZIndex && $zIndex !== Infinity) $zIndex = ++$maxZIndex;
// If the event target is an input, don't do anything
if (targetElement.tagName === 'INPUT') return;
//Dispatch nodeClick event fo rdeveloper use
dispatch('nodeClicked', { node, e });
// Stop event from propagating to other mousedown listeners
e.stopPropagation();
// Prevent the default behavir of text selection on drag
// May be safe to move this to the global mouse move listener
e.preventDefault();
// If the node or graph is locked, don't do anything
if ($locked || $nodeLock) return;
// Set our global tracking boolean to true
$tracking = true;
// Capture the initial click position
$initialClickPosition = $cursor;
// Right click sets editing node
if (e.button === 2 && $editable) {
$editing = node;
}
// Handle selection logic
nodeSelectLogic(e);
}
function nodeSelectLogic(e: MouseEvent | TouchEvent) {
let groupData: Group;
let parent;
let isParent = false;
// Check if the node is in a group
const nodeGroup: GroupKey | null = $group;
// If it is in a group, check if it's the parent
if (nodeGroup) {
groupData = $groups[nodeGroup];
parent = get(groupData.parent);
isParent = parent === node;
}
// If it is the parent, set the active group to the group
// If it isn't the parent, set the active group to "selected"
if (isParent) {
$activeGroup = nodeGroup;
} else {
$activeGroup = 'selected';
}
// If you click on a node that is already selected
if (!e.shiftKey && selected) {
$activeGroup = 'selected';
} else {
// If you click on a new node outside of the current group, clear the group
if (!e.shiftKey && !selected && !e.shiftKey) {
$selectedNodes.clear();
$selectedNodes = $selectedNodes;
}
// Toggle the selected state of the node
toggleSelected();
}
// Capture the initial positions of the nodes in the group
$initialNodePositions = captureGroup($groups['selected'].nodes);
}
// Delete the node from the store
function destroy() {
nodeStore.delete(id);
}
import { writable } from 'svelte/store';
const nodeConnectEvent = writable<null | MouseEvent>(null);
setContext('nodeConnectEvent', nodeConnectEvent);
function onMouseUp(e: MouseEvent) {
const mouseDeltaX = $cursor.x - $initialClickPosition.x;
const mouseDeltaY = $cursor.y - $initialClickPosition.y;
const combinedDelta = Math.abs(mouseDeltaX) + Math.abs(mouseDeltaY);
if (combinedDelta < 4) dispatch('nodeReleased', { e });
$nodeConnectEvent = e;
}
// Custom action to handle Node interactions
function grabHandle(node: HTMLElement) {
node.addEventListener('mousedown', handleNodeClicked);
node.addEventListener('touchstart', handleNodeTouch);
return {
destroy() {
node.removeEventListener('mousedown', handleNodeClicked);
node.removeEventListener('touchstart', handleNodeTouch);
}
};
}
</script>
<!-- svelte-ignore a11y-non-interactive-element -->
{#if !hidden}
<div
{id}
class="svelvet-node"
class:selected
class:locked={$locked || $nodeLock}
style:top="{actualPosition.y}px"
style:left="{actualPosition.x}px"
style:width="{$widthStore}px"
style:height="{$heightStore}px"
style:z-index={$zIndex}
style:transform="rotate({$rotation}deg)"
style:--prop-background-color={$bgColor || (isDefault ? null : 'transparent')}
style:--prop-text-color={$textColor}
style:--prop-border-color={$borderColor}
style:--prop-selection-color={$selectionColor}
style:--prop-border-radius={$borderRadius ? `${$borderRadius}px` : isDefault ? null : '0px'}
style:--prop-border-width={$borderWidth || (isDefault ? null : '0px')}
on:contextmenu|preventDefault|stopPropagation
on:keydown|preventDefault|self={handleKeydown}
on:mouseup={onMouseUp}
use:grabHandle
bind:clientWidth={$widthStore}
bind:clientHeight={$heightStore}
bind:this={DOMnode}
tabIndex={0}
>
{#if !collapsed}
<slot {grabHandle} {selected} {destroy} />
<div id={`anchors-west-${node.id}`} class="anchors left" />
<div id={`anchors-east-${node.id}`} class="anchors right" />
<div id={`anchors-north-${node.id}`} class="anchors top" />
<div id={`anchors-south-${node.id}`} class="anchors bottom" />
{/if}
</div>
{/if}
<style>
.svelvet-node {
position: absolute;
pointer-events: all;
display: flex;
justify-content: center;
align-items: center;
will-change: top, left;
cursor: var(--node-cursor, var(--default-node-cursor));
--final-border-width: var(
--prop-border-width,
var(--node-border-width, var(--default-node-border-width))
);
--final-border-color: var(
--prop-border-color,
var(--node-border-color, var(--default-node-border-color))
);
--final-selection-color: var(
--prop-selection-color,
var(--node-selection-color, var(--default-node-selection-color))
);
border-radius: var(
--prop-border-radius,
var(--node-border-radius, var(--default-node-border-radius))
);
background-color: var(--prop-background-color, var(--node-color, var(--default-node-color)));
color: var(--prop-text-color, var(--text-color, var(--default-text-color)));
box-shadow: 0 0 0 var(--final-border-width) var(--final-border-color),
var(--default-node-shadow);
}
.anchors {
/* outline: solid 1px red; */
display: flex;
position: absolute;
justify-content: center;
align-items: center;
z-index: 1;
pointer-events: none;
}
.top,
.bottom {
width: 100%;
justify-content: space-around;
}
.top {
transform: translate(0px, -50%);
top: 0px;
}
.bottom {
transform: translate(0px, 50%);
bottom: 0px;
}
.left,
.right {
height: 100%;
flex-direction: column;
justify-content: space-around;
}
.left {
transform: translate(-50%);
left: 0px;
}
.right {
transform: translate(50%);
right: 0px;
}
.locked {
cursor: not-allowed;
}
.selected {
box-shadow: 0 0 0 var(--final-border-width) var(--final-selection-color),
var(--default-node-shadow);
}
</style>