forked from vitejs/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.vue
More file actions
547 lines (480 loc) · 15.5 KB
/
Copy pathGraph.vue
File metadata and controls
547 lines (480 loc) · 15.5 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
<script setup lang="ts">
import type { HierarchyLink, HierarchyNode } from 'd3-hierarchy'
import type { ModuleImport, ModuleListItem, SessionContext } from '~~/shared/types'
import { onKeyPressed, useEventListener, useMagicKeys } from '@vueuse/core'
import { hierarchy, tree } from 'd3-hierarchy'
import { linkHorizontal, linkVertical } from 'd3-shape'
import { computed, nextTick, onMounted, reactive, ref, shallowReactive, shallowRef, useTemplateRef, watch } from 'vue'
import { useZoomElement } from '~/composables/zoomElement'
const props = defineProps<{
session: SessionContext
modules: ModuleListItem[]
}>()
interface Node {
module: ModuleListItem
import?: ModuleImport
expanded?: boolean
hasChildren: boolean
}
type Link = HierarchyLink<Node> & {
id: string
import?: ModuleImport
}
const graphRender = ref<'normal' | 'mini'>('normal')
const SPACING = reactive({
width: computed(() => graphRender.value === 'normal' ? 400 : 10),
height: computed(() => graphRender.value === 'normal' ? 55 : 20),
linkOffset: computed(() => graphRender.value === 'normal' ? 20 : 0),
margin: computed(() => 800),
gap: computed(() => graphRender.value === 'normal' ? 150 : 100),
})
const container = useTemplateRef<HTMLDivElement>('container')
const isGrabbing = ref(false)
const width = ref(window.innerWidth)
const height = ref(window.innerHeight)
const nodesRefMap = shallowReactive(new Map<string, HTMLDivElement>())
const isUpdating = ref(false)
const isFirstCalculateGraph = ref(true)
const collapsedNodes = shallowReactive(new Set<string>())
const childToParentMap = shallowReactive(new Map<string, string>())
const nodes = shallowRef<HierarchyNode<Node>[]>([])
const links = shallowRef<Link[]>([])
const nodesMap = shallowReactive(new Map<string, HierarchyNode<Node>>())
const linksMap = shallowReactive(new Map<string, Link>())
const ZOOM_MIN = 0.4
const ZOOM_MAX = 2
const { control } = useMagicKeys()
const { scale, zoomIn, zoomOut } = useZoomElement(container, {
wheel: control,
minScale: ZOOM_MIN,
maxScale: ZOOM_MAX,
})
onKeyPressed(['-', '_'], (e) => {
if (e.ctrlKey)
zoomOut()
})
onKeyPressed(['=', '+'], (e) => {
if (e.ctrlKey)
zoomIn()
})
const modulesMap = computed(() => {
const map = new Map<string, ModuleListItem>()
for (const module of props.modules) {
map.set(module.id, module)
}
return map
})
const rootModules = computed(() => {
return props.modules.filter(x => x.importers.length === 0)
})
const createLinkHorizontal = linkHorizontal()
.x(d => d[0])
.y(d => d[1])
const createLinkVertical = linkVertical()
.x(d => d[0])
.y(d => d[1])
function calculateGraph(focusOnFirstRooeNode = true) {
// Unset the canvas size, and recalculate again after nodes are rendered
width.value = window.innerWidth
height.value = window.innerHeight
const seen = new Set<ModuleListItem>()
const root = hierarchy<Node>(
{ module: { id: '~root' } } as any,
(parent) => {
if (parent.module.id === '~root') {
rootModules.value.forEach((x) => {
seen.add(x)
if (isFirstCalculateGraph.value) {
childToParentMap.set(x.id, '~root')
}
})
return rootModules.value.map(x => ({
module: x,
expanded: !collapsedNodes.has(x.id),
hasChildren: false,
}))
}
if (collapsedNodes.has(parent.module.id)) {
return []
}
const modules = parent.module.imports
.map((x): Node | undefined => {
const module = modulesMap.value.get(x.module_id)
if (!module)
return undefined
if (seen.has(module))
return undefined
// Check if the module is a child of the current parent
if (childToParentMap.has(module.id) && childToParentMap.get(module.id) !== parent.module.id)
return undefined
seen.add(module)
if (isFirstCalculateGraph.value) {
childToParentMap.set(module.id, parent.module.id)
}
return {
module,
import: x,
expanded: !collapsedNodes.has(module.id),
hasChildren: false,
}
})
.filter(x => x !== undefined)
return modules
},
)
if (isFirstCalculateGraph.value) {
isFirstCalculateGraph.value = false
}
// Calculate the layout
const layout = tree<Node>()
.nodeSize([SPACING.height, SPACING.width + SPACING.gap])
layout(root)
const _nodes = root.descendants()
for (const node of _nodes) {
// Rotate the graph from top-down to left-right
[node.x, node.y] = [node.y! - SPACING.width, node.x!]
if (node.data.module.imports) {
node.data.hasChildren = node.data.module.imports
?.filter(subNode => childToParentMap.get(subNode.module_id) === node.data.module.id)
.length > 0
}
}
// Offset the graph and adding margin
const minX = Math.min(..._nodes.map(n => n.x!))
const minY = Math.min(..._nodes.map(n => n.y!))
if (minX < SPACING.margin) {
for (const node of _nodes) {
node.x! += Math.abs(minX) + SPACING.margin
}
}
if (minY < SPACING.margin) {
for (const node of _nodes) {
node.y! += Math.abs(minY) + SPACING.margin
}
}
nodes.value = _nodes
nodesMap.clear()
for (const node of _nodes) {
nodesMap.set(node.data.module.id, node)
}
const _links = root.links()
.filter(x => x.source.data.module.id !== '~root')
.map((x): Link => {
return {
...x,
import: x.source.data.import,
id: `${x.source.data.module.id}|${x.target.data.module.id}`,
}
})
linksMap.clear()
for (const link of _links) {
linksMap.set(link.id, link)
}
links.value = _links
nextTick(() => {
width.value = (container.value!.scrollWidth / scale.value + SPACING.margin)
height.value = (container.value!.scrollHeight / scale.value + SPACING.margin)
const moduleId = rootModules.value?.[0]?.id
if (focusOnFirstRooeNode && moduleId) {
nextTick(() => {
focusOn(moduleId, false)
})
}
})
}
function focusOn(id: string, animated = true) {
const el = nodesRefMap.get(id)
el?.scrollIntoView({
block: 'center',
inline: 'center',
behavior: animated ? 'smooth' : 'instant',
})
}
function adjustScrollPositionAfterToggle(id: string, beforePosition: { x: number, y: number }) {
// Ensure this runs after the nextTick inside calculateGraph completes (width and height are computed)
nextTick(() => {
nextTick(() => {
const newNode = nodesRefMap.get(id)
if (newNode && beforePosition && container.value) {
const containerRect = container.value.getBoundingClientRect()
const newRect = newNode.getBoundingClientRect()
const viewportDiffX = newRect.left - containerRect.left - beforePosition.x
const viewportDiffY = newRect.top - containerRect.top - beforePosition.y
container.value.scrollLeft += viewportDiffX
container.value.scrollTop += viewportDiffY
}
})
})
}
function toggleNode(id: string) {
if (isUpdating.value)
return
isUpdating.value = true
const node = nodesRefMap.get(id)
let beforePosition: null | { x: number, y: number } = null
// Record position relative to the scroll container to avoid drift after reflow
if (node && container.value) {
const containerRect = container.value.getBoundingClientRect()
const rect = node.getBoundingClientRect()
beforePosition = {
x: rect.left - containerRect.left,
y: rect.top - containerRect.top,
}
}
if (collapsedNodes.has(id)) {
collapsedNodes.delete(id)
}
else {
collapsedNodes.add(id)
}
calculateGraph(false)
// Adjust scroll position after layout changes
if (beforePosition) {
adjustScrollPositionAfterToggle(id, beforePosition)
}
isUpdating.value = false
}
function expandAll() {
if (isUpdating.value)
return
isUpdating.value = true
collapsedNodes.clear()
calculateGraph()
setTimeout(() => {
isUpdating.value = false
}, 300)
}
function collapseAll() {
if (isUpdating.value)
return
isUpdating.value = true
props.modules.forEach((module) => {
if (module.imports.length > 0) {
collapsedNodes.add(module.id)
}
})
calculateGraph()
setTimeout(() => {
isUpdating.value = false
}, 300)
}
function generateLink(link: Link) {
if (link.target.x! <= link.source.x!) {
return createLinkVertical({
source: [link.source.x! + SPACING.width / 2 - SPACING.linkOffset, link.source.y!],
target: [link.target.x! - SPACING.width / 2 + SPACING.linkOffset, link.target.y!],
})
}
return createLinkHorizontal({
source: [link.source.x! + SPACING.width / 2 - SPACING.linkOffset, link.source.y!],
target: [link.target.x! - SPACING.width / 2 + SPACING.linkOffset, link.target.y!],
})
}
function getLinkColor(_link: Link) {
return 'stroke-#8885'
}
function handleDraggingScroll() {
let x = 0
let y = 0
const SCROLLBAR_THICKNESS = 20
useEventListener(container, 'mousedown', (e) => {
// prevent dragging when clicking on scrollbar
const rect = container.value!.getBoundingClientRect()
const distRight = rect.right - e.clientX
const distBottom = rect.bottom - e.clientY
if (distRight <= SCROLLBAR_THICKNESS || distBottom <= SCROLLBAR_THICKNESS) {
return
}
isGrabbing.value = true
x = container.value!.scrollLeft + e.pageX
y = container.value!.scrollTop + e.pageY
})
useEventListener(container, 'contextmenu', e => e.preventDefault())
useEventListener('mouseleave', () => isGrabbing.value = false)
useEventListener('mouseup', () => isGrabbing.value = false)
useEventListener('mousemove', (e) => {
if (!isGrabbing.value)
return
e.preventDefault()
container.value!.scrollLeft = x - e.pageX
container.value!.scrollTop = y - e.pageY
})
}
onMounted(() => {
handleDraggingScroll()
watch(
() => props.modules,
() => {
isFirstCalculateGraph.value = true
collapsedNodes.clear()
childToParentMap.clear()
calculateGraph()
},
{ immediate: true },
)
watch(
() => graphRender.value,
() => calculateGraph(),
)
})
</script>
<template>
<div
ref="container"
w-full h-screen of-scroll relative select-none
:class="isGrabbing ? 'cursor-grabbing' : ''"
>
<div
:style="{
width: `${width * scale}px`,
height: `${height * scale}px`,
}"
>
<!-- Make this <div> in order to expand the scroll bar -->
<div
flex="~ items-center justify-center"
:style="{ transform: `scale(${scale})`, transformOrigin: '0 0' }"
>
<div
absolute left-0 top-0
:style="{
width: `${width}px`,
height: `${height}px`,
}"
class="bg-dots"
/>
<svg pointer-events-none absolute left-0 top-0 z-graph-link :width="width" :height="height">
<g>
<path
v-for="link of links"
:key="link.id"
:d="generateLink(link)!"
:class="getLinkColor(link)"
:stroke-dasharray="link.import?.kind === 'dynamic-import' ? '3 6' : undefined"
fill="none"
/>
</g>
</svg>
<template
v-for="node of nodes"
:key="node.data.module.id"
>
<template v-if="node.data.module.id !== '~root'">
<div
absolute
class="group z-graph-node flex gap-1 items-center"
:style="{
left: `${node.x}px`,
top: `${node.y}px`,
transform: 'translate(-50%, -50%)',
}"
>
<div
flex="~ items-center gap-1"
bg-glass
border="~ base rounded"
class="group-hover:bg-active block px2 p1"
:style="{
minWidth: graphRender === 'normal' ? `${SPACING.width}px` : undefined,
maxWidth: '400px',
maxHeight: '50px',
overflow: 'hidden',
transition: 'all 0.3s ease',
}"
>
<DisplayModuleId
:id="node.data.module.id"
:ref="(el: any) => nodesRefMap.set(node.data.module.id, el?.$el)"
:link="true"
:session="session"
:minimal="true"
flex="1"
/>
</div>
<!-- Expand/Collapse Button -->
<div class="w-4">
<button
v-if="node.data.hasChildren"
w-4
h-4
rounded-full
flex="items-center justify-center"
text-xs
border="~ active"
class="flex cursor-pointer z-graph-node-active bg-base"
:disabled="isUpdating"
:class="{ 'cursor-not-allowed': isUpdating, 'hover:bg-active': !isUpdating }"
:title="node.data.expanded ? 'Collapse' : 'Expand'"
@click.stop="toggleNode(node.data.module.id)"
>
<div
class="text-primary"
:class="[
node.data.expanded ? 'i-ph-minus' : 'i-ph-plus',
]"
transition="transform duration-200"
/>
</button>
</div>
</div>
</template>
</template>
</div>
</div>
<div
fixed right-6 bottom-6 z-panel-nav flex="~ col gap-2 items-center"
>
<div w-10 flex="~ items-center justify-center">
<DisplayTimeoutView :content="`${Math.round(scale * 100)}%`" class="text-sm" />
</div>
<div bg-glass rounded-full border border-base shadow flex="~ col gap-1 p1">
<button
v-tooltip.left="'Expand All'"
w-10 h-10 rounded-full hover:bg-active op-fade
hover:op100 flex="~ items-center justify-center"
:disabled="isUpdating"
:class="{ 'op50 cursor-not-allowed': isUpdating, 'hover:bg-active': !isUpdating }"
title="Expand All"
@click="expandAll()"
>
<div class="i-carbon:expand-categories" />
</button>
<button
v-tooltip.left="'Collapse All'"
w-10 h-10 rounded-full hover:bg-active op-fade
hover:op100 flex="~ items-center justify-center"
:disabled="isUpdating"
:class="{ 'op50 cursor-not-allowed': isUpdating, 'hover:bg-active': !isUpdating }"
title="Collapse All"
@click="collapseAll()"
>
<div class="i-carbon:collapse-categories" />
</button>
<div border="t base" my1 />
<button
v-tooltip.left="'Zoom In (Ctrl + =)'"
:disabled="scale >= ZOOM_MAX"
w-10 h-10 rounded-full hover:bg-active op-fade
hover:op100 disabled:op20 disabled:bg-none
disabled:cursor-not-allowed
flex="~ items-center justify-center"
title="Zoom In (Ctrl + =)"
@click="zoomIn()"
>
<div i-ph-magnifying-glass-plus-duotone />
</button>
<button
v-tooltip.left="'Zoom Out (Ctrl + -)'"
:disabled="scale <= ZOOM_MIN"
w-10 h-10 rounded-full hover:bg-active op-fade hover:op100
disabled:op20 disabled:bg-none disabled:cursor-not-allowed
flex="~ items-center justify-center"
title="Zoom Out (Ctrl + -)"
@click="zoomOut()"
>
<div i-ph-magnifying-glass-minus-duotone />
</button>
</div>
</div>
</div>
</template>