All files / src/components FpsMonitor.vue

0% Statements 0/63
0% Branches 0/22
0% Functions 0/15
0% Lines 0/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { RotateCcw } from '@lucide/vue'
import Button from '@/components/ui/button/button.vue'
 
defineOptions({ inheritAttrs: false })
 
/* ---------- props ---------- */
const props = defineProps({
  /** 采样间隔(毫秒):FPS 上报与柱状图刷新周期 */
  sampleInterval: { type: Number, default: 500 },
  /** 柱状图保留的历史帧数 */
  historySize: { type: Number, default: 48 },
  /** 基准 FPS:用于颜色分级与柱高换算 */
  baseFps: { type: Number, default: 60 },
})
 
/* ---------- 公共状态 ---------- */
const currentFps = ref(0)
const averageFps = ref(0)
const minimumFps = ref(null)
const history = ref([])
 
/* 非法入参归一化:采样间隔/帧数/基准值过低时取最小值,避免除零或空图 */
const normalizedSampleInterval = computed(() => Math.max(100, props.sampleInterval))
const normalizedHistorySize = computed(() => Math.max(1, Math.floor(props.historySize)))
const normalizedBaseFps = computed(() => Math.max(1, props.baseFps))
 
/* rAF 循环高频写入的窗口计数保持普通变量,避免无谓的响应式开销 */
let animationFrameId = 0
let sampleFrames = 0
let sampleStartedAt = 0
let totalFrames = 0
let totalTime = 0
 
/* ---------- FPS 采样 ---------- */
function resetSampleWindow() {
  sampleFrames = 0
  sampleStartedAt = performance.now()
}
 
function tick(now) {
  sampleFrames += 1
  totalFrames += 1
 
  const elapsed = now - sampleStartedAt
  if (elapsed >= normalizedSampleInterval.value) {
    const fps = Math.round((sampleFrames * 1000) / elapsed)
    currentFps.value = fps
    minimumFps.value = minimumFps.value == null ? fps : Math.min(minimumFps.value, fps)
    totalTime += elapsed
    averageFps.value = Math.round((totalFrames * 1000) / totalTime)
    history.value = [...history.value, fps].slice(-normalizedHistorySize.value)
    sampleFrames = 0
    sampleStartedAt = now
  }
 
  animationFrameId = requestAnimationFrame(tick)
}
 
/* ---------- 统计重置 ---------- */
function reset() {
  currentFps.value = 0
  averageFps.value = 0
  minimumFps.value = null
  history.value = []
  totalFrames = 0
  totalTime = 0
  resetSampleWindow()
}
 
/* 切后台时浏览器暂停 rAF,恢复前台后重置采样窗口,避免把暂停时长计入均值 */
function handleVisibilityChange() {
  if (!document.hidden) resetSampleWindow()
}
 
/* ---------- 颜色分级与柱状图 ---------- */
function getFpsColor(fps) {
  if (fps >= normalizedBaseFps.value * (5 / 6)) return 'var(--fms-success)'
  if (fps >= normalizedBaseFps.value / 2) return 'var(--fms-warning)'
  return 'var(--fms-danger)'
}
 
const currentFpsColor = computed(() => getFpsColor(currentFps.value))
 
/* 柱高按基准 FPS 换算并夹在 8%–100%,保证低帧率时仍有可见柱体 */
const barStyles = computed(() =>
  history.value.map((fps) => {
    const height = Math.max(8, Math.min(100, (fps / normalizedBaseFps.value) * 100))
    return {
      height: `${height}%`,
      backgroundColor: getFpsColor(fps),
    }
  }),
)
 
/* ---------- 生命周期 ---------- */
onMounted(() => {
  resetSampleWindow()
  document.addEventListener('visibilitychange', handleVisibilityChange)
  animationFrameId = requestAnimationFrame(tick)
})
 
onBeforeUnmount(() => {
  cancelAnimationFrame(animationFrameId)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>
 
<template>
  <aside class="fps-monitor" aria-label="FPS 性能监控" v-bind="$attrs">
    <div class="fps-monitor__header">
      <span class="fps-monitor__label">FPS</span>
      <strong class="fps-monitor__current" :style="{ color: currentFpsColor }">
        {{ currentFps || '--' }}
      </strong>
      <Button
        type="ghost"
        class="fps-monitor__reset"
        title="重置统计"
        aria-label="重置 FPS 统计"
        @click="reset"
      >
        <RotateCcw />
      </Button>
    </div>
 
    <div class="fps-monitor__chart" aria-hidden="true">
      <span v-for="(bar, index) in barStyles" :key="index" class="fps-monitor__bar" :style="bar" />
    </div>
 
    <div class="fps-monitor__summary">
      <span
        >avg <b>{{ averageFps || '--' }}</b></span
      >
      <span
        >min <b>{{ minimumFps ?? '--' }}</b></span
      >
    </div>
  </aside>
</template>
 
<style scoped lang="scss">
.fps-monitor {
  position: fixed;
  top: 8px;
  right: 8px;
  z-index: var(--fms-z-popover);
  display: flex;
  flex-direction: column;
  gap: 6px;
  width: 132px;
  padding: 8px 10px;
  color: var(--fms-text);
  font-size: 12px;
  line-height: 1.4;
  letter-spacing: 0;
  user-select: none;
  background: var(--fms-card);
  border: 1px solid var(--fms-border);
  border-radius: var(--fms-control-radius);
  box-shadow: var(--fms-popover-shadow);
}
 
.fps-monitor__header {
  display: flex;
  align-items: center;
  gap: 6px;
  min-height: 24px;
}
 
.fps-monitor__label {
  color: var(--fms-text-secondary);
  font-weight: 600;
}
 
.fps-monitor__current {
  flex: 1;
  font-size: 18px;
  font-variant-numeric: tabular-nums;
  line-height: 1;
}
 
.fps-monitor__chart {
  display: flex;
  align-items: flex-end;
  gap: 1px;
  height: 32px;
  overflow: hidden;
}
 
.fps-monitor__bar {
  flex: 1;
  min-width: 0;
  border-radius: 1px;
}
 
.fps-monitor__summary {
  display: flex;
  justify-content: space-between;
  color: var(--fms-text-secondary);
}
 
.fps-monitor__summary b {
  color: var(--fms-text);
  font-variant-numeric: tabular-nums;
}
 
/* 重置按钮:组件库 Button 无 size 枚举,在 ghost 变体基础上压缩为 20×20 小方钮 */
.fps-monitor .fps-monitor__reset {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  min-height: 0;
  padding: 0;
  border: none;
  border-radius: var(--fms-control-radius);
  font-size: 14px;
  line-height: 1;
  color: var(--fms-text-secondary);
  cursor: pointer;
  transition:
    background-color 150ms ease,
    color 150ms ease;
 
  &:hover {
    background: var(--fms-secondary-hover);
    color: var(--fms-text);
  }
}
</style>