Files
filecodebox/src/components/common/SmoothTrendCanvas.vue
T

459 lines
15 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="relative overflow-visible rounded-[30px] border" :class="panelClass">
<canvas
ref="canvasRef"
class="block h-80 min-h-80 w-full touch-none select-none md:h-72 md:min-h-72"
@wheel.prevent="handleWheel"
@pointerdown="handlePointerDown"
@pointermove="handlePointerMove"
@pointerup="handlePointerUp"
@pointercancel="handlePointerCancel"
@pointerleave="handlePointerLeave"
@dblclick.prevent="resetWindow"
/>
<div
v-if="tooltip"
class="pointer-events-none absolute z-30 w-max min-w-36 max-w-80 whitespace-nowrap rounded-xl border px-3 py-2 text-xs shadow-xl"
:class="tooltipClass"
:style="{
left: `${tooltip.left}px`,
top: `${tooltip.top}px`,
transform: tooltip.transform
}"
>
<p class="font-semibold">{{ tooltip.date }}</p>
<p>下载次数:{{ tooltip.downloads }}</p>
<p>上传次数:{{ tooltip.uploads }}</p>
<p>下载流量:{{ tooltip.downloadTraffic }}</p>
<p>上传流量:{{ tooltip.uploadTraffic }}</p>
</div>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import type { AnalyticsDailyRow } from '@/types'
const props = defineProps<{
rows: AnalyticsDailyRow[]
isDarkMode: boolean
}>()
const emit = defineEmits<{
windowChange: [text: string]
}>()
type DragState = {
lastX: number
time: number
}
type TooltipState = {
left: number
top: number
date: string
downloads: number
uploads: number
downloadTraffic: string
uploadTraffic: string
transform: string
}
type ChartPoint = {
x: number
y: number
row: AnalyticsDailyRow
}
const canvasRef = ref<HTMLCanvasElement | null>(null)
const offset = ref(0)
const windowSize = ref(30)
const drag = ref<DragState | null>(null)
const hoverX = ref<number | null>(null)
const hoverVisual = ref<{ x: number; downloadY: number; uploadY: number } | null>(null)
const velocity = ref(0)
const rafId = ref<number | null>(null)
const inertiaRafId = ref<number | null>(null)
const lastInertiaTime = ref(0)
const lastHoverTime = ref(0)
const tooltip = ref<TooltipState | null>(null)
const INERTIA_REFERENCE_FRAME_MS = 1000 / 120
const INERTIA_MAX_FRAME_MS = 1000 / 30
const INERTIA_DECAY_PER_120HZ_FRAME = 0.96
const INERTIA_STOP_VELOCITY = 0.01
const HOVER_EASE_PER_120HZ_FRAME = 0.34
const HOVER_SNAP_DISTANCE = 0.2
const panelClass = computed(() =>
props.isDarkMode
? 'border-[#40545c] bg-[linear-gradient(135deg,rgba(34,49,56,0.96),rgba(24,35,42,0.92))] shadow-md shadow-black/25'
: 'border-[#d4e0e3] bg-[linear-gradient(135deg,#f8fbfb,#edf5f6)] shadow-md shadow-[#a9bdc2]/35'
)
const tooltipClass = computed(() =>
props.isDarkMode
? 'border-[#40545c] bg-[#203039] text-[#eef5f5]'
: 'border-[#c9d9dd] bg-[#fbfdfd] text-[#263f48]'
)
const formatBytes = (value: number | string | undefined) => {
const bytes = Number(value || 0)
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1)
return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`
}
const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value))
const getDefaultWindow = () => {
const width = canvasRef.value?.getBoundingClientRect().width || window.innerWidth
return Math.max(2, Math.min(props.rows.length || 2, width < 640 ? 14 : 60))
}
const clampState = () => {
const total = props.rows.length
windowSize.value = Math.max(
2,
Math.min(windowSize.value || getDefaultWindow(), Math.max(2, total || 2))
)
offset.value = Math.max(0, Math.min(offset.value, Math.max(0, total - windowSize.value)))
}
const scheduleDraw = () => {
if (rafId.value !== null) return
rafId.value = window.requestAnimationFrame((timestamp) => {
rafId.value = null
draw(timestamp)
})
}
const draw = (timestamp = performance.now()) => {
const canvas = canvasRef.value
if (!canvas) return
const ctx = canvas.getContext('2d')
if (!ctx) return
const rect = canvas.getBoundingClientRect()
if (!rect.width || !rect.height) return
clampState()
const dpr = window.devicePixelRatio || 1
const targetWidth = Math.round(rect.width * dpr)
const targetHeight = Math.round(rect.height * dpr)
if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
canvas.width = targetWidth
canvas.height = targetHeight
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
ctx.clearRect(0, 0, rect.width, rect.height)
const total = props.rows.length
const start = Math.max(0, Math.floor(offset.value) - 1)
const end = Math.min(total, Math.ceil(offset.value + windowSize.value) + 2)
const visible = props.rows.slice(start, end)
const mobile = rect.width < 640
const padLeft = mobile ? 34 : 42
const padRight = mobile ? 16 : 20
const padTop = 26
const padBottom = mobile ? 42 : 36
const width = Math.max(1, rect.width - padLeft - padRight)
const height = Math.max(1, rect.height - padTop - padBottom)
const max = Math.max(
1,
...visible.flatMap((row) => [Number(row.downloads || 0), Number(row.uploads || 0)])
)
const muted = props.isDarkMode ? '#9ca3af' : '#6b7280'
const border = props.isDarkMode ? '#374151' : '#e5e7eb'
const downloadColor = props.isDarkMode ? '#8fb6c5' : '#5f8fa3'
const uploadColor = props.isDarkMode ? '#a9c7b8' : '#759f8e'
ctx.strokeStyle = border
ctx.lineWidth = 1
ctx.fillStyle = muted
ctx.font = '12px system-ui'
for (let i = 0; i < 4; i += 1) {
const y = padTop + (height * i) / 3
ctx.beginPath()
ctx.moveTo(padLeft, y)
ctx.lineTo(padLeft + width, y)
ctx.stroke()
ctx.fillText(String(Math.round(max * (1 - i / 3))), 4, y + 4)
}
const denominator = Math.max(1, windowSize.value - 1)
const buildPoints = (field: 'downloads' | 'uploads') =>
visible
.map((row, index) => {
const sourceIndex = start + index
return {
x: padLeft + ((sourceIndex - offset.value) / denominator) * width,
y: padTop + height - (Number(row[field] || 0) / max) * height,
row
}
})
.filter((point) => point.x >= padLeft - 50 && point.x <= padLeft + width + 50)
const drawSeries = (points: ChartPoint[], color: string) => {
ctx.strokeStyle = color
ctx.lineWidth = 3
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.beginPath()
points.forEach((point, index) => {
if (index) ctx.lineTo(point.x, point.y)
else ctx.moveTo(point.x, point.y)
})
ctx.stroke()
ctx.fillStyle = color
points.forEach((point) => {
ctx.beginPath()
ctx.arc(point.x, point.y, mobile ? 4.5 : 3.5, 0, Math.PI * 2)
ctx.fill()
})
}
const downloadPoints = buildPoints('downloads')
const uploadPoints = buildPoints('uploads')
drawSeries(downloadPoints, downloadColor)
drawSeries(uploadPoints, uploadColor)
ctx.font = '12px system-ui'
ctx.fillStyle = muted
ctx.fillText('下载', padLeft, 16)
ctx.fillText('上传', padLeft + 58, 16)
ctx.fillStyle = downloadColor
ctx.fillRect(padLeft - 14, 8, 8, 8)
ctx.fillStyle = uploadColor
ctx.fillRect(padLeft + 44, 8, 8, 8)
const points = downloadPoints
const drawHoverPoint = (point: Pick<ChartPoint, 'x' | 'y'>, color: string) => {
ctx.fillStyle = props.isDarkMode ? '#111827' : '#fff'
ctx.strokeStyle = color
ctx.lineWidth = 3
ctx.beginPath()
ctx.arc(point.x, point.y, mobile ? 8 : 6, 0, Math.PI * 2)
ctx.fill()
ctx.stroke()
}
const leftRow = props.rows[Math.max(0, Math.round(offset.value))]
const rightRow = props.rows[Math.min(total - 1, Math.round(offset.value + windowSize.value - 1))]
if (total) {
ctx.fillStyle = muted
ctx.fillText(leftRow?.date || '', padLeft, rect.height - 10)
const last = rightRow?.date || ''
ctx.fillText(
last,
Math.max(padLeft, rect.width - padRight - ctx.measureText(last).width),
rect.height - 10
)
}
emit(
'windowChange',
total
? `${Math.floor(offset.value) + 1}-${Math.min(total, Math.ceil(offset.value + windowSize.value))} / ${total}`
: '无数据'
)
if (hoverX.value !== null && points.length && total) {
const hoverRatio = clamp((hoverX.value - padLeft) / width, 0, 1)
const sourceIndex = Math.round(clamp(offset.value + hoverRatio * denominator, 0, total - 1))
const row = props.rows[sourceIndex]
const snapX = padLeft + ((sourceIndex - offset.value) / denominator) * width
const downloads = Number(row.downloads || 0)
const uploads = Number(row.uploads || 0)
const downloadTraffic = Number(row.downloadTraffic || 0)
const uploadTraffic = Number(row.uploadTraffic || 0)
const downloadY = padTop + height - (downloads / max) * height
const uploadY = padTop + height - (uploads / max) * height
const elapsed = lastHoverTime.value
? Math.min(timestamp - lastHoverTime.value, INERTIA_MAX_FRAME_MS)
: INERTIA_REFERENCE_FRAME_MS
lastHoverTime.value = timestamp
if (!hoverVisual.value) {
hoverVisual.value = { x: snapX, downloadY, uploadY }
} else {
const ease = 1 - Math.pow(1 - HOVER_EASE_PER_120HZ_FRAME, elapsed / INERTIA_REFERENCE_FRAME_MS)
const nextX = hoverVisual.value.x + (snapX - hoverVisual.value.x) * ease
const nextDownloadY = hoverVisual.value.downloadY + (downloadY - hoverVisual.value.downloadY) * ease
const nextUploadY = hoverVisual.value.uploadY + (uploadY - hoverVisual.value.uploadY) * ease
hoverVisual.value = {
x: Math.abs(nextX - snapX) < HOVER_SNAP_DISTANCE ? snapX : nextX,
downloadY:
Math.abs(nextDownloadY - downloadY) < HOVER_SNAP_DISTANCE ? downloadY : nextDownloadY,
uploadY: Math.abs(nextUploadY - uploadY) < HOVER_SNAP_DISTANCE ? uploadY : nextUploadY
}
}
const visual = hoverVisual.value
const anchorY = Math.min(visual.downloadY, visual.uploadY)
const placeBelow = anchorY < 104
const tooltipInset = Math.min(mobile ? 116 : 132, Math.max(48, rect.width / 2 - 8))
ctx.strokeStyle = props.isDarkMode ? 'rgba(148, 163, 184, 0.35)' : 'rgba(91, 121, 132, 0.28)'
ctx.lineWidth = 1
ctx.beginPath()
ctx.moveTo(visual.x, padTop)
ctx.lineTo(visual.x, padTop + height)
ctx.stroke()
tooltip.value = {
left: clamp(visual.x, tooltipInset, rect.width - tooltipInset),
top: placeBelow ? anchorY + 16 : anchorY - 12,
date: row.date,
downloads,
uploads,
downloadTraffic: formatBytes(downloadTraffic),
uploadTraffic: formatBytes(uploadTraffic),
transform: placeBelow ? 'translate(-50%, 0)' : 'translate(-50%, -100%)'
}
drawHoverPoint({ x: visual.x, y: visual.downloadY }, downloadColor)
drawHoverPoint({ x: visual.x, y: visual.uploadY }, uploadColor)
if (
Math.abs(visual.x - snapX) >= HOVER_SNAP_DISTANCE ||
Math.abs(visual.downloadY - downloadY) >= HOVER_SNAP_DISTANCE ||
Math.abs(visual.uploadY - uploadY) >= HOVER_SNAP_DISTANCE
) {
scheduleDraw()
}
} else {
hoverVisual.value = null
lastHoverTime.value = 0
tooltip.value = null
}
}
const pan = (deltaX: number, shouldScheduleDraw = true) => {
const rect = canvasRef.value?.getBoundingClientRect()
if (!rect) return
offset.value += (-deltaX / Math.max(1, rect.width)) * Math.max(1, windowSize.value - 1) * 1.15
clampState()
if (shouldScheduleDraw) scheduleDraw()
}
const zoom = (factor: number, center = 0.5) => {
clampState()
const minWindow = Math.min(props.rows.length || 2, window.innerWidth < 640 ? 5 : 7)
const next = Math.max(minWindow, Math.min(props.rows.length || 2, windowSize.value * factor))
const anchor = offset.value + windowSize.value * center
windowSize.value = next
offset.value = anchor - next * center
clampState()
scheduleDraw()
}
const cancelInertia = () => {
if (inertiaRafId.value !== null) {
window.cancelAnimationFrame(inertiaRafId.value)
inertiaRafId.value = null
}
lastInertiaTime.value = 0
}
const applyInertia = (timestamp: number) => {
if (Math.abs(velocity.value) < INERTIA_STOP_VELOCITY) {
cancelInertia()
return
}
const elapsed = lastInertiaTime.value
? Math.min(timestamp - lastInertiaTime.value, INERTIA_MAX_FRAME_MS)
: INERTIA_REFERENCE_FRAME_MS
lastInertiaTime.value = timestamp
pan(velocity.value * elapsed, false)
draw(timestamp)
velocity.value *= Math.pow(
INERTIA_DECAY_PER_120HZ_FRAME,
elapsed / INERTIA_REFERENCE_FRAME_MS
)
inertiaRafId.value = window.requestAnimationFrame(applyInertia)
}
const handleWheel = (event: WheelEvent) => {
const rect = canvasRef.value?.getBoundingClientRect()
zoom(event.deltaY > 0 ? 1.16 : 0.86, rect ? (event.clientX - rect.left) / rect.width : 0.5)
}
const handlePointerDown = (event: PointerEvent) => {
canvasRef.value?.setPointerCapture(event.pointerId)
cancelInertia()
velocity.value = 0
drag.value = { lastX: event.clientX, time: event.timeStamp || performance.now() }
}
const handlePointerMove = (event: PointerEvent) => {
const rect = canvasRef.value?.getBoundingClientRect()
const pointerEvents = event.getCoalescedEvents?.() || [event]
const latestEvent = pointerEvents[pointerEvents.length - 1] || event
if (rect) hoverX.value = latestEvent.clientX - rect.left
if (!drag.value) {
scheduleDraw()
return
}
pointerEvents.forEach((pointerEvent) => {
const now = pointerEvent.timeStamp || performance.now()
const deltaX = pointerEvent.clientX - drag.value!.lastX
const deltaTime = Math.max(1, now - drag.value!.time)
velocity.value = deltaX / deltaTime
pan(deltaX)
drag.value = { lastX: pointerEvent.clientX, time: now }
})
}
const handlePointerUp = () => {
drag.value = null
cancelInertia()
inertiaRafId.value = window.requestAnimationFrame(applyInertia)
}
const handlePointerCancel = () => {
drag.value = null
}
const handlePointerLeave = () => {
drag.value = null
hoverX.value = null
hoverVisual.value = null
lastHoverTime.value = 0
scheduleDraw()
}
const resetWindow = () => {
windowSize.value = getDefaultWindow()
offset.value = Math.max(0, props.rows.length - windowSize.value)
scheduleDraw()
}
const handleResize = () => scheduleDraw()
watch(
() => props.rows,
async () => {
await nextTick()
resetWindow()
},
{ deep: true }
)
onMounted(async () => {
await nextTick()
resetWindow()
window.addEventListener('resize', handleResize)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize)
if (rafId.value !== null) window.cancelAnimationFrame(rafId.value)
cancelInertia()
})
defineExpose({ zoom, resetWindow })
</script>