SplitBar.tsx 2.26 KB
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>
  );
}