@floless/app 0.168.0 → 0.169.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/cli-actions.mjs +8 -1
  2. package/dist/floless-server.cjs +83100 -68895
  3. package/dist/skills/floless-app-rfi/SKILL.md +4 -2
  4. package/dist/templates/college-phase-exporter.flo +7 -2
  5. package/dist/templates/trimble-list-projects.flo +10 -2
  6. package/dist/web/agent-steps.js +2 -2
  7. package/dist/web/agents.js +49 -13
  8. package/dist/web/app.css +44 -3
  9. package/dist/web/app.js +47 -4
  10. package/dist/web/aware-update-client.js +4 -4
  11. package/dist/web/aware.js +401 -31
  12. package/dist/web/chat.css +10 -0
  13. package/dist/web/chat.js +223 -22
  14. package/dist/web/commands-drawing-check.js +3 -0
  15. package/dist/web/commands-shell.js +111 -4
  16. package/dist/web/commands-steel.js +9 -2
  17. package/dist/web/commands-vector.js +69 -0
  18. package/dist/web/drawing-check-editor.html +10 -0
  19. package/dist/web/drawing-check-editor.js +502 -182
  20. package/dist/web/failure-copy.js +20 -2
  21. package/dist/web/flo-3d.js +310 -0
  22. package/dist/web/flo-card.js +72 -0
  23. package/dist/web/guide.js +3 -1
  24. package/dist/web/index.html +26 -4
  25. package/dist/web/instructor.js +3 -0
  26. package/dist/web/model-editor-steel-adapter.js +41 -1
  27. package/dist/web/model-viewport-toolbar.js +11 -0
  28. package/dist/web/pages.js +17 -14
  29. package/dist/web/panels.js +1 -1
  30. package/dist/web/project-history.js +2 -2
  31. package/dist/web/project-modules.js +3 -3
  32. package/dist/web/project-reconciliation.js +1 -1
  33. package/dist/web/project-rfis.js +2 -2
  34. package/dist/web/project-workflows.js +6 -4
  35. package/dist/web/renderers.js +6 -0
  36. package/dist/web/report-csp.js +68 -0
  37. package/dist/web/revit-editor.js +1 -1
  38. package/dist/web/run-history.js +2 -3
  39. package/dist/web/steel-3d-flo.js +309 -0
  40. package/dist/web/steel-3d-view.js +159 -0
  41. package/dist/web/steel-editor.html +130 -9
  42. package/dist/web/terminal-requests.js +78 -0
  43. package/dist/web/tool-updates.js +3 -2
  44. package/dist/web/vector-3d.html +1 -1
  45. package/dist/web/vector-editor.html +50 -8
  46. package/dist/web/workspace-root-management.js +1 -1
  47. package/dist/web/workspaces.js +626 -140
  48. package/launch.mjs +5 -0
  49. package/package.json +8 -8
@@ -311,22 +311,73 @@ export function focusKey(el) {
311
311
  * Replace `container`'s markup and put keyboard focus back on the same control, if it is still there.
312
312
  * Every re-render of the page goes through this, so a re-render that lands while the person is on another
313
313
  * control (a PUT answering after they pressed Tab, a review that loads late) never drops their focus.
314
+ * @param {(el: any) => boolean} [keepTyped] @param {(el: any) => void} [leaving]
314
315
  */
315
- export function paintKeepingFocus(doc, container, html) {
316
+ export function paintKeepingFocus(doc, container, html, keepTyped = () => true, leaving = () => {}) {
316
317
  const active = doc.activeElement;
317
318
  const key = active && container.contains(active) ? focusKey(active) : null;
318
- // A text field being typed in keeps what was typed and where the caret was.
319
- const typing = key && active.tagName === 'INPUT' && /^(text|search|)$/i.test(active.type || '')
320
- ? { value: active.value, start: active.selectionStart, end: active.selectionEnd } : null;
319
+ // A text field being typed in stays in the page, the very same field, so it keeps its text, its caret and the
320
+ // browser's own record that it was edited: leaving it sends it exactly as if no repaint had happened (#3121).
321
+ // Text already sent as a choice is not typing (keepTyped says so): the field shows what was saved.
322
+ const typing = key && active.tagName === 'INPUT' && /^(text|search|)$/i.test(active.type || '') && keepTyped(active);
323
+ if (typing && paintAround(doc, container, html, active, key)) return true;
324
+ const was = typing ? { value: active.value, start: active.selectionStart, end: active.selectionEnd } : null;
325
+ // The field being typed in is about to leave the page (the new markup has no place for it, or this browser cannot
326
+ // move it there): the browser may say it changed as it goes, which is the repaint, not the person (`leaving`).
327
+ if (was) leaving(active);
321
328
  container.innerHTML = html;
322
329
  const again = key ? container.querySelector(key) : null;
323
- if (again && typing) {
324
- again.value = typing.value;
325
- if (typeof again.setSelectionRange === 'function' && typing.start != null) again.setSelectionRange(typing.start, typing.end);
330
+ // A browser that cannot move the field: its text and caret are copied into the new one instead.
331
+ if (again && was) {
332
+ again.value = was.value;
333
+ if (typeof again.setSelectionRange === 'function' && was.start != null) again.setSelectionRange(was.start, was.end);
326
334
  }
327
335
  if (again && again.focus) again.focus();
328
336
  return !!again;
329
337
  }
338
+ /**
339
+ * Put `html` into `container` with `live` in it, never taking `live` out of the page. Where the new markup holds the
340
+ * field at the same depth under the same kinds of element, its ancestors are kept and given the new markup's
341
+ * attributes, and everything beside them is replaced. Elsewhere, the new markup goes in beside the old and the field
342
+ * is moved into its place with `moveBefore`, which keeps focus, caret and the browser's edited state. False, with
343
+ * nothing changed, when the new markup has no place for the field or this browser cannot move it.
344
+ */
345
+ function paintAround(doc, container, html, live, key) {
346
+ const next = doc.createElement(container.tagName);
347
+ next.innerHTML = html;
348
+ const fresh = next.querySelector(key);
349
+ if (!fresh) return false;
350
+ // The field's value attribute is left alone: the text in it is the person's.
351
+ const syncAttributes = (L, F) => {
352
+ const keep = (name) => L === live && name === 'value';
353
+ for (const a of [...L.attributes]) if (!keep(a.name) && !F.hasAttribute(a.name)) L.removeAttribute(a.name);
354
+ for (const a of [...F.attributes]) if (!keep(a.name)) L.setAttribute(a.name, a.value);
355
+ };
356
+ const path = (el, top) => { const out = []; for (let n = el; n && n !== top; n = n.parentNode) out.unshift(n); return out; };
357
+ const liveP = path(live, container), freshP = path(fresh, next);
358
+ if (liveP.length !== freshP.length || liveP.some((n, i) => n.tagName !== freshP[i].tagName)) {
359
+ if (typeof fresh.parentNode.moveBefore !== 'function') return false;
360
+ const old = [...container.childNodes];
361
+ for (const n of [...next.childNodes]) container.appendChild(n);
362
+ syncAttributes(live, fresh);
363
+ fresh.parentNode.moveBefore(live, fresh);
364
+ fresh.remove();
365
+ for (const n of old) n.remove();
366
+ return true;
367
+ }
368
+ liveP.forEach((L, i) => {
369
+ const F = freshP[i], into = i ? liveP[i - 1] : container, from = i ? freshP[i - 1] : next;
370
+ syncAttributes(L, F);
371
+ for (const n of [...into.childNodes]) if (n !== L) n.remove();
372
+ let after = false;
373
+ for (const n of [...from.childNodes]) {
374
+ if (n === F) after = true;
375
+ else if (after) into.appendChild(n);
376
+ else into.insertBefore(n, L);
377
+ }
378
+ });
379
+ return true;
380
+ }
330
381
  /** After an edit: give focus back to the edited control only when nothing holds focus. */
331
382
  export function refocusIfLost(doc, container, selector) {
332
383
  if (doc.activeElement && doc.activeElement !== doc.body) return false;
@@ -381,6 +432,37 @@ export function whereOnSheet(box) {
381
432
  return v === 'middle' && h === 'centre' ? 'centre' : `${v} ${h}`;
382
433
  }
383
434
 
435
+ /**
436
+ * The band that says the checklist changed before some of the person's changes were saved, and which ones. It names
437
+ * no cause: another window, AI Chat or this page's own upload of several drawings all look the same from here. With the way back (#3121). `unsaved`: [{ what, gone }], in the order the person made them; `state`: 'ok'
438
+ * (the latest version is shown), 'behind' or 'reading' (it is being read), 'failed' (it could not be read). Nothing
439
+ * is lost and nothing is sent without the person: Apply makes the changes again on the version now shown.
440
+ */
441
+ export const UNSAVED_SHOWN = 5;
442
+ export function unsavedBandHtml({ unsaved = [], state = 'ok', showAll = false } = {}) {
443
+ const n = unsaved.length;
444
+ const line = (u) => `${esc(u.what)}${u.unusable ? ' <span class="note">— not a size FloLess can use, so it can’t be applied</span>'
445
+ : u.gone ? ' <span class="note">— no longer on the checklist, so it won’t be sent again</span>' : ''}`;
446
+ let head;
447
+ if (!n) head = '<p>The checklist changed since this page last showed it.</p>';
448
+ else if (n === 1) head = `<p>The checklist changed before your change went in, so it wasn’t saved: ${line(unsaved[0])}.</p>`;
449
+ else {
450
+ const shown = showAll ? unsaved : unsaved.slice(0, UNSAVED_SHOWN);
451
+ const more = n - shown.length;
452
+ head = `<p>The checklist changed before ${n} of your changes went in, so they weren’t saved:</p>
453
+ <ul class="unsaved-list${showAll ? ' all' : ''}" id="unsaved-list">${shown.map((u) => `<li>${line(u)}</li>`).join('')}</ul>
454
+ ${n > UNSAVED_SHOWN ? `<button type="button" class="link" data-act="unsaved-show-all" data-command-id="drawing-check.unsaved-show-all" aria-expanded="${showAll}" aria-controls="unsaved-list">${showAll ? 'Show fewer' : `Show all ${n}`}</button>${more ? ` <span class="note">and ${more} more</span>` : ''}` : ''}`;
455
+ }
456
+ const reading = state === 'reading' || state === 'behind';
457
+ const sendable = unsaved.filter((u) => !u.gone).length;
458
+ const tail = state === 'failed' ? 'Couldn’t get the latest version just now.' : reading ? 'Getting the latest version…' : 'The page now shows the latest version.';
459
+ const buttons = [
460
+ state === 'ok' && sendable ? `<button type="button" class="primary" data-act="unsaved-apply" data-command-id="drawing-check.unsaved-apply">${sendable === 1 ? 'Apply my change again' : 'Apply my changes again'}</button>` : '',
461
+ state === 'failed' ? '<button type="button" class="primary" data-act="reload" data-command-id="drawing-check.reload">Reload</button>' : '',
462
+ `<button type="button" data-act="unsaved-dismiss" data-command-id="drawing-check.unsaved-dismiss" data-tip="${n ? 'Discard these changes: nothing more is sent' : 'Hide this message'}">Dismiss</button>`,
463
+ ].filter(Boolean).join('');
464
+ return `<div class="band unsaved" role="status" aria-live="polite">${head}<p class="unsaved-state" tabindex="-1">${tail}</p><div class="row-actions">${buttons}</div></div>`;
465
+ }
384
466
  /**
385
467
  * One open question from proposing: the question, one button per candidate with where it was seen, and
386
468
  * "Neither: I'll type the label". Deliberately NO default and no "Suggested" tag, unlike the preflight
@@ -699,7 +781,12 @@ function boot() {
699
781
  let body = null;
700
782
  try { body = await res.json(); } catch { /* an empty or non-JSON body */ }
701
783
  if (!res.ok || (body && body.ok === false)) {
702
- const e = new Error((body && typeof body.error === 'string' && body.error) || 'That didn’t work. Try again.');
784
+ // #3097: the server's sentence only when it wrote one for the person (failure-copy.js), never raw exception text.
785
+ const said = typeof globalThis.personText === 'function' ? globalThis.personText(body) : '';
786
+ const reads = /^(GET|HEAD)$/i.test(String(opts?.method || 'GET'));
787
+ const e = new Error(said || (typeof globalThis.failureCopy === 'function'
788
+ ? globalThis.failureCopy({ status: res.status, body }, { retrySafe: reads }).text
789
+ : 'That didn’t work. Try again.'));
703
790
  e.status = res.status; e.body = body; throw e;
704
791
  }
705
792
  return { body, res };
@@ -707,10 +794,102 @@ function boot() {
707
794
  const jsonOpts = (method, data, extra = {}) => ({ method, headers: { 'content-type': 'application/json', ...extra }, body: JSON.stringify(data ?? {}) });
708
795
 
709
796
  // ── loading ──
797
+ // ── what the server holds, and the person's choices still on their way (#3121) ──
798
+ // S.saved is the draft as the server holds it, as far as this page knows; S.pending the person's checklist choices
799
+ // not answered yet, in order. S.draft is derived: the saved draft with every pending choice applied (rebuild), so a
800
+ // read or an answer can replace the saved draft at any time without flicking a pending tick back. Only adopt()
801
+ // changes S.saved, and it paints in the same task: what the person clicks on is always what was adopted, plus their
802
+ // own pending choices. S.gen counts versions this page did not make from what it showed (another window's change,
803
+ // an unconditional answer, a read that found a different draft); each choice carries the gen it was made on and is
804
+ // held, never sent, when that is no longer the gen on screen (choose). S.serial counts every adoption, so a late
805
+ // answer or read is never adopted over a newer one. S.sync: 'ok', 'behind' (a save was refused: the server holds a
806
+ // newer draft), 'reading' (that draft is being read) or 'failed'; S.complete is false while an answer that carried
807
+ // only part of the draft waits for the whole of it.
808
+ Object.assign(S, { saved: { draft: null, etag: null }, pending: [], unsaved: [], gen: 0, serial: 0, sync: 'ok', complete: true, showAllUnsaved: false });
809
+ let booted = false;
810
+ const syncState = () => (S.sync !== 'ok' ? S.sync : S.complete ? 'ok' : 'reading');
811
+ // An answer's draft parts replace the saved ones; an optional part the answer carries as null is deleted (Propose).
812
+ const OPTIONAL_PARTS = new Set(['titleBlock', 'partList']);
813
+ function rebuild() {
814
+ const d = S.saved.draft ? structuredClone(S.saved.draft) : null;
815
+ if (d) for (const c of S.pending) c.apply(d);
816
+ S.draft = d; S.etag = S.saved.etag;
817
+ // A change listed as not saved whose item, field or question is gone from the draft now shown says so, and is
818
+ // never sent again (Apply skips it).
819
+ for (const u of S.unsaved) u.gone = !!d && !u.apply(structuredClone(d));
820
+ }
821
+ // The checklist as it now stands, painted unless a run is on screen (no checklist control is, and the run view is
822
+ // not to be rebuilt by a draft change).
823
+ function paint() {
824
+ for (const show of heldDialogs) show();
825
+ if (!booted || (S.tab === 'runs' && S.run)) return;
826
+ renderKeepingScroll();
827
+ }
828
+ /**
829
+ * Take on a draft the server holds. `draft` replaces it whole; `parts` replaces those fields only (an answer carries
830
+ * part of the draft). `own`: a conditional write of this page's that was sent on the version shown, so its answer is
831
+ * what the person's own choice made of it. Anything else that brings a different version, or completes one that was
832
+ * shown in part, is a version the person has not seen: S.gen moves on.
833
+ */
834
+ function adopt({ draft, parts, etag, own = false }) {
835
+ const before = S.saved.etag, completing = !S.complete && draft !== undefined;
836
+ if (draft !== undefined) S.saved.draft = draft;
837
+ else {
838
+ S.saved.draft = S.saved.draft || {};
839
+ for (const [k, v] of Object.entries(parts)) { if (v == null && OPTIONAL_PARTS.has(k)) delete S.saved.draft[k]; else if (v !== undefined) S.saved.draft[k] = v; }
840
+ }
841
+ S.saved.etag = etag;
842
+ S.serial++;
843
+ if (!own && (etag !== before || completing)) S.gen++;
844
+ if (draft !== undefined) S.complete = true;
845
+ else if (!own) { S.complete = false; readAll(); }
846
+ rebuild();
847
+ paint();
848
+ }
849
+ /** A write's answer, `sent` = { etag, serial, cond } captured as it went out: adopted unless a newer draft was
850
+ * adopted while it was out, which it must not roll back; then the whole draft is read again. */
851
+ function adoptAnswer(sent, parts, etag) {
852
+ if (S.serial !== sent.serial) { S.complete = false; readAll(); rebuild(); paint(); return false; }
853
+ adopt({ parts, etag, own: !!sent.cond && sent.etag === S.saved.etag });
854
+ return true;
855
+ }
856
+ const sending = (etag = S.saved.etag) => ({ etag, serial: S.serial, cond: true });
857
+ // Read the whole draft on the checklist queue: after a refusal (every choice already queued is held at its turn,
858
+ // since S.sync is not 'ok'), and after an answer that carried only part of it. Choices made after this is queued
859
+ // wait behind it, so when their turn comes the whole draft has been shown.
860
+ let readQueued = false;
861
+ function readAll() {
862
+ if (readQueued) return;
863
+ readQueued = true;
864
+ void itemsQueue(async () => {
865
+ readQueued = false;
866
+ if (S.sync === 'behind' || S.sync === 'failed') S.sync = 'reading';
867
+ paint();
868
+ // A read made while this page's own write is out (an upload of several drawings) waits for it without using up
869
+ // a try: only reads with nothing of ours out count, so the page does not call the latest version unreadable.
870
+ for (let tries = 0, waits = 0; tries < 5 && waits < 200; ) {
871
+ let got;
872
+ try { got = await loadDraft(); } catch { break; }
873
+ if (got !== 'stale') { S.sync = 'ok'; await loadReview(); paint(); return; }
874
+ if (ownWrites > 0) waits++; else tries++;
875
+ await new Promise((r) => setTimeout(r, 300)); // read again after it
876
+ }
877
+ S.sync = 'failed';
878
+ paint();
879
+ });
880
+ }
881
+ /** Read the draft. 'adopted' or 'same' (what was read is shown), or 'stale': a write of this page's own was out or
882
+ * started while it read, or another adoption landed, so the answer may predate it and nothing is adopted. */
710
883
  async function loadDraft() {
711
- S.clearNote = ''; S.mainNote = ''; S.breakNote = ''; S.breakError = ''; S.breakTyped = null; // a note about the last change says nothing true about a draft read afresh
884
+ const token = { serial: S.serial, seq: ownWriteSeq, busy: ownWrites > 0 };
885
+ const stale = () => token.busy || token.seq !== ownWriteSeq || token.serial !== S.serial;
712
886
  const res = await fetch(`/api/contract/${encodeURIComponent(APP)}?project=${encodeURIComponent(PROJECT)}&quietMissing=1`, { credentials: 'same-origin' });
713
- if (res.status === 204) { S.draft = null; S.etag = null; return; }
887
+ if (res.status === 204) {
888
+ if (stale()) return 'stale';
889
+ const same = S.saved.etag === null && S.complete;
890
+ adopt({ draft: null, etag: null });
891
+ return same ? 'same' : 'adopted';
892
+ }
714
893
  if (res.status === 404) throw new Error('This profile could not be found. It may have been archived; open it again from Workspaces.');
715
894
  // No Drawing Checker on this account: the server's own access copy explains it; "reload" would not help.
716
895
  if (res.status === 403) {
@@ -720,11 +899,15 @@ function boot() {
720
899
  throw new Error(S.accessError);
721
900
  }
722
901
  if (!res.ok) throw new Error('This profile could not be read. Reload to try again.');
723
- S.draft = await res.json();
724
- S.etag = res.headers.get('ETag');
902
+ const draft = await res.json(), etag = res.headers.get('ETag');
903
+ if (stale()) return 'stale';
904
+ S.clearNote = ''; S.mainNote = ''; S.breakNote = ''; S.breakError = ''; S.breakTyped = null; // a note about the last change says nothing true about a draft read afresh
905
+ const same = etag === S.saved.etag && S.complete;
906
+ adopt({ draft, etag });
907
+ return same ? 'same' : 'adopted';
725
908
  }
726
909
  async function loadTitleChanges() {
727
- try { S.tbChanges = (await call(`${base}/title-block`)).body.changes || []; } catch { S.tbChanges = []; }
910
+ try { return (await call(`${base}/title-block`)).body.changes || []; } catch { return []; }
728
911
  }
729
912
  /** The title-block changes to show in the approval dialog: a list, 'approved-unreadable', or 'failed'. */
730
913
  async function titleChangesForApproval() {
@@ -734,15 +917,21 @@ function boot() {
734
917
  } catch { return 'failed'; }
735
918
  }
736
919
  async function loadReview() {
737
- S.reviewError = '';
738
920
  // Both land before anything renders: a title-block summary arriving late used to re-render after focus
739
921
  // had been put back, dropping it.
740
- const changes = loadTitleChanges();
741
- try {
742
- const { body } = await call(`/api/projects/${encodeURIComponent(PROJECT)}/approval-review`);
743
- S.review = body && body.reviewable ? body : null;
744
- } catch { S.review = null; S.reviewError = 'Approval status couldn’t be read. Reload to try again.'; }
745
- await changes;
922
+ // A draft adopted while these were out may have changed what they say: they are shown only when no draft was
923
+ // adopted meanwhile, and read again otherwise, a few times at most.
924
+ for (let tries = 0; tries < 3; tries++) {
925
+ const serial = S.serial;
926
+ const changes = loadTitleChanges();
927
+ let review = null, reviewError = '';
928
+ try {
929
+ const { body } = await call(`/api/projects/${encodeURIComponent(PROJECT)}/approval-review`);
930
+ review = body && body.reviewable ? body : null;
931
+ } catch { reviewError = 'Approval status couldn’t be read. Reload to try again.'; }
932
+ const tbChanges = await changes;
933
+ if (serial === S.serial) { S.review = review; S.reviewError = reviewError; S.tbChanges = tbChanges; return; }
934
+ }
746
935
  }
747
936
  async function loadRuns() {
748
937
  S.runsError = '';
@@ -764,27 +953,44 @@ function boot() {
764
953
  // allSettled, not all: every read must land before the page decides which failure to explain.
765
954
  const settled = await Promise.allSettled([loadDraft(), loadReview(), loadRuns(), loadColours(), loadDesignSet()]);
766
955
  const failed = settled.find((r) => r.status === 'rejected');
956
+ // The whole draft was read and shown: the page is current again. A read that crossed a write of this page's
957
+ // own adopted nothing; it is read again once that write has answered.
958
+ if (settled[0].status === 'fulfilled') {
959
+ if (settled[0].value === 'stale') refreshSoon({ draft: true });
960
+ else if (S.sync !== 'reading') S.sync = 'ok';
961
+ }
767
962
  S.loadError = failed ? (failed.reason && failed.reason.message) || 'This profile could not be read. Reload to try again.' : '';
768
963
  // A module refusal (no Drawing Checker access) is the one answer that explains every other failure,
769
964
  // so its own copy is what the page says.
770
965
  if (S.accessError) S.loadError = S.accessError;
771
966
  if (!S.tab) S.tab = landingTab({ hasApproved: hasApproved(), referenceCount: references().length });
967
+ booted = true;
772
968
  render();
773
969
  }
774
970
 
775
971
  // ── shell ──
972
+ // The text fields typed in since their text was last sent (#3121). A repaint keeps such a field in the page; one
973
+ // that only has focus is drawn afresh and shows the version just adopted. Recorded from the typing itself.
974
+ const typedIn = new WeakSet();
975
+ // The field being typed in while a repaint takes it out of the page: the `change` its removal fires is ignored.
976
+ let leavingField = null;
776
977
  const TABS = [['references', 'Reference drawings'], ['checklist', 'Checklist'], ['runs', 'Runs'], ['colours', 'Markup colours']];
777
978
  function render() {
778
979
  const v = approvedVersion();
779
980
  const client = (S.draft && S.draft.client) || 'Client profile';
780
- paintKeepingFocus(document, root, `
981
+ let left = null;
982
+ try { paintKeepingFocus(document, root, `
781
983
  <header><span class="name">${esc(client)}</span>
782
984
  ${v !== null ? `<span class="pill approved">v${v} approved</span>` : '<span class="pill">Draft</span>'}
783
985
  ${S.review && S.review.groups && S.review.groups.length && v !== null ? '<span class="pill">Changes not approved</span>' : ''}
784
986
  <span class="sp"></span></header>
785
987
  <nav role="tablist" aria-label="Drawing Checker">${TABS.map(([k, l]) =>
786
988
  `<button type="button" role="tab" id="tab-${k}" aria-controls="panel-${k}" aria-selected="${S.tab === k}" tabindex="${S.tab === k ? 0 : -1}" data-tab="${k}" data-command-id="drawing-check.tab#${esc(k)}" data-command-instance-label="${l}">${l}</button>`).join('')}</nav>
787
- <main>${S.loadError ? `<section role="tabpanel"><div class="wrap"><p class="${S.accessError ? 'band' : 'err-line'}" role="alert">${esc(S.loadError)}</p><button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div></section>` : panel()}</main>`);
989
+ <main>${S.loadError ? `<section role="tabpanel"><div class="wrap"><p class="${S.accessError ? 'band' : 'err-line'}" role="alert">${esc(S.loadError)}</p><button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div></section>` : panel()}</main>`, (el) => typedIn.has(el), (el) => { leavingField = el; left = { el, value: el.value }; }); }
990
+ finally { leavingField = null; }
991
+ // Gone from the page: what was typed is listed as not saved, never sent unfinished and never silently lost. (A
992
+ // browser that cannot move a field copies it into the new one, which then has focus.)
993
+ if (left && !root.contains(document.activeElement)) holdTyping(left);
788
994
  if (S.tab === 'runs' && S.run) mountRunView();
789
995
  }
790
996
  /** Repaint without moving the tab's scrolled list: render() replaces the scrolling panel, which starts at the top. */
@@ -865,8 +1071,9 @@ function boot() {
865
1071
  if (b.dataset.dlg === 'cancel') { closeDialog(); return; }
866
1072
  b.disabled = true;
867
1073
  try {
868
- const { body } = await call(`${base}/references/${encodeURIComponent(sha)}`, { method: 'DELETE', headers: S.etag ? { 'if-match': S.etag } : {} });
869
- S.draft.references = body.references; S.etag = body.etag; S.kept.delete(sha);
1074
+ const sent = sending(); // conditional on the version shown: its answer is the person's own change
1075
+ const { body } = await call(`${base}/references/${encodeURIComponent(sha)}`, { method: 'DELETE', headers: sent.etag ? { 'if-match': sent.etag } : {} });
1076
+ adoptAnswer(sent, { references: body.references }, body.etag); S.kept.delete(sha);
870
1077
  S.uploadNote = `${ref.name} was taken out of the reference drawings. Propose again on the Checklist to update what was learned from it.`;
871
1078
  closeDialog(false);
872
1079
  try { await Promise.all([loadDraft(), loadReview()]); }
@@ -975,11 +1182,12 @@ function boot() {
975
1182
  st.busy = true; paintFoot(); live.textContent = 'Adding…';
976
1183
  const p = st.plan;
977
1184
  try {
1185
+ // Conditional on the version the plan was read from: the person's own change only if that is the one shown.
1186
+ const sent = { ...sending(p.draftEtag || null), cond: !!p.draftEtag };
978
1187
  const { body } = await call(`${base}/references/design-issue`, jsonOpts('POST',
979
1188
  { issueId: p.issueId, files: [...st.ticks].sort((a, b) => a - b), planKey: p.planKey, expected: p.expected },
980
1189
  p.draftEtag ? { 'if-match': p.draftEtag } : {}));
981
- S.draft = S.draft || { references: [] };
982
- S.draft.references = body.references; if (body.etag) S.etag = body.etag;
1190
+ if (body.etag) adoptAnswer(sent, { references: body.references }, body.etag);
983
1191
  if (body.added.length) S.newSinceApproval += body.added.length;
984
1192
  const parts = [];
985
1193
  if (body.added.length) parts.push(`${body.added.length} drawing${body.added.length === 1 ? '' : 's'} added from ${body.label}.`);
@@ -1048,8 +1256,11 @@ function boot() {
1048
1256
  for (let i = 0; i < pdfs.length; i++) {
1049
1257
  S.uploadNote = `Adding ${pdfs[i].name} (${i + 1} of ${pdfs.length})…`; render();
1050
1258
  try {
1259
+ const sent = { ...sending(), cond: false }; // unconditional, like Propose
1051
1260
  const { body } = await call(`${base}/references?name=${encodeURIComponent(pdfs[i].name)}`, { method: 'POST', headers: { 'content-type': 'application/pdf' }, body: pdfs[i] });
1052
- if (S.draft) S.draft.references = body.references; added++;
1261
+ // Adopted even on a profile with no draft yet: the first upload creates it, and the read that follows shows it.
1262
+ adoptAnswer(sent, { references: body.references }, body.etag);
1263
+ added++;
1053
1264
  } catch (e) { failed.push(e.message); }
1054
1265
  }
1055
1266
  if (added) S.newSinceApproval += added;
@@ -1058,14 +1269,16 @@ function boot() {
1058
1269
  if (skipped) notes.push(`${skipped} file${skipped === 1 ? '' : 's'} skipped: not PDF${skipped === 1 ? '' : 's'}.`);
1059
1270
  notes.push(...failed);
1060
1271
  S.uploadNote = notes.join(' ');
1061
- await Promise.all([loadDraft(), loadReview()]).catch(() => {});
1272
+ // The whole draft, and the approval status with it, is read on the checklist queue after an upload's answer (adopt).
1062
1273
  render();
1063
1274
  }
1064
1275
 
1065
1276
  // ── checklist ──
1066
1277
  function checklistHtml() {
1278
+ // Held changes are listed even when another window left no references: they stay offered, never silently gone.
1279
+ const band = S.conflict || S.unsaved.length ? unsavedBandHtml({ unsaved: S.unsaved, state: syncState(), showAll: S.showAllUnsaved }) : '';
1067
1280
  if (!references().length) {
1068
- return `<div class="wrap"><h2>Checklist</h2><p class="lede">Add reference drawings first: the checklist is proposed from drawings this client already trusts.</p>
1281
+ return `<div class="wrap"><h2 tabindex="-1">Checklist</h2>${band}<p class="lede">Add reference drawings first: the checklist is proposed from drawings this client already trusts.</p>
1069
1282
  <button type="button" class="link" data-tab="references" data-command-id="drawing-check.tab#references" data-command-instance-label="Reference drawings">Go to Reference drawings</button></div>`;
1070
1283
  }
1071
1284
  const list = items();
@@ -1084,13 +1297,13 @@ function boot() {
1084
1297
  ? mainPartHtml(it, { touched: ((S.draft && S.draft.touched) || []).includes(`item:${it.id}.mainRow`), note: S.mainNote, locatedOn: list.some((x) => x.enabled && x.rule && x.rule.type === 'parts-located') }) : ''}${it.rule && it.rule.type === 'parts-located'
1085
1298
  ? lineBreakHtml(it, { touched: ((S.draft && S.draft.touched) || []).includes(`item:${it.id}.lineBreakPt`), note: S.breakNote, error: S.breakError, typed: S.breakTyped }) : ''}`;
1086
1299
  }).join('');
1087
- return `<div class="wrap"><h2>Checklist</h2>
1300
+ return `<div class="wrap"><h2 tabindex="-1">Checklist</h2>
1088
1301
  <p class="lede">Common doesn’t mean required. Tick only what this client needs.</p>
1089
1302
  ${pendingAsksNotice(S.draft && S.draft.titleBlock)}
1090
1303
  ${clientFieldHtml((S.draft && S.draft.client) || '')}
1091
1304
  <div class="row-actions"><button type="button" class="${list.length ? '' : 'primary'}" data-act="propose" data-command-id="drawing-check.propose">${list.length ? 'Propose again from references' : 'Propose from references'}</button>
1092
1305
  <button type="button" data-act="add-item" data-command-id="drawing-check.add-item">Add item from client standard…</button></div>
1093
- ${S.conflict ? '<div class="band">This checklist changed in another window. Reload to see the latest. <button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div>' : ''}
1306
+ ${band}
1094
1307
  ${S.checklistError ? `<p class="err-line" role="alert">${esc(S.checklistError)}</p>` : ''}
1095
1308
  ${list.length ? `<div class="list">${rows}</div>` : '<p class="note">No items yet. Propose them from the reference drawings.</p>'}
1096
1309
  ${titleBlockHtml(S.draft && S.draft.titleBlock, { pages, note: S.titleNote, noteField: S.titleNoteField, saving: S.tbSaving, typed: S.typed })}
@@ -1121,157 +1334,246 @@ function boot() {
1121
1334
  },
1122
1335
  });
1123
1336
  }
1124
- // Rides the checklist queue: one draft, one etag, one PUT at a time.
1125
- function putClearances(standard) {
1337
+ // ── checklist choices: one queue, one draft, one etag, one PUT at a time (#3121) ──
1338
+ // A choice shows at once (its `apply`, on the derived draft) and goes out when its turn comes, with the etag the page
1339
+ // then holds. It is held, never sent, when the page has since adopted a version the person did not make from what
1340
+ // they saw (its gen is no longer S.gen), or a refusal said the server holds a newer one (S.sync is not 'ok'): sending
1341
+ // it then would write a choice made on the old draft over the newer one. A held choice is listed as not saved and
1342
+ // offered back (unsavedBandHtml), or kept in the dialog it came from. The handlers call these before any await, so
1343
+ // the gen a choice carries is the one on screen when the person acted.
1344
+ const itemsQueue = serialise();
1345
+ let itemsInFlight = 0, choiceSeq = 0;
1346
+ // The newest choice for each thing, and for each item or field the newest removal of it: an older choice that is
1347
+ // held after a newer one was made is not offered back over it.
1348
+ const latest = new Map(), removedAt = new Map();
1349
+ /**
1350
+ * Queue a choice. `key` names what it changes and `family` the item or field it belongs to (a removal, `removes`,
1351
+ * takes the family's other choices with it). `apply(draft)` shows it on a draft and says whether its target is still
1352
+ * there; `url`/`body` send it; `parts(body)` are the draft parts its answer brings; `answered(body, newest)` sets its
1353
+ * note; `failed(e)` says a failure that is not a refusal; `held()` and `settled()` tidy up. `what` says it in the
1354
+ * band, `redo()` makes it again. `dialog`: kept in the dialog it came from when held, not listed.
1355
+ * Resolves to the answer's body, null (failed) or 'held'.
1356
+ */
1357
+ function choose(c, { unsent = false } = {}) {
1358
+ c.seq = ++choiceSeq; c.gen = S.gen;
1359
+ latest.set(c.key, c.seq);
1360
+ if (c.removes) removedAt.set(c.family, c.seq);
1361
+ // The newest choice for a thing retires the offer of an older one.
1362
+ S.unsaved = S.unsaved.filter((u) => u.key !== c.key && !(c.removes && u.family === c.family));
1363
+ // Text still being typed when its field left the page: listed as not saved, never sent.
1364
+ if (unsent) { hold(c); return Promise.resolve('held'); }
1365
+ S.pending.push(c); rebuild(); paint();
1126
1366
  itemsInFlight++;
1127
1367
  return itemsQueue(async () => {
1128
- S.checklistError = ''; S.clearNote = '';
1129
1368
  try {
1130
- const { body } = await call(`${base}/clearances`, jsonOpts('PUT', { standard }, S.etag ? { 'if-match': S.etag } : {}));
1131
- S.etag = body.etag;
1132
- const filled = (body.items.find((i) => i.rule && i.rule.type === 'hole-bolt')?.rule.clearances || []).length;
1133
- S.clearNote = `Filled with ${filled} starter row${filled === 1 ? '' : 's'} from ${STANDARD_NAMES[standard]}.`;
1134
- // As putItems: only the LAST answer repaints the list, so ticks queued behind this fill never flick back.
1135
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1136
- else {
1137
- // Not the last answer: keep the filled rows (the table must match the note), leave the rest of the list as it stands.
1138
- const mine = S.draft.items.find((i) => i.rule && i.rule.type === 'hole-bolt');
1139
- const theirs = body.items.find((i) => i.rule && i.rule.type === 'hole-bolt');
1140
- if (mine && theirs) mine.rule.clearances = theirs.rule.clearances;
1369
+ if (c.gen !== S.gen || S.sync !== 'ok') { hold(c); return 'held'; }
1370
+ const sent = sending();
1371
+ let body;
1372
+ try { ({ body } = await call(c.url, jsonOpts('PUT', c.body, sent.etag ? { 'if-match': sent.etag } : {}))); }
1373
+ catch (e) {
1374
+ if (e.status === 412 || e.status === 428) {
1375
+ // The server holds a newer draft: everything queued behind this is held at its turn, and the draft is
1376
+ // read once they have all had it (readAll queues behind them).
1377
+ S.conflict = true; S.sync = 'behind'; readAll();
1378
+ hold(c); return 'held';
1379
+ }
1380
+ S.pending = S.pending.filter((p) => p !== c); rebuild(); // its optimistic change goes; what is saved shows
1381
+ if (c.failed) c.failed(e); else S.checklistError = e.message;
1382
+ paint(); return null;
1141
1383
  }
1142
- } catch (e) {
1143
- if (e.status === 412 || e.status === 428) S.conflict = true;
1144
- else S.checklistError = e.message;
1145
- await loadDraft().catch(() => {});
1146
- render();
1147
- } finally { itemsInFlight--; }
1384
+ S.pending = S.pending.filter((p) => p !== c);
1385
+ if (c.answered) c.answered(body, latest.get(c.key) === c.seq);
1386
+ if (adoptAnswer(sent, c.parts(body), body.etag) && itemsInFlight === 1) { await loadReview(); paint(); }
1387
+ return body;
1388
+ } finally {
1389
+ itemsInFlight--;
1390
+ if (c.settled) { c.settled(); paint(); }
1391
+ }
1148
1392
  });
1149
1393
  }
1150
- // The line break: one PUT on the checklist queue, as the main part setting. Each save is numbered: an earlier
1151
- // answer never puts back a value over a later one still queued (diff review r1), and the answer to the last save
1152
- // shows what was saved even when other edits are still queued.
1153
- let breakSaves = 0;
1154
- function putLineBreak(pt) {
1155
- itemsInFlight++;
1156
- const save = ++breakSaves;
1157
- return itemsQueue(async () => {
1158
- S.checklistError = ''; S.breakNote = '';
1159
- try {
1160
- const { body } = await call(`${base}/line-break`, jsonOpts('PUT', { pt }, S.etag ? { 'if-match': S.etag } : {}));
1161
- S.etag = body.etag;
1162
- S.breakNote = pt ? `The largest break closed is now ${pt} pt. The checklist has to be approved again.` : 'Breaks in drawn lines are no longer closed. The checklist has to be approved again.';
1163
- const r7 = body.items.find((x) => x.rule && x.rule.type === 'parts-located');
1164
- if (r7) S.draft.touched = [...new Set([...(S.draft.touched || []), `item:${r7.id}.lineBreakPt`])];
1165
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1166
- else if (save === breakSaves) {
1167
- const mine = items().find((x) => x.rule && x.rule.type === 'parts-located');
1168
- if (mine && r7) { mine.rule.lineBreakPt = r7.rule.lineBreakPt; render(); }
1169
- }
1170
- // Otherwise a later save is still queued: its value stays as shown, and the note waits for its answer.
1171
- else S.breakNote = '';
1172
- } catch (e) {
1173
- if (e.status === 412 || e.status === 428) S.conflict = true;
1174
- else S.checklistError = e.message;
1175
- await loadDraft().catch(() => {});
1176
- render();
1177
- } finally { itemsInFlight--; }
1394
+ function hold(c) {
1395
+ S.pending = S.pending.filter((p) => p !== c);
1396
+ rebuild();
1397
+ if (c.held) c.held();
1398
+ const newest = latest.get(c.key) === c.seq && !((removedAt.get(c.family) || 0) > c.seq);
1399
+ if (newest && !c.dialog) {
1400
+ S.unsaved.push({ key: c.key, family: c.family, what: c.what, redo: c.redo, apply: c.apply, gone: !!S.draft && !c.apply(structuredClone(S.draft)) });
1401
+ }
1402
+ paint();
1403
+ }
1404
+ /** Apply my changes again: each listed change is made again on the draft now shown, in order, in this one task. */
1405
+ function applyUnsaved() {
1406
+ if (syncState() !== 'ok') return;
1407
+ // Making a change again takes it off the list (choose retires the older one of each key), so a second click finds
1408
+ // nothing to send twice; a change whose target is gone stays listed, never sent.
1409
+ const again = S.unsaved.filter((u) => !u.gone);
1410
+ S.conflict = false;
1411
+ for (const u of again) void u.redo();
1412
+ }
1413
+ const itemLabel = (id) => { const it = items().find((i) => i.id === id); return it ? (it.display || it.label || id) : id; };
1414
+ const fieldLabel = (name) => { const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === name); return (f && f.label) || FIELD_WORDS[name] || name; };
1415
+ const findItem = (d, id) => (d.items || []).find((i) => i.id === id);
1416
+ const findField = (d, name) => ((d.titleBlock && d.titleBlock.fields) || []).find((x) => x.name === name);
1417
+ const withTouched = (key) => [...new Set([...((S.saved.draft && S.saved.draft.touched) || []), key])];
1418
+
1419
+ function putClearances(standard) {
1420
+ S.checklistError = ''; S.clearNote = '';
1421
+ return choose({
1422
+ key: 'clearances', family: 'clearances', what: `Filled the clearance table from ${STANDARD_NAMES[standard]}`,
1423
+ url: `${base}/clearances`, body: { standard },
1424
+ apply: (d) => (d.items || []).some((i) => i.rule && i.rule.type === 'hole-bolt'),
1425
+ parts: (b) => ({ items: b.items }),
1426
+ answered: (b) => {
1427
+ const filled = (b.items.find((i) => i.rule && i.rule.type === 'hole-bolt')?.rule.clearances || []).length;
1428
+ S.clearNote = `Filled with ${filled} starter row${filled === 1 ? '' : 's'} from ${STANDARD_NAMES[standard]}.`;
1429
+ },
1430
+ redo: () => putClearances(standard),
1178
1431
  });
1179
1432
  }
1180
- // Whether the main part's mark is the assembly mark: one PUT on the checklist queue, as the clearance fill.
1181
- // Each main part click is numbered: an answer settles the choice on the page unless a later click is on its way.
1182
- let mainClicks = 0;
1183
- function putMainPart(assemblyMark) {
1184
- itemsInFlight++;
1185
- const click = ++mainClicks;
1186
- return itemsQueue(async () => {
1187
- S.checklistError = ''; S.mainNote = '';
1188
- try {
1189
- const { body } = await call(`${base}/main-part`, jsonOpts('PUT', { assemblyMark }, S.etag ? { 'if-match': S.etag } : {}));
1190
- S.etag = body.etag;
1191
- S.mainNote = `Main part set to “${assemblyMark ? 'same as the assembly mark' : 'the first marked row'}”. The checklist has to be approved again.`;
1192
- // The server marks the setting the person's; so does the page, for the "set by you" chip.
1193
- const r1 = mainRowItem(body.items);
1194
- if (r1) S.draft.touched = [...new Set([...(S.draft.touched || []), `item:${r1.id}.mainRow`])];
1195
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1196
- else if (click === mainClicks) {
1197
- // Not the last answer, but the last main part click: what was saved is shown, even if a reload after
1198
- // another edit's refusal put back the old choice. Other items wait for the last answer (review r2).
1199
- const mine = mainRowItem(S.draft.items);
1200
- if (mine && r1 && mine.id === r1.id) { mine.rule.mainRow = r1.rule.mainRow; render(); }
1201
- }
1202
- // Otherwise a later click is still queued: its choice stays as shown.
1203
- } catch (e) {
1204
- if (e.status === 412 || e.status === 428) S.conflict = true;
1205
- else S.checklistError = e.message;
1206
- await loadDraft().catch(() => {});
1207
- render();
1208
- } finally { itemsInFlight--; }
1209
- });
1433
+ // The line break. Its note waits for the answer to the newest line-break choice: an earlier answer says nothing
1434
+ // true about a value still on its way.
1435
+ function putLineBreak(pt, { unsent = false } = {}) {
1436
+ S.checklistError = ''; S.breakNote = '';
1437
+ const r7 = (d) => (d.items || []).find((x) => x.rule && x.rule.type === 'parts-located');
1438
+ return choose({
1439
+ key: 'line-break', family: 'line-break', what: pt ? `Set the line break to ${pt} pt` : 'Switched off closing breaks in drawn lines',
1440
+ url: `${base}/line-break`, body: { pt },
1441
+ apply: (d) => { const it = r7(d); if (it) it.rule.lineBreakPt = pt; return !!it; },
1442
+ parts: (b) => { const it = r7(b); return { items: b.items, ...(it ? { touched: withTouched(`item:${it.id}.lineBreakPt`) } : {}) }; },
1443
+ answered: (_b, newest) => {
1444
+ S.breakNote = !newest ? '' : pt ? `The largest break closed is now ${pt} pt. The checklist has to be approved again.` : 'Breaks in drawn lines are no longer closed. The checklist has to be approved again.';
1445
+ },
1446
+ redo: () => putLineBreak(pt),
1447
+ }, { unsent });
1210
1448
  }
1211
- // Checklist edits go out ONE AT A TIME. Two quick ticks used to send the second PUT with the etag the
1212
- // page held before the first answered, which the server rightly refused (412) — shown as "changed in
1213
- // another window" and the tick reverted. Each queued PUT reads S.etag when it actually goes out.
1214
- const itemsQueue = serialise();
1215
- let itemsInFlight = 0;
1216
- function putItems(edits) {
1217
- itemsInFlight++;
1218
- return itemsQueue(async () => {
1219
- S.checklistError = '';
1220
- try {
1221
- const { body } = await call(`${base}/items`, jsonOpts('PUT', { items: edits }, S.etag ? { 'if-match': S.etag } : {}));
1222
- S.etag = body.etag;
1223
- // Only the LAST answer replaces the list: an earlier one predates ticks still queued behind it,
1224
- // and painting it would flick those ticks back until their own answer arrived. The list keeps its scroll.
1225
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); renderKeepingScroll(); }
1226
- return body;
1227
- } catch (e) {
1228
- if (e.status === 412 || e.status === 428) S.conflict = true;
1229
- else S.checklistError = e.message;
1230
- await loadDraft().catch(() => {}); // show what the profile really holds, not the optimistic ticks
1231
- renderKeepingScroll();
1232
- return null;
1233
- } finally { itemsInFlight--; }
1449
+ // Whether the main part's mark is the assembly mark.
1450
+ function putMainPart(assemblyMark) {
1451
+ S.checklistError = ''; S.mainNote = '';
1452
+ const row = assemblyMark ? 'mark-equals-assembly' : 'first-marked-row';
1453
+ const words = assemblyMark ? 'same as the assembly mark' : 'the first marked row';
1454
+ return choose({
1455
+ key: 'main-part', family: 'main-part', what: `Set the main part to “${words}”`,
1456
+ url: `${base}/main-part`, body: { assemblyMark },
1457
+ apply: (d) => { const it = mainRowItem(d.items); if (it) it.rule.mainRow = row; return !!it; },
1458
+ // The server marks the setting the person's; so does the page, for the "set by you" chip.
1459
+ parts: (b) => { const r1 = mainRowItem(b.items); return { items: b.items, ...(r1 ? { touched: withTouched(`item:${r1.id}.mainRow`) } : {}) }; },
1460
+ answered: (_b, newest) => { if (newest) S.mainNote = `Main part set to “${words}”. The checklist has to be approved again.`; },
1461
+ redo: () => putMainPart(assemblyMark),
1234
1462
  });
1235
1463
  }
1236
- // The client goes out on the same queue as the ticks: one draft, one etag, one PUT at a time.
1237
- function putClient(client) {
1238
- itemsInFlight++;
1239
- return itemsQueue(async () => {
1240
- S.checklistError = '';
1241
- try {
1242
- const { body } = await call(`${base}/client`, jsonOpts('PUT', { client }, S.etag ? { 'if-match': S.etag } : {}));
1243
- S.etag = body.etag; S.draft.client = body.client;
1244
- await loadReview();
1245
- } catch (e) {
1246
- if (e.status === 412 || e.status === 428) S.conflict = true;
1247
- else S.checklistError = e.message;
1248
- await loadDraft().catch(() => {});
1249
- } finally { itemsInFlight--; }
1250
- render();
1464
+ /** One item edit: ticked or not, removed, or added (from the Add item dialog, which keeps it if it is held). */
1465
+ function putItems(edits, { dialog = false } = {}) {
1466
+ S.checklistError = '';
1467
+ const e = edits[0];
1468
+ const label = e.id ? itemLabel(e.id) : e.label;
1469
+ const kind = e.remove ? 'remove' : e.id ? 'enabled' : 'add';
1470
+ const family = e.id ? `item:${e.id}` : `item-add:${e.label}`;
1471
+ return choose({
1472
+ key: kind === 'add' ? family : `${family}:${kind}`, family, removes: kind === 'remove', dialog,
1473
+ what: kind === 'remove' ? `Removed “${label}”` : kind === 'add' ? `Added “${label}”` : `${e.enabled ? 'Ticked' : 'Unticked'} “${label}”`,
1474
+ url: `${base}/items`, body: { items: edits },
1475
+ apply: (d) => { if (kind === 'add') return true; const it = findItem(d, e.id); if (it && kind === 'enabled') it.enabled = e.enabled; return !!it; },
1476
+ parts: (b) => ({ items: b.items }),
1477
+ redo: () => putItems(edits, { dialog }),
1251
1478
  });
1252
1479
  }
1253
- // Title-block edits ride the same queue: one draft, one etag, one PUT at a time.
1254
- function putTitleBlock(change) {
1255
- itemsInFlight++;
1256
- return itemsQueue(async () => {
1257
- S.checklistError = ''; S.titleNote = ''; S.titleNoteField = '';
1258
- try {
1259
- const { body } = await call(`${base}/title-block`, jsonOpts('PUT', change, S.etag ? { 'if-match': S.etag } : {}));
1260
- S.etag = body.etag;
1261
- if (itemsInFlight === 1) { S.draft.titleBlock = body.titleBlock; S.draft.items = body.items; }
1262
- if (body.note) { S.titleNote = body.note; S.titleNoteField = body.noteField || ''; }
1480
+ // A field being typed in that a repaint took out of the page (another window's version has no place for it):
1481
+ // what was typed, if it would change anything, is listed as not saved with the way to make it on this version.
1482
+ function holdTyping({ el, value }) {
1483
+ const text = value.replace(/\s+/g, ' ').trim(), d = S.draft || {};
1484
+ if (el.id === 'client-name') { if (text && text !== d.client) putClient(text, { unsent: true }); return; }
1485
+ if (el.id === 'line-break-pt') {
1486
+ const got = parseLineBreak(value), it = (d.items || []).find((x) => x.rule && x.rule.type === 'parts-located');
1487
+ if (!('why' in got)) { if (!it || got.pt !== (it.rule.lineBreakPt ?? 0)) putLineBreak(got.pt, { unsent: true }); return; }
1488
+ // Not a size yet (half-typed, like "."): listed as typed so it is not lost, and only Dismiss is offered.
1489
+ if (text) {
1490
+ S.unsaved = S.unsaved.filter((u) => u.key !== 'line-break');
1491
+ S.unsaved.push({ key: 'line-break', family: 'line-break', what: `Typed “${text}” as the line break`, unusable: true, gone: true, apply: () => false, redo: () => {} });
1492
+ paint();
1493
+ }
1494
+ return;
1495
+ }
1496
+ if (el.dataset.tbLabel) {
1497
+ const f = findField(d, el.dataset.tbLabel);
1498
+ if (text && (!f || text !== f.label)) putTitleBlock({ field: el.dataset.tbLabel, label: text }, { unsent: true });
1499
+ return;
1500
+ }
1501
+ if (el.dataset.typedLabel && text) putTitleBlock({ answer: { ask: el.dataset.typedLabel, label: text } }, { unsent: true });
1502
+ }
1503
+ function putClient(client, { unsent = false } = {}) {
1504
+ S.checklistError = '';
1505
+ return choose({
1506
+ key: 'client', family: 'client', what: `Set the client name to “${client}”`,
1507
+ url: `${base}/client`, body: { client },
1508
+ apply: (d) => { d.client = client; return true; },
1509
+ parts: (b) => ({ client: b.client }),
1510
+ redo: () => putClient(client),
1511
+ }, { unsent });
1512
+ }
1513
+ /** A title-block change: an answer to a question, a field's read way, label or requiredness, removing a field,
1514
+ * or adding one (from the Add field dialog, which keeps it if it is held). */
1515
+ function putTitleBlock(change, { dialog = false, unsent = false } = {}) {
1516
+ S.checklistError = ''; S.titleNote = ''; S.titleNoteField = '';
1517
+ const tb = (d) => d.titleBlock || {};
1518
+ let key, family, what, apply = () => true;
1519
+ if (change.answer) {
1520
+ const { ask, choice, label } = change.answer;
1521
+ const a = (tb(S.draft || {}).asks || []).find((x) => x.id === ask);
1522
+ const said = label !== undefined ? `“${label}”` : (a && a.choices.find((x) => x.id === choice)?.label) || choice;
1523
+ key = family = `ask:${ask}`;
1524
+ what = `Answered “${a ? a.question : ask}”: ${said}`;
1525
+ apply = (d) => (tb(d).asks || []).some((x) => x.id === ask && (label !== undefined || x.choices.some((y) => y.id === choice)));
1526
+ } else if (change.add) {
1527
+ key = family = `field-add:${change.add.label}`;
1528
+ what = `Added the field “${change.add.label}”`;
1529
+ } else if (change.remove) {
1530
+ family = `field:${change.remove}`; key = `${family}:remove`;
1531
+ what = `Removed the field “${fieldLabel(change.remove)}”`;
1532
+ apply = (d) => !!findField(d, change.remove);
1533
+ } else {
1534
+ const name = change.field, L = fieldLabel(name);
1535
+ const prop = 'read' in change ? 'read' : 'label' in change ? 'label' : 'required';
1536
+ family = `field:${name}`; key = `${family}:${prop}`;
1537
+ what = prop === 'read' ? `Set “${L}” to read: ${(READ_WORDS[change.read] || change.read).toLowerCase()}`
1538
+ : prop === 'label' ? `Renamed “${L}” to “${change.label}”` : `Made “${L}” ${change.required ? 'required' : 'optional'}`;
1539
+ apply = (d) => { const f = findField(d, name); if (f) f[prop] = change[prop]; return !!f; };
1540
+ }
1541
+ return choose({
1542
+ key, family, removes: !!change.remove, what, apply, dialog,
1543
+ url: `${base}/title-block`, body: change,
1544
+ parts: (b) => ({ titleBlock: b.titleBlock, items: b.items }),
1545
+ answered: (b) => {
1546
+ if (b.note) { S.titleNote = b.note; S.titleNoteField = b.noteField || ''; }
1263
1547
  if (change.answer) delete S.typed[change.answer.ask];
1264
- await loadReview();
1265
- return body;
1266
- } catch (e) {
1267
- if (e.status === 412 || e.status === 428) S.conflict = true;
1548
+ },
1549
+ failed: (e) => {
1268
1550
  // A typed answer the server refused stays in its field, with the reason beside it.
1269
- else if (change.answer && change.answer.label !== undefined) S.typed[change.answer.ask] = { value: change.answer.label, error: e.message };
1551
+ if (change.answer && change.answer.label !== undefined) S.typed[change.answer.ask] = { value: change.answer.label, error: e.message };
1270
1552
  else S.checklistError = e.message;
1271
- await loadDraft().catch(() => {});
1272
- return null;
1273
- } finally { itemsInFlight--; S.tbSaving = false; render(); }
1274
- });
1553
+ },
1554
+ // A held typed answer is listed with the other changes; its field closes rather than keep text that was not saved.
1555
+ held: () => { if (change.answer) delete S.typed[change.answer.ask]; },
1556
+ settled: () => { S.tbSaving = false; },
1557
+ redo: () => putTitleBlock(change, { dialog }),
1558
+ }, { unsent });
1559
+ }
1560
+ // A dialog's add that was held: the dialog keeps what was typed and says why, while the latest version is read.
1561
+ const heldDialogs = new Set();
1562
+ function showHeldInDialog(scrim, btn, idleText, line) {
1563
+ const show = () => {
1564
+ if (!openDialog || openDialog.scrim !== scrim) { heldDialogs.delete(show); return; }
1565
+ const state = syncState();
1566
+ line.hidden = false;
1567
+ line.textContent = state === 'reading' ? 'Not added: the checklist changed while this was being added. Getting the latest version…'
1568
+ : state === 'failed' ? 'Not added: the checklist changed while this was being added, and the latest version couldn’t be read just now. Cancel, then reload the profile.'
1569
+ : 'Not added: the checklist changed while this was being added. The page behind this window now shows the latest. Add it again, or cancel to look first.';
1570
+ btn.hidden = state === 'failed';
1571
+ btn.disabled = state !== 'ok';
1572
+ btn.textContent = state === 'ok' ? idleText : 'Getting the latest version…';
1573
+ if (state === 'ok') heldDialogs.delete(show);
1574
+ };
1575
+ heldDialogs.add(show);
1576
+ show();
1275
1577
  }
1276
1578
  function addFieldDialog() {
1277
1579
  showDialog({
@@ -1292,8 +1594,9 @@ function boot() {
1292
1594
  const err = scrim.querySelector('#af-err');
1293
1595
  if (!label) { err.hidden = false; err.textContent = 'Write the label as it appears on the drawings.'; return; }
1294
1596
  e.target.disabled = true; e.target.textContent = 'Looking for it…';
1295
- const res = await putTitleBlock({ add: { label, required: scrim.querySelector('#af-required').checked } });
1597
+ const res = await putTitleBlock({ add: { label, required: scrim.querySelector('#af-required').checked } }, { dialog: true });
1296
1598
  if (!openDialog || openDialog.scrim !== scrim) return;
1599
+ if (res === 'held') { showHeldInDialog(scrim, scrim.querySelector('[data-dlg="add"]'), 'Add field', err); return; }
1297
1600
  if (!res) { e.target.disabled = false; e.target.textContent = 'Add field'; err.hidden = false; err.textContent = S.checklistError || 'The field could not be added. Try again.'; return; }
1298
1601
  closeDialog();
1299
1602
  });
@@ -1305,11 +1608,12 @@ function boot() {
1305
1608
  S.checklistError = ''; S.uploadNote = ''; S.clearNote = '';
1306
1609
  const btn = root.querySelector('[data-act="propose"]'); if (btn) { btn.disabled = true; btn.textContent = 'Reading the reference drawings…'; }
1307
1610
  try {
1611
+ // Unconditional: its answer may include another window's change, so it is a version the person has not seen,
1612
+ // and it carries only part of the draft: the whole draft is read after it (adopt).
1613
+ const sent = { ...sending(), cond: false };
1308
1614
  const { body } = await call(`${base}/propose`, { method: 'POST' });
1309
- S.draft.items = body.items; S.etag = body.etag; S.newSinceApproval = 0;
1310
- if (body.titleBlock) S.draft.titleBlock = body.titleBlock; else delete S.draft.titleBlock;
1311
- if (body.partList) S.draft.partList = body.partList; else delete S.draft.partList;
1312
- if (body.client) S.draft.client = body.client;
1615
+ S.newSinceApproval = 0;
1616
+ adoptAnswer(sent, { items: body.items, titleBlock: body.titleBlock ?? null, partList: body.partList ?? null, ...(body.client ? { client: body.client } : {}) }, body.etag);
1313
1617
  if (body.unreadable && body.unreadable.length) S.checklistError = `Couldn’t read ${body.unreadable.join(', ')}; the other drawings were used.`;
1314
1618
  await loadReview();
1315
1619
  } catch (e) { S.checklistError = e.message; }
@@ -1382,8 +1686,9 @@ function boot() {
1382
1686
  if (!label || !text) { err.hidden = false; err.textContent = 'Give the item a name and the text to look for.'; return; }
1383
1687
  e.target.disabled = true; e.target.textContent = 'Testing…';
1384
1688
  const before = new Set(items().map((i) => i.id));
1385
- const res = await putItems([{ label, text, display: label, enabled: true }]);
1689
+ const res = await putItems([{ label, text, display: label, enabled: true }], { dialog: true });
1386
1690
  if (!openDialog || openDialog.scrim !== scrim) return;
1691
+ if (res === 'held') { showHeldInDialog(scrim, scrim.querySelector('[data-dlg="test"]'), 'Add and test on reference drawings', err); return; }
1387
1692
  if (!res) { e.target.disabled = false; e.target.textContent = 'Add and test on reference drawings'; err.hidden = false; err.textContent = S.checklistError || 'The item could not be added. Try again.'; return; }
1388
1693
  const added = res.items.find((i) => !before.has(i.id));
1389
1694
  scrim.dataset.added = added ? added.id : '';
@@ -2267,18 +2572,18 @@ function boot() {
2267
2572
  if (t.dataset.tbRead) {
2268
2573
  const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === t.dataset.tbRead);
2269
2574
  const refocus = () => root.querySelector(`[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`)?.focus();
2270
- if (f && f.read !== t.dataset.mode) { f.read = t.dataset.mode; render(); refocus(); await putTitleBlock({ field: f.name, read: t.dataset.mode }); }
2575
+ if (f && f.read !== t.dataset.mode) { const saving = putTitleBlock({ field: f.name, read: t.dataset.mode }); refocus(); await saving; }
2271
2576
  refocusIfLost(document, root, `[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`);
2272
2577
  return;
2273
2578
  }
2274
2579
  if (t.dataset.mainRow) {
2275
2580
  const it = mainRowItem(items());
2276
2581
  const want = t.dataset.mainRow === 'yes', row = want ? 'mark-equals-assembly' : 'first-marked-row';
2277
- // As a read mode: the choice shows at once; the answer (or a reload after a refusal) settles it.
2582
+ // As a read mode: the choice shows at once; its answer settles it, or it is listed as not saved.
2278
2583
  if (it && it.rule.mainRow !== row) {
2279
- it.rule.mainRow = row; S.mainNote = ''; render();
2584
+ const saving = putMainPart(want);
2280
2585
  root.querySelector('[data-main-row][aria-checked="true"]')?.focus();
2281
- await putMainPart(want);
2586
+ await saving;
2282
2587
  }
2283
2588
  refocusIfLost(document, root, '[data-main-row][aria-checked="true"]');
2284
2589
  return;
@@ -2293,7 +2598,19 @@ function boot() {
2293
2598
  return;
2294
2599
  }
2295
2600
  // A refresh waits for this load (refreshNow awaits `loaded`), so a change announced while it runs is read after it.
2601
+ // Reload keeps the changes listed as not saved (#3121): they are the person's, offered until applied or dismissed.
2296
2602
  if (act === 'reload') { S.conflict = false; S.checklistError = ''; await (loaded = loadAll()); return; }
2603
+ if (act === 'unsaved-apply') {
2604
+ applyUnsaved();
2605
+ (root.querySelector('.unsaved-state') || root.querySelector('section[role=tabpanel] h2'))?.focus();
2606
+ return;
2607
+ }
2608
+ if (act === 'unsaved-dismiss') {
2609
+ S.unsaved = []; S.conflict = false; S.showAllUnsaved = false; render();
2610
+ root.querySelector('section[role=tabpanel] h2')?.focus();
2611
+ return;
2612
+ }
2613
+ if (act === 'unsaved-show-all') { S.showAllUnsaved = !S.showAllUnsaved; render(); root.querySelector('[data-act="unsaved-show-all"]')?.focus(); return; }
2297
2614
  if (act === 'pick-refs') { document.getElementById('ref-file')?.click(); return; }
2298
2615
  if (act === 'use-design-set') { designSetDialog(t); return; }
2299
2616
  if (act === 'pick-again') { designSetDialog(t, t.dataset.issue); return; }
@@ -2321,11 +2638,14 @@ function boot() {
2321
2638
  if (act === 'reset-colours') { await saveColours({ pass: DEFAULT_COLOURS.pass, fail: DEFAULT_COLOURS.fail, question: DEFAULT_COLOURS['dont-know'] }); }
2322
2639
  });
2323
2640
  root.addEventListener('input', (e) => {
2641
+ typedIn.add(e.target);
2324
2642
  const id = e.target.dataset && e.target.dataset.typedLabel;
2325
2643
  if (id) S.typed[id] = { value: e.target.value, error: '' };
2326
2644
  });
2327
2645
  root.addEventListener('change', async (e) => {
2328
2646
  const t = e.target;
2647
+ if (t === leavingField) return; // fired by the repaint taking it out of the page, not by the person
2648
+ typedIn.delete(t); // its text is sent (or put back) now: a repaint shows what was saved
2329
2649
  if (t.id === 'ref-file') { const files = [...t.files]; t.value = ''; if (files.length) await uploadReferences(files); return; }
2330
2650
  if (t.id === 'run-file') { const files = [...t.files]; t.value = ''; await checkDrawings(files); return; }
2331
2651
  if (t.id === 'client-name') {
@@ -2343,7 +2663,7 @@ function boot() {
2343
2663
  if ('why' in got) { S.breakError = got.why; S.breakTyped = t.value; S.breakNote = ''; render(); refocusIfLost(document, root, '#line-break-pt'); return; }
2344
2664
  S.breakError = ''; S.breakTyped = null;
2345
2665
  const was = typeof it.rule.lineBreakPt === 'number' ? it.rule.lineBreakPt : 0;
2346
- if (got.pt !== was) { it.rule.lineBreakPt = got.pt; render(); await putLineBreak(got.pt); }
2666
+ if (got.pt !== was) await putLineBreak(got.pt);
2347
2667
  else render();
2348
2668
  refocusIfLost(document, root, '#line-break-pt');
2349
2669
  return;
@@ -2371,8 +2691,6 @@ function boot() {
2371
2691
  // is painted now, so the footer's "N of M items ticked" counts it at once rather than when the save and the
2372
2692
  // review after it have answered (#2570). Focus stays on the box (paintKeepingFocus) and the list where it was
2373
2693
  // scrolled; an earlier tick's error is not announced again as if this one had failed.
2374
- const it = items().find((i) => i.id === t.dataset.item);
2375
- if (it) { it.enabled = t.checked; S.checklistError = ''; renderKeepingScroll(); }
2376
2694
  await putItems([{ id: t.dataset.item, enabled: t.checked }]);
2377
2695
  root.querySelector(`[data-item="${CSS.escape(t.dataset.item)}"]`)?.focus();
2378
2696
  return;
@@ -2387,7 +2705,7 @@ function boot() {
2387
2705
  // Tabs: arrow keys move between them (role=tablist); in a read-mode radiogroup they move the choice.
2388
2706
  root.addEventListener('keydown', (e) => {
2389
2707
  if (e.key === 'Enter' && e.target.dataset && e.target.dataset.typedLabel) {
2390
- e.preventDefault(); root.querySelector(`[data-typed-use="${CSS.escape(e.target.dataset.typedLabel)}"]`)?.click(); return;
2708
+ e.preventDefault(); typedIn.delete(e.target); root.querySelector(`[data-typed-use="${CSS.escape(e.target.dataset.typedLabel)}"]`)?.click(); return;
2391
2709
  }
2392
2710
  const radio = e.target.closest('.seg [role=radio]');
2393
2711
  if (radio && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
@@ -2454,11 +2772,13 @@ function boot() {
2454
2772
  const was = { refs: references(), designSet: S.designSetError ? null : S.designSet };
2455
2773
  const seq = ownWriteSeq;
2456
2774
  const before = JSON.stringify([S.draft, S.etag, S.designSet, S.designSetError, S.review]);
2457
- let failed = false;
2775
+ let failed = false, stale = false;
2458
2776
  await Promise.all([
2459
2777
  w.designSet ? loadDesignSet() : null,
2460
- draft ? loadDraft().then(loadReview).catch(() => { failed = true; }) : null,
2778
+ // A read that crossed a write of this page's own adopted nothing (#3121): read again once it has answered.
2779
+ draft ? loadDraft().then((got) => { if (got === 'stale') stale = true; else return loadReview(); }).catch(() => { failed = true; }) : null,
2461
2780
  ]);
2781
+ if (stale) refreshSoon({ draft: true });
2462
2782
  if (before === JSON.stringify([S.draft, S.etag, S.designSet, S.designSetError, S.review]) && !failed) return;
2463
2783
  const note = referencesChangeNote(was, { refs: references(), designSet: S.designSetError ? null : S.designSet });
2464
2784
  if (failed) S.liveNote = 'This page could not read the latest reference drawings just now. Reload the profile to see them.';