This commit is contained in:
2025-11-15 14:36:16 +08:00
parent 5cf0704d33
commit 03b2ce017a
15 changed files with 916 additions and 87 deletions
+81
View File
@@ -0,0 +1,81 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { prisma } from '@/src/lib/prisma'
import { applyFit, basicStats, genId, getSampleRateHz } from '@/src/lib/utils'
const DataSchema = z.object({
code: z.array(z.number().int()).min(1, 'code array empty').max(4096, 'too many points'),
fit: z.object({ a: z.number(), b: z.number() }).optional(),
recStartMs: z.number().int().nonnegative().optional(),
recEndMs: z.number().int().nonnegative().optional(),
})
export async function POST(req: NextRequest) {
try {
const json = await req.json()
const parsed = DataSchema.safeParse(json)
if (!parsed.success) {
const first = parsed.error.errors[0]
return Response.json({ error: first?.message ?? 'invalid body' }, { status: 400 })
}
const { code, fit, recStartMs, recEndMs } = parsed.data
if (code.length > 4096) {
return Response.json({ error: 'payload too large' }, { status: 413 })
}
const sampleCount = code.length
const { min: codeMin, max: codeMax, avg: codeAvg } = basicStats(code)
let forceMin: number | null = null
let forceMax: number | null = null
let forceAvg: number | null = null
if (fit) {
const forces = applyFit(code, fit.a, fit.b)
const s = basicStats(forces)
forceMin = s.min
forceMax = s.max
forceAvg = s.avg
}
let duration: number
if (
typeof recStartMs === 'number' &&
typeof recEndMs === 'number' &&
Number.isFinite(recStartMs) &&
Number.isFinite(recEndMs) &&
recEndMs > recStartMs
) {
duration = (recEndMs - recStartMs) / 1000
} else {
const sampleRate = getSampleRateHz()
duration = sampleCount / sampleRate
}
const ts = new Date()
const id = genId()
await prisma.recording.create({
data: {
id,
timestamp: ts,
sample_count: sampleCount,
duration,
code_data: code.map((n) => Math.trunc(n)),
rec_start_ms: typeof recStartMs === 'number' ? BigInt(Math.trunc(recStartMs)) : null,
rec_end_ms: typeof recEndMs === 'number' ? BigInt(Math.trunc(recEndMs)) : null,
fit_a: fit?.a ?? null,
fit_b: fit?.b ?? null,
code_min: codeMin,
code_max: codeMax,
code_avg: codeAvg,
force_min: forceMin,
force_max: forceMax,
force_avg: forceAvg,
} ,
})
return Response.json({ success: true, id, timestamp: ts.toISOString() })
} catch (err) {
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
+77
View File
@@ -0,0 +1,77 @@
import { NextRequest } from 'next/server'
import { z } from 'zod'
import { prisma } from '@/src/lib/prisma'
const ExportSchema = z.object({
ids: z.array(z.string()).min(1),
format: z.enum(['csv', 'json']),
})
export async function POST(req: NextRequest) {
try {
const body = await req.json()
const parsed = ExportSchema.safeParse(body)
if (!parsed.success) return Response.json({ error: 'invalid body' }, { status: 400 })
const { ids, format } = parsed.data
const rows = await prisma.recording.findMany({
where: { id: { in: ids } },
orderBy: { timestamp: 'asc' },
// Cast select to any to accommodate freshly added fields before prisma generate
select: {
id: true,
timestamp: true,
code_data: true,
fit_a: true,
fit_b: true,
sample_count: true,
duration: true,
rec_start_ms: true,
rec_end_ms: true,
} ,
})
if (format === 'json') {
const payload = rows.map((r) => ({
id: r.id,
timestamp: new Date(r.timestamp).toISOString(),
code: r.code_data,
fit: r.fit_a != null ? { a: r.fit_a, b: r.fit_b } : undefined,
sampleCount: r.sample_count,
duration: r.duration,
}))
return new Response(JSON.stringify(payload), {
headers: {
'content-type': 'application/json; charset=utf-8',
'content-disposition': `attachment; filename="export-${Date.now()}.json"`,
},
})
}
// CSV
let csv = 'recordId,timestamp,index,timeSec,code,force\n'
for (const r of rows) {
let step = r.sample_count > 0 ? r.duration / r.sample_count : 0
if (r.rec_start_ms != null && r.rec_end_ms != null && r.sample_count > 0) {
const dtMs = Number((r.rec_end_ms as bigint) - (r.rec_start_ms as bigint))
if (Number.isFinite(dtMs) && dtMs > 0) step = dtMs / 1000 / r.sample_count
}
const hasFit = r.fit_a != null
for (let i = 0; i < r.code_data.length; i++) {
const t = (i * step).toFixed(6)
const code = r.code_data[i]
const force = hasFit ? r.fit_a! * code + (r.fit_b ?? 0) : ''
csv += `${r.id},${new Date(r.timestamp).toISOString()},${i},${t},${code},${hasFit ? force : ''}\n`
}
}
return new Response(csv, {
headers: {
'content-type': 'text/csv; charset=utf-8',
'content-disposition': `attachment; filename="export-${Date.now()}.csv"`,
},
})
} catch (err) {
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
+63
View File
@@ -0,0 +1,63 @@
import { NextRequest } from 'next/server'
import { prisma } from '@/src/lib/prisma'
import { isAuthorizedDelete } from '@/src/lib/utils'
export async function GET(_req: NextRequest, { params }: { params: { id: string } }) {
try {
const rec = await prisma.recording.findUnique({
where: { id: params.id },
select: {
id: true,
timestamp: true,
code_data: true,
fit_a: true,
fit_b: true,
sample_count: true,
duration: true,
code_min: true,
code_max: true,
code_avg: true,
force_min: true,
force_max: true,
force_avg: true,
},
})
if (!rec) return Response.json({ error: 'not found' }, { status: 404 })
return Response.json({
id: rec.id,
timestamp: rec.timestamp.toISOString(),
code: rec.code_data,
fit: rec.fit_a != null ? { a: rec.fit_a, b: rec.fit_b } : undefined,
sampleCount: rec.sample_count,
duration: rec.duration,
stats: {
codeMin: rec.code_min,
codeMax: rec.code_max,
codeAvg: rec.code_avg,
forceMin: rec.force_min ?? undefined,
forceMax: rec.force_max ?? undefined,
forceAvg: rec.force_avg ?? undefined,
},
})
} catch (err) {
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
export async function DELETE(req: NextRequest, { params }: { params: { id: string } }) {
try {
if (!isAuthorizedDelete(req)) {
return Response.json({ error: 'unauthorized' }, { status: 401 })
}
const rec = await prisma.recording.delete({ where: { id: params.id } })
return Response.json({ success: true, id: rec.id })
} catch (err: any) {
if (err?.code === 'P2025') {
return Response.json({ error: 'not found' }, { status: 404 })
}
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
+91
View File
@@ -0,0 +1,91 @@
import { NextRequest } from 'next/server'
import { prisma } from '@/src/lib/prisma'
export async function GET(req: NextRequest) {
try {
const { searchParams } = new URL(req.url)
const page = Math.max(1, parseInt(searchParams.get('page') || '1', 10) || 1)
const pageSizeRaw = parseInt(searchParams.get('pageSize') || '20', 10) || 20
const pageSize = Math.min(100, Math.max(1, pageSizeRaw))
const startDate = searchParams.get('startDate')
const endDate = searchParams.get('endDate')
const hasFit = ((): boolean | undefined => {
const v = searchParams.get('hasFit')
return v === null ? undefined : v === 'true'
})()
const sortBy = searchParams.get('sortBy') || 'timestamp' // timestamp | duration | maxValue
const sortOrder = (searchParams.get('sortOrder') === 'asc' ? 'asc' : 'desc') as 'asc' | 'desc'
const where: any = {}
if (startDate || endDate) {
where.timestamp = {}
if (startDate) where.timestamp.gte = new Date(startDate)
if (endDate) where.timestamp.lte = new Date(endDate)
}
if (hasFit === true) where.NOT = { fit_a: null }
if (hasFit === false) where.fit_a = null
let orderBy: any
if (sortBy === 'duration') orderBy = { duration: sortOrder }
else if (sortBy === 'maxValue') {
if (hasFit === true) orderBy = { force_max: sortOrder }
else orderBy = { code_max: sortOrder }
} else {
orderBy = { timestamp: sortOrder }
}
const [total, rows] = await Promise.all([
prisma.recording.count({ where }),
prisma.recording.findMany({
where,
orderBy,
skip: (page - 1) * pageSize,
take: pageSize,
select: {
id: true,
timestamp: true,
sample_count: true,
duration: true,
fit_a: true,
fit_b: true,
code_min: true,
code_max: true,
code_avg: true,
force_min: true,
force_max: true,
force_avg: true,
},
}),
])
const data = rows.map((r) => ({
id: r.id,
timestamp: r.timestamp.toISOString(),
sampleCount: r.sample_count,
duration: r.duration,
hasFit: r.fit_a !== null && r.fit_a !== undefined,
fit: r.fit_a !== null && r.fit_a !== undefined ? { a: r.fit_a!, b: r.fit_b! } : undefined,
stats: {
codeMin: r.code_min,
codeMax: r.code_max,
codeAvg: r.code_avg,
forceMin: r.force_min ?? undefined,
forceMax: r.force_max ?? undefined,
forceAvg: r.force_avg ?? undefined,
},
}))
return Response.json({
data,
pagination: {
total,
page,
pageSize,
totalPages: Math.max(1, Math.ceil(total / pageSize)),
},
})
} catch (err) {
console.error(err)
return Response.json({ error: 'internal error' }, { status: 500 })
}
}
+142 -58
View File
@@ -1,65 +1,149 @@
import Image from "next/image";
"use client"
import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
type RecordItem = {
id: string
timestamp: string
sampleCount: number
duration: number
hasFit: boolean
fit?: { a: number; b: number }
stats: {
codeMin: number
codeMax: number
codeAvg: number
forceMin?: number
forceMax?: number
forceAvg?: number
}
}
export default function Home() {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [data, setData] = useState<RecordItem[]>([])
const [total, setTotal] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(12)
const [hasFit, setHasFit] = useState<'all' | 'fit' | 'raw'>('all')
const [sortBy, setSortBy] = useState<'timestamp' | 'duration' | 'maxValue'>('timestamp')
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')
const [startDate, setStartDate] = useState('')
const [endDate, setEndDate] = useState('')
const totalPages = useMemo(() => Math.max(1, Math.ceil(total / pageSize)), [total, pageSize])
useEffect(() => {
const controller = new AbortController()
async function run() {
setLoading(true)
setError(null)
try {
const params = new URLSearchParams()
params.set('page', String(page))
params.set('pageSize', String(pageSize))
params.set('sortBy', sortBy)
params.set('sortOrder', sortOrder)
if (startDate) params.set('startDate', new Date(startDate).toISOString())
if (endDate) params.set('endDate', new Date(endDate).toISOString())
if (hasFit === 'fit') params.set('hasFit', 'true')
if (hasFit === 'raw') params.set('hasFit', 'false')
const res = await fetch(`/api/records?${params.toString()}`, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const j = await res.json()
setData(j.data)
setTotal(j.pagination.total)
} catch (e: any) {
if (e.name !== 'AbortError') setError(e.message || '加载失败')
} finally {
setLoading(false)
}
}
run()
return () => controller.abort()
}, [page, pageSize, hasFit, sortBy, sortOrder, startDate, endDate])
return (
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
<div className="min-h-screen bg-zinc-50 text-zinc-900 dark:bg-black dark:text-zinc-100">
<div className="mx-auto max-w-6xl p-4 sm:p-6">
<header className="mb-4 flex flex-col gap-3 sm:mb-6 sm:flex-row sm:items-end sm:justify-between">
<h1 className="text-2xl font-semibold">ESP32 数据采集系统</h1>
<div className="flex flex-wrap items-end gap-2">
<div className="flex items-center gap-2">
<label className="text-sm">开始</label>
<input type="date" value={startDate} onChange={(e) => setStartDate(e.target.value)} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900" />
</div>
<div className="flex items-center gap-2">
<label className="text-sm">结束</label>
<input type="date" value={endDate} onChange={(e) => setEndDate(e.target.value)} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900" />
</div>
<select value={hasFit} onChange={(e) => setHasFit(e.target.value )} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900">
<option value="all">全部</option>
<option value="fit">仅已拟合</option>
<option value="raw">仅未拟合</option>
</select>
<select value={sortBy} onChange={(e) => setSortBy(e.target.value )} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900">
<option value="timestamp">按时间</option>
<option value="duration">按时长</option>
<option value="maxValue">按最大值</option>
</select>
<select value={sortOrder} onChange={(e) => setSortOrder(e.target.value )} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900">
<option value="desc">降序</option>
<option value="asc">升序</option>
</select>
<select value={pageSize} onChange={(e) => { setPageSize(parseInt(e.target.value)); setPage(1) }} className="rounded border border-zinc-300 bg-white px-2 py-1 text-sm dark:bg-zinc-900">
{[12, 20, 50, 100].map((n) => (
<option key={n} value={n}>{n}/页</option>
))}
</select>
</div>
</header>
{error && <div className="mb-4 rounded bg-red-100 px-3 py-2 text-red-800">{error}</div>}
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{loading && Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="h-40 animate-pulse rounded-lg bg-zinc-200 dark:bg-zinc-800" />
))}
{!loading && data.map((r) => (
<div key={r.id} className="flex h-48 flex-col justify-between rounded-lg border border-zinc-200 bg-white p-4 shadow-sm transition hover:shadow-md dark:border-zinc-800 dark:bg-zinc-950">
<div>
<div className="flex items-center justify-between">
<div className="text-sm text-zinc-500">{new Date(r.timestamp).toLocaleString()}</div>
<span className={`rounded-full px-2 py-0.5 text-xs ${r.hasFit ? 'bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-300' : 'bg-zinc-100 text-zinc-700 dark:bg-zinc-800 dark:text-zinc-300'}`}>{r.hasFit ? '已拟合' : '未拟合'}</span>
</div>
<div className="mt-2 text-xl font-semibold">{r.sampleCount} 点 · {r.duration.toFixed(2)} s</div>
<div className="mt-1 text-sm text-zinc-600 dark:text-zinc-400">
{r.hasFit ? (
<>
力值: {r.stats.forceMin?.toFixed(2)} ~ {r.stats.forceMax?.toFixed(2)} mN · 均值 {r.stats.forceAvg?.toFixed(2)}
</>
) : (
<>
码值: {r.stats.codeMin} ~ {r.stats.codeMax} · 均值 {r.stats.codeAvg.toFixed(2)}
</>
)}
</div>
</div>
<div className="flex items-center justify-between">
{r.hasFit && r.fit && (
<div className="text-[11px] text-zinc-500">y = {r.fit.a.toFixed(4)}x + {r.fit.b.toFixed(3)}</div>
)}
<div className="ml-auto flex gap-2">
<Link href={`/records/${r.id}`} className="rounded-md bg-zinc-900 px-3 py-1.5 text-sm text-white dark:bg-zinc-100 dark:text-black">查看</Link>
</div>
</div>
</div>
))}
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
<div className="mt-6 flex items-center justify-center gap-4">
<button className="rounded border px-3 py-1.5 disabled:opacity-50" onClick={() => setPage((p) => Math.max(1, p - 1))} disabled={page <= 1}>上一页</button>
<div className="text-sm">{page} / {totalPages}</div>
<button className="rounded border px-3 py-1.5 disabled:opacity-50" onClick={() => setPage((p) => Math.min(totalPages, p + 1))} disabled={page >= totalPages}>下一页</button>
</div>
</main>
</div>
</div>
);
)
}
+260
View File
@@ -0,0 +1,260 @@
"use client"
import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
Tooltip,
Legend,
} from 'chart.js'
import { Line, Bar, Scatter } from 'react-chartjs-2'
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, BarElement, Tooltip, Legend)
type Detail = {
id: string
timestamp: string
code: number[]
fit?: { a: number; b: number }
sampleCount: number
duration: number
stats: {
codeMin: number
codeMax: number
codeAvg: number
forceMin?: number
forceMax?: number
forceAvg?: number
}
}
function toFixed(n: number | undefined | null, d = 3) {
if (n == null || Number.isNaN(n)) return '-'
return n.toFixed(d)
}
export default function Page({ params }: { params: { id: string } }) {
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [rec, setRec] = useState<Detail | null>(null)
useEffect(() => {
const controller = new AbortController()
async function run() {
setLoading(true)
setError(null)
try {
const res = await fetch(`/api/records/${params.id}`, { signal: controller.signal })
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const j = await res.json()
setRec(j)
} catch (e: any) {
if (e.name !== 'AbortError') setError(e.message || '加载失败')
} finally {
setLoading(false)
}
}
run()
return () => controller.abort()
}, [params.id])
const timeAxis = useMemo(() => {
if (!rec) return [] as number[]
const step = rec.sampleCount > 0 ? rec.duration / rec.sampleCount : 0
return Array.from({ length: rec.sampleCount }, (_, i) => +(i * step).toFixed(6))
}, [rec])
const forceSeries = useMemo(() => {
if (!rec?.fit) return undefined
const { a, b } = rec.fit
return rec.code.map((c) => a * c + b)
}, [rec])
const codeHistogram = useMemo(() => buildHistogram(rec?.code || [], 30), [rec])
const forceHistogram = useMemo(() => buildHistogram(forceSeries || [], 30), [forceSeries])
return (
<div className="min-h-screen bg-zinc-50 text-zinc-900 dark:bg-black dark:text-zinc-100">
<div className="mx-auto max-w-6xl p-4 sm:p-6">
<div className="mb-4 flex items-center justify-between">
<div className="flex items-center gap-3">
<Link href="/" className="rounded border px-3 py-1.5">← 返回</Link>
<h1 className="text-xl font-semibold">记录 {rec?.id || params.id}</h1>
</div>
<div className="flex gap-2">
<a
href={`/api/export`}
onClick={async (e) => {
e.preventDefault()
const body = JSON.stringify({ ids: [params.id], format: 'csv' as const })
const res = await fetch('/api/export', { method: 'POST', headers: { 'content-type': 'application/json' }, body })
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `record-${params.id}.csv`
a.click()
URL.revokeObjectURL(url)
}}
className="rounded bg-zinc-900 px-3 py-1.5 text-white dark:bg-zinc-100 dark:text-black"
>导出 CSV</a>
</div>
</div>
{loading && <div className="rounded bg-zinc-200 p-4 dark:bg-zinc-800">加载中...</div>}
{error && <div className="rounded bg-red-100 p-4 text-red-800">{error}</div>}
{rec && (
<div className="flex flex-col gap-6">
<section className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">上传时间</div>
<div className="mt-1 text-lg">{new Date(rec.timestamp).toLocaleString()}</div>
</div>
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">采样</div>
<div className="mt-1 text-lg">{rec.sampleCount} 点 · {rec.duration.toFixed(3)} s · {(rec.sampleCount / rec.duration).toFixed(2)} Hz</div>
</div>
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">拟合</div>
<div className="mt-1 text-lg">{rec.fit ? `y = ${rec.fit.a.toFixed(4)}x + ${rec.fit.b.toFixed(3)}` : '未拟合'}</div>
</div>
</section>
<section className="grid grid-cols-1 gap-4 sm:grid-cols-3">
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">码值统计</div>
<div className="mt-1 text-lg">[{rec.stats.codeMin} ~ {rec.stats.codeMax}] · 均值 {toFixed(rec.stats.codeAvg, 2)}</div>
</div>
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">力值统计</div>
<div className="mt-1 text-lg">{rec.fit ? `[${toFixed(rec.stats.forceMin, 2)} ~ ${toFixed(rec.stats.forceMax, 2)}] mN · 均值 ${toFixed(rec.stats.forceAvg, 2)}` : '—'}</div>
</div>
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="text-sm text-zinc-500">峰峰值</div>
<div className="mt-1 text-lg">码值 {rec.stats.codeMax - rec.stats.codeMin}{rec.fit && rec.stats.forceMax != null && rec.stats.forceMin != null ? ` · 力值 ${(rec.stats.forceMax - rec.stats.forceMin).toFixed(2)} mN` : ''}</div>
</div>
</section>
<section className="rounded-lg border p-4 dark:border-zinc-800">
<div className="mb-3 text-sm text-zinc-500">时序曲线</div>
<Line
data={{
labels: timeAxis,
datasets: [
{
type: 'line' as const,
label: '码值',
data: rec.code,
borderColor: '#0ea5e9',
backgroundColor: 'rgba(14,165,233,0.2)',
borderWidth: 1.5,
yAxisID: 'yCode',
pointRadius: 0,
},
...(rec.fit && forceSeries
? [
{
type: 'line' as const,
label: '力值 (mN)',
data: forceSeries,
borderColor: '#22c55e',
backgroundColor: 'rgba(34,197,94,0.2)',
borderWidth: 1.5,
yAxisID: 'yForce',
pointRadius: 0,
},
]
: []),
],
}}
options={{
responsive: true,
interaction: { mode: 'index', intersect: false },
plugins: { legend: { position: 'top' as const } },
scales: {
x: { title: { display: true, text: '时间 (s)' } },
yCode: { type: 'linear' as const, position: 'left' as const, title: { display: true, text: '码值' } },
yForce: { type: 'linear' as const, position: 'right' as const, title: { display: true, text: '力值 (mN)' }, grid: { drawOnChartArea: false } },
},
}}
/>
</section>
<section className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="mb-3 text-sm text-zinc-500">码值分布直方图</div>
<Bar
data={{
labels: codeHistogram.labels,
datasets: [
{
label: '频数',
data: codeHistogram.counts,
backgroundColor: 'rgba(14,165,233,0.3)',
borderColor: '#0ea5e9',
},
],
}}
options={{ scales: { x: { title: { display: true, text: '码值' } }, y: { title: { display: true, text: '数量' } } } }}
/>
</div>
<div className="rounded-lg border p-4 dark:border-zinc-800">
<div className="mb-3 text-sm text-zinc-500">线性度散点图</div>
{rec.fit && forceSeries ? (
<Scatter
data={{
datasets: [
{
label: '码值 vs 力值',
data: rec.code.map((c, i) => ({ x: c, y: forceSeries[i] })),
backgroundColor: '#22c55e',
},
],
}}
options={{
scales: {
x: { title: { display: true, text: '码值' } },
y: { title: { display: true, text: '力值 (mN)' } },
},
plugins: { legend: { display: false } },
}}
/>
) : (
<div className="text-sm text-zinc-500">无拟合参数,无法绘制</div>
)}
</div>
</section>
</div>
)}
</div>
</div>
)
}
function buildHistogram(values: number[], bins: number) {
if (!values.length || bins <= 0) return { labels: [] as string[], counts: [] as number[] }
let min = values[0]
let max = values[0]
for (const v of values) {
if (v < min) min = v
if (v > max) max = v
}
if (min === max) {
return { labels: [min.toFixed(2)], counts: [values.length] }
}
const step = (max - min) / bins
const edges = Array.from({ length: bins + 1 }, (_, i) => min + i * step)
const counts = Array.from({ length: bins }, () => 0)
for (const v of values) {
let idx = Math.floor((v - min) / step)
if (idx >= bins) idx = bins - 1
if (idx < 0) idx = 0
counts[idx]++
}
const labels = Array.from({ length: bins }, (_, i) => `${edges[i].toFixed(1)}~${edges[i + 1].toFixed(1)}`)
return { labels, counts }
}