File size: 6,093 Bytes
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { useEffect, useRef, useState } from "react";
import { fileDate, intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceHistory } from "./intelligenceApi";

export default function History({ path, api, revision, onRestored, onBusy }: {
  path: string; api: IntelligenceApi; revision: number; onRestored: (file: IntelligenceFile) => void; onBusy: (busy: boolean) => void;
}) {
  const [history, setHistory] = useState<IntelligenceHistory | null>(null);
  const [version, setVersion] = useState(0);
  const [retry, setRetry] = useState(0);
  const [problem, setProblem] = useState("");
  const [notice, setNotice] = useState("");
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const writing = useRef(false);
  const generation = useRef(0);
  const panelRef = useRef<HTMLElement>(null);
  const focusVersion = useRef<number | null>(null);
  useEffect(() => {
    const abort = new AbortController();
    generation.current += 1;
    setHistory(null); setLoading(true); setProblem("");
    void api.history(path, version, abort.signal).then((value) => {
      if (!abort.signal.aborted) setHistory(value);
    }).catch((error: unknown) => {
      if (!abort.signal.aborted) setProblem(intelligenceProblem(error, "History could not be read. Try again."));
    }).finally(() => { if (!abort.signal.aborted) setLoading(false); });
    return () => { generation.current += 1; abort.abort(); };
  }, [api, path, version, revision, retry]);
  useEffect(() => {
    if (history && focusVersion.current !== null) {
      panelRef.current?.querySelector<HTMLButtonElement>(`[data-version="${focusVersion.current}"]`)?.focus();
      focusVersion.current = null;
    }
  }, [history]);

  async function restore() {
    if (!history || writing.current) return;
    const active = generation.current;
    writing.current = true; setBusy(true); onBusy(true); setProblem(""); setNotice("");
    try {
      const file = await api.restore(path, history.selectedVersion, history.latestVersion);
      if (generation.current !== active) return;
      focusVersion.current = file.version;
      setNotice(`Restored as version ${file.version}.`); setVersion(0); onRestored(file);
    } catch (error) {
      if (generation.current === active) {
        setProblem(intelligenceProblem(error, "The restore could not be confirmed. Reload and try again."));
        setHistory(null);
      }
    } finally {
      writing.current = false; onBusy(false);
      setBusy(false);
    }
  }
  const selected = history?.history.find((entry) => entry.version === history.selectedVersion);
  const atLimit = !!history && history.latestVersion >= history.limits.maxVersions;
  return <section ref={panelRef} className="intelligence-history" data-testid="intelligence-history" aria-label="File history" aria-busy={loading || busy}>
    <div className="intelligence-history-heading"><h3>History</h3>
      {history ? <span className="intelligence-meta" data-testid="intelligence-trimmed">{history.trimmed.toLocaleString()} versions trimmed</span> : null}</div>
    {notice ? <p className="intelligence-meta" role="status">{notice}</p> : null}
    {problem ? <div className="intelligence-feedback" role="alert"><span>{problem}</span>
      <button type="button" className="intelligence-button" disabled={busy} onClick={() => { setVersion(0); setRetry((value) => value + 1); }}>Reload</button></div> : null}
    {loading ? <div className="intelligence-skeleton" role="status" aria-label="Loading history"><span /><span /></div> : null}
    {history ? <>
      <ol className="intelligence-history-list" aria-label="Versions">
        {history.history.map((entry) => <li key={entry.version}>
          <button type="button" className="intelligence-button intelligence-history-version" disabled={busy} data-version={entry.version}
            aria-pressed={history.selectedVersion === entry.version} onClick={() => { focusVersion.current = entry.version; setVersion(entry.version); setNotice(""); }}>
            <span className="intelligence-history-label">Version {entry.version}{entry.version === history.latestVersion ? " · Current" : ""}</span>
            <span>{entry.authorKind === "system" ? "By system"
              : entry.authorKind === "agent" ? `By agent · ${entry.author} for ${entry.onBehalfOf}` : `By hand · ${entry.author}`}</span>
            <time dateTime={entry.created}>{fileDate(entry.created)}</time>
            {entry.approvedBy?.length ? <span>Approved by {entry.approvedBy.join(", ")}</span> : null}
            {entry.restoredFrom ? <span>Restored from version {entry.restoredFrom}</span> : null}
          </button>
        </li>)}
      </ol>
      {selected ? <div data-testid="intelligence-history-diff">
        <h3>Version {selected.version} changes</h3>
        <p className="intelligence-meta">{history.previousVersion ? `Compared with version ${history.previousVersion}`
          : history.diff === null ? "Previous version unavailable." : "First version"}</p>
        {history.diff ? <pre className="intelligence-diff" tabIndex={0} aria-label="Version diff">{history.diff.split("\n").map((line, index) =>
          <span key={index} className={line.startsWith("+") && !line.startsWith("+++") ? "intelligence-diff-add"
            : line.startsWith("-") && !line.startsWith("---") ? "intelligence-diff-remove" : undefined}>{line}{"\n"}</span>)}</pre>
          : history.diff === "" ? <p className="intelligence-meta">No text changes.</p> : null}
      </div> : null}
      {atLimit ? <p className="intelligence-meta">This file has 100 versions. Save further work in a new file.</p> : null}
      {history.canRestore && history.selectedVersion !== history.latestVersion ? <div className="intelligence-proposal-actions">
        <button type="button" className="intelligence-button" disabled={busy || atLimit} onClick={() => void restore()}>
          {busy ? "Restoring…" : `Restore version ${history.selectedVersion}`}</button>
      </div> : null}
    </> : null}
  </section>;
}