-
Notifications
You must be signed in to change notification settings - Fork 151
/
client.ts
407 lines (361 loc) · 10.6 KB
/
client.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
import type { Ref } from 'vue'
import { computed, createApp, h, markRaw, nextTick, ref, shallowReactive, shallowRef, watch } from 'vue'
import { createHooks } from 'hookable'
import { debounce } from 'perfect-debounce'
import type { Router } from 'vue-router'
import type { $Fetch } from 'ofetch'
import type { NuxtDevtoolsHostClient, TimelineEventRoute, TimelineMetrics } from '../../../types'
import { initTimelineMetrics } from '../../function-metrics-helpers'
import Main from './Main.vue'
import { popupWindow, state } from './state'
// eslint-disable-next-line ts/prefer-ts-expect-error
// @ts-ignore tsconfig
import { useAppConfig, useRuntimeConfig } from '#imports'
const clientRef = shallowRef<NuxtDevtoolsHostClient>()
export { clientRef as client }
export type ColorScheme = 'dark' | 'light'
export async function setupDevToolsClient({
nuxt,
clientHooks,
timeMetric,
router,
}: {
nuxt: any
clientHooks: any
timeMetric: any
router: Router
}) {
const isInspecting = ref(false)
const colorMode = useClientColorMode()
const timeline = initTimelineMetrics()
const client: NuxtDevtoolsHostClient = shallowReactive({
nuxt: markRaw(nuxt as any),
hooks: createHooks(),
inspector: getInspectorInstance(),
getIframe,
syncClient,
devtools: {
toggle() {
if (state.value.open)
client.devtools.close()
else
client.devtools.open()
},
close() {
if (!state.value.open)
return
state.value.open = false
if (popupWindow.value) {
try {
popupWindow.value.close()
}
catch (e) {
}
popupWindow.value = null
}
},
open() {
if (state.value.open)
return
state.value.open = true
return nextTick(() => {
client.syncClient()
})
},
async navigate(path: string) {
if (!state.value.open)
await client.devtools.open()
await client.hooks.callHook('host:action:navigate', path)
},
async reload() {
await client.hooks.callHook('host:action:reload')
},
},
app: {
appConfig: useAppConfig() as any,
reload() {
location.reload()
},
navigate(path: string, hard = false) {
if (hard)
location.href = path
else
router.push(path)
},
colorMode,
frameState: state,
$fetch: globalThis.$fetch as $Fetch,
},
metrics: {
clientPlugins: () => window.__NUXT_DEVTOOLS_PLUGINS_METRIC__,
clientHooks: () => Object.values(clientHooks),
clientTimeline: () => timeline,
loading: () => timeMetric,
},
})
window.__NUXT_DEVTOOLS_HOST__ = client
let iframe: HTMLIFrameElement | undefined
function syncClient() {
if (!client.inspector)
client.inspector = getInspectorInstance()
try {
iframe?.contentWindow?.__NUXT_DEVTOOLS_VIEW__?.setClient(client)
}
catch (e) {
// cross-origin
}
return client
}
function getIframe() {
if (!iframe) {
const runtimeConfig = useRuntimeConfig()
const CLIENT_PATH = `${runtimeConfig.app.baseURL}/__nuxt_devtools__/client`.replace(/\/+/g, '/')
const initialUrl = CLIENT_PATH + state.value.route
try {
iframe = document.createElement('iframe')
iframe.id = 'nuxt-devtools-iframe'
iframe.allow = 'cross-origin-isolated'
iframe.setAttribute('credentialless', 'true')
iframe.src = initialUrl
iframe.onload = async () => {
try {
await waitForClientInjection()
client.syncClient()
}
catch (e) {
console.error('Nuxt DevTools client injection failed')
console.error(e)
}
}
}
catch (e) {
console.error(e)
}
}
return iframe
}
function waitForClientInjection(retry = 20, timeout = 300) {
let lastError: any
const test = () => {
try {
return !!iframe?.contentWindow?.__NUXT_DEVTOOLS_VIEW__
}
catch (e) {
lastError = e
}
return false
}
if (test())
return
return new Promise<void>((resolve, reject) => {
const interval = setInterval(() => {
if (test()) {
clearInterval(interval)
resolve()
}
else if (retry-- <= 0) {
clearInterval(interval)
reject(lastError)
}
}, timeout)
})
}
function enableComponentInspector() {
window.__VUE_INSPECTOR__?.enable()
isInspecting.value = true
}
function disableComponentInspector() {
if (!window.__VUE_INSPECTOR__?.enabled)
return
window.__VUE_INSPECTOR__?.disable()
client?.hooks.callHook('host:inspector:close')
isInspecting.value = false
}
function getInspectorInstance(): NuxtDevtoolsHostClient['inspector'] {
const componentInspector = window.__VUE_INSPECTOR__
if (componentInspector) {
componentInspector.openInEditor = async (baseUrl, file, line, column) => {
disableComponentInspector()
await client.hooks.callHook('host:inspector:click', baseUrl, file, line, column)
}
componentInspector.onUpdated = () => {
client.hooks.callHook('host:inspector:update', {
...componentInspector.linkParams,
...componentInspector.position,
})
}
}
return markRaw({
isEnabled: isInspecting,
enable: enableComponentInspector,
disable: disableComponentInspector,
toggle: () => {
if (window.__VUE_INSPECTOR__?.enabled)
disableComponentInspector()
else
enableComponentInspector()
},
instance: componentInspector,
})
}
setupRouteTracking(timeline, router)
setupReactivity(client, router, timeline)
clientRef.value = client
// Experimental: Picture-in-Picture mode
// https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
const documentPictureInPicture = window.documentPictureInPicture
if (documentPictureInPicture?.requestWindow) {
client.devtools.popup = async () => {
const iframe = getIframe()
if (!iframe)
return
const pip = popupWindow.value = await documentPictureInPicture.requestWindow({
width: Math.round(window.innerWidth * state.value.width / 100),
height: Math.round(window.innerHeight * state.value.height / 100),
}) as Window
const style = pip.document.createElement('style')
style.innerHTML = `
body {
margin: 0;
padding: 0;
}
iframe {
width: 100vw;
height: 100vh;
border: none;
outline: none;
}
`
pip.__NUXT_DEVTOOLS_DISABLE__ = true
pip.__NUXT_DEVTOOLS_IS_POPUP__ = true
pip.__NUXT__ = window.parent?.__NUXT__ || window.__NUXT__
pip.document.title = 'Nuxt DevTools'
pip.document.head.appendChild(style)
pip.document.body.appendChild(iframe)
pip.addEventListener('resize', () => {
state.value.width = Math.round(pip.innerWidth / window.innerWidth * 100)
state.value.height = Math.round(pip.innerHeight / window.innerHeight * 100)
})
pip.addEventListener('pagehide', () => {
popupWindow.value = null
pip.close()
})
}
}
client.syncClient()
const holder = document.createElement('div')
holder.id = 'nuxt-devtools-container'
holder.setAttribute('data-v-inspector-ignore', 'true')
document.body.appendChild(holder)
// Shortcut to toggle devtools
addEventListener('keydown', (e) => {
if (e.code === 'KeyD' && e.altKey && e.shiftKey)
client.devtools.toggle()
})
const app = createApp({
render: () => h(Main, { client }),
devtools: {
hide: true,
},
})
app.mount(holder)
}
export function useClientColorMode(): Ref<ColorScheme> {
const explicitColor = ref<ColorScheme>()
const systemColor = ref<ColorScheme>()
const elements = [
document.documentElement,
document.body,
]
const ob = new MutationObserver(getExplicitColor)
elements.forEach((el) => {
ob.observe(el, {
attributes: true,
attributeFilter: ['class'],
})
})
const preferDarkQuery = window.matchMedia('(prefers-color-scheme: dark)')
const preferLightQuery = window.matchMedia('(prefers-color-scheme: light)')
preferDarkQuery.addEventListener('change', getSystemColor)
preferLightQuery.addEventListener('change', getSystemColor)
function getExplicitColor() {
let color: ColorScheme | undefined
for (const el of elements) {
if (el.classList.contains('dark')) {
color = 'dark'
break
}
if (el.classList.contains('light')) {
color = 'light'
break
}
}
explicitColor.value = color
}
function getSystemColor() {
if (preferDarkQuery.matches)
systemColor.value = 'dark'
else if (preferLightQuery.matches)
systemColor.value = 'light'
else
systemColor.value = undefined
}
getExplicitColor()
getSystemColor()
return computed(() => explicitColor.value || systemColor.value || 'light')
}
function setupRouteTracking(timeline: TimelineMetrics, router: Router) {
// Add initial route event
if (timeline.options.enabled && router?.currentRoute?.value?.path) {
const start = timeline.events[0]?.start || Date.now()
timeline.events.unshift({
type: 'route',
from: router.currentRoute.value.path,
to: router.currentRoute.value.path,
start,
end: start,
})
}
let lastRouteEvent: TimelineEventRoute | undefined
router?.afterEach(() => {
if (lastRouteEvent && !lastRouteEvent?.end)
lastRouteEvent.end = Date.now()
})
router?.beforeEach((to, from) => {
if (!timeline.options.enabled)
return
lastRouteEvent = {
type: 'route',
from: from.path,
to: to.path,
start: Date.now(),
}
timeline.events.push(lastRouteEvent)
})
}
function setupReactivity(client: NuxtDevtoolsHostClient, router: Router | undefined, timeMetric: TimelineMetrics) {
const refreshReactivity = debounce(() => {
client.hooks.callHook('host:update:reactivity')
}, 100, { trailing: true })
// trigger update for reactivity
watch(() => [
client.nuxt.payload,
client.app.colorMode.value,
client.metrics.loading(),
timeMetric,
], () => {
refreshReactivity()
}, { deep: true })
// trigger update for route change
router?.afterEach(() => {
refreshReactivity()
})
// trigger update for app mounted
client.nuxt.hook('app:mounted', () => {
refreshReactivity()
})
// record last route
client.hooks.hook('devtools:navigate', (path) => {
state.value.route = path
})
}