// The design test, for each picture marked The original graphic. Once the choice has stood for the settle time, the // test joins the page's queue and runs by itself, one test at a time, in the order the pictures were marked; its turn // with the server is test_turn.js's, this browser's scanner scanner.js's, and test_view.js shows it. Marking the // picture otherwise, or removing it, stops its test; an answer is kept, and shows again when the picture is marked // The original graphic again. Nothing is stored, and what this browser's scanner read stays in the page. import { getJson, t } from './copy.js'; import { planFor } from './plan.js'; import { hidden } from './frames.js'; import { decide, fits, partFor, probe, probed, useTest } from './scanner.js'; import { fetchHealth, late, leave, rawNotText, refusal, turn, useTurn } from './test_turn.js'; import { announce, howTest, paintTest, useView } from './test_view.js'; import { mirroredByRecord } from './record.js'; let S = null; // web/data/test.json, or null: the page starts no test let health = 'unknown'; // the server's test, as /api/health says: 'unknown' (not read, or the read failed), 'on', 'off' let reading = null; // the health read in flight let joins = 0; // tests this browser's scanner joined by itself this page session (Try again can pass S.join) const queue = []; // the pictures whose tests wait their turn, in order let active = null; // the picture whose test has the page's turn let lastEnd = 0; // when the page's last test ended let wake = 0; // the queue's timer /** app.js, at the start: the test's settings. Never throws: a missing or broken file leaves the test off. */ export async function loadTest(url) { try { const s = await getJson(url); if (!fits(s)) return; S = s; useTest(s); useTurn(s, { paint, tell, joined: () => { joins += 1; queue.forEach(paint); } }); useView(s, { again: retryTest, add: addScanner, leave: leaveOut }); } catch { /* no test: the page loads as before */ } } /** Whether the page runs design tests: test.json says so, and the server's test isn't off. */ export const testOn = () => S?.page === true && health !== 'off'; /** yours.js: the choice's hint says a test sends the picture again, only while tests run. */ export const testChoiceHint = () => (testOn() ? t('test.choice_hint') : ''); /** A picture's test record, or null. */ export const testOf = (p) => p.test || null; /** app.js, once the words are in: "How your pictures are placed" says a test sends the picture again (only while * tests run); a page closed, reloaded or put in the back-forward cache leaves its test on the server, and a page * shown again from that cache runs its queue again. Time the page spends frozen (as Chrome freezes a tab in the * background), when it doesn't run, is left out of the budget for this browser's fetches (frames.js); a page hidden * but running keeps fetching at the link's own pace, so that time counts. */ export function initTest() { if (!S?.page) return; howText(); window.addEventListener('pagehide', leavePage); window.addEventListener('pageshow', (e) => { if (e.persisted) pump(); }); const away = (e) => hidden(e.type === 'freeze'); for (const type of ['freeze', 'resume']) window.addEventListener(type, away, { capture: true }); } const howText = () => howTest(testOn()); /** app.js, after pictures are added: the server's test is read once, with the first picture. */ export function testAdded() { if (S?.page && health === 'unknown' && !reading) readHealth(); } function readHealth() { reading = fetchHealth() .then((h) => { if (h) health = h.design?.on === true ? 'on' : 'off'; }, () => { /* read again next time */ }) .then(() => { reading = null; if (health === 'off') { howText(); for (const p of [...queue]) drop(p); } return health; }); return reading; } const healthNow = () => (health !== 'unknown' ? Promise.resolve(health) : reading || readHealth()); /** plan_view.js, after what a picture shows changed (the change's own words said first). The original graphic: its * test starts once the choice has stood for the settle time (arrowing past it sends nothing), or its kept answer * shows again. Anything else: a test settling, waiting or running stops, and the server drops it; an answer or a * can't line is kept, hidden. */ export function kindChanged(p) { if (!S?.page) return; if (p.kind === 'graphic' && !p.test) { const rec = (p.test = fresh({ by: 'visitor', truthsDiffer: rawNotText(p.result) }, 'settling')); rec.timer = setTimeout(() => gate(p, rec), S.page_waits.settle_s * 1000); startProbe(); } else if (p.kind !== 'graphic' && p.test && !['done', 'cant'].includes(p.test.state)) { stop(p); pump(); } paint(p); } /** app.js, when a picture's reading returns: one already marked The original graphic (read again, or marked by its * own record) is tested at once, with no settle time. */ export function readingReturned(p) { if (!S?.page || p.kind !== 'graphic' || p.status !== 'done' || p.test) return; const rec = (p.test = fresh({ by: 'reading', truthsDiffer: rawNotText(p.result) }, 'settling')); startProbe(); gate(p, rec); } /** app.js, when a picture is removed, or read again (its reading may change): its test stops, the server drops it, * and nothing is kept. */ export function pictureRemoved(p) { if (!p.test) return; stop(p); pump(); } /** The probe runs once a page session, when a picture is first marked The original graphic and the server's test is * on; tests that wait then show what this browser's scanner will do. */ function startProbe() { healthNow().then((h) => { if (h === 'on') probe().then(() => queue.forEach(paint)); }); } /** The settle time has passed, or a reading returned: no test (and no line) without a width planned from a scanner's * version, a kept original, or the server's test on; while /api/health can't be read, the unreachable line, with Try * again; a line for the page's own refusals; else the queue. */ async function gate(p, rec) { const plan = planFor(p); const fit = p.kind === 'graphic' && p.file && plan && plan.mode !== 'cant' && !plan.estimated && !mirroredByRecord(p); const h = fit ? await healthNow() : 'off'; if (p.test !== rec) return; if (h !== 'on') { if (h === 'off') return drop(p); Object.assign(rec, { state: 'failed', line: t('errors.unreachable'), retry: true }); tell(p, rec, 'end'); return paint(p); } rec.why = refusal(p.result, p.drawn); rec.state = rec.why ? 'cant' : 'queued'; if (rec.why) tell(p, rec, 'end'); else { queue.push(p); if (active || queue.length > 1) tell(p, rec, 'queued'); } paint(p); pump(); } /** The queue's first test starts when none of the page's has its turn, between_tests_s after the last one ended. */ function pump() { clearTimeout(wake); if (!S || active || !queue.length) return; const left = lastEnd + S.page_waits.between_tests_s * 1000 - Date.now(); if (left > 0) { wake = setTimeout(pump, left); return; } active = queue.shift(); run(active, active.test); } /** A test's turn: what this browser's scanner does in it (the probe waited for at most probe_wait_s), then the * server's part (test_turn.js), then its end. */ async function run(p, rec) { rec.ctl = new AbortController(); rec.state = 'slot'; paint(p); let out; try { rec.part = await decide(rec, joins); rec.first ||= rec.part.decision; // kept when the test starts again rec.decided = true; out = await turn(p, rec, rec.ctl.signal); } catch (err) { // a failure in the page's words (upload.js), or the server unreachable const line = err.retry === undefined ? t('errors.unreachable') : err.message; out = { state: 'failed', line, retry: err.retry !== false }; } if (p.test === rec && !rec.ctl.signal.aborted) end(p, rec, out); } /** A turn ends: an answer, a can't line or a failure, said once; or the test waits at the queue's head again (a 404 * or a lost slot, the first time), or no test runs (the server's test is off). Then the next test's turn. */ function end(p, rec, out) { rec.ctl.abort(); leave(rec); active = null; lastEnd = Date.now(); if (out.off) { health = 'off'; howText(); for (const q of [p, ...queue]) drop(q); } else if (out.redo && rec[out.redo] < 1) { p.test = fresh({ ...rec, [out.redo]: rec[out.redo] + 1 }, 'queued'); queue.unshift(p); } else { Object.assign(rec, out.redo ? late() : out); tell(p, rec, 'end'); } paint(p); pump(); } /** Show the test; one that hasn't started shows what this browser's scanner would do in it. */ function paint(p) { const rec = p.test; if (S && rec && !rec.decided && rec.state !== 'settling') rec.part = partFor(rec, joins, probed()); paintTest(p); } /** testNote: after the visitor's own marking, the test's first state unnamed (the marking's words were just said); * then, naming the picture, a test from the queue when it starts or is told busy (once), and each test's last line. */ function tell(p, rec, what) { if ((what === 'start' && rec.said && (!rec.waited || rec.busy)) || (what === 'busy' && rec.busy)) return; announce(p, what, rec.said || rec.by !== 'visitor'); rec.said = true; rec.waited ||= what === 'queued'; rec.busy ||= what === 'busy'; } /** A new test record: one started again keeps who started it, its first decision, whether it counted towards the * bound, Add, what was said, how often the server dropped it or its slot, and whether its code's two truths differ * (test_turn.js: from the first reading where it shows it, rawNotText, else from the 202). */ const fresh = (from, state) => ({ state, by: from.by, first: from.first, counted: from.counted, added: from.added, said: from.said, busy: from.busy, drops: from.drops || 0, conflicts: from.conflicts || 0, truthsDiffer: from.truthsDiffer, }); /** A test left: its timer and requests stopped, what the server holds dropped, nothing kept. */ function stop(p) { const rec = p.test; clearTimeout(rec.timer); rec.ctl?.abort(); leave(rec); if (queue.includes(p)) queue.splice(queue.indexOf(p), 1); if (active === p) { active = null; lastEnd = Date.now(); } p.test = null; } function drop(p) { if (p.test) stop(p); paint(p); } /** Try again and Add: the test starts afresh at the end of the queue, its old one left on the server; test_view.js * then moves focus to its state line. A new test, so its busy line is said again if it is told busy. */ function restart(p, rec, extra) { stop(p); const waits = Boolean(active) || queue.length > 0; p.test = { ...fresh(rec, 'queued'), drops: 0, conflicts: 0, said: true, busy: false, waited: waits, ...extra }; queue.push(p); paint(p); pump(); } /** Try again (after a fallback, Save-Data, the deadline, busy or an unreachable server): where line 2 asked to try * again for this browser's scanner, it comes back, as with Add (never for a part only shown before the test ran). */ export function retryTest(p) { const rec = p.test; const again = Boolean(rec?.decided) && ['save_data', 'late', 'broken'].includes(rec.part?.decision); if (rec) restart(p, rec, { added: rec.added || again }); } /** Add {name}: before the picture is sent, the test takes this browser's scanner; after, it starts again with it. */ export function addScanner(p) { const rec = p.test; if (!rec) return; if (!['queued', 'slot', 'busy'].includes(rec.state)) { restart(p, rec, { added: true }); return; } rec.added = true; if (rec.decided && rec.part.decision === 'offered') rec.part.decision = 'joins'; paint(p); } /** Leave it out: the browser's part ends at once (its fetches aborted, the polls then carry frames=0), and the test * finishes with zxing-cpp's and WeChat's answers. */ export function leaveOut(p) { const part = p.test?.part; if (!part?.running) return; part.left = true; part.ctl.abort(); paint(p); } /** pagehide: the active test is left on the server (keepalive, so it goes as the page goes) and waits at the queue's * head; a page shown again from the back-forward cache runs it again (pageshow). */ function leavePage() { const p = active; if (!p) return; const rec = p.test; rec.ctl?.abort(); leave(rec, true); active = null; p.test = fresh(rec, 'queued'); queue.unshift(p); paint(p); }