@floless/app 0.134.0 → 0.134.1

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.
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
- <title>Steel Filter</title>
6
+ <title>Drawing Filter</title>
7
7
  <!-- Mirrors the shell's light/dark choice onto this document's <html> — see web/frame-theme.js for
8
8
  why it reads localStorage rather than being poked by the parent. Classic, non-deferred and in
9
9
  <head> on purpose: the attribute has to land before first paint or a light user sees a dark flash. -->
@@ -82,9 +82,22 @@ header b{font-size:14px} header .sp{flex:1}
82
82
  cyan "non-default, click to act" chip the sibling editors use — no new colour. */
83
83
  .stat.conflict{color:var(--cyan);border:1px solid var(--cyan);background:var(--cyan-soft);border-radius:4px;padding:1px 6px;cursor:pointer}
84
84
  button{background:var(--btn);color:var(--text);border:1px solid var(--ctrl-border);border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui}
85
- button:hover{background:var(--btn-hover)} button:disabled{opacity:.5;cursor:default}
85
+ button:hover{background:var(--btn-hover)} button:disabled,button[aria-disabled="true"]{opacity:.5;cursor:default}
86
+ button[aria-disabled="true"]:hover{background:var(--btn)}
86
87
  button.primary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink)} button.primary:hover{background:var(--brand-hover)}
87
88
  button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
89
+ /* The terminal read pauses at this exact control. Pulse only while the URL carries the live
90
+ revision checkpoint, then remove the cue as soon as Save begins. Brand-blue, not a new alert
91
+ colour: this is the next action, not an error. Reduced motion keeps the ring without animation. */
92
+ @keyframes save-required-pulse{
93
+ 0%,100%{box-shadow:0 0 0 1px color-mix(in srgb,var(--brand) 46%,transparent),0 0 0 transparent}
94
+ 50%{box-shadow:0 0 0 3px color-mix(in srgb,var(--brand) 34%,transparent),0 0 16px color-mix(in srgb,var(--brand) 46%,transparent)}
95
+ }
96
+ #save.needs-save{animation:save-required-pulse 1.2s ease-in-out 3 forwards}
97
+ @media (prefers-reduced-motion:reduce){#save.needs-save{animation:none;box-shadow:0 0 0 3px color-mix(in srgb,var(--brand) 38%,transparent)}}
98
+ .stat.required-step{color:var(--brand);font-weight:600}
99
+ .stat.required-step:focus-visible{outline:2px solid var(--brand);outline-offset:3px;border-radius:3px}
100
+ .stat.required-step[hidden]{display:none}
88
101
  /* Sheet switcher — a themed combobox, NOT a native <select>.
89
102
  A <select>'s CLOSED state takes styling fine; its arrow and its option list do not. Those are drawn
90
103
  by the OS, so they come up as a light panel against this dark theme no matter what the rule says —
@@ -129,8 +142,41 @@ button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
129
142
  /* Mirrors app.css's .sr-only. Needed here because this page does not load app.css, and the sheet
130
143
  switcher has no VISIBLE label beside it the way the workflow/project pickers do. */
131
144
  .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
145
+ /* The layer sign-off confirm step — the FIRST true modal on this surface (#eye and .sheet-popover are
146
+ non-modal popovers). Built from this page's own tokens; it introduces no colour, font or effect the
147
+ page did not already have, and it reuses the .sheet-popover panel treatment so the two panel
148
+ surfaces read as one family.
149
+ The backdrop colour is inlined rather than tokenized, the same way #conflictBanner inlines its own:
150
+ one single-purpose alert surface does not earn a --scrim token. Add one if a second modal appears. */
151
+ #signoffOverlay{position:fixed;inset:0;z-index:90;display:flex;align-items:center;justify-content:center;padding:20px;background:rgba(15,23,42,.6)}
152
+ /* Explicit and LOAD-BEARING, the same case as .sheet-combo[hidden] above: this page has no global
153
+ [hidden] rule and the author `display` here beats the UA's by origin, so without this the element
154
+ would stay on screen with `hidden` set — silently inert. */
155
+ #signoffOverlay[hidden]{display:none}
156
+ #signoffPanel{width:100%;max-width:460px;max-height:min(560px,86vh);display:flex;flex-direction:column;background:var(--panel);border:1px solid var(--line);border-radius:8px;box-shadow:var(--shadow-lg);padding:18px;animation:sheet-in .14s ease-out}
157
+ #signoffPanel h2{margin:0 0 8px;font-size:15px;font-weight:600;color:var(--text)}
158
+ .signoff-desc{margin:0 0 14px;color:var(--mut);font-size:12.5px;line-height:1.5}
159
+ /* Amber left rail, not a filled banner: the page already uses --warn as its "at risk" signal on the
160
+ Unsaved dot, and a filled amber block would out-shout the primary action next to it. */
161
+ .signoff-notice{border-left:3px solid var(--warn);background:var(--bg);border-radius:0 4px 4px 0;padding:8px 10px;margin:0 0 12px;font-size:12px;line-height:1.5}
162
+ .signoff-notice[hidden]{display:none}
163
+ .signoff-notice b{display:block;color:var(--warn);margin-bottom:2px}
164
+ .signoff-notice p{margin:0;color:var(--text)}
165
+ /* A scroll container — themed by the global `*` scrollbar rules at the top of this sheet, exactly as
166
+ .sheet-list is, so no native white bar can appear inside the modal. */
167
+ .signoff-list{list-style:none;margin:0 0 14px;padding:4px;overflow-y:auto;flex:1;min-height:0;border:1px solid var(--line);border-radius:6px;background:var(--bg)}
168
+ .signoff-list[hidden]{display:none}
169
+ .signoff-row{display:flex;align-items:baseline;gap:10px;padding:6px 8px;font-size:12.5px;border-bottom:1px solid var(--line)}
170
+ .signoff-row:last-child{border-bottom:none}
171
+ .signoff-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}
172
+ .signoff-count{flex:none;color:var(--mut);font-size:11px;cursor:default}
173
+ .signoff-actions{display:flex;justify-content:flex-end;gap:8px;flex:none}
174
+ .signoff-actions button[hidden]{display:none}
132
175
  /* Themed tooltip — replaces native title= so no light OS tooltip leaks onto the dark theme. */
133
- #tooltip{position:fixed;z-index:80;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:11.5px;line-height:1.35;color:var(--text);pointer-events:none;max-width:260px;box-shadow:var(--shadow-tip);opacity:0;transition:opacity .12s}
176
+ /* Above EVERY surface it can be shown over, the sign-off overlay (z-index 90) included: a tooltip
177
+ that renders behind the thing it is describing is worse than no tooltip, because the control still
178
+ advertises one. Raise this whenever a higher surface is added. */
179
+ #tooltip{position:fixed;z-index:100;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:11.5px;line-height:1.35;color:var(--text);pointer-events:none;max-width:260px;box-shadow:var(--shadow-tip);opacity:0;transition:opacity .12s}
134
180
  #tooltip.show{opacity:1}
135
181
  #app{display:flex;flex:1;min-height:0}
136
182
  #panel{width:300px;flex:0 0 300px;background:var(--panel);border-right:1px solid var(--line);padding:14px;overflow-y:auto;display:flex;flex-direction:column;gap:18px}
@@ -143,6 +189,13 @@ button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
143
189
  .opts label em{margin-left:auto;color:var(--mut);font-style:normal;font-size:11px}
144
190
  .opts .sw{width:12px;height:12px;border-radius:3px;flex:0 0 12px;border:1px solid var(--ctrl-border)}
145
191
  .opts label.textlayer{opacity:.55;cursor:default}
192
+ /* A row whose facet value has no canonical key (#805 Phase D slice D1). buildFacet sets
193
+ `aria-disabled` on the checkbox — NOT the `disabled` property, which would take it out of the tab
194
+ order and hide the refusal from Instructor; see the comment there. This is presentation only, and
195
+ deliberately reuses button:disabled's own .5/cursor:default rather than inventing a third muted-row
196
+ treatment beside .textlayer (.55) and .facet.dim (.4). */
197
+ .opts label.novalue{opacity:.5;cursor:default}
198
+ input[type=checkbox][aria-disabled="true"]{cursor:default}
146
199
  /* Fully custom checkbox — the native unchecked widget is a white/grey square that breaks the dark baseline. */
147
200
  input[type=checkbox]{-webkit-appearance:none;appearance:none;width:14px;height:14px;flex:none;border:1px solid var(--ctrl-border);border-radius:3px;background:transparent;cursor:pointer;margin:0;vertical-align:middle}
148
201
  input[type=checkbox]:checked{background:var(--brand);border-color:var(--brand);background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 10 8' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 4l3 3 5-5' stroke='%23fff' stroke-width='1.6' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center}
@@ -165,6 +218,11 @@ input:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
165
218
  to 4.7:1 on the dark panel but 3.8:1 on the light one, and these rows still carry a live checkbox. */
166
219
  [data-theme="light"] input[type=checkbox]{background:var(--bg)}
167
220
  [data-theme="light"] .opts label.textlayer{opacity:.7}
221
+ /* .novalue gets the same lift, and for the same reason .textlayer needed one: opacity does not
222
+ composite symmetrically across grounds, so .5 that reads as "quiet" on the dark panel reads as
223
+ "barely there" on the light one. This is the row LEAST able to afford that — it is the one
224
+ carrying an explanation of why it cannot be ticked. */
225
+ [data-theme="light"] .opts label.novalue{opacity:.65}
168
226
  .hint{color:var(--mut);font-size:11px;line-height:1.5}
169
227
  /* #count is the footer's only child since #603 took the Fit/Zoom buttons out of the rail, so the
170
228
  flex row that used to wrap around them is gone with them — as are #count's width:100% and
@@ -285,6 +343,7 @@ body.publication-blocked #empty{position:static;flex:1}
285
343
  <span id="src" class="stat"></span>
286
344
  <span class="sp"></span>
287
345
  <span id="saved" class="stat"></span>
346
+ <span id="saveRequiredStatus" class="stat required-step" role="status" aria-live="polite" tabindex="-1" hidden>Ready — press Save filter</span>
288
347
  <button id="save" data-command-id="filter.save" class="primary" disabled>Save filter</button>
289
348
  </header>
290
349
  <div id="app">
@@ -358,6 +417,26 @@ body.publication-blocked #empty{position:static;flex:1}
358
417
  <button class="eall primary" id="eyeAddAll" data-command-id="filter.eyedropper-add">Add all to filter</button>
359
418
  </div>
360
419
 
420
+ <!-- The layer sign-off confirm step. Only ever opened for a revision read that has layers switched
421
+ OFF: those are the layers whose every element the completion proof may later dismiss as a group,
422
+ so this is where a human takes that decision on the record. Nothing in the list is interactive —
423
+ to change the list, Cancel and re-tick in the panel, which is the one place selection is edited. -->
424
+ <div id="signoffOverlay" hidden>
425
+ <div id="signoffPanel" role="dialog" aria-modal="true" aria-labelledby="signoffTitle" aria-describedby="signoffDesc">
426
+ <h2 id="signoffTitle">Confirm layers as not steel</h2>
427
+ <p class="signoff-desc" id="signoffDesc">These layers are switched off in your filter, so this read treats every element on them as not steel — dismissed as a group, with no line-by-line reason. Layers left on can’t be dismissed this way.</p>
428
+ <div class="signoff-notice" id="signoffNotice" role="status" hidden></div>
429
+ <h3 id="signoffListLabel" class="sr-only">Layers to approve as not steel</h3>
430
+ <ul class="signoff-list" id="signoffList" aria-labelledby="signoffListLabel"></ul>
431
+ <div class="signoff-actions">
432
+ <button id="signoffCancel" data-command-id="filter.signoff-cancel">Cancel</button>
433
+ <button id="signoffApprove" class="primary" data-command-id="filter.signoff-approve">Approve these layers as not steel</button>
434
+ <button id="signoffClose" data-command-id="filter.signoff-close" hidden>Close</button>
435
+ <button id="signoffReload" class="primary" data-command-id="filter.signoff-reload" hidden>Reload page</button>
436
+ </div>
437
+ </div>
438
+ </div>
439
+
361
440
  <!-- The Instructor seam. Classic, parser-inserted and BEFORE this page's own script on
362
441
  purpose: classic scripts run synchronously in document order while modules are deferred, so
363
442
  window.Commands is guaranteed to exist by the time anything below reads it.
@@ -370,12 +449,15 @@ body.publication-blocked #empty{position:static;flex:1}
370
449
  <script>window.InstructorReporter.mount({ surface: 'steel-filter' });</script>
371
450
 
372
451
  <script type="module">
373
- import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, liveOverlayElements, bgRect, textFontSize, applySelToFilter, hasUnsupportedSingleSheetFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, NOTE_TEXT } from './steel-filter-core.js';
452
+ import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, liveOverlayElements, bgRect, textFontSize, applySelToFilter, hasUnsupportedSingleSheetFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, dismissibleLayerNames, FACET_DIMS, FACET_DIM_BY_CONTROL, MODE_ORDER, facetKey, NOTE_TEXT } from './steel-filter-core.js';
374
453
 
375
454
  const APP_ID = new URLSearchParams(location.search).get('app') || '';
376
455
  // Workspaces use a project-keyed contract; an empty project id is the app-keyed workflow surface.
377
456
  const PROJECT = new URLSearchParams(location.search).get('project') || '';
378
457
  let revisionRequest = new URLSearchParams(location.search).get('revisionRequest') || '';
458
+ // Monotonic ownership for async Save results. The id alone cannot distinguish A→empty (A's own
459
+ // completion) from A→B→empty (B arrived and was then cleared while A was still in flight).
460
+ let revisionCheckpointGeneration = 0;
379
461
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
380
462
  const CONTRACT_QS = PROJECT ? (PROJECT_QS + '&quietMissing=1') : PROJECT_QS;
381
463
  const SVGNS = 'http://www.w3.org/2000/svg';
@@ -389,6 +471,7 @@ const overlay = document.getElementById('overlay');
389
471
  const bgImg = svg.querySelector('image.bg');
390
472
  const countEl = document.getElementById('count');
391
473
  const savedEl = document.getElementById('saved');
474
+ const saveRequiredStatus = document.getElementById('saveRequiredStatus');
392
475
  const saveBtn = document.getElementById('save');
393
476
 
394
477
  let C = null; // the full contract
@@ -403,6 +486,8 @@ let conflicted = false; // latched once a save is refused, so a second click do
403
486
  let sheets = []; // normalizeFilter(F).sheets — per-sheet geometry
404
487
  let active = 0; // index into sheets
405
488
  let parseWarned = false; // latch, so a broken stream cannot spam the console
489
+ let checkpointSaveBlocked = false; // a half-completed checkpoint must reload before it can be retried safely
490
+ let saveInFlight = false; // parent checkpoint polling must not re-enable Save during the queued write
406
491
 
407
492
  function setSaved(state){
408
493
  // The state→(class, label) map is `statChip` in steel-filter-core.js, where it is table-tested.
@@ -420,7 +505,7 @@ function setSaved(state){
420
505
  if(actionable){
421
506
  savedEl.setAttribute('role', 'button');
422
507
  savedEl.setAttribute('tabindex', '0');
423
- savedEl.setAttribute('aria-label', text + ' — show what changed');
508
+ savedEl.setAttribute('aria-label', text + (state === 'signoff-blocked' ? ' — show why the approval was refused' : ' — show what changed'));
424
509
  } else {
425
510
  savedEl.removeAttribute('role'); savedEl.removeAttribute('tabindex'); savedEl.removeAttribute('aria-label');
426
511
  }
@@ -455,10 +540,20 @@ function setSaved(state){
455
540
  let lastBanner; // the last DOCUMENT message, so the header chip can re-open a bar the user dismissed
456
541
  function showChangedBanner(message, opts){
457
542
  const kind = (opts && opts.kind) || 'document';
458
- const old = document.getElementById('conflictBanner'); if(old) old.remove();
543
+ const dismissible = !opts || opts.dismissible !== false;
544
+ const requiredRecovery = !!(opts && opts.requiredRecovery);
545
+ const old = document.getElementById('conflictBanner');
546
+ // A failed required checkpoint disables Save, so Reload is the only way forward. A later SSE
547
+ // reconnect/disconnect notice must not replace that action with a dismissible channel message.
548
+ if(old && old.dataset.requiredRecovery === 'true' && !requiredRecovery) return;
549
+ if(old) old.remove();
459
550
  if(kind === 'document') lastBanner = message;
460
551
  const bar = document.createElement('div');
461
552
  bar.id = 'conflictBanner';
553
+ bar.dataset.requiredRecovery = String(requiredRecovery);
554
+ bar.setAttribute('role', 'alert');
555
+ bar.setAttribute('aria-live', 'assertive');
556
+ bar.setAttribute('aria-atomic', 'true');
462
557
  // The bar keeps its saturated blue skin in BOTH themes — it is an alert, and it earns its prominence
463
558
  // by not being the page's own surface. Its SHADOW is themed, because that one is not a choice: an
464
559
  // 18px black glow thrown up a white page is the artifact, not the emphasis.
@@ -470,6 +565,7 @@ function showChangedBanner(message, opts){
470
565
  || 'This model changed somewhere else since you opened it — your save didn’t go through. '
471
566
  + 'Reload and reapply your changes.';
472
567
  const reload = document.createElement('button');
568
+ reload.setAttribute('data-command-id', 'filter.reload');
473
569
  reload.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
474
570
  reload.textContent = '↻ Reload';
475
571
  // No local draft in this surface, so a plain reload is already safe (unlike the steel editor, whose
@@ -482,6 +578,8 @@ function showChangedBanner(message, opts){
482
578
  // prompt remains the thing that stops silent data loss.
483
579
  reload.onclick = () => { if(kind === 'document') dirty = false; location.reload(); };
484
580
  const dismiss = document.createElement('button');
581
+ dismiss.setAttribute('data-command-id', 'filter.dismiss-message');
582
+ dismiss.setAttribute('aria-label', 'Dismiss message');
485
583
  dismiss.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
486
584
  dismiss.textContent = '✕';
487
585
  // Dismissing hides the bar but must not erase the FACT that the view is behind — otherwise the only
@@ -498,8 +596,11 @@ function showChangedBanner(message, opts){
498
596
  if(kind !== 'document') return;
499
597
  if(!savedEl.classList.contains('conflict') && !savedEl.classList.contains('err')) setSaved('stale');
500
598
  };
501
- bar.appendChild(msg); bar.appendChild(reload); bar.appendChild(dismiss);
599
+ bar.appendChild(msg); bar.appendChild(reload); if(dismissible) bar.appendChild(dismiss);
502
600
  document.body.appendChild(bar);
601
+ // A required checkpoint failure disables Save and leaves Reload as the only recovery. Announce the
602
+ // alert above, then put keyboard focus on that remaining action instead of stranding it on Save.
603
+ if(!dismissible) setTimeout(() => reload.focus(), 0);
503
604
  }
504
605
  // `.stat.conflict` ships `cursor:pointer` and, until now, nothing behind it — a control that looks clickable
505
606
  // and does nothing. Back it: clicking the cyan chip re-opens the document bar it belongs to. (In the 'Save
@@ -507,11 +608,108 @@ function showChangedBanner(message, opts){
507
608
  // no other route exists at all.) Keyboard-reachable because setSaved gives the actionable states
508
609
  // role=button + tabindex; a control only a mouse can reach is half a control.
509
610
  function reopenBanner(){ if(savedEl.classList.contains('conflict')) showChangedBanner(lastBanner); }
510
- savedEl.onclick = reopenBanner;
611
+ // One cyan chip, two explanations — route to whichever state it is actually carrying, or the chip
612
+ // becomes a control that re-opens the wrong thing.
613
+ function reopenChipExplanation(){ if(signoffOutcome) reopenSignOffProblem(); else reopenBanner(); }
614
+ savedEl.onclick = reopenChipExplanation;
511
615
  savedEl.addEventListener('keydown', e => {
512
- if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenBanner(); }
616
+ if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenChipExplanation(); }
513
617
  });
514
- function markDirty(){ dirty = true; saveBtn.disabled = false; setSaved('dirty'); }
618
+ function markDirty(){
619
+ dirty = true; saveBtn.disabled = checkpointSaveBlocked; setSaved('dirty');
620
+ if(revisionRequest) syncRequiredSaveCue();
621
+ }
622
+
623
+ function setRequiredSaveCue(checkpoint, ready){
624
+ saveBtn.classList.toggle('needs-save', ready);
625
+ saveRequiredStatus.hidden = !checkpoint;
626
+ saveRequiredStatus.textContent = ready ? 'Ready — press Save filter' : 'Select drawing lines first';
627
+ if(checkpoint){
628
+ saveBtn.setAttribute('aria-describedby', 'saveRequiredStatus');
629
+ saveBtn.setAttribute('data-tip', ready
630
+ ? 'Required next step: save this Drawing Filter, then return to the terminal AI that prepared it and tell it to continue'
631
+ : 'Select at least one drawing line in the filter before saving');
632
+ if(ready) saveBtn.removeAttribute('data-blocked-reason');
633
+ else saveBtn.setAttribute('data-blocked-reason', 'Select at least one drawing line in the Drawing Filter before saving.');
634
+ } else {
635
+ saveBtn.removeAttribute('aria-describedby');
636
+ saveBtn.removeAttribute('data-tip');
637
+ saveBtn.removeAttribute('data-blocked-reason');
638
+ }
639
+ }
640
+
641
+ function syncRequiredSaveCue(){
642
+ if(saveInFlight){ setRequiredSaveCue(false, false); saveBtn.disabled = true; return; }
643
+ if(checkpointSaveBlocked){ setRequiredSaveCue(false, false); saveBtn.disabled = true; return; }
644
+ const checkpoint = !!revisionRequest && !!C && !!F && !!sel && !conflicted;
645
+ const ready = checkpoint && sheets.some(sheet => (sheet.elements || []).some(el => matchesActive(el, mode, sel)));
646
+ setRequiredSaveCue(checkpoint, ready);
647
+ // The checkpoint always explains the next action, but only a non-empty selection can be saved.
648
+ // A valid prepared filter may already be ready; otherwise the first facet edit re-evaluates it.
649
+ if(checkpoint) saveBtn.disabled = !ready;
650
+ else saveBtn.disabled = !dirty && !conflicted;
651
+ }
652
+
653
+ // A checkpoint Save is two writes: first the exact Filter, then the request's "filter saved" receipt.
654
+ // Freeze every selection control across BOTH awaits so a click cannot change `sel` after the request body
655
+ // was serialized and then be incorrectly cleared by the successful response. Navigation outside this
656
+ // iframe remains available; only the editor whose snapshot is in flight becomes inert.
657
+ function setFilterEditingLocked(locked){
658
+ const app = document.getElementById('app');
659
+ const eye = document.getElementById('eye');
660
+ // The eyedropper is intentionally portalled outside #app so it can float over the canvas. Close it
661
+ // and lock that separate surface too; otherwise an already-open Add button can mutate `sel` after
662
+ // the contract body was serialized while the checkpoint receipt is still pending.
663
+ if(locked) closeEye();
664
+ // Save and the sign-off dialog are TWO independent lock owners. On a checkpoint refusal the
665
+ // `finally` below releases Save while the dialog deliberately stays open; clearing inert there
666
+ // exposed the whole editor behind an aria-modal surface. Leave modal-owned inert in place and let
667
+ // restoreSignoffBackground() restore the exact pre-dialog state when the dialog actually closes.
668
+ const signoff = document.getElementById('signoffOverlay');
669
+ const signoffOwnsLock = !!signoff && !signoff.hidden;
670
+ app.inert = !!locked || signoffOwnsLock;
671
+ eye.inert = !!locked || signoffOwnsLock;
672
+ if(locked) app.setAttribute('aria-busy', 'true');
673
+ else app.removeAttribute('aria-busy');
674
+ if(locked) eye.setAttribute('aria-busy', 'true');
675
+ else eye.removeAttribute('aria-busy');
676
+ }
677
+
678
+ // Same-origin parent bridge: polling may complete, fail, or clear a checkpoint while this editor has
679
+ // unsaved facet changes. Update only the checkpoint state and URL; never reload the document away.
680
+ window.__floRevisionCheckpoint = {
681
+ setRequest(value){
682
+ const nextRequest = String(value || '');
683
+ if(nextRequest !== revisionRequest){
684
+ revisionCheckpointGeneration += 1;
685
+ // The sign-off list belongs to the exact checkpoint that opened it. Keeping it visible after
686
+ // polling advances to another request would let an old list be approved against the new read
687
+ // when the layer names happen to match.
688
+ retireSignOffForCheckpointChange();
689
+ checkpointSaveBlocked = false;
690
+ // Reload-only recovery belongs to the exact checkpoint that failed. If polling advances,
691
+ // replaces, or clears that request, remove its stale alert before the new checkpoint can enable
692
+ // Save; otherwise the screen simultaneously says “Reload is the only way forward” and offers a
693
+ // working Save button. Preserve ordinary unsaved filter state for the new request.
694
+ const recovery = document.getElementById('conflictBanner');
695
+ if(recovery && recovery.dataset.requiredRecovery === 'true'){
696
+ recovery.remove();
697
+ lastBanner = undefined;
698
+ // `conflicted` belongs to checkpoint A's refused conditional write. Carrying it into B makes
699
+ // B look usable while every Save silently reopens A's vanished warning. Retire the latch with
700
+ // the exact required-recovery banner; an ordinary external-edit conflict remains untouched.
701
+ conflicted = false;
702
+ setSaved(dirty ? 'dirty' : '');
703
+ }
704
+ }
705
+ revisionRequest = nextRequest;
706
+ const url = new URL(location.href);
707
+ if(revisionRequest) url.searchParams.set('revisionRequest', revisionRequest);
708
+ else url.searchParams.delete('revisionRequest');
709
+ history.replaceState(null, '', url.pathname + url.search);
710
+ syncRequiredSaveCue();
711
+ },
712
+ };
515
713
 
516
714
  // ── Live updates: reacting to a write that did not come from this tab ──
517
715
  //
@@ -815,11 +1013,18 @@ function initFromFilter(){
815
1013
  // Facets are GLOBAL — one selection for every sheet. The producer (skill step 1b) MUST aggregate
816
1014
  // the UNION of layers/thicknesses/colors across all sheets here; a facet value present on a sheet
817
1015
  // but missing from these lists has no toggle, so its elements would silently stay hidden.
818
- buildFacet('layers', F.layers || [], 'name', it => it.name, it => it.name);
819
- buildFacet('thicknesses', F.thicknesses || [], 'w', it => it.w + ' pt', it => it.w);
820
- buildFacet('colors', F.colors || [], 'hex', it => it.hex, it => it.hex);
1016
+ buildFacet('layers', F.layers || [], it => it.name);
1017
+ // Labelled from the CANONICAL width, not the raw one: 0.123 and 0.124 are one value now, and a row
1018
+ // labelled "0.123 pt" that governs both would name a width the human is not deciding about. Layers
1019
+ // and colours keep their raw text — case-folding a hex does not make it a different colour, and the
1020
+ // row should still read as the drawing set recorded it.
1021
+ //
1022
+ // Through `thicknessLabel`, which handles the two ways a row can have no canonical width — see it.
1023
+ buildFacet('thicknesses', F.thicknesses || [], it => thicknessLabel(it.w));
1024
+ buildFacet('colors', F.colors || [], it => it.hex);
821
1025
  buildSheetSwitcher();
822
1026
  setSheet(active);
1027
+ syncRequiredSaveCue();
823
1028
  }
824
1029
 
825
1030
  // ── sheet switcher ──────────────────────────────────────────────────────────────────────────────
@@ -1023,20 +1228,239 @@ function hasRasterContext(){ return !!((sheets[active] && sheets[active].page) |
1023
1228
 
1024
1229
  function setOf(facet){ return facet === 'layers' ? sel.layers : facet === 'thicknesses' ? sel.thicknesses : sel.colors; }
1025
1230
 
1026
- function buildFacet(facet, items, valueKey, label, selValue){
1231
+ const FACET_NOUN = { layers: 'layer', thicknesses: 'thickness', colors: 'colour' };
1232
+
1233
+ /**
1234
+ * ONE sentence for a row whose value is not a value for its dimension — the hover tip, the
1235
+ * screen-reader description and Instructor's blocked reason are the same words, because three
1236
+ * wordings of one refusal is three things to keep in step.
1237
+ *
1238
+ * It says the tick will be CLEARED, not merely that the value is invalid: a stored `on: true` on such
1239
+ * a row is discarded on the next Save (the value can never enter the selection), and a human who is
1240
+ * told only "isn't valid" would not expect their saved flag to change underneath them.
1241
+ */
1242
+ const NO_VALUE_REASON = (facet) => 'This ' + FACET_NOUN[facet] + '’s value isn’t valid, so it can’t be selected — saving will clear its tick. It only happens on a hand-edited or third-party filter; ask your terminal AI to re-read the drawing to fix it.';
1243
+ /** The other way a picked value is unusable: it is well-formed, but this filter lists no row for it,
1244
+ * so nothing could persist it. Distinct copy, because the fix is different — the drawing set's
1245
+ * control lists are incomplete, not its values malformed. */
1246
+ const NO_ROW_REASON = (facet) => 'This ' + FACET_NOUN[facet] + ' isn’t in the filter’s list, so it can’t be ticked or saved. Ask your terminal AI to re-read the drawing so every value on the sheets gets a control.';
1247
+ let noValueSeq = 0;
1248
+
1249
+ /**
1250
+ * How a thickness reads on screen: the CANONICAL width, because that is the value being decided —
1251
+ * 0.123 and 0.124 are one value now, and a row labelled "0.123 pt" governing both names a width
1252
+ * nobody is choosing about.
1253
+ *
1254
+ * Two fallbacks, and they are different. A width that is not a NUMBER still has something to show, so
1255
+ * it shows that: the row is already refused by its dimming and its tooltip, and the label's remaining
1256
+ * job is to say WHICH row is being refused. A width that is absent entirely has nothing to show, and
1257
+ * "undefined pt" is not a value — it says the row is broken without saying anything the human can act
1258
+ * on. (Both were live: the first was caught by a real browser pass, the second by review, because
1259
+ * every test fixture had a `w` of some kind.)
1260
+ *
1261
+ * There is a THIRD case, and it is deliberately NOT handled here: `NaN` and `Infinity` are numbers, so
1262
+ * `facetKey` returns them and this renders "NaN pt" as an ordinary, tickable row. That is consistent
1263
+ * on purpose — the ledger's predicate selects on them too, so a row the panel refused would disagree
1264
+ * with the audit — and it is harmless downstream, because `isDismissibleFacetValue` refuses them and
1265
+ * the census `keyOf` refuses them, so such a value can never authorise a dismissal. It is also not
1266
+ * reachable from a stored contract: JSON carries neither literal. Making the panel reject them would
1267
+ * require a panel-only key rule, which is the producer/consumer split this whole slice removes.
1268
+ */
1269
+ function thicknessLabel(w){
1270
+ const key = facetKey('thickness', w);
1271
+ if(key !== undefined) return key + ' pt';
1272
+ return w === undefined || w === null ? 'No thickness recorded' : w + ' pt';
1273
+ }
1274
+ /** dim -> control name. DERIVED from the shared descriptor, never retyped: a hand-maintained second
1275
+ * copy of the mapping is the exact defect this slice exists to remove, one file over. */
1276
+ const FACET_CONTROL_OF = Object.fromEntries(MODE_ORDER.map(dim => [dim, FACET_DIMS[dim].control]));
1277
+
1278
+ /**
1279
+ * Which dimensions a picked element OFFERS a row for — APPLICABILITY, which is a different question
1280
+ * from whether the value can be added.
1281
+ *
1282
+ * Conflating the two hid exactly the refusal this slice exists to surface: requiring a usable
1283
+ * canonical key here meant a line with `w: "bad"` simply had no Thickness row, so nothing was
1284
+ * refused, nothing was explained, and "Add all" silently took two values of three.
1285
+ *
1286
+ * Thickness is INAPPLICABLE to text, and to a stroke whose canonical width is not above zero — a
1287
+ * hairline has no meaningful width and the Filter shows no `0 pt` row to add it to, so hiding it is
1288
+ * honest. A width that is not a NUMBER is a different case: the element HAS a stroke, so the row is
1289
+ * offered and then refused, with the reason attached.
1290
+ *
1291
+ * `NaN` and a negative width fall on the INAPPLICABLE side, because `width > 0` is false for both.
1292
+ * That is the same answer `eyedropperAdd`'s own `hasStroke` gives, so the popover never offers a row
1293
+ * the adder would skip — but unlike a malformed width it is hidden rather than explained. Left as is:
1294
+ * neither is reachable from a stored contract (JSON carries no `NaN`), and the alternative is a
1295
+ * fourth state on a popover that already has three.
1296
+ */
1297
+ function eyeOffers(el, dim){
1298
+ if(dim !== 'thickness') return true;
1299
+ if(el.kind === 'text') return false;
1300
+ const width = facetKey('thickness', el.w);
1301
+ return width === undefined || width > 0;
1302
+ }
1303
+ function eyeAddableDims(el){
1304
+ return ['layer', 'thickness', 'color'].filter(dim => eyeOffers(el, dim) && eyeAddable(el, dim));
1305
+ }
1306
+
1307
+ /**
1308
+ * Can this picked value actually be added — meaning, will it SURVIVE a save?
1309
+ *
1310
+ * Two conditions, and the second is easy to miss. The value must have a canonical key, and the filter
1311
+ * must carry a CONTROL ROW for it: `applySelToFilter` writes `on` flags onto rows and nothing else, so
1312
+ * a key with no row is silently dropped the moment the contract is written. Accepting one put a value
1313
+ * in the selection, changed the canvas and the "N selected" readout, and then left Save disabled —
1314
+ * a visible edit with no route to persistence and no warning, which `beforeunload` cannot even catch
1315
+ * because nothing was ever marked dirty.
1316
+ *
1317
+ * The producer is supposed to make this impossible (see the aggregate-the-union note in
1318
+ * `initFromFilter`), so a missing row is a producer bug — and refusing it loudly is how that bug
1319
+ * becomes visible instead of becoming a lost edit.
1320
+ */
1321
+ function eyeAddable(el, dim){
1322
+ const key = facetKey(dim, el[FACET_DIMS[dim].elementKey]);
1323
+ if(key === undefined) return false;
1324
+ return (F[FACET_DIMS[dim].control] || []).some(it => facetRowKey(FACET_DIMS[dim].control, it) === key);
1325
+ }
1326
+
1327
+ /**
1328
+ * THE one way this page reads a control row's facet value — the shared canonicaliser, indexed through
1329
+ * the shared descriptor (#805 Phase D slice D1).
1330
+ *
1331
+ * Every producer and consumer of the selection Set goes through it: this page's checkbox state,
1332
+ * All/None and the eyedropper, and core's `selFromFilter` / `matchesActive` / `applySelToFilter`. A
1333
+ * raw value read anywhere in that chain is not a near miss — a Set holding `#abc123` asked for
1334
+ * `#ABC123` answers "no", so the row renders ticked and Save writes it OFF, with no error and nothing
1335
+ * on screen to notice. `undefined` means the row's value is not a value for its dimension at all.
1336
+ */
1337
+ function facetRowKey(facet, it){
1338
+ const dim = FACET_DIM_BY_CONTROL[facet];
1339
+ return facetKey(dim, it[FACET_DIMS[dim].rowKey]);
1340
+ }
1341
+
1342
+ /**
1343
+ * Would Save write a different `on` than this facet's ROWS currently hold?
1344
+ *
1345
+ * The same expression `applySelToFilter` uses for those rows, deliberately — asking "did the
1346
+ * selection Set move" instead misses every edit that changes a persisted flag without changing the
1347
+ * Set: a stored tick on an unselectable row (which Save clears), and a row with no `on` at all
1348
+ * (which Save writes out).
1349
+ *
1350
+ * Named for what it measures, and NOT `saveWouldChange`: Save also persists `filter.mode`,
1351
+ * `F.sheets` and `F.active`, none of which this sees. Those are covered elsewhere — the mode
1352
+ * checkboxes mark dirty unconditionally, and switching sheets is navigation rather than an edit
1353
+ * (see `setSheet`). A name promising totality would invite the next caller to rely on one.
1354
+ */
1355
+ function facetOnWouldChange(facet){
1356
+ const s = setOf(facet);
1357
+ return (F[facet] || []).some(it => {
1358
+ const key = facetRowKey(facet, it);
1359
+ return it.on !== (key !== undefined && s.has(key));
1360
+ });
1361
+ }
1362
+
1363
+ /**
1364
+ * Tell the facet's bulk controls what they can actually do.
1365
+ *
1366
+ * `#eyeAddAll` was taught to say when it must drop a value; `all`/`none` run over the SAME
1367
+ * unselectable rows, are used far more, and said nothing — click "all", watch two of three rows tick,
1368
+ * and the control that half-failed offers no explanation. The refusal was reachable only by hovering
1369
+ * the row, not the control that just declined to act on it.
1370
+ *
1371
+ * The labels stay "all"/"none" — they are 4-character controls in a 300px panel and there is nowhere
1372
+ * to put a longer word — so the honesty rides on the tooltip and on `data-blocked-reason`, which is
1373
+ * what Instructor reads. When NOTHING in the list can be moved, they refuse outright.
1374
+ */
1375
+ function syncFacetBulk(facet){
1376
+ const items = F[facet] || [];
1377
+ const usable = items.filter(it => facetRowKey(facet, it) !== undefined).length;
1378
+ for(const attr of ['data-all', 'data-none']){
1379
+ const button = document.querySelector(`[${attr}="${facet}"]`);
1380
+ if(!button) continue;
1381
+ if(usable === items.length){
1382
+ button.removeAttribute('aria-disabled');
1383
+ button.removeAttribute('data-blocked-reason');
1384
+ button.removeAttribute('data-tip');
1385
+ continue;
1386
+ }
1387
+ const verb = attr === 'data-all' ? 'ticks' : 'unticks';
1388
+ const reason = usable === 0
1389
+ ? `No ${FACET_NOUN[facet]} in this list has a value the filter can use, so this does nothing. ${NO_VALUE_REASON(facet)}`
1390
+ : `This ${verb} the ${usable} usable ${FACET_NOUN[facet]}${usable === 1 ? '' : 's'} — ${items.length - usable} in this list ${items.length - usable === 1 ? 'has a value' : 'have values'} the filter can’t use.`;
1391
+ if(usable === 0) button.setAttribute('aria-disabled', 'true'); else button.removeAttribute('aria-disabled');
1392
+ button.setAttribute('data-blocked-reason', reason);
1393
+ button.setAttribute('data-tip', reason);
1394
+ }
1395
+ }
1396
+
1397
+ function buildFacet(facet, items, label){
1398
+ const dim = FACET_DIM_BY_CONTROL[facet];
1027
1399
  const box = document.querySelector(`#facet-${facet} .opts`);
1028
1400
  box.replaceChildren();
1029
1401
  for(const it of items){
1030
- const val = it[valueKey];
1402
+ const val = it[FACET_DIMS[dim].rowKey];
1403
+ const key = facetRowKey(facet, it);
1031
1404
  const isText = facet === 'layers' && it.drawable === false;
1032
1405
  const wrap = document.createElement('label');
1033
1406
  wrap.setAttribute('data-command-id', 'filter.facet-toggle');
1034
- if(isText) wrap.className = 'textlayer';
1407
+ // The no-value case is tested BEFORE `isText` on purpose: a layer row can be both undrawable and
1408
+ // wrong-typed, and if .textlayer won it would render as an ordinary muted row with a checkbox that
1409
+ // silently refuses to stay ticked and no explanation — this slice's own defect, relocated.
1410
+ //
1411
+ // The tip rides on the LABEL, never on the input: a disabled control does not reliably fire
1412
+ // pointerover, so a data-tip on the checkbox would simply never render. The label wraps the row.
1413
+ if(key === undefined){
1414
+ wrap.className = 'novalue';
1415
+ wrap.setAttribute('data-tip', NO_VALUE_REASON(facet));
1416
+ } else if(isText) wrap.className = 'textlayer';
1035
1417
  const cb = document.createElement('input');
1036
1418
  cb.type = 'checkbox';
1037
- cb.checked = setOf(facet).has(selValue(it));
1419
+ cb.checked = key !== undefined && setOf(facet).has(key);
1038
1420
  cb.value = String(val);
1039
- cb.addEventListener('change', () => { const s = setOf(facet); cb.checked ? s.add(selValue(it)) : s.delete(selValue(it)); markDirty(); apply(); });
1421
+ // syncFacetChecks(), not just this one box: two rows whose values canonicalise the same (a
1422
+ // `#ABC123` beside a `#abc123`) are ONE selection value, so the sibling must move with it rather
1423
+ // than sit stale until the next rebuild. A no-op on every filter our own extractor produces.
1424
+ // `aria-disabled`, NOT the `disabled` property, and the difference is the whole point.
1425
+ //
1426
+ // A truly disabled input is out of the tab order and fires no pointer events, so nothing can
1427
+ // reach it: Instructor's `focusFor` resolves UPWARD from the hovered/focused element
1428
+ // (`closest('button, …, input, …')` in web/instructor.js), and from a `<label>` carrier it cannot
1429
+ // descend into the box. `disabled` here meant the state was set and no reader existed — a record
1430
+ // nobody could read, which is this epic's own failure shape in miniature. `aria-disabled` keeps
1431
+ // the control focusable and hoverable, so `focusFor` lands ON it and reads exactly the two things
1432
+ // it looks for: `target.getAttribute('aria-disabled') === 'true'` and `data-blocked-reason`.
1433
+ //
1434
+ // It also fixes the modality gap: a `data-tip` renders on pointerover only, so a keyboard or
1435
+ // screen-reader user got nothing. `aria-describedby` points at a real node carrying the same
1436
+ // sentence, and the row stays reachable by Tab to hear it.
1437
+ //
1438
+ // The cost is that a click still toggles the box natively, so the handler puts it back. Refusing
1439
+ // visibly beats refusing silently — and the reason is one hover, one Tab or one `?` away.
1440
+ if(key === undefined){
1441
+ const why = document.createElement('span');
1442
+ why.className = 'sr-only';
1443
+ why.id = 'novalue-' + facet + '-' + noValueSeq++;
1444
+ why.textContent = NO_VALUE_REASON(facet);
1445
+ cb.setAttribute('aria-disabled', 'true');
1446
+ cb.setAttribute('aria-describedby', why.id);
1447
+ cb.setAttribute('data-blocked-reason', NO_VALUE_REASON(facet));
1448
+ // Snap the box back, and mark dirty when the row's STORED flag disagrees with what Save will
1449
+ // write. Otherwise the refusal copy promises "saving will clear its tick" on a page whose Save
1450
+ // button nothing can enable.
1451
+ cb.addEventListener('change', () => { cb.checked = false; if(facetOnWouldChange(facet)) markDirty(); });
1452
+ // Appended to the LIST, not to the row. A <label> wrapping an input contributes its text to that
1453
+ // input's accessible NAME, and `.sr-only` clips a node visually without removing it from the
1454
+ // accname computation - so parking the sentence inside `wrap` made the checkbox announce the
1455
+ // whole refusal as its name, then `aria-describedby` read it out a second time, with the value
1456
+ // the user is actually looking at arriving last. `aria-describedby` resolves document-wide, so
1457
+ // a sibling works and announces once, as a description.
1458
+ box.appendChild(why);
1459
+ }
1460
+ else cb.addEventListener('change', () => { const s = setOf(facet); cb.checked ? s.add(key) : s.delete(key); syncFacetChecks(); markDirty(); apply(); });
1461
+ // NOTE: the per-row handler always marks dirty — a click on a live row IS an edit, even when the
1462
+ // resulting flag matches what was stored (the user re-ticked what they just unticked). Only the
1463
+ // bulk controls need `saveWouldChange`, because only they can run over rows they cannot move.
1040
1464
  wrap.appendChild(cb);
1041
1465
  if(facet === 'layers'){
1042
1466
  const sw = document.createElement('span'); sw.className = 'sw';
@@ -1048,9 +1472,16 @@ function buildFacet(facet, items, valueKey, label, selValue){
1048
1472
  wrap.appendChild(sw);
1049
1473
  }
1050
1474
  wrap.appendChild(document.createTextNode(' ' + label(it) + ' '));
1051
- const c = document.createElement('em'); c.textContent = it.count; wrap.appendChild(c);
1475
+ const c = document.createElement('em'); c.textContent = it.count;
1476
+ // The count spans the WHOLE drawing set — schedule and detail sheets included — while the canvas
1477
+ // stat chip counts only what is shown on THIS sheet. Two numbers that count different things are
1478
+ // on screen together, so the one that is not obvious carries the explanation. data-tip, never
1479
+ // title=. (The sign-off step says the same thing about the same number.)
1480
+ c.setAttribute('data-tip', 'Elements on this ' + FACET_NOUN[facet] + ' across the whole drawing set — every sheet, and lines, text and circles alike — not just the sheet on screen.');
1481
+ wrap.appendChild(c);
1052
1482
  box.appendChild(wrap);
1053
1483
  }
1484
+ syncFacetBulk(facet);
1054
1485
  }
1055
1486
 
1056
1487
  function syncFacetChecks(){
@@ -1059,8 +1490,8 @@ function syncFacetChecks(){
1059
1490
  const cbs = document.querySelectorAll(`#facet-${facet} input[type=checkbox]`);
1060
1491
  cbs.forEach((cb, i) => {
1061
1492
  const it = items[i]; if(!it) return;
1062
- const v = facet === 'thicknesses' ? it.w : (facet === 'layers' ? it.name : it.hex);
1063
- cb.checked = setOf(facet).has(v);
1493
+ const key = facetRowKey(facet, it);
1494
+ cb.checked = key !== undefined && setOf(facet).has(key);
1064
1495
  });
1065
1496
  }
1066
1497
  }
@@ -1093,13 +1524,34 @@ document.querySelectorAll('input[name=dim]').forEach(cb => cb.addEventListener('
1093
1524
  mode = canonicalMode([...document.querySelectorAll('input[name=dim]:checked')].map(c => c.value));
1094
1525
  markDirty(); apply();
1095
1526
  }));
1096
- document.querySelectorAll('[data-all]').forEach(b => b.addEventListener('click', () => setAllFacet(b.dataset.all, true)));
1097
- document.querySelectorAll('[data-none]').forEach(b => b.addEventListener('click', () => setAllFacet(b.dataset.none, false)));
1527
+ // KNOWING EQUIVALENT MUTANT (both lines): removing the `aria-disabled` guard turns no test red. It is
1528
+ // set only when NO row in the list has a usable key, and `setAllFacet` skips exactly those rows — so
1529
+ // the handler is a provable no-op in the only state the guard fires in. Kept because a control that
1530
+ // says it will do nothing should not run its handler, and recorded here so the next person reading a
1531
+ // sweep can tell it from an untested branch. The gate a user can observe is the `aria-disabled` and
1532
+ // the reason set by `syncFacetBulk`, both of which ARE tested.
1533
+ document.querySelectorAll('[data-all]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.all, true); }));
1534
+ document.querySelectorAll('[data-none]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.none, false); }));
1098
1535
  function setAllFacet(facet, on){
1099
1536
  const s = setOf(facet);
1100
1537
  const items = F[facet] || [];
1101
- for(const it of items){ const v = facet === 'thicknesses' ? it.w : (facet === 'layers' ? it.name : it.hex); on ? s.add(v) : s.delete(v); }
1102
- syncFacetChecks(); markDirty(); apply();
1538
+ // CANONICAL keys, exactly as the per-row handler and the eyedropper add them. Adding a raw value
1539
+ // here was the concrete regression this slice exists to prevent: All ticks the box, Save writes OFF.
1540
+ // A row with no canonical key is skipped — it is not selectable at all, and its checkbox is disabled.
1541
+ // An All that alters nothing must not claim an unsaved edit: on a list whose rows are ALL
1542
+ // unselectable, an unconditional markDirty() made All and None produce the identical outcome — no
1543
+ // visible change plus an "Unsaved ●" chip — which is exactly the report a user cannot tell a working
1544
+ // control from a broken one by.
1545
+ //
1546
+ // But "did the SET move" is the wrong question, and asking it hid two real edits. A row whose value
1547
+ // has no canonical key carries a stored `on` that Save is about to CLEAR — the refusal copy promises
1548
+ // exactly that — and a row with no `on` at all carries a load-time default Save is about to write
1549
+ // explicitly. Neither moves the Set, so neither enabled Save, and on an all-unselectable facet the
1550
+ // promise "saving will clear its tick" had no route to a save at all.
1551
+ //
1552
+ // So the question is the honest one: would Save write a different `on` than the row holds now?
1553
+ for(const it of items){ const key = facetRowKey(facet, it); if(key !== undefined){ on ? s.add(key) : s.delete(key); } }
1554
+ syncFacetChecks(); if(facetOnWouldChange(facet)) markDirty(); apply();
1103
1555
  }
1104
1556
 
1105
1557
  // --- eyedropper: pick a line/label -> popover, + Add each / Add all ---
@@ -1109,25 +1561,80 @@ function openEyedropper(clientX, clientY, el){
1109
1561
  eyeEl = el;
1110
1562
  const body = document.getElementById('eyeBody');
1111
1563
  const rows = [];
1112
- rows.push(eyeRow('Layer', el.layer, 'layer', `<span class="sw" style="background:${safeColor(layerColor[el.layer])}"></span>`));
1113
- if(el.kind !== 'text' && el.w > 0) rows.push(eyeRow('Thickness', el.w + ' pt', 'thickness', ''));
1114
- rows.push(eyeRow('Color', el.color, 'color', `<span class="sw" style="background:${safeColor(el.color)}"></span>`));
1564
+ // A picked element whose value is not a value for its dimension cannot be added — `eyedropperAdd`
1565
+ // skips it. The checkbox in the panel REFUSES VISIBLY for the same value, so a + Add that quietly
1566
+ // did nothing would be the same refusal on two surfaces with only one of them honest.
1567
+ const addable = (dim) => eyeAddable(el, dim);
1568
+ const dropped = ['layer', 'thickness', 'color'].filter(dim => eyeOffers(el, dim) && !addable(dim));
1569
+ const whyBlocked = (dim) => facetKey(dim, el[FACET_DIMS[dim].elementKey]) === undefined
1570
+ ? NO_VALUE_REASON(FACET_CONTROL_OF[dim]) : NO_ROW_REASON(FACET_CONTROL_OF[dim]);
1571
+ rows.push(eyeRow('Layer', el.layer, 'layer', `<span class="sw" style="background:${safeColor(layerColor[el.layer])}"></span>`, addable('layer'), whyBlocked('layer')));
1572
+ // Offered when applicable, refused when unusable — the same two-step as layer and colour.
1573
+ if(eyeOffers(el, 'thickness')) rows.push(eyeRow('Thickness', thicknessLabel(el.w), 'thickness', '', addable('thickness'), whyBlocked('thickness')));
1574
+ rows.push(eyeRow('Color', el.color, 'color', `<span class="sw" style="background:${safeColor(el.color)}"></span>`, addable('color'), whyBlocked('color')));
1115
1575
  body.innerHTML = rows.join('');
1116
- body.querySelectorAll('button[data-add]').forEach(b => b.onclick = () => { eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEye(); });
1576
+ body.querySelectorAll('button[data-add]:not([aria-disabled])').forEach(b => b.onclick = () => { eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEye(); });
1577
+ // The Add-all control tells the truth about what it is about to do — including refusing outright
1578
+ // when the pick offers nothing this filter can express.
1579
+ const addAll = document.getElementById('eyeAddAll');
1580
+ const addableCount = eyeAddableDims(el).length;
1581
+ addAll.textContent = addableCount === 0 ? 'Add all to filter'
1582
+ : dropped.length ? 'Add the ' + addableCount + ' usable value' + (addableCount === 1 ? '' : 's')
1583
+ : 'Add all to filter';
1584
+ if(addableCount === 0){
1585
+ addAll.setAttribute('aria-disabled', 'true');
1586
+ addAll.setAttribute('data-blocked-reason', whyBlocked(dropped[0]));
1587
+ addAll.setAttribute('data-tip', whyBlocked(dropped[0]));
1588
+ } else {
1589
+ addAll.removeAttribute('aria-disabled');
1590
+ addAll.removeAttribute('data-blocked-reason');
1591
+ if(dropped.length) addAll.setAttribute('data-tip', whyBlocked(dropped[0]));
1592
+ else addAll.removeAttribute('data-tip');
1593
+ }
1117
1594
  eye.classList.add('show');
1118
1595
  const w = eye.offsetWidth || 220, h = eye.offsetHeight || 160;
1119
1596
  eye.style.left = Math.min(clientX + 8, window.innerWidth - w - 8) + 'px';
1120
1597
  eye.style.top = Math.min(clientY + 8, window.innerHeight - h - 8) + 'px';
1121
1598
  }
1122
- function eyeRow(k, v, which, swatch){
1599
+ function eyeRow(k, v, which, swatch, addable, reason){
1123
1600
  // data-tip, never title=: .v ellipsizes, so this row NEEDS a tooltip to show a long layer name in
1124
1601
  // full — and a native title= would draw it as the light OS bubble, the one browser default this
1125
1602
  // surface still leaked. The themed #tooltip handler at the foot of this file renders it.
1126
- return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-add="${which}" data-command-id="filter.eyedropper-add">+ Add</button></div>`;
1603
+ //
1604
+ // `aria-disabled` rather than `disabled`, for the same reason the facet checkbox uses it: a
1605
+ // disabled button is unreachable by hover, Tab and Instructor alike, so the refusal would carry no
1606
+ // explanation on any modality. The click handler is simply not bound to it.
1607
+ const why = reason || NO_VALUE_REASON(FACET_CONTROL_OF[which]);
1608
+ const blocked = addable ? '' : ` aria-disabled="true" data-blocked-reason="${esc(why)}" data-tip="${esc(why)}"`;
1609
+ return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-add="${which}" data-command-id="filter.eyedropper-add"${blocked}>+ Add</button></div>`;
1127
1610
  }
1128
1611
  function closeEye(){ eye.classList.remove('show'); eyeEl = null; }
1129
1612
  document.getElementById('eyeClose').onclick = closeEye;
1130
- document.getElementById('eyeAddAll').onclick = () => { if(eyeEl){ eyedropperAdd(sel, eyeEl, 'all'); syncFacetChecks(); markDirty(); apply(); } closeEye(); };
1613
+ // "Add all" is the THIRD surface this refusal has to be honest on, and it was the one left dishonest:
1614
+ // the per-dimension + Add buttons refuse visibly while this one stayed enabled and quietly added two
1615
+ // of three — or, for an element with nothing addable, closed the popover having changed nothing and
1616
+ // raised an "Unsaved ●" chip anyway. That is verbatim the failure `setAllFacet` above exists to fix.
1617
+ //
1618
+ // So it is gated on whether ANY offered dimension is addable, it says which one it is dropping when it
1619
+ // cannot take them all, and it marks dirty only when it actually added something.
1620
+ document.getElementById('eyeAddAll').onclick = () => {
1621
+ if(eyeEl && eyeAddableDims(eyeEl).length){
1622
+ // Per DIMENSION, never `'all'`. `eyedropperAdd`'s own `'all'` adds every value with a canonical
1623
+ // key, and it cannot know which of them this filter lists a row for — so it would add exactly the
1624
+ // unsaveable value the button has just said it is dropping. Adding what was advertised, and only
1625
+ // that, is what makes the label true.
1626
+ for(const dim of eyeAddableDims(eyeEl)) eyedropperAdd(sel, eyeEl, dim);
1627
+ // The SAME question setAllFacet asks, for the same reason: adding a value that is already ticked
1628
+ // changes nothing, and a pick with nothing addable changes nothing at all — neither is an edit.
1629
+ syncFacetChecks(); if(['layers','thicknesses','colors'].some(facetOnWouldChange)) markDirty(); apply();
1630
+ }
1631
+ // KNOWING EQUIVALENT MUTANT: dropping the `eyeAddableDims(...).length` guard turns no test red,
1632
+ // because `eyedropperAdd` skips every unusable value anyway and `saveWouldChange` then reports no
1633
+ // edit — the call is a provable no-op. It is kept as defence in depth and to state the intent, and
1634
+ // recorded here so the next person reading a sweep can tell it from an untested branch. The gate
1635
+ // that a user can actually observe is the `aria-disabled` + reason set in `openEyedropper`.
1636
+ closeEye();
1637
+ };
1131
1638
 
1132
1639
  // --- pan/zoom via viewBox; a click (no drag) on an element opens the eyedropper ---
1133
1640
  let base = { x:0, y:0, w:1000, h:1000 }, vb = { ...base }, drag = null;
@@ -1167,7 +1674,7 @@ document.getElementById('fit2').onclick = fit;
1167
1674
  document.getElementById('zoomsteel2').onclick = zoomSteel;
1168
1675
 
1169
1676
  // --- save: write the selection + mode onto C.filter and PUT the contract ---
1170
- saveBtn.onclick = save;
1677
+ saveBtn.onclick = () => { void beginSave(); };
1171
1678
  // Serialize THIS tab's writes, as the steel editor does. Without it the page conflicts with ITSELF:
1172
1679
  // markDirty() re-enables Save while a save is in flight, so a second click sent a second PUT carrying the
1173
1680
  // SAME If-Match tag — one won, the other came back 412 and latched a conflict caused by nobody but the user.
@@ -1178,6 +1685,238 @@ saveBtn.onclick = save;
1178
1685
  let writeQueue = Promise.resolve();
1179
1686
  const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
1180
1687
  function save(){ return queueWrite(saveNow); }
1688
+ function blockRequiredCheckpointSave(message){
1689
+ checkpointSaveBlocked = true;
1690
+ setSaved('err');
1691
+ setRequiredSaveCue(false, false);
1692
+ saveBtn.disabled = true;
1693
+ showChangedBanner(message, { dismissible:false, requiredRecovery:true });
1694
+ }
1695
+
1696
+ /* ── the layer sign-off confirm step ────────────────────────────────────────────────
1697
+ A layer switched OFF is one whose every element the completion proof may dismiss as a group, with
1698
+ no line-by-line reason. So for a revision read, Save first shows the human exactly that list and
1699
+ asks them to approve it; the ordered names ride out with the Save and the server records the
1700
+ approval against them. No OFF layers means nothing is being dismissed wholesale, so there is no
1701
+ decision to record and the step is skipped entirely rather than shown empty. */
1702
+ let signoffNames = []; // the ordered list currently displayed and about to be submitted
1703
+ let pendingSignOff = null; // handed to saveNow for exactly one checkpoint POST
1704
+ let signoffOutcome = null; // a 409 code from the checkpoint, for the notice below
1705
+ let signoffBusy = false; // a write is in flight: dismissal is locked
1706
+ const signoffOverlay = document.getElementById('signoffOverlay');
1707
+ const signoffPanel = document.getElementById('signoffPanel');
1708
+ const signoffList = document.getElementById('signoffList');
1709
+ const signoffNotice = document.getElementById('signoffNotice');
1710
+ const signoffCancel = document.getElementById('signoffCancel');
1711
+ const signoffApprove = document.getElementById('signoffApprove');
1712
+ const signoffCloseBtn = document.getElementById('signoffClose');
1713
+ const signoffReload = document.getElementById('signoffReload');
1714
+ const SIGNOFF_APPROVE_LABEL = 'Approve these layers as not steel';
1715
+
1716
+ /** What the human is told when the server refuses the approval. Both cases open by saying the filter
1717
+ * edit is safe, because it literally is: the contract PUT has already committed by the time the
1718
+ * checkpoint can refuse, and only the checkpoint and the approval are withheld. */
1719
+ const SIGNOFF_PROBLEMS = {
1720
+ 'steel-layer-signoff-stale': {
1721
+ title: 'The layer list changed since you approved it',
1722
+ body: 'Your filter changes were saved. This page is now showing an out-of-date list, so approving it again would be refused for the same reason — reload to see the current layers and approve those.',
1723
+ },
1724
+ 'steel-census-scope-missing': {
1725
+ title: 'This read can’t record a layer approval yet',
1726
+ body: 'Your filter changes were saved. This request’s drawing scan was made before layer approval existed and covers only the model sheets — ask your terminal AI to re-read this revision, then reload and approve the list.',
1727
+ },
1728
+ };
1729
+
1730
+ /**
1731
+ * The counts shown are `filter.layers[].count`: every element on that layer across the drawing set,
1732
+ * text and circles included, and NOT split by page role. Labelled for exactly that, because the
1733
+ * honest number is the one the human is deciding against.
1734
+ *
1735
+ * Takes the count ONCE per name, never a sum across rows. Summing was right while each row carried
1736
+ * its own partial tally, and became wrong the moment `mergeWholeSetLayerCensus` started stamping the
1737
+ * GROUP's whole-set count onto every row of a canonical group: two rows for one layer then each
1738
+ * reported the whole population, and adding them doubled it. That number is what a human reads on the
1739
+ * sign-off modal at the moment they authorise a wholesale dismissal, so an inflated one is exactly
1740
+ * the kind of wrong this surface cannot afford. (Two individually-correct changes that were jointly
1741
+ * wrong — found by review, not by a test, because no fixture had a duplicated name.)
1742
+ *
1743
+ * `Number.isFinite` still gates: a junk count is not a count, and `null` renders as "element count
1744
+ * unknown" rather than a number nobody can trust.
1745
+ */
1746
+ function layerElementCount(name){
1747
+ for(const row of (F && F.layers) || []) if(row && row.name === name && Number.isFinite(row.count)) return row.count;
1748
+ return null;
1749
+ }
1750
+
1751
+ function setSignoffMode(problem){
1752
+ const failed = !!problem;
1753
+ signoffNotice.hidden = !failed;
1754
+ signoffList.hidden = failed;
1755
+ signoffCancel.hidden = failed; signoffApprove.hidden = failed;
1756
+ signoffCloseBtn.hidden = !failed; signoffReload.hidden = !failed;
1757
+ if(!failed) return;
1758
+ // Neither refusal can be cleared by pressing Approve again, so the approve pair is REPLACED rather
1759
+ // than left on screen as a false affordance.
1760
+ const copy = SIGNOFF_PROBLEMS[problem];
1761
+ signoffNotice.textContent = '';
1762
+ const heading = document.createElement('b'); heading.textContent = copy.title;
1763
+ const body = document.createElement('p'); body.textContent = copy.body;
1764
+ signoffNotice.append(heading, body);
1765
+ // Approve held focus when it was pressed, and it has just been HIDDEN — leaving focus on a hidden
1766
+ // control drops it on <body>. Reload is the only action that can make this checkpoint retryable, so
1767
+ // put focus there; Close remains available only to dismiss the explanation.
1768
+ signoffReload.focus();
1769
+ }
1770
+
1771
+ let signoffCoveredSurfaces = [];
1772
+ function coverSignoffBackground(){
1773
+ if(signoffCoveredSurfaces.length) return;
1774
+ signoffCoveredSurfaces = ['app', 'eye'].map((id) => document.getElementById(id)).filter(Boolean).map((element) => ({
1775
+ element,
1776
+ hadInert: element.hasAttribute('inert'),
1777
+ ariaHidden: element.getAttribute('aria-hidden'),
1778
+ }));
1779
+ for(const { element } of signoffCoveredSurfaces){
1780
+ element.setAttribute('inert', '');
1781
+ element.setAttribute('aria-hidden', 'true');
1782
+ }
1783
+ }
1784
+ function restoreSignoffBackground(){
1785
+ for(const { element, hadInert, ariaHidden } of signoffCoveredSurfaces){
1786
+ // The Save transaction may still own this lock when polling retires the dialog's checkpoint.
1787
+ // Release only the dialog's share; saveNow.finally performs the last unlock after both writes.
1788
+ if(!hadInert && !saveInFlight) element.removeAttribute('inert');
1789
+ else element.setAttribute('inert', '');
1790
+ if(ariaHidden === null) element.removeAttribute('aria-hidden');
1791
+ else element.setAttribute('aria-hidden', ariaHidden);
1792
+ }
1793
+ signoffCoveredSurfaces = [];
1794
+ }
1795
+
1796
+ function openSignOff(names){
1797
+ signoffNames = names;
1798
+ signoffList.textContent = '';
1799
+ for(const name of names){
1800
+ const count = layerElementCount(name);
1801
+ const row = document.createElement('li'); row.className = 'signoff-row';
1802
+ const label = document.createElement('span'); label.className = 'signoff-name';
1803
+ // data-tip, never title=: .signoff-name ellipsizes, so a long layer name needs the themed tooltip.
1804
+ label.textContent = name; label.setAttribute('data-tip', name);
1805
+ const shown = document.createElement('span'); shown.className = 'signoff-count';
1806
+ shown.textContent = count === null ? 'element count unknown' : count.toLocaleString() + ' element' + (count === 1 ? '' : 's') + ' on this layer';
1807
+ shown.setAttribute('data-tip', 'Every element on this layer across the whole drawing set — lines, text and circles — not only the framing linework.');
1808
+ row.append(label, shown);
1809
+ signoffList.append(row);
1810
+ }
1811
+ setSignoffMode(null);
1812
+ coverSignoffBackground();
1813
+ signoffOverlay.hidden = false;
1814
+ // Cancel takes focus, not Approve: a stray Enter must not fire the consequential action before the
1815
+ // list has been read.
1816
+ signoffCancel.focus();
1817
+ }
1818
+
1819
+ function closeSignOff(){
1820
+ if(signoffOverlay.hidden) return;
1821
+ signoffOverlay.hidden = true;
1822
+ restoreSignoffBackground();
1823
+ signoffNames = [];
1824
+ // A refusal is not resolved by dismissing its explanation. Leave the header carrying the state, as
1825
+ // a control that brings the explanation back — the same cyan "non-default, click to act" chip the
1826
+ // page already uses for a write conflict.
1827
+ if(signoffOutcome) setSaved('signoff-blocked');
1828
+ // Focus must never be dropped on <body>. Save is DISABLED the instant a save succeeds and a
1829
+ // disabled control cannot take focus, so the fallback is the layer list the user came from — which
1830
+ // is also where they would go next to change what is ticked. (A real browser pass caught this:
1831
+ // returning focus to Save is right on Cancel and wrong on the success path.)
1832
+ // `:not([aria-disabled])`, and then ANY facet row: the first layer row can now be an unselectable
1833
+ // one, and a row that refuses input is not somewhere to leave the user. `:not(.dim)` too — a facet
1834
+ // whose dimension is unchecked carries `pointer-events:none; opacity:.4`, so a box inside it is
1835
+ // focusable but visually and pointer-inert, which is a worse landing spot than it looks. The mode
1836
+ // checkboxes are the last resort — always present, never dimmed — because the rule is never to drop
1837
+ // focus on <body>.
1838
+ const back = saveBtn.disabled
1839
+ ? (document.querySelector('#facet-layers:not(.dim) .opts input:not([aria-disabled])')
1840
+ || document.querySelector('.facet:not(.dim) .opts input:not([aria-disabled])')
1841
+ || document.querySelector('input[name=dim]'))
1842
+ : saveBtn;
1843
+ if(back) back.focus();
1844
+ }
1845
+
1846
+ /** Retire a checkpoint-owned decision surface when polling replaces that checkpoint. */
1847
+ function retireSignOffForCheckpointChange(){
1848
+ const wasVisible = !signoffOverlay.hidden;
1849
+ signoffOverlay.hidden = true;
1850
+ restoreSignoffBackground();
1851
+ signoffNames = [];
1852
+ pendingSignOff = null;
1853
+ signoffOutcome = null;
1854
+ // A dismissed refusal is hidden but still checkpoint-owned: closeSignOff deliberately preserves
1855
+ // signoffOutcome so its status chip can reopen the explanation. A replacement must retire that state
1856
+ // too, without moving focus when no dialog is currently on screen.
1857
+ if(!wasVisible) return;
1858
+ // The replacement request's cue is painted later in the same turn. Move focus after that paint so
1859
+ // a keyboard user does not remain parked on a control inside the now-hidden dialog.
1860
+ setTimeout(() => {
1861
+ const target = saveBtn.disabled ? saveRequiredStatus : saveBtn;
1862
+ if(target && !target.hidden) target.focus();
1863
+ }, 0);
1864
+ }
1865
+
1866
+ function setSignoffBusy(busy){
1867
+ signoffBusy = busy;
1868
+ signoffCancel.disabled = busy; signoffApprove.disabled = busy;
1869
+ signoffApprove.textContent = busy ? 'Saving…' : SIGNOFF_APPROVE_LABEL;
1870
+ }
1871
+
1872
+ async function approveSignOff(){
1873
+ if(signoffBusy) return;
1874
+ setSignoffBusy(true);
1875
+ pendingSignOff = signoffNames.slice();
1876
+ signoffOutcome = null;
1877
+ try { await save(); } finally { setSignoffBusy(false); pendingSignOff = null; }
1878
+ // A checkpoint refusal keeps the modal open and explains itself. Anything else (a 412 conflict, a
1879
+ // 428, a dropped connection) is a document-level failure the page's own chip and banner already
1880
+ // explain — duplicating that inside the modal would fork one failure into two stories.
1881
+ if(signoffOutcome) setSignoffMode(signoffOutcome); else closeSignOff();
1882
+ }
1883
+
1884
+ /** Bring the refusal explanation back — the chip is the only route once the dialog is dismissed. */
1885
+ function reopenSignOffProblem(){
1886
+ if(!signoffOutcome) return;
1887
+ coverSignoffBackground();
1888
+ signoffOverlay.hidden = false;
1889
+ setSignoffMode(signoffOutcome);
1890
+ }
1891
+ signoffApprove.onclick = () => { void approveSignOff(); };
1892
+ signoffCancel.onclick = () => { if(!signoffBusy) closeSignOff(); };
1893
+ signoffCloseBtn.onclick = closeSignOff;
1894
+ signoffReload.onclick = () => location.reload();
1895
+ signoffOverlay.addEventListener('pointerdown', (e) => { if(e.target === signoffOverlay && !signoffBusy) closeSignOff(); });
1896
+ signoffPanel.addEventListener('keydown', (e) => {
1897
+ if(e.key === 'Escape' && !signoffBusy){ e.preventDefault(); closeSignOff(); return; }
1898
+ if(e.key !== 'Tab') return;
1899
+ // A real trap over the VISIBLE actions — the two hidden ones belong to the other state.
1900
+ const stops = [signoffCancel, signoffApprove, signoffCloseBtn, signoffReload].filter((b) => !b.hidden && !b.disabled);
1901
+ if(!stops.length) return;
1902
+ const first = stops[0], last = stops[stops.length - 1];
1903
+ if(e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
1904
+ else if(!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
1905
+ });
1906
+
1907
+ /** Save's entry point: write the live selection onto the filter, then confirm the dismissals first. */
1908
+ async function beginSave(){
1909
+ // `!sel` (not just `!F`) for the same reason saveNow checks it — an empty state can carry a truthy
1910
+ // filter with nothing rendered.
1911
+ if(!C || !F || !sel) return;
1912
+ if(conflicted){ showChangedBanner(); return; }
1913
+ applySelToFilter(F, sel, mode);
1914
+ // Only a revision read records an approval, and only when something is actually being dismissed.
1915
+ const names = revisionRequest ? dismissibleLayerNames(F) : [];
1916
+ if(!names.length){ pendingSignOff = null; await save(); return; }
1917
+ openSignOff(names);
1918
+ }
1919
+
1181
1920
  async function saveNow(){
1182
1921
  // `!sel` (not just `!F`) is the honest gate: an empty state can carry a truthy `filter` with nothing
1183
1922
  // rendered, and applySelToFilter would then dereference a null `sel` and throw uncaught.
@@ -1188,6 +1927,9 @@ async function saveNow(){
1188
1927
  // A second click while already conflicted must NOT silently re-fire a request we know will fail —
1189
1928
  // just re-surface the explanation.
1190
1929
  if(conflicted){ showChangedBanner(); return; }
1930
+ saveInFlight = true;
1931
+ setFilterEditingLocked(true);
1932
+ setRequiredSaveCue(false, false);
1191
1933
  saveBtn.disabled = true; setSaved('saving');
1192
1934
  // Name this write BEFORE sending it, deliberately: the server broadcasts before it replies, so the echo
1193
1935
  // can reach our own listener while this `await` is still pending — and an id we did not yet know would
@@ -1195,26 +1937,42 @@ async function saveNow(){
1195
1937
  // only runs with `dirty` true, so an unnamed echo takes the BANNER arm and accuses the AI of updating the
1196
1938
  // filter the user was in the middle of saving, while never adopting the new etag.
1197
1939
  const mid = newMutationId(CRYPTO); claimMutation(mid);
1940
+ // The parent can update `revisionRequest` while either fetch is in flight. One click must finish
1941
+ // the same checkpoint it started, so capture the id once and use it for both requests.
1942
+ const checkpointRequest = revisionRequest;
1943
+ const checkpointGeneration = revisionCheckpointGeneration;
1198
1944
  try {
1199
1945
  const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
1200
1946
  // TOTAL, as of P1c: a write with no precondition is refused (428). No tag means we read through the
1201
1947
  // BAKED fallback (the GET tags only store-backed documents) — this app has no draft yet — so the
1202
1948
  // honest precondition is `If-None-Match: *`, "I believe this store is empty".
1203
1949
  if(serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
1204
- if(revisionRequest) headers['x-floless-filter-request'] = revisionRequest;
1950
+ if(checkpointRequest) headers['x-floless-filter-request'] = checkpointRequest;
1205
1951
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C) });
1206
1952
  if(res.status === 428){ // a writer here sent no precondition — a bug in our code, not a user error.
1207
1953
  // NOT the conflict copy: nothing else wrote, so "changed somewhere else" would be a lie. This bar
1208
1954
  // is Reload-only (no overwrite button), which is already the right shape for a 428.
1209
1955
  releaseMutation(mid);
1210
1956
  console.error('save refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
1211
- setSaved('err'); saveBtn.disabled = false;
1212
- showChangedBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
1957
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
1958
+ if(checkpointRequest){
1959
+ blockRequiredCheckpointSave('FloLess couldn’t complete this required Drawing Filter save. Reload the Drawing Filter, review the selections, and press Save filter again. If it keeps happening, please report it.');
1960
+ } else {
1961
+ setSaved('err'); saveBtn.disabled = false; syncRequiredSaveCue();
1962
+ showChangedBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
1963
+ }
1213
1964
  return;
1214
1965
  }
1215
1966
  if(res.status === 412){
1216
1967
  releaseMutation(mid);
1217
- conflicted = true; setSaved('conflict'); saveBtn.disabled = false; showChangedBanner(); return;
1968
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
1969
+ conflicted = true;
1970
+ if(checkpointRequest){
1971
+ blockRequiredCheckpointSave('This Drawing Filter changed before the required save could finish. Reload the Drawing Filter, review the selections, and press Save filter again.');
1972
+ } else {
1973
+ setSaved('conflict'); saveBtn.disabled = false; syncRequiredSaveCue(); showChangedBanner();
1974
+ }
1975
+ return;
1218
1976
  }
1219
1977
  if(!res.ok){ releaseMutation(mid); throw new Error(await res.text()); }
1220
1978
  // NOTE the asymmetry, and that it is deliberate: success does NOT release the id. The echo for this
@@ -1222,20 +1980,74 @@ async function saveNow(){
1222
1980
  // external change and reload itself the instant the user saved. The id is consumed by that echo, or
1223
1981
  // dropped when the write fails, or discarded when the SSE channel closes (nothing can echo after that).
1224
1982
  const t = res.headers.get('ETag'); if(t) serverEtag = t;
1225
- if(revisionRequest && PROJECT && serverEtag){
1226
- const checkpoint = await fetch(`/api/projects/${encodeURIComponent(PROJECT)}/revision-requests/${encodeURIComponent(revisionRequest)}/filter-saved`, {
1227
- method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify({etag:serverEtag}),
1983
+ if(checkpointRequest && PROJECT && serverEtag){
1984
+ const body = { etag: serverEtag };
1985
+ // The ordered names the confirm step displayed and the human approved — never a hash, so the
1986
+ // browser does not have to reproduce the server's canonical JSON, and never the full layer
1987
+ // list, so the assertion stays specific to what was actually shown.
1988
+ if(pendingSignOff) body.layerSignOff = { dismissedLayers: pendingSignOff };
1989
+ const checkpoint = await fetch(`/api/projects/${encodeURIComponent(PROJECT)}/revision-requests/${encodeURIComponent(checkpointRequest)}/filter-saved`, {
1990
+ method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify(body),
1228
1991
  });
1229
- if(!checkpoint.ok) throw new Error(await checkpoint.text());
1230
- revisionRequest = '';
1231
- history.replaceState(null, '', location.pathname + PROJECT_QS);
1992
+ if(!checkpoint.ok){
1993
+ let payload = null; try { payload = await checkpoint.json(); } catch(_){ payload = null; }
1994
+ const code = payload && payload.code;
1995
+ if(checkpoint.status === 409 && SIGNOFF_PROBLEMS[code]){
1996
+ // The contract PUT has ALREADY committed by the time this route is called — that is what
1997
+ // it is for. So the user's edit is not lost and no rollback is attempted (one would be an
1998
+ // unsafe write against a document they may have edited further); only the checkpoint and
1999
+ // the approval are withheld, and the modal says exactly that.
2000
+ // The contract IS saved, so 'Unsaved' would be a lie — but so is a bare 'saved ✓' on a read
2001
+ // that cannot proceed. Remember the refusal so closing the dialog leaves a chip that names
2002
+ // the state and re-opens the explanation, instead of a dead end that looks finished.
2003
+ if(revisionRequest === checkpointRequest){
2004
+ signoffOutcome = code;
2005
+ dirty = false;
2006
+ checkpointSaveBlocked = true;
2007
+ setRequiredSaveCue(false, false);
2008
+ saveBtn.disabled = true;
2009
+ setSaved('signoff-blocked');
2010
+ }
2011
+ return;
2012
+ }
2013
+ throw new Error(payload ? (payload.error || JSON.stringify(payload)) : 'the Drawing Filter checkpoint was refused');
2014
+ }
2015
+ if(revisionRequest === checkpointRequest){
2016
+ revisionRequest = '';
2017
+ history.replaceState(null, '', location.pathname + PROJECT_QS);
2018
+ }
1232
2019
  }
1233
- dirty = false; setSaved('saved');
2020
+ // A newer request can become the required checkpoint after BOTH of A's writes succeeded. A's
2021
+ // success is real, but it cannot satisfy B or turn off B's required Save cue. Leave the editor's
2022
+ // existing dirty state intact so the user is still told exactly what the new checkpoint needs.
2023
+ const checkpointAdvanced = checkpointRequest && revisionCheckpointGeneration !== checkpointGeneration;
2024
+ const ownBroadcastClear = checkpointAdvanced && !revisionRequest
2025
+ && revisionCheckpointGeneration === checkpointGeneration + 1;
2026
+ if(checkpointAdvanced && !ownBroadcastClear){ setSaved(dirty ? 'dirty' : ''); syncRequiredSaveCue(); return; }
2027
+ dirty = false; setSaved('saved'); syncRequiredSaveCue();
1234
2028
  } catch(e){
1235
2029
  // The id is deliberately KEPT here. No response arrived, so we do not know whether the write landed —
1236
2030
  // and if it did, it broadcast, and releasing would make that echo look external and blame the AI for the
1237
2031
  // user's own save. A retained id costs nothing (see releaseMutation).
1238
- console.error('filter save failed', e); setSaved('err'); saveBtn.disabled = false;
2032
+ console.error('filter save failed', e);
2033
+ // A newer checkpoint can arrive while either write for the old one is in flight. The old failure
2034
+ // remains diagnostic in the console, but it must not latch the newer request into reload-only
2035
+ // recovery or replace its Ready cue with a stale error.
2036
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
2037
+ setSaved('err');
2038
+ if(checkpointRequest){
2039
+ // The contract PUT may already have succeeded while the checkpoint POST failed. Retrying with
2040
+ // the old ETag would only produce another refusal, so stop the Ready pulse and give one safe,
2041
+ // explicit recovery action instead of inviting an endless click loop.
2042
+ blockRequiredCheckpointSave('FloLess couldn’t complete this required Drawing Filter save. Reload the Drawing Filter, review the selections, and press Save filter again.');
2043
+ } else {
2044
+ saveBtn.disabled = false;
2045
+ showChangedBanner('FloLess couldn’t save that Drawing Filter change. Reload and try again.');
2046
+ }
2047
+ } finally {
2048
+ saveInFlight = false;
2049
+ setFilterEditingLocked(false);
2050
+ syncRequiredSaveCue();
1239
2051
  }
1240
2052
  }
1241
2053
  window.addEventListener('beforeunload', e => { if(dirty){ e.preventDefault(); e.returnValue = ''; } });
@@ -1245,7 +2057,7 @@ window.addEventListener('beforeunload', e => { if(dirty){ e.preventDefault(); e.
1245
2057
  // backstop so an intentional close doesn't re-trigger the native prompt.
1246
2058
  window.__floGuard = {
1247
2059
  isDirty: () => dirty,
1248
- save: async () => { await save(); return !dirty; },
2060
+ save: async () => { await beginSave(); return !dirty; },
1249
2061
  discard: () => { dirty = false; },
1250
2062
  };
1251
2063
 
@@ -1273,6 +2085,13 @@ window.__filterTest = {
1273
2085
  sheetOptionTexts: () => sheetOptions().map(o => o.textContent),
1274
2086
  pick: (i) => { const el = nodes[i].el; openEyedropper(Math.round(window.innerWidth / 2), 200, el); return el; },
1275
2087
  addAll: () => document.getElementById('eyeAddAll').click(),
2088
+ // Layer sign-off state, so a real browser pass can assert the control and the list it SUBMITS, not
2089
+ // only that a modal appeared.
2090
+ signoffOpen: () => !signoffOverlay.hidden,
2091
+ signoffNames: () => [...signoffNames],
2092
+ signoffRows: () => [...signoffList.querySelectorAll('.signoff-row')].map(row => row.textContent),
2093
+ signoffNotice: () => (signoffNotice.hidden ? null : signoffNotice.textContent),
2094
+ signoffActions: () => [...document.querySelectorAll('.signoff-actions button')].filter(b => !b.hidden).map(b => b.textContent),
1276
2095
  };
1277
2096
 
1278
2097
  // Themed tooltips (replaces native title=) — one shared element, shown on data-tip hover after a short