File size: 13,945 Bytes
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
 
 
 
 
 
 
 
 
971c29d
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// ---------------------------------------------------------------------------
// sheet/ImportDialog.tsx β€” W51-T13 (owner instruction 7, ruling R1, contracts C4 and C8).
//
// THE IMPORT DOOR. One .xlsx goes in, the server reads it with openpyxl, and this dialog says what
// is happening while it does: Reading, Cells, Formats, Recalculating, a bar, and then the one line
// that says whether the import is TRUE rather than merely finished β€” "Matched N of M formula
// cells", which is R1's differential ("done when every computed cell matches the file's cached
// value") stated as a number.
//
// β›”β›” NOTHING HERE OPENS THE FILE. R1 puts openpyxl on the server, and a client that parsed the
// same bytes would be a second reader disagreeing with the first about merged cells, shared strings
// and cached values β€” a disagreement that surfaces as a wrong number on a screen rather than as an
// error. `file.size` and `file.name` are metadata the browser already had; they are the whole of
// what this file knows about the workbook.
//
// β›” THE POLL HAS FIVE TERMINAL CONDITIONS, NOT THREE. C4 names two (`done`, `refused`); a loop
// that stopped only on those spins forever against a job that stalls, and the dialog then lies
// about work that is not happening. The other three are the tick CAP, CANCEL and UNMOUNT, all
// three arbitrated by ONE run token: every `setState` in the loop is preceded by a check that the
// run it belongs to is still the current one, so a cancelled poll cannot paint over a fresh one.
//
// ⚠ THE SHELL IS `ConfirmDialog`, NOT A SECOND DIALOG SHAPED LIKE IT (contract C8). It brings the
// centered panel, the quiet Cancel first, initial focus on Cancel, the focus trap, Escape, the
// backdrop and the return of focus to the opener. This file adds a BODY and nothing else. In
// particular it installs no Escape handler of its own: `useOverlayLayer` inside the kit already
// claims the key, and a second claimant would race the first.
//
// ⚠ `busy` LOCKS BOTH BUTTONS WHILE THE JOB RUNS, and that is the kit's semantics rather than an
// oversight. The read happens in a server thread that a client dismissal cannot stop, so a live
// Cancel would promise a cancellation nobody performs. The tick cap is what bounds the lock.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useRef, useState } from "react";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import {
  BYTES_PER_MB,
  IMPORT_MAX_BYTES,
  IMPORT_MAX_MB,
  importWorkbook,
  readImportJob,
} from "./sheetApi";
import type { ImportJob, ImportState, Result } from "./sheetApi";

export interface ImportDialogProps {
  open: boolean;
  /** Dismissed without importing anything, or closed after the job ended. */
  onCancel: () => void;
  /** The import landed: this is the workbook it made, and the host opens it. */
  onOpened: (workbookId: string) => void;
  /** Retain the server's success sentence before opening unmounts this dialog. */
  onSummary?: (summary: string) => void;
}

/** 750ms x 240 ticks is three minutes, which is the cap and the sentence below agrees with it. */
const POLL_MS = 750;
const POLL_TICKS = 240;
const POLL_MINUTES = Math.round((POLL_MS * POLL_TICKS) / 60000);

/** The word each state wears, sentence case, exactly as the done-when names them. */
const STATE_LABEL: Record<ImportState, string> = {
  reading: "Reading",
  cells: "Cells",
  formats: "Formats",
  recalc: "Recalculating",
  done: "Done",
  refused: "Stopped",
};

/** ...and the sentence under it, because a single word is a label and not an explanation. */
const STATE_NOTE: Record<ImportState, string> = {
  reading: "Reading the file.",
  cells: "Reading the cells and their values.",
  formats: "Reading the number formats.",
  recalc: "Recalculating every formula and comparing it to the file.",
  done: "Opening the workbook.",
  refused: "The import stopped.",
};

const NOT_AVAILABLE = "Importing a workbook is not available yet.";

const wait = (ms: number) => new Promise<void>((done) => { window.setTimeout(done, ms); });

/**
 * β›”β›” THE ORDER OF THESE BRANCHES IS THE WHOLE OF THE CHECK, and it is ordered by WHAT EACH STATUS
 * PROVES rather than by the numbers. A 413 and any NAMED refusal both prove the route is THERE and
 * answered about this file; only an unnamed 4xx is evidence of absence. Read the other way round,
 * the first oversized file would convince this client permanently that import does not exist, with
 * nothing on screen saying what actually happened.
 *
 * ⚠ AND THE FALLBACK IS KEYED ON `>= 400` EXCEPT 403, NEVER ON A CODE LIST. An unbuilt route under
 * a path parameter answers 405, not 404 [[an-unbuilt-route-under-a-path-param-answers-405]], and a
 * 403 is a permission answer from a route that plainly exists.
 */
/**
 * β›”β›” `unknown` IS NOT THE ONLY UNNAMED CODE, AND THAT COST THIS TICKET ITS DONE-WHEN.
 * The API wraps EVERY HTTP error in its own envelope, so an unbuilt route answers
 *     {"error": {"code": "http_405", "message": "Method Not Allowed"}}
 * and `res.code !== "unknown"` reads that as a NAMED refusal. The dialog then showed the reason
 * phrase `Method Not Allowed` to a person who asked to import a spreadsheet, and the
 * not-available-yet sentence below was unreachable. Measured in a live browser, not predicted.
 * ⭐ A code the SERVER'S OWN VOCABULARY defines (`sheet_too_many_cells`, `workbook_too_large`)
 * is a sentence worth showing. `http_<status>` is the transport restating itself.
 */
const HTTP_ENVELOPE = /^http_\d{3}$/;

export function refusalSentence(res: { status: number; code: string; message: string }): string {
  const named = res.code !== "unknown" && !HTTP_ENVELOPE.test(res.code);
  if (res.status === 0) return res.message;
  if (res.status === 413) {
    return named
      ? res.message
      : `That file is over the ${IMPORT_MAX_MB} MB limit the server accepts.`;
  }
  if (named) return res.message;
  if (res.status === 403) return res.message;
  if (res.status >= 400 && res.status !== 403) return NOT_AVAILABLE;
  return res.message;
}

/**
 * The client's own two refusals, said as sentences naming the cap and the count.
 *
 * ⚠ THE COMPARISON AND THE PRINTED NUMBER SHARE ONE DIVISOR, or a file could read "25.0 MB" on
 * screen and still be refused. The test is `>` rather than `>=`, so a file exactly at the cap is
 * offered to the server, which is the side that owns the limit.
 */
export function fileRefusal(file: File): string {
  if (!/\.xlsx$/i.test(file.name)) {
    return "Loopable reads .xlsx workbooks. Choose a file saved in that format.";
  }
  if (file.size > IMPORT_MAX_BYTES) {
    const mb = (file.size / BYTES_PER_MB).toFixed(1);
    return `This file is ${mb} MB; the limit is ${IMPORT_MAX_MB} MB.`;
  }
  return "";
}

/** How many formula cells the differential is over. Zero means there is nothing to state. */
export function formulaCellsSeen(job: ImportJob | null): number {
  const report = job?.report;
  return report ? report.matched + report.mismatched.length : 0;
}

type Phase = "idle" | "running" | "ended";

export default function ImportDialog({ open, onCancel, onOpened, onSummary }: ImportDialogProps) {
  const [file, setFile] = useState<File | null>(null);
  const [phase, setPhase] = useState<Phase>("idle");
  const [job, setJob] = useState<ImportJob | null>(null);
  const [sentence, setSentence] = useState("");
  /** Remounts the native input, which is the only way to clear what it is showing. */
  const [pick, setPick] = useState(0);

  /**
   * β›” THE RUN TOKEN IS WHAT MAKES CANCEL AND UNMOUNT TERMINAL. Bumping it orphans every pending
   * tick of the loop that read the old value, so a poll whose dialog is gone cannot call
   * `setState` on an unmounted component or reopen a stale progress bar over a fresh import.
   */
  const runRef = useRef(0);
  const stop = useCallback(() => { runRef.current += 1; }, []);
  useEffect(() => () => { runRef.current += 1; }, []);

  const poll = useCallback(async (id: string, run: number) => {
    for (let tick = 0; tick < POLL_TICKS; tick += 1) {
      await wait(POLL_MS);
      if (run !== runRef.current) return;
      const read: Result<ImportJob> = await readImportJob(id);
      if (run !== runRef.current) return;
      if (!read.ok) {
        setPhase("ended");
        setSentence(refusalSentence(read));
        return;
      }
      setJob(read.value);
      if (read.value.state === "refused") {
        setPhase("ended");
        setSentence(read.value.sentence || "The import stopped and the server did not say why.");
        return;
      }
      if (read.value.state === "done") {
        setPhase("ended");
        if (read.value.workbook_id) {
          onSummary?.(read.value.sentence ?? "");
          onOpened(read.value.workbook_id);
          return;
        }
        setSentence("The import finished and the server did not say which workbook it made.");
        return;
      }
    }
    setPhase("ended");
    setSentence(
      `Nothing has come back from the import for ${POLL_MINUTES} minutes. `
      + "Close this and try again.",
    );
  }, [onOpened, onSummary]);

  const start = useCallback(async () => {
    if (!file) {
      setSentence("Choose an .xlsx file to import.");
      return;
    }
    const refused = fileRefusal(file);
    if (refused) {
      setSentence(refused);
      return;
    }
    stop();
    const run = runRef.current;
    setSentence("");
    setJob(null);
    setPhase("running");
    const started = await importWorkbook(file);
    if (run !== runRef.current) return;
    if (!started.ok) {
      setPhase("ended");
      setSentence(refusalSentence(started));
      return;
    }
    if (!started.value.job) {
      setPhase("ended");
      setSentence("The server accepted the file and did not say which job is reading it.");
      return;
    }
    await poll(started.value.job, run);
  }, [file, poll, stop]);

  /** After a refusal the primary starts over rather than silently re-posting the same file. */
  const reset = useCallback(() => {
    stop();
    setJob(null);
    setSentence("");
    setFile(null);
    setPick((n) => n + 1);
    setPhase("idle");
  }, [stop]);

  const dismiss = useCallback(() => { stop(); onCancel(); }, [onCancel, stop]);

  const onPrimary = () => {
    if (phase === "running") return;
    if (phase === "ended") { reset(); return; }
    void start();
  };

  const running = phase === "running";
  const ended = phase === "ended";
  const pct = Math.round((job?.progress ?? 0) * 100);
  const seen = formulaCellsSeen(job);
  const report = job?.report;

  return (
    <ConfirmDialog
      open={open}
      title="Import a workbook"
      confirmLabel={ended ? "Choose another file" : "Import"}
      cancelLabel={phase === "idle" ? "Cancel" : "Close"}
      tone="primary"
      busy={running}
      onConfirm={onPrimary}
      onCancel={dismiss}
      body={
        <div className="sheet-import">
          <p className="sheet-import-note">
            Loopable reads the values, the formulas, the number formats and the layout. Files up to
            {` ${IMPORT_MAX_MB}`} MB.
          </p>

          {/* β›” THE NATIVE INPUT, ON PURPOSE. It is keyboard reachable, it carries the operating
              system's own file browser, and `accept` filters the picker without ever opening a
              byte. A custom drop zone would be a second control shape for a job the platform
              already does better. */}
          <input
            key={pick}
            className="sheet-import-file"
            type="file"
            accept=".xlsx"
            aria-label="The .xlsx file to import"
            disabled={running}
            onChange={(event) => {
              const next = event.currentTarget.files?.[0] ?? null;
              setFile(next);
              setSentence(next ? fileRefusal(next) : "");
            }}
          />

          {job ? (
            <div className="sheet-import-progress">
              <p className="sheet-import-state">{STATE_LABEL[job.state]}</p>
              <div
                className="sheet-import-bar"
                role="progressbar"
                aria-label="Import progress"
                aria-valuemin={0}
                aria-valuemax={100}
                aria-valuenow={pct}
              >
                <span className="sheet-import-fill" style={{ width: `${pct}%` }} />
              </div>
              <p className="sheet-import-note">{STATE_NOTE[job.state]}</p>
            </div>
          ) : null}

          {/* ⭐ R1'S DIFFERENTIAL, AND IT IS GUARDED ON HAVING SEEN A FORMULA AT ALL. "Matched 0 of
              0 formula cells" is a measurement nobody took, printed on a screen, which is the same
              rule `sheetApi.ts` states for a recalc time the server never measured. A workbook with
              no formulas shows no line rather than a row of zeroes. */}
          {report && seen > 0 ? (
            <p className="sheet-import-line">
              {seen === 1
                ? `Matched ${report.matched} of ${seen} formula cell.`
                : `Matched ${report.matched} of ${seen} formula cells.`}
            </p>
          ) : null}

          {report && report.unsupported.length > 0 ? (
            <div className="sheet-import-unsupported">
              <p className="sheet-import-line">These parts of the file did not come across.</p>
              {report.unsupported.map((item) => (
                <p className="sheet-import-note" key={item}>{item}</p>
              ))}
            </div>
          ) : null}

          {/* The server's own words, verbatim. A rephrasing here would be this client inventing a
              reason for something only the server watched happen. */}
          {sentence ? <p className="sheet-import-refusal">{sentence}</p> : null}
        </div>
      }
    />
  );
}