// --------------------------------------------------------------------------- // 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 = { 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 = { 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((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_` 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(null); const [phase, setPhase] = useState("idle"); const [job, setJob] = useState(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 = 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 (

Loopable reads the values, the formulas, the number formats and the layout. Files up to {` ${IMPORT_MAX_MB}`} MB.

{/* ⛔ 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. */} { const next = event.currentTarget.files?.[0] ?? null; setFile(next); setSentence(next ? fileRefusal(next) : ""); }} /> {job ? (

{STATE_LABEL[job.state]}

{STATE_NOTE[job.state]}

) : 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 ? (

{seen === 1 ? `Matched ${report.matched} of ${seen} formula cell.` : `Matched ${report.matched} of ${seen} formula cells.`}

) : null} {report && report.unsupported.length > 0 ? (

These parts of the file did not come across.

{report.unsupported.map((item) => (

{item}

))}
) : 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 ?

{sentence}

: null} } /> ); }