fix(stage-web): improve performance visualizer (#2344)
This commit is contained in:
@@ -71,6 +71,7 @@
|
||||
"driver.js": "catalog:",
|
||||
"drizzle-orm": "catalog:",
|
||||
"embla-carousel-vue": "catalog:",
|
||||
"es-toolkit": "catalog:",
|
||||
"gpuu": "catalog:",
|
||||
"hono": "catalog:",
|
||||
"html2canvas": "catalog:",
|
||||
|
||||
@@ -1,24 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import type { LagMetric } from '../../stores/devtools-lag'
|
||||
|
||||
import { Button, IconButton } from '@proj-airi/ui'
|
||||
import { useDraggable, useElementBounding } from '@vueuse/core'
|
||||
import { clamp } from 'es-toolkit/math'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed, shallowRef, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import { useDevtoolsLagStore } from '../../stores/devtools-lag'
|
||||
|
||||
const { n, t } = useI18n()
|
||||
const store = useDevtoolsLagStore()
|
||||
const { enabled, buffers, recording } = storeToRefs(store)
|
||||
const { enabled, buffers, lastRecording, recording, recordingElapsedMs, supported } = storeToRefs(store)
|
||||
|
||||
const hovered = ref(false)
|
||||
const dragBoundary = useTemplateRef<HTMLElement>('dragBoundary')
|
||||
const overlay = useTemplateRef<HTMLElement>('overlay')
|
||||
const dragHandle = useTemplateRef<HTMLElement>('dragHandle')
|
||||
const positionInitialized = shallowRef(false)
|
||||
|
||||
const metrics: Array<{ key: LagMetric, label: string, enabled: () => boolean }> = [
|
||||
{ key: 'fps', label: 'FPS', enabled: () => enabled.value.fps },
|
||||
{ key: 'frameDuration', label: 'Frame (ms)', enabled: () => enabled.value.frameDuration },
|
||||
{ key: 'longtask', label: 'Long task (ms)', enabled: () => enabled.value.longtask },
|
||||
{ key: 'memory', label: 'Memory (MB)', enabled: () => enabled.value.memory },
|
||||
const metrics: Array<{ key: LagMetric, labelKey: string }> = [
|
||||
{
|
||||
key: 'fps',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.fps.label',
|
||||
},
|
||||
{
|
||||
key: 'frameDuration',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.frame-duration.label',
|
||||
},
|
||||
{
|
||||
key: 'longtask',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.long-task.label',
|
||||
},
|
||||
{
|
||||
key: 'memory',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.memory.label',
|
||||
},
|
||||
]
|
||||
|
||||
const visibleMetrics = computed(() => metrics.filter(metric => metric.enabled()))
|
||||
const visibleMetrics = computed(() => metrics.filter(metric => (
|
||||
enabled.value[metric.key] && supported.value[metric.key]
|
||||
)))
|
||||
const hasAnyEnabled = computed(() => visibleMetrics.value.length > 0)
|
||||
const metricStatsMap = computed<Record<LagMetric, ReturnType<typeof store.calcStats>>>(() => {
|
||||
const result = {} as Record<LagMetric, ReturnType<typeof store.calcStats>>
|
||||
@@ -30,20 +52,66 @@ const metricStatsMap = computed<Record<LagMetric, ReturnType<typeof store.calcSt
|
||||
})
|
||||
const metricsWithStats = computed(() => visibleMetrics.value.map(metric => ({
|
||||
...metric,
|
||||
hasSamples: buffers.value[metric.key].length > 0,
|
||||
stats: metricStatsMap.value[metric.key],
|
||||
})))
|
||||
const recordingElapsedSeconds = computed(() => Math.min(60, Math.floor(recordingElapsedMs.value / 1000)))
|
||||
const recordingButtonLabel = computed(() => recording.value
|
||||
? t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.stop')
|
||||
: t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.record'))
|
||||
|
||||
function formatValue(metric: string, value: number) {
|
||||
const { width: boundaryWidth, height: boundaryHeight } = useElementBounding(dragBoundary)
|
||||
const { width: overlayWidth, height: overlayHeight } = useElementBounding(overlay)
|
||||
const { position, isDragging } = useDraggable(overlay, {
|
||||
containerElement: dragBoundary,
|
||||
handle: dragHandle,
|
||||
preventDefault: true,
|
||||
restrictInView: true,
|
||||
onEnd() {
|
||||
positionInitialized.value = true
|
||||
clampPosition()
|
||||
},
|
||||
})
|
||||
|
||||
const overlayPosition = computed(() => ({
|
||||
left: `${position.value.x}px`,
|
||||
top: `${position.value.y}px`,
|
||||
}))
|
||||
|
||||
watch(
|
||||
[hasAnyEnabled, boundaryWidth, boundaryHeight, overlayWidth, overlayHeight],
|
||||
([visible, availableWidth, availableHeight, currentWidth, currentHeight]) => {
|
||||
if (!visible || availableWidth <= 0 || availableHeight <= 0 || currentWidth <= 0 || currentHeight <= 0)
|
||||
return
|
||||
|
||||
if (!positionInitialized.value) {
|
||||
resetPosition()
|
||||
return
|
||||
}
|
||||
|
||||
clampPosition()
|
||||
},
|
||||
{ flush: 'post' },
|
||||
)
|
||||
|
||||
function formatValue(metric: LagMetric, value: number) {
|
||||
if (!Number.isFinite(value))
|
||||
return '--'
|
||||
|
||||
if (metric === 'memory')
|
||||
return `${(value / 1048576).toFixed(1)}`
|
||||
if (metric === 'memory') {
|
||||
return n(value / 1048576, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
}
|
||||
|
||||
if (metric === 'fps')
|
||||
return value.toFixed(0)
|
||||
return n(value, { maximumFractionDigits: 0 })
|
||||
|
||||
return value.toFixed(1)
|
||||
return n(value, {
|
||||
minimumFractionDigits: 1,
|
||||
maximumFractionDigits: 1,
|
||||
})
|
||||
}
|
||||
|
||||
function barSeries(metric: LagMetric) {
|
||||
@@ -56,72 +124,133 @@ function barSeries(metric: LagMetric) {
|
||||
}))
|
||||
}
|
||||
|
||||
function toggleRecording() {
|
||||
if (recording.value) {
|
||||
const snapshot = store.stopRecording()
|
||||
if (snapshot)
|
||||
store.exportCsv(snapshot)
|
||||
return
|
||||
}
|
||||
function clampPosition(nextX = position.value.x, nextY = position.value.y) {
|
||||
const maxX = Math.max(0, boundaryWidth.value - overlayWidth.value)
|
||||
const maxY = Math.max(0, boundaryHeight.value - overlayHeight.value)
|
||||
|
||||
store.startRecording()
|
||||
position.value = {
|
||||
x: clamp(nextX, 0, maxX),
|
||||
y: clamp(nextY, 0, maxY),
|
||||
}
|
||||
}
|
||||
|
||||
function resetPosition() {
|
||||
clampPosition(0, boundaryHeight.value - overlayHeight.value)
|
||||
positionInitialized.value = true
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="hasAnyEnabled"
|
||||
:style="{ opacity: hovered ? 1 : 0.3 }"
|
||||
class="fixed bottom-3 left-3 z-50"
|
||||
p-3
|
||||
flex="~ col gap-2"
|
||||
rounded="xl"
|
||||
bg="neutral-900/80"
|
||||
text="white sm"
|
||||
shadow="xl"
|
||||
transition="opacity 200ms ease"
|
||||
@mouseenter="hovered = true"
|
||||
@mouseleave="hovered = false"
|
||||
>
|
||||
<div flex="~ row items-center gap-2" justify-between>
|
||||
<div text="xs neutral-200" uppercase tracking="wide">
|
||||
Performance Overlay
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded bg-white/10 px-2 py-1 text-xs transition-colors hover:bg-white/20"
|
||||
@click="toggleRecording"
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="hasAnyEnabled"
|
||||
ref="dragBoundary"
|
||||
:style="{
|
||||
top: 'calc(env(safe-area-inset-top, 0px) + 0.75rem)',
|
||||
right: 'calc(env(safe-area-inset-right, 0px) + 0.75rem)',
|
||||
bottom: 'calc(env(safe-area-inset-bottom, 0px) + 0.75rem)',
|
||||
left: 'calc(env(safe-area-inset-left, 0px) + 0.75rem)',
|
||||
}"
|
||||
:class="['pointer-events-none fixed z-[900]']"
|
||||
>
|
||||
<section
|
||||
ref="overlay"
|
||||
data-testid="performance-overlay"
|
||||
:style="overlayPosition"
|
||||
:class="[
|
||||
'pointer-events-auto absolute w-72 max-h-full max-w-full overflow-y-auto rounded-xl p-3',
|
||||
'flex flex-col gap-2',
|
||||
'bg-neutral-950/92 text-sm text-white shadow-xl backdrop-blur-lg',
|
||||
'transition-opacity duration-150 ease-out motion-reduce:transition-none',
|
||||
positionInitialized ? 'opacity-100' : 'opacity-0',
|
||||
isDragging ? 'select-none' : '',
|
||||
]"
|
||||
>
|
||||
<span
|
||||
class="inline-block h-2 w-2 rounded-full"
|
||||
:class="recording ? 'bg-red-400' : 'bg-neutral-400'"
|
||||
/>
|
||||
<span>{{ recording ? 'Stop' : 'Record' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<header :class="['flex items-center gap-2']">
|
||||
<div
|
||||
ref="dragHandle"
|
||||
:class="[
|
||||
'shrink-0 touch-none select-none',
|
||||
isDragging ? 'cursor-grabbing' : 'cursor-grab',
|
||||
]"
|
||||
>
|
||||
<IconButton
|
||||
icon="i-solar:menu-dots-bold-duotone"
|
||||
:aria-label="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.move')"
|
||||
:title="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.move')"
|
||||
/>
|
||||
</div>
|
||||
<div :class="['min-w-0 flex-1 truncate text-xs font-medium text-neutral-200 uppercase tracking-wide']">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.title') }}
|
||||
</div>
|
||||
<IconButton
|
||||
icon="i-solar:restart-bold-duotone"
|
||||
:aria-label="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.reset-position')"
|
||||
:title="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.reset-position')"
|
||||
@click="resetPosition"
|
||||
/>
|
||||
</header>
|
||||
|
||||
<div v-for="metric in metricsWithStats" :key="metric.key" flex="~ col gap-1">
|
||||
<div flex="~ row items-center justify-between">
|
||||
<span text="xs neutral-100">{{ metric.label }}</span>
|
||||
<span text="xs neutral-300">
|
||||
<template v-if="metric.stats.latest">
|
||||
avg {{ formatValue(metric.key, metric.stats.avg) }}
|
||||
/
|
||||
p95 {{ formatValue(metric.key, metric.stats.p95) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
--
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-10 flex items-end gap-0.5 overflow-hidden rounded bg-white/5 px-1 py-1">
|
||||
<div
|
||||
v-for="(bar, index) in barSeries(metric.key)"
|
||||
:key="index"
|
||||
:style="{ width: bar.width, height: bar.height }"
|
||||
class="bg-white/50"
|
||||
/>
|
||||
</div>
|
||||
v-for="metric in metricsWithStats"
|
||||
:key="metric.key"
|
||||
:class="['flex flex-col gap-1']"
|
||||
>
|
||||
<div :class="['flex items-center justify-between gap-3']">
|
||||
<span :class="['min-w-0 truncate text-xs text-neutral-100']">
|
||||
{{ t(metric.labelKey) }}
|
||||
</span>
|
||||
<span :class="['shrink-0 font-mono text-xs text-neutral-300 tabular-nums']">
|
||||
<template v-if="metric.hasSamples">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.average') }}
|
||||
{{ formatValue(metric.key, metric.stats.avg) }}
|
||||
/
|
||||
p95 {{ formatValue(metric.key, metric.stats.p95) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
--
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
:class="['h-10 overflow-hidden rounded bg-white/5 px-1 py-1', 'flex items-end gap-0.5']"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<div
|
||||
v-for="(bar, index) in barSeries(metric.key)"
|
||||
:key="index"
|
||||
:style="{ width: bar.width, height: bar.height }"
|
||||
:class="['bg-white/50']"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer :class="['flex items-center gap-2 pt-2']">
|
||||
<Button
|
||||
size="sm"
|
||||
:icon="recording ? 'i-solar:stop-circle-bold-duotone' : 'i-solar:record-circle-bold-duotone'"
|
||||
:label="recordingButtonLabel"
|
||||
:color="recording ? 'red' : 'neutral'"
|
||||
:outline="false"
|
||||
@click="store.toggleRecording"
|
||||
/>
|
||||
<span
|
||||
v-if="recording"
|
||||
:class="['font-mono text-xs text-neutral-300 tabular-nums']"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{{ n(recordingElapsedSeconds) }}s / 60s
|
||||
</span>
|
||||
<span v-else :class="['flex-1']" />
|
||||
<IconButton
|
||||
icon="i-solar:export-bold-duotone"
|
||||
:disabled="!lastRecording"
|
||||
:aria-label="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.export')"
|
||||
:title="t('tamagotchi.settings.devtools.pages.performance-visualizer.overlay.export')"
|
||||
@click="store.exportCsv()"
|
||||
/>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import en from '@proj-airi/i18n/locales/en'
|
||||
|
||||
import { createPinia } from 'pinia'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { render } from 'vitest-browser-vue'
|
||||
import { createI18n } from 'vue-i18n'
|
||||
|
||||
import PerformanceOverlay from './PerformanceOverlay.vue'
|
||||
|
||||
import { useDevtoolsLagStore } from '../../stores/devtools-lag'
|
||||
|
||||
import 'virtual:uno.css'
|
||||
|
||||
describe('performance overlay recording controls', () => {
|
||||
it('keeps CSV export separate from stopping a recording', async () => {
|
||||
// ROOT CAUSE:
|
||||
//
|
||||
// The overlay exported a CSV file when the user stopped a recording.
|
||||
// The settings page only saved the recording, so the same action had two
|
||||
// different outcomes. We keep export as a separate explicit action.
|
||||
const pinia = createPinia()
|
||||
const store = useDevtoolsLagStore(pinia)
|
||||
const exportCsv = vi.spyOn(store, 'exportCsv')
|
||||
store.enabled.fps = true
|
||||
|
||||
const screen = await render(PerformanceOverlay, {
|
||||
global: {
|
||||
plugins: [
|
||||
pinia,
|
||||
createI18n({
|
||||
legacy: false,
|
||||
locale: 'en',
|
||||
messages: {
|
||||
en,
|
||||
},
|
||||
}),
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
await screen.getByRole('button', { name: 'Record', exact: true }).click()
|
||||
expect(store.recording).toBe(true)
|
||||
|
||||
await screen.getByRole('button', { name: 'Stop', exact: true }).click()
|
||||
expect(store.recording).toBe(false)
|
||||
expect(exportCsv).not.toHaveBeenCalled()
|
||||
|
||||
store.toggleAll(false)
|
||||
})
|
||||
})
|
||||
@@ -7,12 +7,28 @@ interface LagEnabled {
|
||||
memory: boolean
|
||||
}
|
||||
|
||||
type LagMetricSupport = Readonly<Record<keyof LagEnabled, boolean>>
|
||||
|
||||
/**
|
||||
* Creates a browser-local sampler for live performance metrics.
|
||||
*
|
||||
* Unsupported metrics stay disabled because their Web APIs do not produce
|
||||
* comparable fallback values.
|
||||
*/
|
||||
export function createLagSampler(tracer: PerfTracer) {
|
||||
let rafId: number | undefined
|
||||
let lastTs: number | undefined
|
||||
let longTaskObserver: PerformanceObserver | undefined
|
||||
let memoryTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const supported: LagMetricSupport = {
|
||||
fps: typeof requestAnimationFrame === 'function',
|
||||
frameDuration: typeof requestAnimationFrame === 'function',
|
||||
longtask: typeof PerformanceObserver !== 'undefined'
|
||||
&& PerformanceObserver.supportedEntryTypes.includes('longtask'),
|
||||
memory: typeof performance !== 'undefined' && 'memory' in performance,
|
||||
}
|
||||
|
||||
function stopRaf() {
|
||||
if (rafId !== undefined) {
|
||||
cancelAnimationFrame(rafId)
|
||||
@@ -58,7 +74,7 @@ export function createLagSampler(tracer: PerfTracer) {
|
||||
|
||||
function startLongTaskObserver() {
|
||||
stopLongTaskObserver()
|
||||
if (!('PerformanceObserver' in window))
|
||||
if (!supported.longtask)
|
||||
return
|
||||
|
||||
try {
|
||||
@@ -89,7 +105,7 @@ export function createLagSampler(tracer: PerfTracer) {
|
||||
function startMemoryTimer() {
|
||||
stopMemoryTimer()
|
||||
const perfWithMemory = performance as Performance & { memory?: { usedJSHeapSize: number } }
|
||||
if (!perfWithMemory.memory)
|
||||
if (!supported.memory || !perfWithMemory.memory)
|
||||
return
|
||||
|
||||
memoryTimer = setInterval(() => {
|
||||
@@ -105,13 +121,13 @@ export function createLagSampler(tracer: PerfTracer) {
|
||||
function start(enabled: LagEnabled) {
|
||||
stop()
|
||||
|
||||
if (enabled.fps || enabled.frameDuration)
|
||||
if ((enabled.fps && supported.fps) || (enabled.frameDuration && supported.frameDuration))
|
||||
startRaf()
|
||||
|
||||
if (enabled.longtask)
|
||||
if (enabled.longtask && supported.longtask)
|
||||
startLongTaskObserver()
|
||||
|
||||
if (enabled.memory)
|
||||
if (enabled.memory && supported.memory)
|
||||
startMemoryTimer()
|
||||
}
|
||||
|
||||
@@ -122,6 +138,7 @@ export function createLagSampler(tracer: PerfTracer) {
|
||||
}
|
||||
|
||||
return {
|
||||
supported,
|
||||
start,
|
||||
stop,
|
||||
}
|
||||
|
||||
@@ -1,111 +1,161 @@
|
||||
<script setup lang="ts">
|
||||
import { ButtonBar, CheckBar } from '@proj-airi/stage-ui/components'
|
||||
import type { LagMetric } from '../../stores/devtools-lag'
|
||||
|
||||
import { Button, FieldCheckbox } from '@proj-airi/ui'
|
||||
import { useMagicKeys, whenever } from '@vueuse/core'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
import { useDevtoolsLagStore } from '../../stores/devtools-lag'
|
||||
|
||||
const { n, t } = useI18n()
|
||||
const lagStore = useDevtoolsLagStore()
|
||||
const { enabled, lastRecording, recording } = storeToRefs(lagStore)
|
||||
const { enabled, lastRecording, recording, recordingElapsedMs, supported } = storeToRefs(lagStore)
|
||||
|
||||
const recordingLabel = computed(() => recording.value ? 'Stop recording (max 60s)' : 'Start recording')
|
||||
const metricDefinitions: Array<{
|
||||
key: LagMetric
|
||||
labelKey: string
|
||||
descriptionKey: string
|
||||
unsupportedKey?: string
|
||||
}> = [
|
||||
{
|
||||
key: 'fps',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.fps.label',
|
||||
descriptionKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.fps.description',
|
||||
},
|
||||
{
|
||||
key: 'frameDuration',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.frame-duration.label',
|
||||
descriptionKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.frame-duration.description',
|
||||
},
|
||||
{
|
||||
key: 'longtask',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.long-task.label',
|
||||
descriptionKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.long-task.description',
|
||||
unsupportedKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.long-task.unsupported',
|
||||
},
|
||||
{
|
||||
key: 'memory',
|
||||
labelKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.memory.label',
|
||||
descriptionKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.memory.description',
|
||||
unsupportedKey: 'tamagotchi.settings.devtools.pages.performance-visualizer.metrics.memory.unsupported',
|
||||
},
|
||||
]
|
||||
|
||||
const metricControls = computed(() => metricDefinitions.map(metric => ({
|
||||
...metric,
|
||||
supported: supported.value[metric.key],
|
||||
})))
|
||||
const recordingElapsedSeconds = computed(() => Math.min(60, Math.floor(recordingElapsedMs.value / 1000)))
|
||||
const recordingLabel = computed(() => recording.value
|
||||
? t('tamagotchi.settings.devtools.pages.performance-visualizer.controls.stop-recording', { seconds: recordingElapsedSeconds.value })
|
||||
: t('tamagotchi.settings.devtools.pages.performance-visualizer.controls.start-recording'))
|
||||
const hasRecording = computed(() => !!lastRecording.value)
|
||||
const allEnabled = computed(() => enabled.value.fps && enabled.value.frameDuration && enabled.value.longtask && enabled.value.memory)
|
||||
const allEnabled = computed({
|
||||
get() {
|
||||
const supportedMetrics = metricDefinitions.filter(metric => supported.value[metric.key])
|
||||
return supportedMetrics.length > 0
|
||||
&& supportedMetrics.every(metric => enabled.value[metric.key])
|
||||
},
|
||||
set(value: boolean) {
|
||||
lagStore.toggleAll(value)
|
||||
},
|
||||
})
|
||||
|
||||
const magicKeys = useMagicKeys()
|
||||
whenever(magicKeys['ctrl+alt+l'], () => toggleAll(true))
|
||||
whenever(magicKeys['ctrl+alt+k'], () => toggleAll(false))
|
||||
|
||||
function toggleAll(on: boolean) {
|
||||
lagStore.toggleAll(on)
|
||||
}
|
||||
whenever(magicKeys['ctrl+alt+l'], () => lagStore.toggleAll(true))
|
||||
whenever(magicKeys['ctrl+alt+k'], () => lagStore.toggleAll(false))
|
||||
|
||||
function exportCsv() {
|
||||
lagStore.exportCsv()
|
||||
}
|
||||
|
||||
function metricDescription(metric: typeof metricControls.value[number]) {
|
||||
if (metric.supported || !metric.unsupportedKey)
|
||||
return t(metric.descriptionKey)
|
||||
|
||||
return t(metric.unsupportedKey)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div flex="~ col gap-4" pb-6>
|
||||
<div flex="~ col gap-2">
|
||||
<div flex="~ row items-center gap-2">
|
||||
<CheckBar
|
||||
:model-value="allEnabled"
|
||||
icon-on="i-solar:sledgehammer-bold-duotone"
|
||||
icon-off="i-solar:sledgehammer-bold-duotone"
|
||||
text="Enable all metrics"
|
||||
description="Toggle all lag metrics (FPS, frame time, long task, memory)"
|
||||
@update:model-value="value => toggleAll(Boolean(value))"
|
||||
/>
|
||||
<ButtonBar
|
||||
:icon="recording ? 'i-solar:stop-circle-bold-duotone' : 'i-solar:recive-bold-duotone'"
|
||||
text="Recording"
|
||||
@click="recording ? lagStore.stopRecording() : lagStore.startRecording()"
|
||||
>
|
||||
{{ recordingLabel }}
|
||||
</ButtonBar>
|
||||
<ButtonBar
|
||||
icon="i-solar:export-bold-duotone"
|
||||
text="Export CSV"
|
||||
:disabled="!hasRecording"
|
||||
@click="exportCsv"
|
||||
>
|
||||
Export last recording
|
||||
</ButtonBar>
|
||||
</div>
|
||||
<div :class="['flex flex-col gap-4', 'pb-6']">
|
||||
<section
|
||||
:class="[
|
||||
'rounded-2xl p-4',
|
||||
'bg-neutral-50/80 dark:bg-neutral-900/50',
|
||||
]"
|
||||
>
|
||||
<FieldCheckbox
|
||||
v-model="allEnabled"
|
||||
:label="t('tamagotchi.settings.devtools.pages.performance-visualizer.controls.enable-all.label')"
|
||||
:description="t('tamagotchi.settings.devtools.pages.performance-visualizer.controls.enable-all.description')"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<div flex="~ col gap-2">
|
||||
<CheckBar
|
||||
v-model="enabled.fps"
|
||||
icon-on="i-solar:activity-bold-duotone"
|
||||
icon-off="i-solar:activity-bold-duotone"
|
||||
text="FPS"
|
||||
description="Collect FPS histogram"
|
||||
/>
|
||||
<CheckBar
|
||||
v-model="enabled.frameDuration"
|
||||
icon-on="i-solar:chart-bold-duotone"
|
||||
icon-off="i-solar:chart-bold-duotone"
|
||||
text="Frame time (ms)"
|
||||
description="Collect frame duration histogram"
|
||||
/>
|
||||
<CheckBar
|
||||
v-model="enabled.longtask"
|
||||
icon-on="i-solar:timer-bold-duotone"
|
||||
icon-off="i-solar:timer-bold-duotone"
|
||||
text="Long tasks"
|
||||
description="PerformanceObserver('longtask')"
|
||||
/>
|
||||
<CheckBar
|
||||
v-model="enabled.memory"
|
||||
icon-on="i-solar:database-bold-duotone"
|
||||
icon-off="i-solar:database-bold-duotone"
|
||||
text="Memory"
|
||||
description="Sample performance.memory every second"
|
||||
/>
|
||||
</div>
|
||||
<div :class="['flex flex-wrap items-center gap-2']">
|
||||
<Button
|
||||
:icon="recording ? 'i-solar:stop-circle-bold-duotone' : 'i-solar:record-circle-bold-duotone'"
|
||||
:label="recordingLabel"
|
||||
:color="recording ? 'red' : 'primary'"
|
||||
variant="secondary"
|
||||
@click="lagStore.toggleRecording"
|
||||
/>
|
||||
<Button
|
||||
icon="i-solar:export-bold-duotone"
|
||||
:label="t('tamagotchi.settings.devtools.pages.performance-visualizer.controls.export-last-recording')"
|
||||
:disabled="!hasRecording"
|
||||
@click="exportCsv"
|
||||
/>
|
||||
<span :class="['text-xs text-neutral-500 dark:text-neutral-400']">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.recording.limit') }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="hasRecording" flex="~ col gap-2" rounded="lg" border="1 dashed neutral-700" p-3>
|
||||
<div text="sm neutral-200">
|
||||
Last recording
|
||||
</div>
|
||||
<div text="xs neutral-400">
|
||||
Started at {{ lastRecording?.startedAt.toFixed(0) }} ms, duration
|
||||
{{ (lastRecording!.stoppedAt - lastRecording!.startedAt).toFixed(0) }} ms
|
||||
</div>
|
||||
<div text="xs neutral-400">
|
||||
Samples:
|
||||
FPS {{ lastRecording?.samples.fps.length }},
|
||||
Frames {{ lastRecording?.samples.frameDuration.length }},
|
||||
Long tasks {{ lastRecording?.samples.longtask.length }},
|
||||
Memory {{ lastRecording?.samples.memory.length }}
|
||||
</div>
|
||||
<div :class="['grid gap-3', 'md:grid-cols-2']">
|
||||
<section
|
||||
v-for="metric in metricControls"
|
||||
:key="metric.key"
|
||||
:class="[
|
||||
'min-w-0 rounded-2xl p-4',
|
||||
'bg-neutral-50/80 dark:bg-neutral-900/50',
|
||||
]"
|
||||
>
|
||||
<FieldCheckbox
|
||||
v-model="enabled[metric.key]"
|
||||
:label="t(metric.labelKey)"
|
||||
:description="metricDescription(metric)"
|
||||
:disabled="!metric.supported"
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div text="xs neutral-500">
|
||||
Overlay is visible when any metric is enabled. Recording caps at 60s.
|
||||
<section
|
||||
v-if="lastRecording"
|
||||
:class="[
|
||||
'flex flex-col gap-2 rounded-2xl p-4',
|
||||
'border border-dashed border-neutral-300 dark:border-neutral-700',
|
||||
]"
|
||||
>
|
||||
<div :class="['text-sm font-medium text-neutral-800 dark:text-neutral-200']">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.recording.title') }}
|
||||
</div>
|
||||
<div :class="['text-xs text-neutral-500 dark:text-neutral-400']">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.recording.duration', {
|
||||
duration: n(lastRecording.stoppedAt - lastRecording.startedAt, { maximumFractionDigits: 0 }),
|
||||
}) }}
|
||||
</div>
|
||||
<div :class="['grid gap-1 text-xs text-neutral-500 dark:text-neutral-400', 'sm:grid-cols-2 lg:grid-cols-4']">
|
||||
<span>{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.metrics.fps.label') }}: {{ n(lastRecording.samples.fps.length) }}</span>
|
||||
<span>{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.metrics.frame-duration.label') }}: {{ n(lastRecording.samples.frameDuration.length) }}</span>
|
||||
<span>{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.metrics.long-task.label') }}: {{ n(lastRecording.samples.longtask.length) }}</span>
|
||||
<span>{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.metrics.memory.label') }}: {{ n(lastRecording.samples.memory.length) }}</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div :class="['text-xs text-neutral-500 dark:text-neutral-400']">
|
||||
{{ t('tamagotchi.settings.devtools.pages.performance-visualizer.description') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { TraceEvent } from '@proj-airi/stage-shared'
|
||||
|
||||
import { defaultPerfTracer, exportCsv as exportCsvFile } from '@proj-airi/stage-shared'
|
||||
import { defineStore } from 'pinia'
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { onScopeDispose, reactive, ref, shallowRef, watch } from 'vue'
|
||||
|
||||
import { createLagSampler } from '../composables/perf/register-lag-sampler'
|
||||
|
||||
@@ -11,7 +11,7 @@ export type LagMetric = 'fps' | 'frameDuration' | 'longtask' | 'memory'
|
||||
interface Sample {
|
||||
ts: number
|
||||
value: number
|
||||
meta?: Record<string, any>
|
||||
meta?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface RecordingSnapshot {
|
||||
@@ -49,7 +49,7 @@ function calcStats(values: number[]) {
|
||||
const sorted = [...values].sort((a, b) => a - b)
|
||||
const idx = Math.max(0, Math.floor(0.95 * (sorted.length - 1)))
|
||||
const p95 = sorted[idx]
|
||||
const latest = values.at(-1)
|
||||
const latest = values.at(-1) ?? 0
|
||||
|
||||
return { avg, p95, latest }
|
||||
}
|
||||
@@ -99,11 +99,14 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
|
||||
const recording = ref(false)
|
||||
const recordingStartedAt = ref<number | null>(null)
|
||||
const recordingElapsedMs = ref(0)
|
||||
const recordingSamples = reactive(createEmptySamples())
|
||||
const lastRecording = ref<RecordingSnapshot>()
|
||||
let recordingTimeout: ReturnType<typeof setTimeout> | undefined
|
||||
let recordingElapsedTimer: ReturnType<typeof setInterval> | undefined
|
||||
|
||||
const sampler = createLagSampler(defaultPerfTracer)
|
||||
const supported = shallowRef(sampler.supported)
|
||||
let unsubscribeTracer: (() => void) | undefined
|
||||
let releaseTracer: (() => void) | undefined
|
||||
|
||||
@@ -112,7 +115,7 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
recordingSamples[metric] = []
|
||||
}
|
||||
|
||||
function applySample(metric: LagMetric, value: number, meta?: Record<string, any>) {
|
||||
function applySample(metric: LagMetric, value: number, meta?: Record<string, unknown>) {
|
||||
const ts = performance.now()
|
||||
const cutoff = ts - windowMs
|
||||
|
||||
@@ -132,8 +135,15 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
|
||||
recording.value = true
|
||||
recordingStartedAt.value = performance.now()
|
||||
recordingElapsedMs.value = 0
|
||||
resetRecordingSamples()
|
||||
|
||||
recordingElapsedTimer = setInterval(() => {
|
||||
if (recordingStartedAt.value === null)
|
||||
return
|
||||
|
||||
recordingElapsedMs.value = performance.now() - recordingStartedAt.value
|
||||
}, 1000)
|
||||
recordingTimeout = setTimeout(stopRecording, 60000)
|
||||
}
|
||||
|
||||
@@ -145,10 +155,17 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
clearTimeout(recordingTimeout)
|
||||
recordingTimeout = undefined
|
||||
}
|
||||
if (recordingElapsedTimer) {
|
||||
clearInterval(recordingElapsedTimer)
|
||||
recordingElapsedTimer = undefined
|
||||
}
|
||||
|
||||
const stoppedAt = performance.now()
|
||||
recordingElapsedMs.value = recordingStartedAt.value === null
|
||||
? 0
|
||||
: stoppedAt - recordingStartedAt.value
|
||||
const snapshot: RecordingSnapshot = {
|
||||
startedAt: recordingStartedAt.value || stoppedAt,
|
||||
startedAt: recordingStartedAt.value ?? stoppedAt,
|
||||
stoppedAt,
|
||||
samples: {
|
||||
fps: [...recordingSamples.fps],
|
||||
@@ -165,6 +182,13 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
function toggleRecording(): RecordingSnapshot | undefined {
|
||||
if (recording.value)
|
||||
return stopRecording()
|
||||
|
||||
startRecording()
|
||||
}
|
||||
|
||||
function stopAll() {
|
||||
sampler.stop()
|
||||
if (unsubscribeTracer) {
|
||||
@@ -176,7 +200,10 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
}
|
||||
|
||||
function ensureSampler() {
|
||||
const anyEnabled = enabled.fps || enabled.frameDuration || enabled.longtask || enabled.memory
|
||||
const anyEnabled = (enabled.fps && supported.value.fps)
|
||||
|| (enabled.frameDuration && supported.value.frameDuration)
|
||||
|| (enabled.longtask && supported.value.longtask)
|
||||
|| (enabled.memory && supported.value.memory)
|
||||
if (!anyEnabled) {
|
||||
stopAll()
|
||||
return
|
||||
@@ -206,18 +233,18 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
if (!releaseTracer)
|
||||
releaseTracer = defaultPerfTracer.acquire('lag-overlay')
|
||||
sampler.start({
|
||||
fps: enabled.fps,
|
||||
frameDuration: enabled.frameDuration,
|
||||
longtask: enabled.longtask,
|
||||
memory: enabled.memory,
|
||||
fps: enabled.fps && supported.value.fps,
|
||||
frameDuration: enabled.frameDuration && supported.value.frameDuration,
|
||||
longtask: enabled.longtask && supported.value.longtask,
|
||||
memory: enabled.memory && supported.value.memory,
|
||||
})
|
||||
}
|
||||
|
||||
function toggleAll(on: boolean) {
|
||||
enabled.fps = on
|
||||
enabled.frameDuration = on
|
||||
enabled.longtask = on
|
||||
enabled.memory = on
|
||||
enabled.fps = on && supported.value.fps
|
||||
enabled.frameDuration = on && supported.value.frameDuration
|
||||
enabled.longtask = on && supported.value.longtask
|
||||
enabled.memory = on && supported.value.memory
|
||||
ensureSampler()
|
||||
}
|
||||
|
||||
@@ -250,11 +277,16 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
// Cleanup on tab close
|
||||
function dispose() {
|
||||
stopRecording()
|
||||
stopAll()
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('beforeunload', () => {
|
||||
stopRecording()
|
||||
stopAll()
|
||||
window.addEventListener('beforeunload', dispose)
|
||||
onScopeDispose(() => {
|
||||
window.removeEventListener('beforeunload', dispose)
|
||||
dispose()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -262,9 +294,12 @@ export const useDevtoolsLagStore = defineStore('devtoolsLag', () => {
|
||||
enabled,
|
||||
buffers,
|
||||
recording,
|
||||
recordingElapsedMs,
|
||||
lastRecording,
|
||||
supported,
|
||||
startRecording,
|
||||
stopRecording,
|
||||
toggleRecording,
|
||||
exportCsv,
|
||||
toggleAll,
|
||||
calcStats,
|
||||
|
||||
@@ -1542,7 +1542,7 @@ pages:
|
||||
section:
|
||||
performance-visualizer:
|
||||
title: Performance Visualizer
|
||||
description: Toggle FPS/long task/memory overlay
|
||||
description: Show FPS, frame time, long tasks, and supported browser memory metrics
|
||||
markdown-stress:
|
||||
title: Markdown Stress
|
||||
description: Stress markdown parsing and rendering with heavy chat payloads
|
||||
|
||||
@@ -57,7 +57,41 @@ devtools:
|
||||
title: Lag Visualizer
|
||||
performance-visualizer:
|
||||
title: Performance Visualizer
|
||||
description: Toggle FPS/long task/memory overlay
|
||||
description: Inspect live performance metrics and runtime diagnostics
|
||||
controls:
|
||||
enable-all:
|
||||
label: Enable all available metrics
|
||||
description: Enable each metric that this browser supports.
|
||||
start-recording: Start recording
|
||||
stop-recording: Stop recording ({seconds}s)
|
||||
export-last-recording: Export last recording
|
||||
metrics:
|
||||
fps:
|
||||
label: FPS
|
||||
description: Frames per second during the last 10 seconds.
|
||||
frame-duration:
|
||||
label: Frame time (ms)
|
||||
description: Time between animation frames during the last 10 seconds.
|
||||
long-task:
|
||||
label: Long tasks
|
||||
description: Main-thread tasks that take at least 50 ms.
|
||||
unsupported: This browser does not expose long-task timing.
|
||||
memory:
|
||||
label: JS heap (MB)
|
||||
description: JavaScript heap usage from Chromium's performance.memory API.
|
||||
unsupported: This browser does not expose JavaScript heap usage.
|
||||
recording:
|
||||
title: Last recording
|
||||
duration: Duration {duration} ms
|
||||
limit: Recording stops after 60 seconds.
|
||||
overlay:
|
||||
title: Performance
|
||||
move: Move performance overlay
|
||||
reset-position: Reset overlay position
|
||||
record: Record
|
||||
stop: Stop
|
||||
export: Export last recording
|
||||
average: avg
|
||||
markdown-stress:
|
||||
title: Markdown Stress
|
||||
description: Stress markdown parsing and rendering with heavy chat payloads
|
||||
|
||||
@@ -1476,7 +1476,7 @@ pages:
|
||||
section:
|
||||
performance-visualizer:
|
||||
title: 性能可视化工具
|
||||
description: 切换 FPS/长任务/内存叠加
|
||||
description: 显示 FPS、帧时间、长任务和浏览器支持的内存指标
|
||||
markdown-stress:
|
||||
title: Markdown Stress
|
||||
description: 用大量聊天负载来测试 Markdown 的解析和渲染能力
|
||||
|
||||
@@ -57,7 +57,41 @@ devtools:
|
||||
title: Lag 可视化
|
||||
performance-visualizer:
|
||||
title: 性能可视化
|
||||
description: 切换 FPS/长任务/内存叠加
|
||||
description: 检查实时性能指标和运行时诊断数据
|
||||
controls:
|
||||
enable-all:
|
||||
label: 启用所有可用指标
|
||||
description: 启用当前浏览器支持的所有指标。
|
||||
start-recording: 开始录制
|
||||
stop-recording: 停止录制({seconds} 秒)
|
||||
export-last-recording: 导出上次录制
|
||||
metrics:
|
||||
fps:
|
||||
label: FPS
|
||||
description: 最近 10 秒内的每秒帧数。
|
||||
frame-duration:
|
||||
label: 帧时间(毫秒)
|
||||
description: 最近 10 秒内动画帧之间的时间。
|
||||
long-task:
|
||||
label: 长任务
|
||||
description: 耗时至少 50 毫秒的主线程任务。
|
||||
unsupported: 当前浏览器不提供长任务计时。
|
||||
memory:
|
||||
label: JS 堆(MB)
|
||||
description: Chromium performance.memory API 提供的 JavaScript 堆用量。
|
||||
unsupported: 当前浏览器不提供 JavaScript 堆用量。
|
||||
recording:
|
||||
title: 上次录制
|
||||
duration: 时长 {duration} 毫秒
|
||||
limit: 录制会在 60 秒后停止。
|
||||
overlay:
|
||||
title: 性能
|
||||
move: 移动性能浮窗
|
||||
reset-position: 重置浮窗位置
|
||||
record: 录制
|
||||
stop: 停止
|
||||
export: 导出上次录制
|
||||
average: 平均
|
||||
markdown-stress:
|
||||
title: Markdown 压力测试
|
||||
description: 用大量聊天负载来测试 Markdown 的解析和渲染能力
|
||||
|
||||
Generated
+3
@@ -2491,6 +2491,9 @@ importers:
|
||||
embla-carousel-vue:
|
||||
specifier: 'catalog:'
|
||||
version: 9.0.0-rc02(vue@3.5.32(typescript@5.9.3))
|
||||
es-toolkit:
|
||||
specifier: 'catalog:'
|
||||
version: 1.50.0
|
||||
gpuu:
|
||||
specifier: 'catalog:'
|
||||
version: 1.0.7
|
||||
|
||||
Reference in New Issue
Block a user