Commit 729df768 by chenwq

feat: 优化趋势图组件样式与功能,增加数据标签支持

1 parent eff78eab
/* 趋势数据卡样式与看板页面同目录,组件只服务本模块;色值全部取 --uj-* 语义令牌。 */ /* 趋势图样式与看板页面同目录,色值全部取设计令牌。 */
.uc-trend { .uc-trend {
display: grid; position: relative;
gap: var(--uj-space-2, 8px);
grid-template-columns: repeat(auto-fit, minmax(104px, 1fr));
margin-top: var(--uj-space-5); margin-top: var(--uj-space-5);
min-height: 264px;
overflow-x: auto;
} }
.uc-trend__item { .uc-trend__chart {
display: block;
width: 100%;
height: 264px;
}
.uc-trend__grid {
stroke: var(--uj-divider);
stroke-width: 1;
}
.uc-trend__line {
fill: none;
stroke: var(--uj-primary);
stroke-linecap: round;
stroke-linejoin: round;
stroke-width: 2.5;
}
.uc-trend__point {
fill: var(--uj-surface);
stroke: var(--uj-primary);
stroke-width: 2.5;
transition: r 160ms ease;
}
.uc-trend__point:hover {
r: 6;
}
.uc-trend__tooltip {
position: absolute;
z-index: 1;
min-width: 150px;
padding: var(--uj-space-3) var(--uj-space-4);
border: 1px solid var(--uj-border);
border-radius: var(--uj-radius-md);
background: var(--uj-surface);
box-shadow: var(--uj-shadow-pop);
color: var(--uj-text-2);
font-size: var(--uj-font-sm);
line-height: 1.6;
pointer-events: none;
transform: translate(-50%, calc(-100% - var(--uj-space-3)));
}
.uc-trend__tooltip-date {
margin-bottom: var(--uj-space-1);
color: var(--uj-text-2);
}
.uc-trend__tooltip-value {
display: flex; display: flex;
flex-direction: column; align-items: center;
gap: var(--uj-space-2); gap: var(--uj-space-2);
min-width: 0; }
padding: var(--uj-space-3) var(--uj-space-4); .uc-trend__tooltip-dot {
border: 1px solid var(--uj-border, #e6ebf2); width: var(--uj-space-1);
border-radius: var(--uj-radius-md, 6px); height: var(--uj-space-1);
background: var(--uj-surface-2, #f8fafc); border-radius: var(--uj-radius-pill);
} background: var(--uj-primary);
.uc-trend__date { }
color: var(--uj-text-3, #8a94a6); .uc-trend__axis-label,
font-size: var(--uj-font-xs, 12px); .uc-trend__unit {
line-height: 1.4; fill: var(--uj-text-3);
} font-size: var(--uj-font-xs);
.uc-trend__value { font-variant-numeric: var(--uj-num);
color: var(--uj-text-1, #1d2533); }
font-size: var(--uj-font-2xl, 20px); .uc-trend__unit {
font-weight: 600; fill: var(--uj-text-header);
font-variant-numeric: var(--uj-num, tabular-nums);
line-height: 1.2;
overflow-wrap: anywhere;
}
.uc-trend__value small {
margin-left: 2px;
color: var(--uj-text-3, #8a94a6);
font-size: var(--uj-font-xs, 12px);
font-weight: 400;
} }
.uc-trend__empty { .uc-trend__empty {
padding: var(--uj-space-8) 0; padding: var(--uj-space-8) 0;
color: var(--uj-text-3, #8a94a6); color: var(--uj-text-3);
font-size: var(--uj-font-sm, 13px); font-size: var(--uj-font-sm);
text-align: center; text-align: center;
} }
import { useEffect, useRef, useState } from 'react';
import type { TrendPoint } from '@/api'; import type { TrendPoint } from '@/api';
import './TrendChart.css'; import './TrendChart.css';
/** /** 看板趋势数据(模块内组件,只服务本看板)。 */
* 看板趋势数据(模块内组件,只服务本看板)。
*
* 为什么不复用 StatCard:趋势点是 date + count 的时间序列,没有环比字段,
* 套 KPI 卡会显示假的「环比 —」。这里做成「一排带边框的紧凑数据卡」:
* 每张卡 = 日期 + 数值,卡片有明确边界,信息清晰,不放任何柱状/条形图。
*/
export interface TrendChartProps { export interface TrendChartProps {
data: TrendPoint[]; data: TrendPoint[];
label: string;
unit?: string; unit?: string;
loading?: boolean; loading?: boolean;
} }
/** 长日期收敛成短标签:有「时:分」取时间,否则取「月-日」,再否则原样。 */ /** 横轴统一展示完整日期;仅纯时间数据保留「时:分」。 */
function shortenDate(date: string): string { function shortenDate(date: string): string {
const fullDate = /(\d{4}[-/]\d{1,2}[-/]\d{1,2})/.exec(date);
if (fullDate) return fullDate[1];
const time = /(\d{1,2}:\d{2})/.exec(date); const time = /(\d{1,2}:\d{2})/.exec(date);
if (time) return time[1]; if (time) return time[1];
const parts = date.split(/[-/]/); const parts = date.split(/[-/]/);
...@@ -28,30 +26,147 @@ function countOf(point: TrendPoint): number { ...@@ -28,30 +26,147 @@ function countOf(point: TrendPoint): number {
return Number.isFinite(n) ? n : 0; return Number.isFinite(n) ? n : 0;
} }
export function TrendChart({ data, unit = '辆', loading = false }: TrendChartProps) { const CHART = { width: 720, height: 264, top: 20, right: 20, bottom: 42, left: 48 } as const;
/**
* 横轴最多保留 7 个日期:既能看出时间跨度,也避免近 30 日时标签互相遮挡。
* 第一个和最后一个日期始终展示,具体数值仍可通过悬停折线点查看。
*/
function visibleLabelIndexes(length: number, width: number): Set<number> {
const maxLabels = Math.max(2, Math.min(7, Math.floor(width / 78)));
if (length <= maxLabels) return new Set(Array.from({ length }, (_, index) => index));
const step = Math.ceil((length - 1) / (maxLabels - 1));
const indexes = new Set<number>();
for (let index = 0; index < length; index += step) indexes.add(index);
indexes.add(length - 1);
return indexes;
}
function displayMax(values: number[]): number {
const max = Math.max(...values, 0);
return max === 0 ? 1 : Math.ceil(max / 5) * 5;
}
/** 清除浮点运算尾数,避免纵轴出现 0.60000000000001 这样的无意义数字。 */
function formatNumber(value: number): string {
return Number(value.toFixed(6)).toString();
}
export function TrendChart({ data, label, unit = '辆', loading = false }: TrendChartProps) {
const containerRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(CHART.width);
const [activeIndex, setActiveIndex] = useState<number | null>(null);
useEffect(() => {
const container = containerRef.current;
if (!container) return undefined;
const updateWidth = () => setWidth(container.clientWidth || CHART.width);
updateWidth();
const observer = new ResizeObserver(updateWidth);
observer.observe(container);
return () => observer.disconnect();
}, [loading]);
if (loading) return <div className="uc-trend__empty">正在加载趋势数据…</div>; if (loading) return <div className="uc-trend__empty">正在加载趋势数据…</div>;
if (data.length === 0) return <div className="uc-trend__empty">暂无趋势数据</div>; if (data.length === 0) return <div className="uc-trend__empty">暂无趋势数据</div>;
const values = data.map(countOf);
const max = displayMax(values);
const chartWidth = Math.max(width, 320);
const plotWidth = chartWidth - CHART.left - CHART.right;
const plotHeight = CHART.height - CHART.top - CHART.bottom;
const xAt = (index: number) =>
CHART.left + (data.length === 1 ? plotWidth / 2 : (index / (data.length - 1)) * plotWidth);
const yAt = (value: number) => CHART.top + plotHeight - (value / max) * plotHeight;
const points = values.map((value, index) => `${xAt(index)},${yAt(value)}`).join(' ');
const labels = visibleLabelIndexes(data.length, width);
const ticks = Array.from({ length: 6 }, (_, index) => (max / 5) * index);
const activePoint = activeIndex === null ? undefined : data[activeIndex];
const activeCount = activeIndex === null ? undefined : values[activeIndex];
const tooltipLeft =
activeIndex === null
? 0
: Math.min(Math.max((xAt(activeIndex) / chartWidth) * width, 92), width - 92);
const tooltipTop = activeIndex === null ? 0 : yAt(activeCount ?? 0);
return ( return (
<div className="uc-trend" role="list" aria-label={`趋势数据,共 ${data.length} 个数据点`}> <div className="uc-trend" ref={containerRef}>
{data.map((point, index) => { <svg
const count = countOf(point); className="uc-trend__chart"
return ( viewBox={`0 0 ${chartWidth} ${CHART.height}`}
<div role="img"
key={`${point.date}-${index}`} aria-label={`趋势折线图,共 ${data.length} 个数据点`}
className="uc-trend__item" >
role="listitem" <title>趋势折线图</title>
aria-label={`${point.date}:${count}${unit}`} {ticks.map((tick) => {
title={`${point.date}:${count}${unit}`} const y = yAt(tick);
> return (
<span className="uc-trend__date">{shortenDate(point.date)}</span> <g key={tick}>
<span className="uc-trend__value"> <line
{count} className="uc-trend__grid"
<small>{unit}</small> x1={CHART.left}
</span> x2={chartWidth - CHART.right}
y1={y}
y2={y}
/>
<text className="uc-trend__axis-label" x={CHART.left - 10} y={y + 4} textAnchor="end">
{formatNumber(tick)}
</text>
</g>
);
})}
<text className="uc-trend__unit" x={CHART.left} y={12}>
{unit}
</text>
<polyline className="uc-trend__line" points={points} />
{data.map((point, index) => {
const count = values[index];
const x = xAt(index);
const y = yAt(count);
return (
<g key={`${point.date}-${index}`}>
<circle
className="uc-trend__point"
cx={x}
cy={y}
r={4}
tabIndex={0}
aria-label={`${point.date}:${formatNumber(count)}${unit}`}
onMouseEnter={() => setActiveIndex(index)}
onMouseLeave={() => setActiveIndex(null)}
onFocus={() => setActiveIndex(index)}
onBlur={() => setActiveIndex(null)}
>
<title>{`${point.date}:${formatNumber(count)}${unit}`}</title>
</circle>
{labels.has(index) ? (
<text
className="uc-trend__axis-label"
x={x}
y={CHART.height - 14}
textAnchor="middle"
>
{shortenDate(point.date)}
</text>
) : null}
</g>
);
})}
</svg>
{activePoint && activeCount !== undefined ? (
<div
className="uc-trend__tooltip"
role="tooltip"
style={{ left: tooltipLeft, top: tooltipTop }}
>
<div className="uc-trend__tooltip-date">{shortenDate(activePoint.date)}</div>
<div className="uc-trend__tooltip-value">
<span className="uc-trend__tooltip-dot" />
{label}:{formatNumber(activeCount)}
{unit}
</div> </div>
); </div>
})} ) : null}
</div> </div>
); );
} }
...@@ -22,12 +22,12 @@ import { dashboardApi, type TrendPoint } from '@/api'; ...@@ -22,12 +22,12 @@ import { dashboardApi, type TrendPoint } from '@/api';
import { errorDetail } from '@/utils/error'; import { errorDetail } from '@/utils/error';
import './index.css'; import './index.css';
/** 今日 / 昨日 / 本月 / 上月:指标卡与趋势卡共用同一组档位定义。 */ /** 指标卡与趋势卡共用同一组档位定义,文案与后端 dateType 的实际含义保持一致。 */
const PERIODS: ReadonlyArray<PeriodOption<number>> = [ const PERIODS: ReadonlyArray<PeriodOption<number>> = [
{ value: 1, label: '今日' }, { value: 1, label: '近7日' },
{ value: 2, label: '昨日' }, { value: 2, label: '本月' },
{ value: 3, label: '本月' }, { value: 3, label: '上月' },
{ value: 4, label: '上月' }, { value: 4, label: '近30日' },
]; ];
/** 指标定义收敛为一份:标签 / 返回字段 / 环比字段 / 单位 / 图标。 */ /** 指标定义收敛为一份:标签 / 返回字段 / 环比字段 / 单位 / 图标。 */
const STATS = [ const STATS = [
...@@ -144,7 +144,7 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise ...@@ -144,7 +144,7 @@ function Trend({ title, load }: { title: string; load: (type: number) => Promise
} }
/> />
) : ( ) : (
<TrendChart data={query.data ?? []} loading={query.isLoading} /> <TrendChart data={query.data ?? []} label={title} loading={query.isLoading} />
)} )}
</UCard> </UCard>
); );
...@@ -177,7 +177,7 @@ export default function Dashboard() { ...@@ -177,7 +177,7 @@ export default function Dashboard() {
queryFn: () => dashboardApi.getdataBoard(params), queryFn: () => dashboardApi.getdataBoard(params),
}); });
return ( return (
<PageShell title="数据看板" description="查看二手车业务的关键指标及趋势。"> <PageShell title="数据看板">
<div className="uc-dashboard"> <div className="uc-dashboard">
{/* outlined:看板三大块需要清晰边界,borderless 的浅底柔影在白底页面上会隐身; {/* outlined:看板三大块需要清晰边界,borderless 的浅底柔影在白底页面上会隐身;
uc-board 同时是容器查询上下文——指标网格按这块卡的实际宽度定列数, uc-board 同时是容器查询上下文——指标网格按这块卡的实际宽度定列数,
...@@ -188,6 +188,7 @@ export default function Dashboard() { ...@@ -188,6 +188,7 @@ export default function Dashboard() {
<UText>请选择门店:</UText> <UText>请选择门店:</UText>
<USelect <USelect
value={merchantNos} value={merchantNos}
allowClear={false}
options={[ options={[
{ label: '全部', value: '' }, { label: '全部', value: '' },
...(stores.data ?? []).map((s) => ({ ...(stores.data ?? []).map((s) => ({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!