-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathEditorPreview.vue
More file actions
513 lines (470 loc) · 15.6 KB
/
EditorPreview.vue
File metadata and controls
513 lines (470 loc) · 15.6 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
<template>
<UICard
v-radar="{ name: 'Editor preview', desc: 'Preview panel for stage preview and project running' }"
class="editor-preview"
>
<UICardHeader>
<div class="header">
{{ $t(headerTitle) }}
</div>
<template v-if="runnerState === 'initial'">
<UIButton
v-radar="{ name: 'Run button', desc: 'Click to run the project in debug mode' }"
class="button"
color="primary"
icon="playHollow"
:loading="handleRun.isLoading.value"
@click="handleRun.fn"
>
{{ $t({ en: 'Run', zh: '运行' }) }}
</UIButton>
<UIButton
v-show="canManageProject"
v-radar="{ name: 'Publish button', desc: 'Click to publish the project' }"
color="secondary"
:disabled="!isOnline"
@click="handlePublishProject"
>
<img :src="publishSvg" style="width: 14px" />
{{ $t({ en: 'Publish', zh: '发布' }) }}
</UIButton>
</template>
<template v-else>
<UIButton
v-radar="{ name: 'Rerun button', desc: 'Click to rerun the project' }"
class="button"
color="primary"
icon="rotate"
:disabled="runnerState !== 'running' || handleStop.isLoading.value"
:loading="handleRerun.isLoading.value && !handleStop.isLoading.value"
@click="handleRerun.fn"
>
{{ $t({ en: 'Rerun', zh: '重新运行' }) }}
</UIButton>
<UIButton
v-radar="{ name: 'Stop button', desc: 'Click to stop the running project' }"
class="button"
color="boring"
icon="end"
:loading="handleStop.isLoading.value"
@click="handleStop.fn"
>
{{ $t({ en: 'Stop', zh: '停止' }) }}
</UIButton>
<UITooltip placement="top-end">
<template #trigger>
<UIButton
v-radar="{ name: 'Enter full screen button', desc: 'Click to enter full screen for the running project' }"
class="button"
color="boring"
icon="enterFullScreen"
:disabled="handleStop.isLoading.value"
@click="handleEnterFullscreen"
></UIButton>
</template>
{{ $t({ en: 'Enter full screen', zh: '进入全屏' }) }}
</UITooltip>
</template>
</UICardHeader>
<div class="main">
<div
ref="stageContainerRef"
class="stage-viewer-container"
:class="{ 'stage-viewer-container--running': runnerState !== 'initial' }"
>
<StageViewer />
<div v-show="fullscreen || runnerState !== 'initial' || runnerHostSticky" class="runner-host">
<ProjectRunnerSurface
ref="projectRunnerSurfaceRef"
v-model:fullscreen="fullscreen"
:project="editorCtx.project"
:runner-state="runnerState"
:on-run="handleRun.fn"
:run-loading="handleRun.isLoading.value"
:on-rerun="handleRerun.fn"
:rerun-loading="handleRerun.isLoading.value"
:on-stop="handleStop.fn"
:stop-loading="handleStop.isLoading.value"
:inline-anchor="getStageInlineAnchor"
@console="handleConsole"
@update:fullscreen="handleFullscreenChange"
@exit="handleExit"
/>
</div>
</div>
</div>
</UICard>
</template>
<script lang="ts">
// Check tools/ispx/log.go for log source
// TODO: Move these types & functions to ProjectRunner, and emit `log` instead of `console` event
type SpxLog = {
level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'
/** RFC 3339 date time string, e.g., `2025-12-04T14:17:36.24+08:00` */
time: string
msg: string
[key: string]: unknown
}
function isSpxLog(obj: any): obj is SpxLog {
return (
obj != null &&
typeof obj === 'object' &&
typeof obj.level === 'string' &&
typeof obj.time === 'string' &&
typeof obj.msg === 'string'
)
}
function parseSpxLog(jsonStr: string): SpxLog | null {
try {
const obj = JSON.parse(jsonStr)
if (isSpxLog(obj)) return obj
} catch {
// ignore
}
return null
}
type SpxInfoLog = SpxLog & {
level: 'INFO'
function: string
/** Source file name, e.g., `NiuXiaoQi.spx` */
file: string
/** Source code line number, starting from 1 */
line: number
}
function isSpxInfoLog(obj: SpxLog): obj is SpxInfoLog {
return obj.level === 'INFO'
}
type SpxPanicLog = SpxLog & {
level: 'ERROR'
msg: 'panic'
/** Panic error message */
error: string
/** Source file name, e.g., `NiuXiaoQi.spx` */
file: string
/** Source code line number, starting from 1 */
line: number
/** Source code column number, starting from 1 */
column: number
}
function isSpxPanicLog(obj: SpxLog): obj is SpxPanicLog {
return obj.level === 'ERROR' && typeof obj.error === 'string' && obj.msg === 'panic'
}
</script>
<script lang="ts" setup>
import dayjs from 'dayjs'
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { capture, useMessageHandle } from '@/utils/exception'
import { useI18n, type LocaleMessage } from '@/utils/i18n'
import { humanizeListWithLimit, untilNotNull } from '@/utils/utils'
import { useSignedInUser } from '@/stores/user'
import { UICard, UICardHeader, UIButton, useConfirmDialog, UITooltip } from '@/components/ui'
import ProjectRunnerSurface from '@/components/project/runner/ProjectRunnerSurface.vue'
import { useEditorCtx } from '@/components/editor/EditorContextProvider.vue'
import {
useCodeEditor,
DiagnosticSeverity,
textDocumentId2CodeFileName,
getInvalidMonitors
} from '@/components/editor/code-editor/spx-code-editor'
import { RuntimeOutputKind, type RuntimeOutput, type RuntimeOutputDraft } from '@/components/editor/runtime'
import StageViewer from './stage-viewer/StageViewer.vue'
import { useNetwork } from '@/utils/network'
import { usePublishProject } from '@/components/project'
import publishSvg from './publish.svg'
const editorCtx = useEditorCtx()
const codeEditor = useCodeEditor()
const { isOnline } = useNetwork()
const signedInUser = useSignedInUser()
const runtime = computed(() => editorCtx.state.runtime)
const runnerState = ref<'initial' | 'loading' | 'running'>('initial')
const projectRunnerSurfaceRef = ref<InstanceType<typeof ProjectRunnerSurface> | null>(null)
const stageContainerRef = ref<HTMLDivElement | null>(null)
const fullscreen = ref(false)
const exitGuard = ref<'idle' | 'manualStopPending'>('idle')
const runnerHostSticky = ref(false)
const lastFilesHash = ref<string | null>(null)
let runnerHostReleaseTimer: number | null = null
watch(
() => [fullscreen.value, runnerState.value],
([isFullscreen, state]) => {
if (isFullscreen || state !== 'initial') {
runnerHostSticky.value = false
if (runnerHostReleaseTimer != null) {
window.clearTimeout(runnerHostReleaseTimer)
runnerHostReleaseTimer = null
}
}
}
)
const headerTitle = computed(() => {
if (runnerState.value === 'loading') return { en: 'Loading', zh: '加载中' } satisfies LocaleMessage
if (runnerState.value === 'running') return { en: 'Running', zh: '运行中' } satisfies LocaleMessage
return { en: 'Preview', zh: '预览' } satisfies LocaleMessage
})
const i18n = useI18n()
const confirm = useConfirmDialog()
const lastPanicOutput = ref<RuntimeOutput | null>(null)
function appendRuntimeOutput(output: RuntimeOutputDraft) {
runtime.value.addOutput(output)
}
function keepRunnerHostVisibleForOverlay() {
runnerHostSticky.value = true
if (runnerHostReleaseTimer != null) window.clearTimeout(runnerHostReleaseTimer)
runnerHostReleaseTimer = window.setTimeout(() => {
runnerHostSticky.value = false
runnerHostReleaseTimer = null
}, 450)
}
function handleConsole(type: 'log' | 'warn', args: unknown[]) {
// Only handle spx logs, which are carried by `console.log`
if (type !== 'log' || typeof args[0] !== 'string') return
const spxLog = parseSpxLog(args[0])
if (spxLog == null) return
if (isSpxInfoLog(spxLog)) {
appendRuntimeOutput({
kind: RuntimeOutputKind.Log,
time: dayjs(spxLog.time).valueOf(),
message: spxLog.msg,
source: {
textDocument: {
uri: `file:///${spxLog.file}`
},
range: {
start: { line: spxLog.line, column: 1 },
end: { line: spxLog.line, column: 1 }
}
}
})
} else if (isSpxPanicLog(spxLog)) {
appendRuntimeOutput({
kind: RuntimeOutputKind.Error,
time: dayjs(spxLog.time).valueOf(),
message: spxLog.error,
source: {
textDocument: {
uri: `file:///${spxLog.file}`
},
range: {
start: { line: spxLog.line, column: spxLog.column },
end: { line: spxLog.line, column: spxLog.column }
}
}
})
} else {
capture(new Error(`Unknown spx runtime log: ${args[0]}`))
}
}
function handleExit(code: number) {
runtime.value.emit('didExit', code)
if (exitGuard.value === 'manualStopPending') {
exitGuard.value = 'idle'
return
}
exitGuard.value = 'idle'
lastPanicOutput.value = null
const shouldRestore = restoreDebugRuntime()
runnerState.value = shouldRestore ? 'running' : 'loading'
}
async function checkAndNotifyCodeError() {
const r = await codeEditor.diagnosticWorkspace()
const codeFilesWithError: LocaleMessage[] = []
for (const item of r.items) {
if (!item.diagnostics.some((d) => d.severity === DiagnosticSeverity.Error)) continue
codeFilesWithError.push(textDocumentId2CodeFileName(item.textDocument))
}
if (codeFilesWithError.length === 0) return
const codeFileNamesWithError = humanizeListWithLimit(codeFilesWithError)
await confirm({
title: i18n.t({ en: 'Error exists in code', zh: '代码中存在错误' }),
content: i18n.t({
en: `There are stills errors in the project code (${codeFileNamesWithError.en}). The project may not run correctly. Are you sure to continue?`,
zh: `当前项目代码(${codeFileNamesWithError.zh}文件)中存在错误,项目可能无法正常运行,确定继续吗?`
})
})
}
async function checkAndNotifyMonitorError() {
const { sprites, stage } = editorCtx.project
const monitors = stage.widgets.filter((w) => w.type === 'monitor')
const spriteNames = new Set(sprites.map((s) => s.name))
const invalidMonitors = await getInvalidMonitors(monitors, spriteNames, (target, signal) =>
codeEditor.getProperties(target, signal)
)
if (invalidMonitors.length === 0) return
const monitorNames = humanizeListWithLimit(invalidMonitors.map((m) => ({ en: m.name, zh: m.name })))
await confirm({
title: i18n.t({ en: 'Invalid monitor configuration', zh: '监视器配置无效' }),
content: i18n.t({
en: `Monitor ${monitorNames.en} has no valid variable configured and will not display correctly. Are you sure to continue?`,
zh: `监视器 ${monitorNames.zh} 未配置有效的变量,运行时将无法正常显示,确定继续吗?`
})
})
}
async function executeRun(action: 'run' | 'rerun') {
exitGuard.value = 'idle'
runnerState.value = 'loading'
lastPanicOutput.value = null
await nextTick()
const surface = await untilNotNull(projectRunnerSurfaceRef)
runtime.value.clearOutputs()
editorCtx.state.runtime.setRunning({ mode: 'debug', initializing: true })
try {
const filesHash = action === 'run' ? await surface.run() : await surface.rerun()
runnerState.value = 'running'
lastFilesHash.value = filesHash
editorCtx.state.runtime.setRunning({ mode: 'debug', initializing: false }, filesHash)
} catch (error) {
runnerState.value = 'running'
editorCtx.state.runtime.setRunning({ mode: 'debug', initializing: false, initializingError: error })
throw error
}
}
const canManageProject = computed(() => {
if (editorCtx.project == null) return false
const signedInUsername = signedInUser.value?.username
if (signedInUsername == null) return false
if (editorCtx.project.owner !== signedInUsername) return false
return true
})
const publishProject = usePublishProject()
const handlePublishProject = useMessageHandle(() => publishProject(editorCtx.project), {
en: 'Failed to publish project',
zh: '发布项目失败'
}).fn
const handleRun = useMessageHandle(
async () => {
await checkAndNotifyCodeError()
await checkAndNotifyMonitorError()
await executeRun('run')
},
{ en: 'Failed to run project', zh: '运行项目失败' }
)
const handleRerun = useMessageHandle(
async () => {
await executeRun('rerun')
},
{ en: 'Failed to rerun project', zh: '重新运行项目失败' }
)
const handleStop = useMessageHandle(
async () => {
const surface = projectRunnerSurfaceRef.value
if (surface == null) return
exitGuard.value = 'manualStopPending'
try {
await surface.stop()
lastPanicOutput.value = null
runnerState.value = 'initial'
editorCtx.state.runtime.setRunning({ mode: 'none' })
} catch (error) {
exitGuard.value = 'idle'
throw error
}
},
{ en: 'Failed to stop project', zh: '停止项目失败' }
)
function restoreDebugRuntime() {
const filesHash = lastFilesHash.value ?? runtime.value.filesHash
if (runnerState.value === 'loading' || filesHash == null) {
editorCtx.state.runtime.setRunning({
mode: 'debug',
initializing: true
})
return false
}
editorCtx.state.runtime.setRunning({ mode: 'debug', initializing: false }, filesHash)
return true
}
function handleFullscreenChange(value: boolean) {
fullscreen.value = value
if (value) {
if (runnerState.value !== 'initial') {
editorCtx.state.runtime.setRunning({
mode: 'debug',
initializing: runnerState.value !== 'running'
})
}
return
}
if (runnerState.value === 'initial') {
keepRunnerHostVisibleForOverlay()
editorCtx.state.runtime.setRunning({ mode: 'none' })
} else {
restoreDebugRuntime()
}
}
function handleEnterFullscreen() {
if (runnerState.value === 'initial') return
handleFullscreenChange(true)
}
onBeforeUnmount(() => {
if (runnerHostReleaseTimer != null) {
window.clearTimeout(runnerHostReleaseTimer)
runnerHostReleaseTimer = null
}
})
function getStageInlineAnchor() {
return stageContainerRef.value
}
</script>
<style scoped lang="scss">
.editor-preview {
// TODO: The fixed height here should be removed. Instead, set the StageViewer size (maintaining 4:3 aspect ratio) and let this container adapt its height accordingly.
height: 422px;
display: flex;
flex-direction: column;
position: relative;
overflow: hidden;
.header {
flex: 1;
color: var(--ui-color-title);
}
.button {
margin: 0 8px;
}
.main {
display: flex;
overflow: hidden;
justify-content: center;
padding: 12px;
height: 100%;
}
.stage-viewer-container {
position: relative;
width: 100%;
height: 100%;
border-radius: var(--ui-border-radius-1);
overflow: hidden;
background-color: var(--ui-color-grey-200);
&--running {
:deep(.stage-viewer) {
filter: blur(4px);
pointer-events: none;
user-select: none;
}
}
.runner-host {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background-color: var(--ui-color-grey-300);
:deep(.project-runner-surface) {
width: 100%;
height: 100%;
display: flex;
}
:deep(.project-runner-surface:not(.fullscreen)) {
align-items: center;
justify-content: center;
}
:deep(.project-runner-surface:not(.fullscreen) .runner) {
width: 100%;
max-width: 100%;
max-height: 100%;
aspect-ratio: 4 / 3;
height: auto;
}
}
}
}
</style>