-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
devtools.ts
590 lines (519 loc) · 15.6 KB
/
devtools.ts
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
import {
App,
CustomInspectorNode,
InspectorNodeTag,
CustomInspectorState,
HookPayloads,
setupDevtoolsPlugin,
TimelineEvent,
} from '@vue/devtools-api'
import { watch } from 'vue'
import { decode } from './encoding'
import { isSameRouteRecord } from './location'
import { RouterMatcher } from './matcher'
import { RouteRecordMatcher } from './matcher/pathMatcher'
import { PathParser } from './matcher/pathParserRanker'
import { Router } from './router'
import { UseLinkDevtoolsContext } from './RouterLink'
import { RouterViewDevtoolsContext } from './RouterView'
import { RouteLocationNormalized } from './types'
import { assign, isArray } from './utils'
/**
* Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Vue instances).
*
* @param routeLocation - routeLocation to format
* @param tooltip - optional tooltip
* @returns a copy of the routeLocation
*/
function formatRouteLocation(
routeLocation: RouteLocationNormalized,
tooltip?: string
) {
const copy = assign({}, routeLocation, {
// remove variables that can contain vue instances
matched: routeLocation.matched.map(matched =>
omit(matched, ['instances', 'children', 'aliasOf'])
),
})
return {
_custom: {
type: null,
readOnly: true,
display: routeLocation.fullPath,
tooltip,
value: copy,
},
}
}
function formatDisplay(display: string) {
return {
_custom: {
display,
},
}
}
// to support multiple router instances
let routerId = 0
export function addDevtools(app: App, router: Router, matcher: RouterMatcher) {
// Take over router.beforeEach and afterEach
// make sure we are not registering the devtool twice
if ((router as any).__hasDevtools) return
;(router as any).__hasDevtools = true
// increment to support multiple router instances
const id = routerId++
setupDevtoolsPlugin(
{
id: 'org.vuejs.router' + (id ? '.' + id : ''),
label: 'Vue Router',
packageName: 'vue-router',
homepage: 'https://router.vuejs.org',
logo: 'https://router.vuejs.org/logo.png',
componentStateTypes: ['Routing'],
app,
},
api => {
if (typeof api.now !== 'function') {
console.warn(
'[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.'
)
}
// display state added by the router
api.on.inspectComponent((payload, ctx) => {
if (payload.instanceData) {
payload.instanceData.state.push({
type: 'Routing',
key: '$route',
editable: false,
value: formatRouteLocation(
router.currentRoute.value,
'Current Route'
),
})
}
})
// mark router-link as active and display tags on router views
api.on.visitComponentTree(({ treeNode: node, componentInstance }) => {
if (componentInstance.__vrv_devtools) {
const info =
componentInstance.__vrv_devtools as RouterViewDevtoolsContext
node.tags.push({
label: (info.name ? `${info.name.toString()}: ` : '') + info.path,
textColor: 0,
tooltip: 'This component is rendered by <router-view>',
backgroundColor: PINK_500,
})
}
// if multiple useLink are used
if (isArray(componentInstance.__vrl_devtools)) {
componentInstance.__devtoolsApi = api
;(
componentInstance.__vrl_devtools as UseLinkDevtoolsContext[]
).forEach(devtoolsData => {
let label = devtoolsData.route.path
let backgroundColor = ORANGE_400
let tooltip: string = ''
let textColor = 0
if (devtoolsData.error) {
label = devtoolsData.error
backgroundColor = RED_100
textColor = RED_700
} else if (devtoolsData.isExactActive) {
backgroundColor = LIME_500
tooltip = 'This is exactly active'
} else if (devtoolsData.isActive) {
backgroundColor = BLUE_600
tooltip = 'This link is active'
}
node.tags.push({
label,
textColor,
tooltip,
backgroundColor,
})
})
}
})
watch(router.currentRoute, () => {
// refresh active state
refreshRoutesView()
api.notifyComponentUpdate()
api.sendInspectorTree(routerInspectorId)
api.sendInspectorState(routerInspectorId)
})
const navigationsLayerId = 'router:navigations:' + id
api.addTimelineLayer({
id: navigationsLayerId,
label: `Router${id ? ' ' + id : ''} Navigations`,
color: 0x40a8c4,
})
// const errorsLayerId = 'router:errors'
// api.addTimelineLayer({
// id: errorsLayerId,
// label: 'Router Errors',
// color: 0xea5455,
// })
router.onError((error, to) => {
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
title: 'Error during Navigation',
subtitle: to.fullPath,
logType: 'error',
time: api.now(),
data: { error },
groupId: (to.meta as any).__navigationId,
},
})
})
// attached to `meta` and used to group events
let navigationId = 0
router.beforeEach((to, from) => {
const data: TimelineEvent<any, any>['data'] = {
guard: formatDisplay('beforeEach'),
from: formatRouteLocation(
from,
'Current Location during this navigation'
),
to: formatRouteLocation(to, 'Target location'),
}
// Used to group navigations together, hide from devtools
Object.defineProperty(to.meta, '__navigationId', {
value: navigationId++,
})
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
time: api.now(),
title: 'Start of navigation',
subtitle: to.fullPath,
data,
groupId: (to.meta as any).__navigationId,
},
})
})
router.afterEach((to, from, failure) => {
const data: TimelineEvent<any, any>['data'] = {
guard: formatDisplay('afterEach'),
}
if (failure) {
data.failure = {
_custom: {
type: Error,
readOnly: true,
display: failure ? failure.message : '',
tooltip: 'Navigation Failure',
value: failure,
},
}
data.status = formatDisplay('❌')
} else {
data.status = formatDisplay('✅')
}
// we set here to have the right order
data.from = formatRouteLocation(
from,
'Current Location during this navigation'
)
data.to = formatRouteLocation(to, 'Target location')
api.addTimelineEvent({
layerId: navigationsLayerId,
event: {
title: 'End of navigation',
subtitle: to.fullPath,
time: api.now(),
data,
logType: failure ? 'warning' : 'default',
groupId: (to.meta as any).__navigationId,
},
})
})
/**
* Inspector of Existing routes
*/
const routerInspectorId = 'router-inspector:' + id
api.addInspector({
id: routerInspectorId,
label: 'Routes' + (id ? ' ' + id : ''),
icon: 'book',
treeFilterPlaceholder: 'Search routes',
})
function refreshRoutesView() {
// the routes view isn't active
if (!activeRoutesPayload) return
const payload = activeRoutesPayload
// children routes will appear as nested
let routes = matcher.getRoutes().filter(
route =>
!route.parent ||
// these routes have a parent with no component which will not appear in the view
// therefore we still need to include them
!route.parent.record.components
)
// reset match state to false
routes.forEach(resetMatchStateOnRouteRecord)
// apply a match state if there is a payload
if (payload.filter) {
routes = routes.filter(route =>
// save matches state based on the payload
isRouteMatching(route, payload.filter.toLowerCase())
)
}
// mark active routes
routes.forEach(route =>
markRouteRecordActive(route, router.currentRoute.value)
)
payload.rootNodes = routes.map(formatRouteRecordForInspector)
}
let activeRoutesPayload: HookPayloads['getInspectorTree'] | undefined
api.on.getInspectorTree(payload => {
activeRoutesPayload = payload
if (payload.app === app && payload.inspectorId === routerInspectorId) {
refreshRoutesView()
}
})
/**
* Display information about the currently selected route record
*/
api.on.getInspectorState(payload => {
if (payload.app === app && payload.inspectorId === routerInspectorId) {
const routes = matcher.getRoutes()
const route = routes.find(
route => (route.record as any).__vd_id === payload.nodeId
)
if (route) {
payload.state = {
options: formatRouteRecordMatcherForStateInspector(route),
}
}
}
})
api.sendInspectorTree(routerInspectorId)
api.sendInspectorState(routerInspectorId)
}
)
}
function modifierForKey(key: PathParser['keys'][number]) {
if (key.optional) {
return key.repeatable ? '*' : '?'
} else {
return key.repeatable ? '+' : ''
}
}
function formatRouteRecordMatcherForStateInspector(
route: RouteRecordMatcher
): CustomInspectorState[string] {
const { record } = route
const fields: CustomInspectorState[string] = [
{ editable: false, key: 'path', value: record.path },
]
if (record.name != null) {
fields.push({
editable: false,
key: 'name',
value: record.name,
})
}
fields.push({ editable: false, key: 'regexp', value: route.re })
if (route.keys.length) {
fields.push({
editable: false,
key: 'keys',
value: {
_custom: {
type: null,
readOnly: true,
display: route.keys
.map(key => `${key.name}${modifierForKey(key)}`)
.join(' '),
tooltip: 'Param keys',
value: route.keys,
},
},
})
}
if (record.redirect != null) {
fields.push({
editable: false,
key: 'redirect',
value: record.redirect,
})
}
if (route.alias.length) {
fields.push({
editable: false,
key: 'aliases',
value: route.alias.map(alias => alias.record.path),
})
}
if (Object.keys(route.record.meta).length) {
fields.push({
editable: false,
key: 'meta',
value: route.record.meta,
})
}
fields.push({
key: 'score',
editable: false,
value: {
_custom: {
type: null,
readOnly: true,
display: route.score.map(score => score.join(', ')).join(' | '),
tooltip: 'Score used to sort routes',
value: route.score,
},
},
})
return fields
}
/**
* Extracted from tailwind palette
*/
const PINK_500 = 0xec4899
const BLUE_600 = 0x2563eb
const LIME_500 = 0x84cc16
const CYAN_400 = 0x22d3ee
const ORANGE_400 = 0xfb923c
// const GRAY_100 = 0xf4f4f5
const DARK = 0x666666
const RED_100 = 0xfee2e2
const RED_700 = 0xb91c1c
function formatRouteRecordForInspector(
route: RouteRecordMatcher
): CustomInspectorNode {
const tags: InspectorNodeTag[] = []
const { record } = route
if (record.name != null) {
tags.push({
label: String(record.name),
textColor: 0,
backgroundColor: CYAN_400,
})
}
if (record.aliasOf) {
tags.push({
label: 'alias',
textColor: 0,
backgroundColor: ORANGE_400,
})
}
if ((route as any).__vd_match) {
tags.push({
label: 'matches',
textColor: 0,
backgroundColor: PINK_500,
})
}
if ((route as any).__vd_exactActive) {
tags.push({
label: 'exact',
textColor: 0,
backgroundColor: LIME_500,
})
}
if ((route as any).__vd_active) {
tags.push({
label: 'active',
textColor: 0,
backgroundColor: BLUE_600,
})
}
if (record.redirect) {
tags.push({
label:
typeof record.redirect === 'string'
? `redirect: ${record.redirect}`
: 'redirects',
textColor: 0xffffff,
backgroundColor: DARK,
})
}
// add an id to be able to select it. Using the `path` is not possible because
// empty path children would collide with their parents
let id = (record as any).__vd_id
if (id == null) {
id = String(routeRecordId++)
;(record as any).__vd_id = id
}
return {
id,
label: record.path,
tags,
children: route.children.map(formatRouteRecordForInspector),
}
}
// incremental id for route records and inspector state
let routeRecordId = 0
const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/
function markRouteRecordActive(
route: RouteRecordMatcher,
currentRoute: RouteLocationNormalized
) {
// no route will be active if matched is empty
// reset the matching state
const isExactActive =
currentRoute.matched.length &&
isSameRouteRecord(
currentRoute.matched[currentRoute.matched.length - 1],
route.record
)
;(route as any).__vd_exactActive = (route as any).__vd_active = isExactActive
if (!isExactActive) {
;(route as any).__vd_active = currentRoute.matched.some(match =>
isSameRouteRecord(match, route.record)
)
}
route.children.forEach(childRoute =>
markRouteRecordActive(childRoute, currentRoute)
)
}
function resetMatchStateOnRouteRecord(route: RouteRecordMatcher) {
;(route as any).__vd_match = false
route.children.forEach(resetMatchStateOnRouteRecord)
}
function isRouteMatching(route: RouteRecordMatcher, filter: string): boolean {
const found = String(route.re).match(EXTRACT_REGEXP_RE)
// reset the matching state
;(route as any).__vd_match = false
if (!found || found.length < 3) {
return false
}
// use a regexp without $ at the end to match nested routes better
const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2])
if (nonEndingRE.test(filter)) {
// mark children as matches
route.children.forEach(child => isRouteMatching(child, filter))
// exception case: `/`
if (route.record.path !== '/' || filter === '/') {
;(route as any).__vd_match = route.re.test(filter)
return true
}
// hide the / route
return false
}
const path = route.record.path.toLowerCase()
const decodedPath = decode(path)
// also allow partial matching on the path
if (
!filter.startsWith('/') &&
(decodedPath.includes(filter) || path.includes(filter))
)
return true
if (decodedPath.startsWith(filter) || path.startsWith(filter)) return true
if (route.record.name && String(route.record.name).includes(filter))
return true
return route.children.some(child => isRouteMatching(child, filter))
}
function omit<T extends object, K extends [...(keyof T)[]]>(obj: T, keys: K) {
const ret = {} as {
[K2 in Exclude<keyof T, K[number]>]: T[K2]
}
for (const key in obj) {
if (!keys.includes(key)) {
// @ts-expect-error
ret[key] = obj[key]
}
}
return ret
}