File size: 2,269 Bytes
98c8696
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f03fdf0
 
 
 
 
 
 
 
 
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
import { useEffect, useState } from "react";
import type { ReactNode } from "react";
import { readSheetCatchUp } from "./sheetApi";
import type { SheetCatchUpStatus } from "./sheetApi";

export default function SheetCatchUp({ workbookId, revision, children }: {
  workbookId: string; revision: number; children: ReactNode;
}) {
  const [status, setStatus] = useState<SheetCatchUpStatus>({ active: false });

  useEffect(() => {
    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 readSheetCatchUp(workbookId, controller.signal);
        if (!active) return;
        if (result.ok) setStatus(result.value);
        else if (result.status === 403 || result.status === 404) setStatus({ active: 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]);

  if (!status.active) {
    if (!status.behind?.length) return children;
    return <>
      <span className="sheet-catch-up-behind" role="status">
        {status.behind.map((entry) => `${entry.source} is behind. ${entry.reason}`).join(" ")}
      </span>
      {children}
    </>;
  }
  const { done, total } = status;
  const measured = typeof done === "number" && Number.isSafeInteger(done) && done >= 0
    && typeof total === "number" && Number.isSafeInteger(total) && total > 0 && done <= total;
  return <div className="sheet-catch-up" role="status" aria-live="polite">
    <span>Updating</span>
    {measured && <>
      <span className="sheet-catch-up-track" role="progressbar" aria-label="Updating"
        aria-valuemin={0} aria-valuemax={total} aria-valuenow={done}>
        <span className="sheet-catch-up-fill" style={{ transform: `scaleX(${done / total})` }} />
      </span>
      <span className="sheet-catch-up-count">{done} of {total}</span>
    </>}
  </div>;
}