History.tsx 9.61 KB
import { useEffect, useMemo, useState } from 'react';
import { toast } from 'sonner';
import {
  RefreshCw,
  FileText,
  Eye,
  History as HistoryIcon,
  Clock,
  CheckCircle2,
  XCircle,
  ListChecks,
  StopCircle,
  Trash2,
} from 'lucide-react';
import { api, onSSE } from '@/lib/api';
import { cancelJob, deleteJob, startPreview as startPreviewAction, clearAllJobs } from '@/lib/jobActions';
import type { Job } from '@/lib/types';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { StatusPill } from '@/components/ui/status-pill';
import { PageHeader } from '@/components/layout/PageHeader';
import { modeLabel } from '@/lib/status';
import { cn } from '@/lib/utils';

function fmt(ts: string | null) {
  if (!ts) return '—';
  const d = new Date(ts);
  if (Number.isNaN(d.getTime())) return ts.slice(0, 19).replace('T', ' ');
  const p = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
}

function duration(j: Job) {
  if (!j.startedAt || !j.finishedAt) return j.status === 'running' ? '进行中' : '—';
  const ms = new Date(j.finishedAt).getTime() - new Date(j.startedAt).getTime();
  if (ms < 0) return '—';
  const s = Math.round(ms / 1000);
  if (s < 60) return `${s}s`;
  return `${Math.floor(s / 60)}m${s % 60}s`;
}

export default function History() {
  const [jobs, setJobs] = useState<Job[]>([]);
  const [loading, setLoading] = useState(true);

  const refresh = async () => {
    try {
      const r = await api.listJobs();
      setJobs(r.jobs);
    } catch (e) {
      toast.error('加载失败', {
        description: e instanceof Error ? e.message : String(e),
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    refresh();
    return onSSE('jobs', (d) => setJobs(d as Job[]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const stats = useMemo(() => {
    const total = jobs.length;
    const done = jobs.filter((j) => j.status === 'done').length;
    const error = jobs.filter((j) => j.status === 'error').length;
    const running = jobs.filter((j) => j.status === 'running').length;
    const rate = total ? Math.round((done / total) * 100) : 0;
    return { total, done, error, running, rate };
  }, [jobs]);

  return (
    <div className="p-6">
      <PageHeader
        icon={HistoryIcon}
        description="所有生成任务持久化记录,跨服务重启不丢失。"
        actions={
          <>
            <Button
              variant="outline"
              size="sm"
              onClick={() => { void clearAllJobs(); }}
              disabled={loading || jobs.length === 0}
              className="text-muted-foreground hover:text-rose-400"
            >
              <Trash2 className="h-4 w-4" /> 清空历史
            </Button>
            <Button variant="outline" size="sm" onClick={refresh} disabled={loading}>
              <RefreshCw className={cn('h-4 w-4', loading && 'animate-spin')} /> 刷新
            </Button>
          </>
        }
      />

      {/* Stat cards */}
      <div className="mt-5 grid grid-cols-2 gap-3 lg:grid-cols-4">
        {[
          { icon: ListChecks, label: '任务总数', value: stats.total, tone: 'text-foreground' },
          { icon: CheckCircle2, label: '成功', value: stats.done, tone: 'text-emerald-500' },
          { icon: XCircle, label: '失败', value: stats.error, tone: 'text-rose-500' },
          { icon: Clock, label: '成功率', value: `${stats.rate}%`, tone: 'text-emerald-500' },
        ].map((s) => (
          <div
            key={s.label}
            className="flex items-center gap-3 rounded-xl border border-border bg-card p-4"
          >
            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-muted">
              <s.icon className={cn('h-5 w-5', s.tone)} />
            </div>
            <div>
              <div className="text-xs text-muted-foreground">{s.label}</div>
              <div className="text-xl font-semibold tabular-nums">{s.value}</div>
            </div>
          </div>
        ))}
      </div>

      {/* Table */}
      <div className="mt-5 overflow-hidden rounded-2xl border border-border bg-card">
        {loading ? (
          <div className="p-10 text-center text-sm text-muted-foreground">
            加载中…
          </div>
        ) : jobs.length === 0 ? (
          <div className="flex flex-col items-center gap-3 p-14 text-center">
            <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
              <HistoryIcon className="h-7 w-7" />
            </div>
            <p className="text-sm text-muted-foreground">暂无任务记录</p>
          </div>
        ) : (
          <div className="scrollbar-thin overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border text-left text-xs uppercase tracking-wider text-muted-foreground">
                  <th className="px-4 py-3 font-medium">状态</th>
                  <th className="px-4 py-3 font-medium">模式</th>
                  <th className="px-4 py-3 font-medium">应用</th>
                  <th className="px-4 py-3 font-medium">Figma 来源</th>
                  <th className="px-4 py-3 font-medium">创建时间</th>
                  <th className="px-4 py-3 font-medium">耗时</th>
                  <th className="px-4 py-3 text-right font-medium">操作</th>
                </tr>
              </thead>
              <tbody>
                {jobs.map((j) => (
                  <tr
                    key={j.id}
                    className="group border-b border-border/60 transition-colors last:border-0 hover:bg-accent/40"
                  >
                    <td className="px-4 py-3">
                      <StatusPill status={j.status} />
                    </td>
                    <td className="px-4 py-3">
                      <Badge variant="neutral">{modeLabel[j.mode]}</Badge>
                    </td>
                    <td className="px-4 py-3 font-medium">{j.appName || '未命名'}</td>
                    <td
                      className="max-w-[240px] truncate px-4 py-3 font-mono text-xs text-muted-foreground"
                      title={j.figmaUrl}
                    >
                      {j.figmaUrl}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
                      {fmt(j.createdAt)}
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
                      {duration(j)}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex justify-end gap-1.5 opacity-0 transition-opacity group-hover:opacity-100">
                        {j.status === 'running' || j.status === 'queued' ? (
                          <button
                            onClick={() => { void cancelJob(j.id); }}
                            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400"
                            title="结束任务"
                          >
                            <StopCircle className="h-4 w-4" />
                          </button>
                        ) : null}
                        {j.reportPath ? (
                          <a
                            href={`/api/job/${j.id}`}
                            className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
                            title="查看报告"
                          >
                            <FileText className="h-4 w-4" />
                          </a>
                        ) : null}
                        <button
                          onClick={() => { void startPreviewAction('已为该任务产物启动预览'); }}
                          className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-foreground"
                          title="在预览中打开"
                        >
                          <Eye className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => { void deleteJob(j.id); }}
                          className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-background hover:text-rose-400"
                          title="删除记录"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Failures */}
      {jobs.some((j) => j.status === 'error' && j.error) && (
        <div className="mt-4 space-y-2">
          {jobs
            .filter((j) => j.status === 'error' && j.error)
            .map((j) => (
              <div
                key={j.id}
                className="flex items-start gap-2 rounded-lg border border-rose-500/25 bg-rose-500/10 p-3 text-xs text-rose-500"
              >
                <XCircle className="mt-0.5 h-4 w-4 shrink-0" />
                <div>
                  <span className="font-medium">{j.appName}</span>:{j.error}
                </div>
              </div>
            ))}
        </div>
      )}
    </div>
  );
}