TimeChart.tsx 13.3 KB
import { useEffect, useRef, useState } from 'react';
import { fmtInt, fmtPercent } from '@/utils/format';

/**
 * 图上的一档:按天时是一天,按星期时是一天里的一个星期几,按小时时是一小时。
 *
 * 三种切法在图上长得一样(一排等宽的位置 + 一个量),所以图表组件只认这一种形状,
 * 「这一档叫什么、点进去看什么」都由外面备好,图表不再猜维度。
 */
export interface ChartSlot {
  key: string;
  /** 轴上的短标签;空串表示这一档不写字(比如只在月初写月份,其余列留白) */
  tick: string;
  /** 读数行与清单里说清这一档的完整说法:「2026-03-05 周四」「08:00—09:00」 */
  label: string;
  count: number;
  /**
   * 这一档自己的参照值(不吃 mean 的那条水平线)。
   *
   * 只有「按星期」会给:一周七天在统计期里出现的天数并不一样,期望值也就不一样。
   * 不给就是全体共用一条水平线,与以前的画法完全一致。
   */
  baseline?: number;
  /** 点这一档去看它的案件清单 */
  open: () => void;
}

interface TimeChartProps {
  slots: ChartSlot[];
  /** 柱状还是折线。同一个数据、同一把尺子,只是换一种读法 */
  shape: 'bar' | 'line';
  /** 占比的分母:当前筛选的命中总数 */
  matched: number;
  /** 虚线位置:这一档平均多少起 */
  mean: number;
  /** 虚线的名字:'日均' / '七天平均' / '时段平均' */
  meanWord: string;
  /** 没人悬停时读数行说什么 */
  idle: string;
}

/** 画图区高度;轴另起一行,免得刻度文字和柱子抢位置 */
const PLOT_H = 176;
const AXIS_H = 24;
/** 顶部留白:最高的柱子也不能顶到框,峰值标记要有个落脚的地方 */
const PAD_TOP = 14;

/**
 * 时间分布的图:柱状 / 折线共用一套坐标。
 *
 * 宽度一律铺满容器、不横向滚动(原先档数多时图比窗口宽、靠左右拖动读全,
 * 后来按用户要求撤掉横向滚动:图的纵向滚动交给面板,横向不另设一条)。
 * 档数多时柱子自然变细,精确读数靠悬停读数行,不靠量柱子的宽。
 *
 * 为什么不画 Y 轴刻度:这张图只回答「哪一段比哪一段多」,长短已经是唯一的编码了,
 * 轴上再排五六个数字等于把同一件事说两遍,还会让人去量刻度。真要精确读数,
 * 鼠标停上去那一档的数字全在上方读数行里;要逐档对比就切「清单」。
 *
 * 唯一的例外是那条虚线 —— 它不是坐标刻度,是「平均」这个参照物:
 * 柱子跨过它就知道这一段比平时多,不用心算。
 */
export function TimeChart({ slots, shape, matched, mean, meanWord, idle }: TimeChartProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [outerW, setOuterW] = useState(0);
  const [hover, setHover] = useState<number | null>(null);

  // svg 的宽就是容器的宽,所以必须实测:抽屉宽度跟着断点变,写死一个数
  // 迟早会比实际可用宽度大或小
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const ro = new ResizeObserver(() => setOuterW(el.clientWidth));
    ro.observe(el);
    setOuterW(el.clientWidth);
    return () => ro.disconnect();
  }, []);

  const n = slots.length;
  const innerW = Math.max(outerW, 1);
  const col = n > 0 ? innerW / n : innerW;

  // 每档的参照值:给了 baseline 就用它,没给就全体共用 mean。七档天数一样时
  // baseline 会全部等于 mean,`stepped` 为 false,画出来仍是一条直线(不多一道锯齿)
  const baseAt = (i: number): number => slots[i]?.baseline ?? mean;
  const stepped = slots.some((s) => s.baseline !== undefined && Math.abs(s.baseline - mean) > 1e-9);

  // 满格取「最高的一档」和「参照线」里更大的那个,再加一点点余量:
  // 全部为 0 时不能除以 0,所以兜到 1 起
  const scale = Math.max(
    slots.reduce((m, s) => Math.max(m, s.count), 0),
    mean,
    slots.reduce((m, s) => Math.max(m, s.baseline ?? 0), 0),
    1,
  );
  const y = (v: number): number => PAD_TOP + (1 - v / scale) * (PLOT_H - PAD_TOP);
  const cx = (i: number): number => i * col + col / 2;

  // 柱子宽度按档数收:七档时不要拉成七根宽带,一百八十档时也不要压没
  const barW = Math.max(2, Math.min(col * 0.62, 44));
  const peak = slots.reduce((best, s, i) => (s.count > (slots[best]?.count ?? 0) ? i : best), 0);
  const cur = hover != null ? (slots[hover] ?? null) : null;
  const curBase = hover != null ? baseAt(hover) : 0;
  // 档数少时才让每一档可聚焦:键盘在几百个格子里挨个 Tab 不是可达性,是惩罚
  const focusable = n <= 40;

  // 刻度:按父级给的标签从左到右摆,摆不下的直接不写。
  // 不做「等间隔抽稀」—— 父级给的标签本身是有含义的(月初),抽稀会把月份抽没。
  const ticks: Array<{ x: number; text: string }> = [];
  let right = -Infinity;
  slots.forEach((s, i) => {
    if (!s.tick) return;
    const w = estimateTickWidth(s.tick);
    const x = cx(i);
    if (x - w / 2 >= right) {
      ticks.push({ x, text: s.tick });
      right = x + w / 2 + 10;
    }
  });

  const points = slots.map((s, i) => ({ x: cx(i), y: y(s.count) }));
  // 逐档参照线:每格画自己那一段。天数相同的那几档自然接成一条直线,
  // 用路径而不是逐格 <line>,是为了让虚线相位连续、不在一格一格之间重新起笔
  const basePath = stepped
    ? slots
        .map((_s, i) => {
          const b = baseAt(i);
          if (!(b > 0)) return '';
          const yy = y(b).toFixed(1);
          return `M${(i * col).toFixed(1)} ${yy} L${((i + 1) * col).toFixed(1)} ${yy}`;
        })
        .filter(Boolean)
        .join(' ')
    : '';
  const hasBase = stepped ? basePath !== '' : mean > 0;
  const linePath = points
    .map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
    .join(' ');
  const areaPath =
    points.length > 1
      ? `${linePath} L${points[points.length - 1].x.toFixed(1)} ${PLOT_H} L${points[0].x.toFixed(1)} ${PLOT_H} Z`
      : '';

  return (
    <div className="hm-tc">
      {/* 读数行做成固定两行:第一行是「哪一档、多少起、占多少」,第二行是
          「与平均相比、点开能看什么」。悬停内容原先和空闲文案挤在同一个可换行的
          flex 行里 —— 内容一长就折成两行、一短又缩回一行,图跟着上下跳,
          看起来就是「提示一下出现一下消失」。现在高度写死、两行都常驻,
          只换文字不换版式。 */}
      <div className="hm-tc__readout">
        <div className="hm-tc__readout-l1">
          {cur ? (
            <>
              <span className="hm-tc__readout-label" title={cur.label}>
                {cur.label}
              </span>
              <b className="hm-tc__readout-value">{fmtInt(cur.count)} 起</b>
              <span className="hm-tc__readout-bit">占命中 {fmtPercent(cur.count, matched)}</span>
            </>
          ) : (
            <span className="hm-tc__readout-idle">{idle}</span>
          )}
        </div>
        <div className="hm-tc__readout-l2">
          {cur && (
            <>
              <span className="hm-tc__readout-bit">
                {meanWord}的 {curBase > 0 ? (cur.count / curBase).toFixed(2) : '0.00'} 倍
              </span>
              {cur.count > 0 && (
                <span className="hm-tc__readout-cta">点一下看这一档的案件清单</span>
              )}
            </>
          )}
        </div>
      </div>

      <div className="hm-tc__scroll" ref={scrollRef} onMouseLeave={() => setHover(null)}>
        <svg
          className="hm-tc__svg"
          width={innerW}
          height={PLOT_H + AXIS_H}
          role={focusable ? 'group' : 'img'}
          aria-label="时间分布图"
        >
          {/* 悬停那一条的底衬:让「读数行说的是哪一列」不用靠眼睛在两处之间来回确认 */}
          {hover != null && cur && (
            <rect className="hm-tc__band" x={hover * col} y={0} width={col} height={PLOT_H} />
          )}

          {hasBase && (
            <>
              {stepped ? (
                <path className="hm-tc__mean" d={basePath} fill="none" />
              ) : (
                <line className="hm-tc__mean" x1={0} x2={innerW} y1={y(mean)} y2={y(mean)} />
              )}
              {/* 标签贴左端:图的开头就是读图起点,参照物的名字放在最先读到的地方。
                  逐档参照时**不写标签**:七档高矮不一,任何一处写下去都会压在折线或柱子上
                  (372px 的面板里半行字就是三根柱子的宽度),而折算口径已经写在图下面那句
                  说明里 —— 那里有完整的一句话,图上留一条台阶状的虚线反而更好认 */}
              {!stepped && (
                <text
                  className="hm-tc__mean-label"
                  x={6}
                  y={y(mean) < 18 ? y(mean) + 12 : y(mean) - 5}
                >
                  {`${meanWord} ${fmtInt(Math.round(mean))} 起`}
                </text>
              )}
            </>
          )}

          {shape === 'bar' &&
            slots.map((s, i) => {
              const h = PLOT_H - y(s.count);
              const x = cx(i) - barW / 2;
              // 0 起的那一档留一截浅色桩而不是什么都不画:这里「没有」本身是要看得见的信息,
              // 空白会被读成「这一段没统计」
              return s.count === 0 ? (
                <rect
                  className="hm-tc__bar hm-tc__bar--empty"
                  key={s.key}
                  x={x}
                  y={PLOT_H - 2}
                  width={barW}
                  height={2}
                />
              ) : (
                <g key={s.key}>
                  <rect
                    className="hm-tc__bar"
                    x={x}
                    y={y(s.count)}
                    width={barW}
                    height={Math.max(h, 1.5)}
                    rx={Math.min(2.5, barW / 2)}
                  />
                  {/* 峰值记号:顶上那块读数写的是「最多的一天/最集中的时段」,
                        图上标出同一档,两句话才对得上。金色只用在这一处 */}
                  {i === peak && barW >= 4 && (
                    <rect
                      className="hm-tc__peak"
                      x={x}
                      y={y(s.count) - 5}
                      width={barW}
                      height={2.5}
                      rx={1.25}
                    />
                  )}
                </g>
              );
            })}

          {shape === 'line' && areaPath && <path className="hm-tc__area" d={areaPath} />}
          {shape === 'line' && points.length > 1 && <path className="hm-tc__line" d={linePath} />}
          {/* 折线在档数多时不画散点:一百八十个点连成一条粗线,只会糊掉走势本身 */}
          {shape === 'line' &&
            col >= 12 &&
            points.map((p, i) => (
              <circle
                key={slots[i].key}
                className={`hm-tc__dot${i === peak ? ' hm-tc__dot--peak' : ''}`}
                cx={p.x}
                cy={p.y}
                r={2.6}
              />
            ))}
          {shape === 'line' && cur && hover != null && (
            <circle
              className="hm-tc__dot hm-tc__dot--hover"
              cx={cx(hover)}
              cy={y(cur.count)}
              r={4}
            />
          )}

          <line className="hm-tc__axis" x1={0} x2={innerW} y1={PLOT_H} y2={PLOT_H} />
          {ticks.map((t, i) => (
            <text className="hm-tc__tick" key={`t${i}`} x={t.x} y={PLOT_H + 16} textAnchor="middle">
              {t.text}
            </text>
          ))}

          {/* 命中区摊在最后一层:一整列从上到下都好点,不必瞄准柱子那一截 */}
          {slots.map((s, i) => {
            const linkable = s.count > 0;
            return (
              <rect
                className={`hm-tc__hit${linkable ? ' hm-tc__hit--link' : ''}`}
                key={`hit-${s.key}`}
                x={i * col}
                y={0}
                width={col}
                height={PLOT_H + AXIS_H}
                tabIndex={focusable && linkable ? 0 : undefined}
                role={focusable && linkable ? 'button' : undefined}
                aria-label={linkable ? `${s.label},${fmtInt(s.count)} 起,查看案件清单` : s.label}
                onMouseEnter={() => setHover(i)}
                onClick={() => {
                  if (linkable) s.open();
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && linkable) s.open();
                }}
              />
            );
          })}
        </svg>
      </div>
    </div>
  );
}

/**
 * 刻度占多宽只能估:SVG 里量文字要等布局,而布局要等宽度、宽度又要先知道标签放不放得下。
 * 中文字按 10.5、数字冒号按 6.2(10px 字号)算,再留 6px 呼吸;
 * 估宽只会偏保守(少放一个标签),不会让两个标签撞上。
 */
function estimateTickWidth(text: string): number {
  let w = 6;
  for (const ch of text) w += /[\u4e00-\u9fff]/.test(ch) ? 10.5 : 6.2;
  return w;
}