DataTable.tsx 7.05 KB
/**
 * 取数结果的展示:可排序、可展开全部、可导出 CSV 的表格;
 * 结果是「一列名称 + 一列数值」的排名时,上面再配一张横向条形图,一眼看出谁多谁少。
 */
import { ArrowDown, ArrowUp, Download } from "lucide-react";
import { useMemo, useState } from "react";
import { cn } from "@/lib/utils";

const isNum = (v: unknown) => typeof v === "number" && Number.isFinite(v);
const fmt = (v: unknown) => (v === null || v === undefined ? "∅"
  : isNum(v) ? (v as number).toLocaleString("zh-CN", { maximumFractionDigits: 2 }) : String(v));

function toCsv(columns: string[], rows: any[][]): string {
  const cell = (v: unknown) => {
    const s = v === null || v === undefined ? "" : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  return [columns, ...rows].map((r) => r.map(cell).join(",")).join("\r\n");
}

export function DataTable({ columns, rows, max = 10, name = "取数结果", total }: {
  columns: string[]; rows: any[][]; max?: number; name?: string;
  /** 实际总行数(rows 可能已经被截断过) */
  total?: number;
}) {
  const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null);
  const [all, setAll] = useState(false);
  const sorted = useMemo(() => {
    if (!sort) return rows;
    const { col, dir } = sort;
    return [...rows].sort((a, b) => {
      const x = a[col], y = b[col];
      if (x === y) return 0;
      if (x === null || x === undefined) return 1;
      if (y === null || y === undefined) return -1;
      return (isNum(x) && isNum(y) ? x - y : String(x).localeCompare(String(y), "zh-CN")) * dir;
    });
  }, [rows, sort]);
  if (!columns?.length) return <p className="text-label text-muted">无数据</p>;
  const shown = all ? sorted : sorted.slice(0, max);
  const download = () => {
    const blob = new Blob(["" + toCsv(columns, sorted)], { type: "text/csv;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `${name}.csv`;
    a.click();
    URL.revokeObjectURL(a.href);
  };
  return (
    <div>
      <div className={cn("overflow-auto rounded-lg border border-line", all && "max-h-96")}>
        <table className="w-full text-label">
          <thead className="sticky top-0 bg-elevated">
            <tr>
              {columns.map((c, i) => (
                <th key={c} className="border-b border-line px-2 py-1.5 text-left font-medium">
                  <button className="inline-flex items-center gap-1 hover:text-brand" title="点击排序"
                          onClick={() => setSort((s) => (s?.col === i ? (s.dir === -1 ? { col: i, dir: 1 } : null) : { col: i, dir: -1 }))}>
                    {c}
                    {sort?.col === i && (sort.dir === -1 ? <ArrowDown className="h-3 w-3" /> : <ArrowUp className="h-3 w-3" />)}
                  </button>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {shown.map((r, i) => (
              <tr key={i} className="odd:bg-ink/[0.02]">
                {r.map((v, j) => <td key={j} className={cn("border-b border-line/60 px-2 py-1", isNum(v) && "tabular-nums")}>{fmt(v)}</td>)}
              </tr>
            ))}
          </tbody>
        </table>
        {rows.length === 0 && <p className="px-2 py-2 text-label text-muted">查询成功,但没有数据</p>}
      </div>
      <div className="mt-1 flex items-center gap-3 text-caption text-muted">
        <span>共 {(total ?? rows.length).toLocaleString("zh-CN")} 行{total && total > rows.length ? `(这里有前 ${rows.length} 行)` : ""}</span>
        {rows.length > max && (
          <button className="text-brand hover:underline" onClick={() => setAll((v) => !v)}>
            {all ? "收起" : `展开全部 ${rows.length} 行`}
          </button>
        )}
        {rows.length > 0 && <button className="inline-flex items-center gap-1 text-brand hover:underline" onClick={download}><Download className="h-3 w-3" />导出 CSV</button>}
      </div>
    </div>
  );
}

/** 这份结果适不适合画排名条形图:2~20 行,最后一列是数值,前面有一列能当名字。返回 [名字列, 数值列]。 */
export function rankColumns(columns: string[], rows: any[][]): [number, number] | null {
  if (rows.length < 2 || rows.length > 20 || columns.length < 2) return null;
  const v = columns.length - 1;
  if (!rows.every((r) => isNum(r[v])) || rows.some((r) => r[v] < 0)) return null;
  // 名字列:优先「××名称」,否则第一个不是数值的列
  let n = columns.findIndex((c, i) => i < v && c.endsWith("名称"));
  if (n < 0) n = columns.findIndex((_, i) => i < v && rows.every((r) => !isNum(r[i])));
  return n < 0 ? null : [n, v];
}

/**
 * 横向排名条形图(单一系列):一种颜色表示大小,名字和数值用正文颜色写在条的两侧,
 * 所以不靠颜色也读得出来;下面的表格就是它的「表格视图」。
 */
export function RankChart({ columns, rows, unit = "" }: { columns: string[]; rows: any[][]; unit?: string }) {
  const [hover, setHover] = useState<number | null>(null);
  const cols = rankColumns(columns, rows);
  if (!cols) return null;
  const [n, v] = cols;
  // 按两个维度拆开时(仓库 × 商品),只写一个名字会出现好几条同名的条:把所有「××名称」列连起来当标签
  const names = columns.map((c, i) => (i < v && c.endsWith("名称") ? i : -1)).filter((i) => i >= 0);
  const labelCols = names.length > 1 ? names : [n];
  const others = columns.map((_, i) => i).filter((i) => !labelCols.includes(i) && i !== v);
  const items = rows.map((r) => ({ label: labelCols.map((i) => String(r[i] ?? "")).filter(Boolean).join(" · "), value: r[v] as number, row: r }))
    .sort((a, b) => b.value - a.value);
  const max = Math.max(...items.map((x) => x.value), 0) || 1;
  return (
    <figure className="rounded-lg border border-line p-3" aria-label={`${columns[v]} 排名条形图`}>
      <figcaption className="mb-2 text-caption text-muted">{columns[v]}{unit ? `(${unit})` : ""} · 从高到低</figcaption>
      <ol className="space-y-1.5">
        {items.map((x, i) => (
          <li key={i} className={cn("grid items-center gap-2", labelCols.length > 1 ? "grid-cols-[minmax(8rem,18rem)_1fr_auto]" : "grid-cols-[minmax(5rem,11rem)_1fr_auto]")}
              onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
              title={[x.label, ...others.map((j) => `${columns[j]}:${fmt(x.row[j])}`), `${columns[v]}:${fmt(x.value)}${unit}`].join("\n")}>
            <span className="truncate text-label">{x.label}</span>
            <span className="relative block h-3">
              <span className="absolute inset-y-0 left-0 w-px bg-line" />
              <span className={cn("absolute inset-y-0 left-0 rounded-r bg-brand transition-opacity", hover !== null && hover !== i && "opacity-40")}
                    style={{ width: `${Math.max(1, (x.value / max) * 100)}%` }} />
            </span>
            <span className="text-label tabular-nums text-ink">{fmt(x.value)}</span>
          </li>
        ))}
      </ol>
    </figure>
  );
}