SplitBar.tsx
2.26 KB
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
export interface SplitBarItem {
/** 图例文本 */
label: string;
/** 原始值,用于计算占比与排序 */
value: number;
/** 条形颜色。不传由调用方按调色板派发 */
color?: string;
}
export interface SplitBarProps {
items: SplitBarItem[];
/** 最多展示条数,其余折叠为「其他」 */
limit?: number;
/** 数值展示格式化 */
formatValue?: (v: number) => string;
/** 总量。不传则由 items 求和 */
total?: number;
}
/**
* 占比条:横向条 + 右侧数值,用于 TOP 区 / TOP 街道排行。
*
* 用纯 div 画条而不是图表库:这类"一行一值"的排行用图表库反而要做数据适配层,
* 而宽度百分比就是一个 inline style 的事。
*/
export function SplitBar({ items, limit = 8, formatValue, total }: SplitBarProps) {
const fmt = formatValue ?? ((v: number) => String(v));
const sorted = [...items].sort((a, b) => b.value - a.value);
let rows = sorted;
if (sorted.length > limit) {
const head = sorted.slice(0, limit - 1);
const tail = sorted.slice(limit - 1);
const rest = tail.reduce((s, it) => s + it.value, 0);
rows = [...head, { label: `其他 ${tail.length} 项`, value: rest, color: 'var(--hm-text-3)' }];
}
const sum = total ?? sorted.reduce((s, it) => s + it.value, 0);
const max = rows.length ? Math.max(...rows.map((r) => r.value)) : 1;
if (!rows.length) return <div className="hm-splitbar__empty">无数据</div>;
return (
<div className="hm-splitbar">
{rows.map((r, i) => (
<div className="hm-splitbar__row" key={`${r.label}-${i}`}>
<div className="hm-splitbar__head">
<span className="hm-splitbar__label" title={r.label}>
{r.label}
</span>
<span className="hm-splitbar__value">
{fmt(r.value)}
{sum > 0 && <em>{((r.value / sum) * 100).toFixed(1)}%</em>}
</span>
</div>
<div className="hm-splitbar__track">
<div
className="hm-splitbar__fill"
style={{
width: `${Math.max((r.value / max) * 100, 1.5)}%`,
background: r.color ?? 'var(--hm-primary)',
}}
/>
</div>
</div>
))}
</div>
);
}