-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathGraphEditor.vue
647 lines (599 loc) · 21.4 KB
/
GraphEditor.vue
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
<script setup lang="ts">
import { codeEditorBindings, graphBindings, interactionBindings } from '@/bindings'
import CodeEditor from '@/components/CodeEditor.vue'
import ComponentBrowser from '@/components/ComponentBrowser.vue'
import {
collapsedNodePlacement,
mouseDictatedPlacement,
nonDictatedPlacement,
previousNodeDictatedPlacement,
type Environment,
} from '@/components/ComponentBrowser/placement'
import GraphEdges from '@/components/GraphEditor/GraphEdges.vue'
import GraphNodes from '@/components/GraphEditor/GraphNodes.vue'
import { performCollapse, prepareCollapsedInfo } from '@/components/GraphEditor/collapsing'
import { Uploader, uploadedExpression } from '@/components/GraphEditor/upload'
import GraphMouse from '@/components/GraphMouse.vue'
import PlusButton from '@/components/PlusButton.vue'
import TopBar from '@/components/TopBar.vue'
import { useDoubleClick } from '@/composables/doubleClick'
import { keyboardBusy, keyboardBusyExceptIn, useEvent } from '@/composables/events'
import { useStackNavigator } from '@/composables/stackNavigator'
import { provideGraphNavigator } from '@/providers/graphNavigator'
import { provideGraphSelection } from '@/providers/graphSelection'
import { provideInteractionHandler } from '@/providers/interactionHandler'
import { provideWidgetRegistry } from '@/providers/widgetRegistry'
import { useGraphStore, type NodeId } from '@/stores/graph'
import type { RequiredImport } from '@/stores/graph/imports'
import { useProjectStore } from '@/stores/project'
import { groupColorVar, useSuggestionDbStore } from '@/stores/suggestionDatabase'
import { bail } from '@/util/assert'
import type { AstId, NodeMetadataFields } from '@/util/ast/abstract'
import { colorFromString } from '@/util/colors'
import { Rect } from '@/util/data/rect'
import { Vec2 } from '@/util/data/vec2'
import * as set from 'lib0/set'
import { toast } from 'react-toastify'
import { computed, onMounted, onScopeDispose, onUnmounted, ref, watch } from 'vue'
import { ProjectManagerEvents } from '../../../ide-desktop/lib/dashboard/src/utilities/ProjectManager'
import { type Usage } from './ComponentBrowser/input'
// Assumed size of a newly created node. This is used to place the component browser.
const DEFAULT_NODE_SIZE = new Vec2(0, 24)
const gapBetweenNodes = 48.0
const viewportNode = ref<HTMLElement>()
const graphNavigator = provideGraphNavigator(viewportNode)
const graphStore = useGraphStore()
const widgetRegistry = provideWidgetRegistry(graphStore.db)
widgetRegistry.loadBuiltins()
const projectStore = useProjectStore()
const componentBrowserVisible = ref(false)
const componentBrowserNodePosition = ref<Vec2>(Vec2.Zero)
const componentBrowserUsage = ref<Usage>({ type: 'newNode' })
const suggestionDb = useSuggestionDbStore()
const interaction = provideInteractionHandler()
/// === UI Messages and Errors ===
function initStartupToast() {
let startupToast = toast.info('Initializing the project. This can take up to one minute.', {
autoClose: false,
})
const removeToast = () => toast.dismiss(startupToast)
projectStore.firstExecution.then(removeToast)
onScopeDispose(removeToast)
}
function initConnectionLostToast() {
let connectionLostToast = 'connectionLostToast'
document.addEventListener(
ProjectManagerEvents.loadingFailed,
() => {
toast.error('Lost connection to Language Server.', {
autoClose: false,
toastId: connectionLostToast,
})
},
{ once: true },
)
onUnmounted(() => {
toast.dismiss(connectionLostToast)
})
}
projectStore.lsRpcConnection.then(
(ls) => {
ls.client.onError((err) => {
toast.error(`Language server error: ${err}`)
})
},
(err) => {
toast.error(`Connection to language server failed: ${JSON.stringify(err)}`)
},
)
projectStore.executionContext.on('executionFailed', (err) => {
toast.error(`Execution Failed: ${JSON.stringify(err)}`, {})
})
onMounted(() => {
initStartupToast()
initConnectionLostToast()
})
const nodeSelection = provideGraphSelection(graphNavigator, graphStore.nodeRects, {
onSelected(id) {
graphStore.db.moveNodeToTop(id)
},
})
const interactionBindingsHandler = interactionBindings.handler({
cancel: () => interaction.handleCancel(),
click: (e) => (e instanceof PointerEvent ? interaction.handleClick(e, graphNavigator) : false),
})
// Return the environment for the placement of a new node. The passed nodes should be the nodes that are
// used as the source of the placement. This means, for example, the selected nodes when creating from a selection
// or the node that is being edited when creating from a port double click.
function environmentForNodes(nodeIds: IterableIterator<NodeId>): Environment {
const nodeRects = graphStore.visibleNodeAreas
const selectedNodeRects = [...nodeIds]
.map((id) => graphStore.vizRects.get(id) ?? graphStore.nodeRects.get(id))
.filter((item): item is Rect => item !== undefined)
const screenBounds = graphNavigator.viewport
const mousePosition = graphNavigator.sceneMousePos
return { nodeRects, selectedNodeRects, screenBounds, mousePosition } as Environment
}
const placementEnvironment = computed(() => environmentForNodes(nodeSelection.selected.values()))
/** Return the position for a new node, assuming there are currently nodes selected. If there are no nodes
* selected, return `undefined`. */
function placementPositionForSelection() {
const hasNodeSelected = nodeSelection.selected.size > 0
if (!hasNodeSelected) return
const gapBetweenNodes = 48.0
return previousNodeDictatedPlacement(DEFAULT_NODE_SIZE, placementEnvironment.value, {
horizontalGap: gapBetweenNodes,
verticalGap: gapBetweenNodes,
}).position
}
/** Where the component browser should be placed when it is opened. */
function targetComponentBrowserNodePosition() {
const editedInfo = graphStore.editedNodeInfo
const isEditingNode = editedInfo != null
if (isEditingNode) {
const targetNode = graphStore.db.nodeIdToNode.get(editedInfo.id)
return targetNode?.position ?? Vec2.Zero
} else {
return (
placementPositionForSelection() ??
mouseDictatedPlacement(DEFAULT_NODE_SIZE, placementEnvironment.value).position
)
}
}
function sourcePortForSelection() {
if (graphStore.editedNodeInfo != null) return undefined
const firstSelectedNode = set.first(nodeSelection.selected)
return graphStore.db.getNodeFirstOutputPort(firstSelectedNode)
}
useEvent(window, 'keydown', (event) => {
interactionBindingsHandler(event) ||
(!keyboardBusy() && graphBindingsHandler(event)) ||
(!keyboardBusyExceptIn(codeEditorArea.value) && codeEditorHandler(event))
})
useEvent(window, 'pointerdown', interactionBindingsHandler, { capture: true })
onMounted(() => viewportNode.value?.focus())
function zoomToSelected() {
if (!viewportNode.value) return
let left = Infinity
let top = Infinity
let right = -Infinity
let bottom = -Infinity
const nodesToCenter =
nodeSelection.selected.size === 0 ? graphStore.db.nodeIdToNode.keys() : nodeSelection.selected
for (const id of nodesToCenter) {
const rect = graphStore.vizRects.get(id) ?? graphStore.nodeRects.get(id)
if (!rect) continue
left = Math.min(left, rect.left)
right = Math.max(right, rect.right)
top = Math.min(top, rect.top)
bottom = Math.max(bottom, rect.bottom)
}
graphNavigator.panAndZoomTo(
Rect.FromBounds(left, top, right, bottom),
0.1,
Math.max(1, graphNavigator.scale),
)
}
const graphBindingsHandler = graphBindings.handler({
undo() {
projectStore.module?.undoManager.undo()
},
redo() {
projectStore.module?.undoManager.redo()
},
startProfiling() {
projectStore.lsRpcConnection.then((ls) => ls.profilingStart(true))
},
stopProfiling() {
projectStore.lsRpcConnection.then((ls) => ls.profilingStop())
},
openComponentBrowser() {
if (keyboardBusy()) return false
if (graphNavigator.sceneMousePos != null && !componentBrowserVisible.value) {
showComponentBrowser()
}
},
newNode() {
if (keyboardBusy()) return false
if (graphNavigator.sceneMousePos != null) {
graphStore.createNode(graphNavigator.sceneMousePos, 'hello "world"! 123 + x')
}
},
deleteSelected() {
graphStore.transact(() => {
graphStore.deleteNodes([...nodeSelection.selected])
nodeSelection.selected.clear()
})
},
zoomToSelected() {
zoomToSelected()
},
selectAll() {
if (keyboardBusy()) return
nodeSelection.selectAll()
},
deselectAll() {
nodeSelection.deselectAll()
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur()
}
graphStore.stopCapturingUndo()
},
toggleVisualization() {
if (keyboardBusy()) return false
graphStore.transact(() => {
const allVisible = set
.toArray(nodeSelection.selected)
.every((id) => !(graphStore.db.nodeIdToNode.get(id)?.vis?.visible !== true))
for (const nodeId of nodeSelection.selected) {
graphStore.setNodeVisualizationVisible(nodeId, !allVisible)
}
})
},
copyNode() {
if (keyboardBusy()) return false
copyNodeContent()
},
pasteNode() {
if (keyboardBusy()) return false
readNodeFromClipboard()
},
collapse() {
if (keyboardBusy()) return false
const selected = new Set(nodeSelection.selected)
if (selected.size == 0) return
try {
const info = prepareCollapsedInfo(selected, graphStore.db)
const currentMethod = projectStore.executionContext.getStackTop()
const currentMethodName = graphStore.db.stackItemToMethodName(currentMethod)
if (currentMethodName == null) {
bail(`Cannot get the method name for the current execution stack item. ${currentMethod}`)
}
const currentFunctionEnv = environmentForNodes(selected.values())
const topLevel = graphStore.topLevel
if (!topLevel) {
bail('BUG: no top level, collapsing not possible.')
}
const { position } = collapsedNodePlacement(DEFAULT_NODE_SIZE, currentFunctionEnv)
graphStore.edit((edit) => {
const { refactoredNodeId, collapsedNodeIds, outputNodeId } = performCollapse(
info,
edit.getVersion(topLevel),
graphStore.db,
currentMethodName,
)
const collapsedFunctionEnv = environmentForNodes(collapsedNodeIds.values())
// For collapsed function, only selected nodes would affect placement of the output node.
collapsedFunctionEnv.nodeRects = collapsedFunctionEnv.selectedNodeRects
edit
.get(refactoredNodeId)
.mutableNodeMetadata()
.set('position', { x: position.x, y: position.y })
if (outputNodeId != null) {
const { position } = previousNodeDictatedPlacement(
DEFAULT_NODE_SIZE,
collapsedFunctionEnv,
)
edit
.get(outputNodeId)
.mutableNodeMetadata()
.set('position', { x: position.x, y: position.y })
}
})
} catch (err) {
console.log('Error while collapsing, this is not normal.', err)
}
},
enterNode() {
if (keyboardBusy()) return false
const selectedNode = set.first(nodeSelection.selected)
if (selectedNode) {
stackNavigator.enterNode(selectedNode)
}
},
exitNode() {
if (keyboardBusy()) return false
stackNavigator.exitNode()
},
})
const { handleClick } = useDoubleClick(
(e: PointerEvent) => {
graphBindingsHandler(e)
},
() => {
stackNavigator.exitNode()
},
)
const codeEditorArea = ref<HTMLElement>()
const showCodeEditor = ref(false)
const codeEditorHandler = codeEditorBindings.handler({
toggle() {
showCodeEditor.value = !showCodeEditor.value
},
})
/** Handle record-once button presses. */
function onRecordOnceButtonPress() {
projectStore.lsRpcConnection.then(async () => {
const modeValue = projectStore.executionMode
if (modeValue == undefined) {
return
}
projectStore.executionContext.recompute('all', 'Live')
})
}
// Watch for changes in the execution mode.
watch(
() => projectStore.executionMode,
(modeValue) => {
projectStore.executionContext.setExecutionEnvironment(modeValue === 'live' ? 'Live' : 'Design')
},
)
const groupColors = computed(() => {
const styles: { [key: string]: string } = {}
for (let group of suggestionDb.groups) {
styles[groupColorVar(group)] = group.color ?? colorFromString(group.name)
}
return styles
})
function showComponentBrowser(nodePosition?: Vec2, usage?: Usage) {
componentBrowserUsage.value = usage ?? { type: 'newNode', sourcePort: sourcePortForSelection() }
componentBrowserNodePosition.value = nodePosition ?? targetComponentBrowserNodePosition()
componentBrowserVisible.value = true
}
function startCreatingNodeFromButton() {
const targetPos =
placementPositionForSelection() ??
nonDictatedPlacement(DEFAULT_NODE_SIZE, placementEnvironment.value).position
showComponentBrowser(targetPos)
}
function hideComponentBrowser() {
graphStore.editedNodeInfo = undefined
componentBrowserVisible.value = false
}
function commitComponentBrowser(content: string, requiredImports: RequiredImport[]) {
if (content != null) {
if (graphStore.editedNodeInfo) {
// We finish editing a node.
graphStore.setNodeContent(graphStore.editedNodeInfo.id, content)
} else if (content != '') {
// We finish creating a new node.
const metadata = undefined
const createdNode = graphStore.createNode(
componentBrowserNodePosition.value,
content,
metadata,
requiredImports,
)
if (createdNode) nodeSelection.setSelection(new Set([createdNode]))
}
}
hideComponentBrowser()
}
// Watch the `editedNode` in the graph store
watch(
() => graphStore.editedNodeInfo,
(editedInfo) => {
if (editedInfo) {
showComponentBrowser(undefined, {
type: 'editNode',
node: editedInfo.id,
cursorPos: editedInfo.initialCursorPos,
})
} else {
hideComponentBrowser()
}
},
)
async function handleFileDrop(event: DragEvent) {
// A vertical gap between created nodes when multiple files were dropped together.
const MULTIPLE_FILES_GAP = 50
if (!event.dataTransfer?.items) return
;[...event.dataTransfer.items].forEach(async (item, index) => {
try {
if (item.kind === 'file') {
const file = item.getAsFile()
if (!file) return
const clientPos = new Vec2(event.clientX, event.clientY)
const offset = new Vec2(0, index * -MULTIPLE_FILES_GAP)
const pos = graphNavigator.clientToScenePos(clientPos).add(offset)
const uploader = await Uploader.Create(
projectStore.lsRpcConnection,
projectStore.dataConnection,
projectStore.contentRoots,
projectStore.awareness,
file,
pos,
projectStore.isOnLocalBackend,
event.shiftKey,
projectStore.executionContext.getStackTop(),
)
const uploadResult = await uploader.upload()
graphStore.createNode(pos, uploadedExpression(uploadResult))
}
} catch (err) {
console.error(`Uploading file failed. ${err}`)
}
})
}
// === Clipboard ===
const ENSO_MIME_TYPE = 'web application/enso'
/** The data that is copied to the clipboard. */
interface ClipboardData {
nodes: CopiedNode[]
}
/** Node data that is copied to the clipboard. Used for serializing and deserializing the node information. */
interface CopiedNode {
expression: string
metadata: NodeMetadataFields | undefined
}
/** Copy the content of the selected node to the clipboard. */
function copyNodeContent() {
const id = nodeSelection.selected.values().next().value
const node = graphStore.db.nodeIdToNode.get(id)
if (!node) return
const content = node.rootSpan.code()
const nodeMetadata = node.rootSpan.nodeMetadata
const metadata = {
position: nodeMetadata.get('position'),
visualization: nodeMetadata.get('visualization'),
}
const copiedNode: CopiedNode = { expression: content, metadata }
const clipboardData: ClipboardData = { nodes: [copiedNode] }
const jsonItem = new Blob([JSON.stringify(clipboardData)], { type: ENSO_MIME_TYPE })
const textItem = new Blob([content], { type: 'text/plain' })
const clipboardItem = new ClipboardItem({ [jsonItem.type]: jsonItem, [textItem.type]: textItem })
navigator.clipboard.write([clipboardItem])
}
async function retrieveDataFromClipboard(): Promise<ClipboardData | undefined> {
const clipboardItems = await navigator.clipboard.read()
let fallback = undefined
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
if (type === ENSO_MIME_TYPE) {
const blob = await clipboardItem.getType(type)
return JSON.parse(await blob.text())
}
if (type === 'text/html') {
const blob = await clipboardItem.getType(type)
const htmlContent = await blob.text()
const excelPayload = await readNodeFromExcelClipboard(htmlContent, clipboardItem)
if (excelPayload) {
return excelPayload
}
}
if (type === 'text/plain') {
const blob = await clipboardItem.getType(type)
const fallbackExpression = await blob.text()
const fallbackNode = { expression: fallbackExpression, metadata: undefined } as CopiedNode
fallback = { nodes: [fallbackNode] } as ClipboardData
}
}
}
return fallback
}
/// Read the clipboard and if it contains valid data, create a node from the content.
async function readNodeFromClipboard() {
let clipboardData = await retrieveDataFromClipboard()
if (!clipboardData) {
console.warn('No valid data in clipboard.')
return
}
const copiedNode = clipboardData.nodes[0]
if (!copiedNode) {
console.warn('No valid node in clipboard.')
return
}
if (copiedNode.expression == null) {
console.warn('No valid expression in clipboard.')
}
graphStore.createNode(
graphNavigator.sceneMousePos ?? Vec2.Zero,
copiedNode.expression,
copiedNode.metadata,
)
}
async function readNodeFromExcelClipboard(
htmlContent: string,
clipboardItem: ClipboardItem,
): Promise<ClipboardData | undefined> {
// Check we have a valid HTML table
// If it is Excel, we should have a plain-text version of the table with tab separators.
if (
clipboardItem.types.includes('text/plain') &&
htmlContent.startsWith('<table ') &&
htmlContent.endsWith('</table>')
) {
const textData = await clipboardItem.getType('text/plain')
const text = await textData.text()
const payload = JSON.stringify(text).replaceAll(/^"|"$/g, '').replaceAll("'", "\\'")
const expression = `'${payload}'.to Table`
return { nodes: [{ expression: expression, metadata: undefined }] } as ClipboardData
}
return undefined
}
function handleNodeOutputPortDoubleClick(id: AstId) {
const srcNode = graphStore.db.getPatternExpressionNodeId(id)
if (srcNode == null) {
console.error('Impossible happened: Double click on port not belonging to any node: ', id)
return
}
const placementEnvironment = environmentForNodes([srcNode].values())
const position = previousNodeDictatedPlacement(DEFAULT_NODE_SIZE, placementEnvironment, {
horizontalGap: gapBetweenNodes,
verticalGap: gapBetweenNodes,
}).position
showComponentBrowser(position, { type: 'newNode', sourcePort: id })
}
const stackNavigator = useStackNavigator()
function handleEdgeDrop(source: AstId, position: Vec2) {
showComponentBrowser(position, { type: 'newNode', sourcePort: source })
}
</script>
<template>
<div
ref="viewportNode"
class="GraphEditor viewport"
:class="{ draggingEdge: graphStore.unconnectedEdge != null }"
:style="groupColors"
v-on.="graphNavigator.events"
v-on..="nodeSelection.events"
@pointerdown="handleClick"
@dragover.prevent
@drop.prevent="handleFileDrop($event)"
>
<div :style="{ transform: graphNavigator.transform }" class="htmlLayer">
<GraphNodes
@nodeOutputPortDoubleClick="handleNodeOutputPortDoubleClick"
@nodeDoubleClick="(id) => stackNavigator.enterNode(id)"
/>
</div>
<GraphEdges :navigator="graphNavigator" @createNodeFromEdge="handleEdgeDrop" />
<ComponentBrowser
v-if="componentBrowserVisible"
ref="componentBrowser"
:navigator="graphNavigator"
:nodePosition="componentBrowserNodePosition"
:usage="componentBrowserUsage"
@accepted="commitComponentBrowser"
@canceled="hideComponentBrowser"
/>
<TopBar
v-model:recordMode="projectStore.recordMode"
:breadcrumbs="stackNavigator.breadcrumbLabels.value"
:allowNavigationLeft="stackNavigator.allowNavigationLeft.value"
:allowNavigationRight="stackNavigator.allowNavigationRight.value"
:zoomLevel="100.0 * graphNavigator.scale"
@breadcrumbClick="stackNavigator.handleBreadcrumbClick"
@back="stackNavigator.exitNode"
@forward="stackNavigator.enterNextNodeFromHistory"
@recordOnce="onRecordOnceButtonPress()"
@fitToAllClicked="zoomToSelected"
@zoomIn="graphNavigator.scale *= 1.1"
@zoomOut="graphNavigator.scale *= 0.9"
/>
<PlusButton @pointerdown.stop="startCreatingNodeFromButton()" @click.stop @pointerup.stop />
<Transition>
<Suspense ref="codeEditorArea">
<CodeEditor v-if="showCodeEditor" />
</Suspense>
</Transition>
<GraphMouse />
</div>
</template>
<style scoped>
.GraphEditor {
position: relative;
contain: layout;
overflow: clip;
user-select: none;
--group-color-fallback: #006b8a;
--node-color-no-type: #596b81;
}
.htmlLayer {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
}
</style>