File size: 7,142 Bytes
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
816fa8a
 
 
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
8cbc29f
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
8cbc29f
816fa8a
 
 
8cbc29f
 
 
 
816fa8a
 
8cbc29f
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import { useEffect, useId, useRef, useState } from "react";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { readRefreshHistory } from "./sheetApi";
import type { SheetRefreshEntry, SheetRefreshHistory } from "./sheetApi";
import "../styles/sdlc73/sheet.css";

function scopeLabel(scope: SheetRefreshEntry["scope"]): string {
  if ("workbook" in scope) return "Workbook";
  if ("cells" in scope) return `${scope.cells.length} cells`;
  return ("cell" in scope ? scope.cell : scope.range).split("!").pop() || "Cells";
}

function timeLabel(at: string): string {
  const date = new Date(at);
  return Number.isNaN(date.getTime()) ? "Time unavailable" : date.toLocaleString();
}

function refreshLabel(entry: SheetRefreshEntry): string {
  if (entry.kind !== "auto") return entry.state === "held" ? "Held" : entry.state === "committed" ? "Committed" : "Attempted";
  return entry.reason === "sync" ? "Automatic sync" : entry.reason === "rollover" ? "Automatic rollover" : "Automatic refresh";
}

export default function RefreshHistory({ workbookId, revision, busy, onRetry }: {
  workbookId: string; revision: number; busy: boolean; onRetry: (id: string) => Promise<void>;
}) {
  const [open, setOpen] = useState(false);
  const [history, setHistory] = useState<SheetRefreshHistory>({ entries: [], lastGoodAt: null, sources: [] });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [retrying, setRetrying] = useState<string | null>(null);
  const [reload, setReload] = useState(0);
  const live = useRef(true);
  useEffect(() => { live.current = true; return () => { live.current = false; }; }, []);
  useEffect(() => {
    if (!open) return;
    setLoading(true);
    let active = true;
    let pending: AbortController | null = null;
    const read = async () => {
      if (pending) return;
      const controller = new AbortController();
      pending = controller;
      const timeout = window.setTimeout(() => controller.abort(), 4000);
      try {
        const result = await readRefreshHistory(workbookId, controller.signal);
        if (!active) return;
        if (result.ok) {
          setHistory(result.value);
          setError("");
        } else {
          setError(result.message);
          if (result.status === 403 || result.status === 404) {
            setHistory({ entries: [], lastGoodAt: null, sources: [] });
            setOpen(false);
          }
        }
      } finally {
        if (active) setLoading(false);
        pending = null;
        window.clearTimeout(timeout);
      }
    };
    void read();
    const timer = window.setInterval(() => { void read(); }, 2000);
    return () => { active = false; window.clearInterval(timer); pending?.abort(); };
  }, [workbookId, revision, open, reload]);

  const retry = async (id: string) => {
    if (retrying || busy) return;
    setRetrying(id);
    try { await onRetry(id); }
    catch { if (live.current) setError("Refresh could not finish."); }
    finally {
      if (live.current) { setRetrying(null); setReload(value => value + 1); }
    }
  };
  return <>
    <button type="button" className="sheet-refresh-history-trigger" aria-haspopup="dialog"
      aria-expanded={open} onClick={() => setOpen(true)}>Refresh history</button>
    {open && <HistoryPanel history={history} error={error} loading={loading} busy={busy || retrying !== null}
      onRetry={id => { void retry(id); }} onClose={() => setOpen(false)} />}
  </>;
}

function HistoryPanel({ history, error, loading, busy, onRetry, onClose }: {
  history: SheetRefreshHistory; error: string; loading: boolean; busy: boolean;
  onRetry: (id: string) => void; onClose: () => void;
}) {
  const panelRef = useRef<HTMLDivElement>(null);
  const titleId = useId();
  useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false,
    initialFocus: "[data-overlay-autofocus]", restoreFocus: true, trapFocus: true });
  return <BodyPortal>
    <div className="lp-dialog-scrim sheet-activity-scrim">
      <div ref={panelRef} className="lp-dialog sheet-activity-panel sheet-refresh-history" role="dialog"
        aria-modal="true" aria-labelledby={titleId}>
        <div className="lp-dialog-head">
          <h2 id={titleId} className="lp-dialog-title">Refresh history</h2>
          <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet"
            data-overlay-autofocus="" onClick={onClose}>Close</button>
        </div>
        <div className="lp-dialog-body sheet-activity-body">
          <p className="sheet-refresh-last-good">Last good refresh: {history.lastGoodAt
            ? <time dateTime={history.lastGoodAt}>{timeLabel(history.lastGoodAt)}</time> : "None yet"}</p>
          {error && <p role="alert">{error}</p>}
          <section aria-label="Sources" aria-busy={loading}>
            <h3 className="sheet-refresh-last-good">Sources</h3>
            {loading && <p className="sheet-activity-detail" role="status">Loading sources</p>}
            {!loading && !error && history.sources.length === 0
              && <p className="sheet-activity-detail">No bound databases</p>}
            {!loading && !error && <ul className="sheet-activity-list">
              {history.sources.map(source => <li key={source.database} className="sheet-activity-write">
                <strong>{source.label}</strong>
                <span className="sheet-activity-detail">{source.connector || "No connector"}
                  {" 路 "}{source.cadence || "Cadence unavailable"}{" 路 "}Last sync: {source.lastSyncAt
                    ? <time dateTime={source.lastSyncAt}>{timeLabel(source.lastSyncAt)}</time> : "Unavailable"}</span>
              </li>)}
            </ul>}
          </section>
          {!error && history.entries.length === 0 && <p className="sheet-activity-detail">No refreshes yet</p>}
          <ol className="sheet-activity-list">
            {history.entries.map(entry => <li key={entry.id} className="sheet-activity-write"
              data-refresh-state={entry.state}>
              <div className="sheet-refresh-history-row">
                <strong>{refreshLabel(entry)}</strong>
                {entry.canRetry && <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet"
                  disabled={busy} onClick={() => onRetry(entry.id)}>Retry</button>}
              </div>
              <span>{entry.kind === "auto"
                ? entry.state === "committed" ? "Committed" : entry.state === "held" ? "Held" : "Attempted"
                : entry.byName || entry.by} 路 {scopeLabel(entry.scope)}</span>
              <span className="sheet-activity-detail">{entry.changedCells} {entry.changedCells === 1 ? "cell" : "cells"} changed 路 <time
                dateTime={entry.at}>{timeLabel(entry.at)}</time></span>
              {entry.state === "held" && <span className="sheet-activity-detail">{entry.reason === "store_catching_up"
                ? "Database updating" : entry.kind === "auto" ? "Refresh incomplete" : "Source unavailable"}</span>}
            </li>)}
          </ol>
        </div>
      </div>
    </div>
  </BodyPortal>;
}