File size: 4,328 Bytes
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useId, useRef, useState } from "react";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { readSheetActivity } from "./sheetApi";
import type { SheetActivityResult, SheetWrite } from "./sheetApi";

export function sheetWriteTime(at: string, now = Date.now()): string {
  const age = Math.max(0, now - Date.parse(at));
  if (!Number.isFinite(age)) return "";
  if (age < 60000) return "just now";
  if (age < 3600000) return `${Math.floor(age / 60000)}m ago`;
  if (age < 86400000) return `${Math.floor(age / 3600000)}h ago`;
  return `${Math.floor(age / 86400000)}d ago`;
}

function writer(write: SheetWrite): string {
  return `${write.byName || write.by}${write.via ? ` via ${write.via}` : ""}`;
}

/** Mounted with the workbook key so a late response cannot name another workbook's writer. */
export default function SheetActivity({ workbookId, revision, lastEdit }: {
  workbookId: string; revision: number; lastEdit?: SheetWrite | null;
}) {
  const [activity, setActivity] = useState<SheetActivityResult>({ lastEdit: lastEdit ?? null, writes: [] });
  const [open, setOpen] = useState(false);
  const [error, setError] = useState("");
  const [now, setNow] = useState(Date.now);

  useEffect(() => {
    let active = true;
    let pending: AbortController | null = null;
    const read = async () => {
      setNow(Date.now());
      if (pending) return;
      const controller = new AbortController();
      pending = controller;
      const timeout = window.setTimeout(() => controller.abort(), 4000);
      try {
        const result = await readSheetActivity(workbookId, controller.signal);
        if (!active) return;
        if (result.ok) {
          setActivity(result.value);
          setError("");
        } else {
          setError(result.message);
          if (result.status === 403 || result.status === 404) {
            setActivity({ lastEdit: null, writes: [] });
            setOpen(false);
          }
        }
      } finally {
        window.clearTimeout(timeout);
        pending = null;
      }
    };
    void read();
    const timer = window.setInterval(() => { void read(); }, 2000);
    return () => {
      active = false;
      window.clearInterval(timer);
      pending?.abort();
    };
  }, [workbookId, revision]);

  const last = activity.lastEdit;
  return <>
    {last && <button type="button" className="sheet-last-edit" onClick={() => setOpen(true)}
      aria-haspopup="dialog" aria-expanded={open} title={new Date(last.at).toLocaleString()}>
      Last edit by {writer(last)} · {sheetWriteTime(last.at, now)}
    </button>}
    {open && <RecentWrites writes={activity.writes} error={error} now={now} onClose={() => setOpen(false)} />}
  </>;
}

function RecentWrites({ writes, error, now, onClose }: {
  writes: SheetWrite[]; error: string; now: number; 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" role="dialog"
        aria-modal="true" aria-labelledby={titleId}>
        <div className="lp-dialog-head">
          <h2 id={titleId} className="lp-dialog-title">Recent writes</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">
          {error ? <p role="status">{error}</p> : null}
          <ol className="sheet-activity-list">
            {writes.map((write) => <li key={write.rev} className="sheet-activity-write">
              <span>{writer(write)}</span>
              <span className="sheet-activity-detail">
                <time dateTime={write.at} title={new Date(write.at).toLocaleString()}>
                  {sheetWriteTime(write.at, now)}
                </time>
                {` · ${write.cells} ${write.cells === 1 ? "cell" : "cells"}`}
              </span>
            </li>)}
          </ol>
        </div>
      </div>
    </div>
  </BodyPortal>;
}