@floless/app 0.134.0 → 0.134.2

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,67 @@ 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
+ /* The magnitude. It sits ABOVE the list deliberately: the two sentences explain what a wholesale
166
+ dismissal IS, and then this says how big it is — which is the decision. `<b>` for the number is
167
+ the same bold-figure-in-a-muted-sentence idiom #count and .stat already use, so no new treatment.
168
+ The pending and failed states carry NO DIGITS AT ALL: a wrong magnitude on this screen is worse
169
+ than none, and a sentence with no number in it cannot be misread as one. */
170
+ .signoff-total{margin:0 0 12px;color:var(--mut);font-size:12.5px;line-height:1.5}
171
+ .signoff-total b{color:var(--text);font-weight:600}
172
+ /* A scroll container — themed by the global `*` scrollbar rules at the top of this sheet, exactly as
173
+ .sheet-list is, so no native white bar can appear inside the modal.
174
+ NO padding here, unlike .sheet-list: `position:sticky` on the group headings computes against the
175
+ scrollport's padding edge, so a padded container lets a scrolling row peek above its own heading. */
176
+ .signoff-list{margin:0;padding:0;overflow-y:auto;flex:1;min-height:0;border:1px solid var(--line);border-radius:6px;background:var(--bg)}
177
+ .signoff-list[hidden]{display:none}
178
+ .signoff-group{padding:0 0 4px}
179
+ /* Sticky, because a real set is 17 line-weight rows plus 8 colour rows plus every off layer inside a
180
+ 560px box: scrolled halfway down it, a human otherwise cannot tell WHICH dimension they are
181
+ approving. Same background as the list so there is no seam, and no new token. */
182
+ .signoff-group-heading{position:sticky;top:0;z-index:1;margin:0;padding:6px 8px;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);background:var(--bg);border-bottom:1px solid var(--line)}
183
+ .signoff-rows{list-style:none;margin:0;padding:4px}
184
+ .signoff-row{display:flex;align-items:baseline;gap:10px;padding:6px 8px;font-size:12.5px;border-bottom:1px solid var(--line)}
185
+ .signoff-row:last-child{border-bottom:none}
186
+ /* The one place a NON-BASELINE colour legitimately appears on this surface: it renders drawing data,
187
+ not chrome. The 1px --ctrl-border ring is what keeps a white or near-white swatch visible against
188
+ the dark ground — the swatch square IS the chip. A third scope of the same 12px declaration the
189
+ panel and the eyedropper already carry; `align-self` corrects for the row's baseline alignment,
190
+ which would otherwise hang the square off the text baseline. */
191
+ .signoff-row .sw{width:12px;height:12px;border-radius:3px;border:1px solid var(--ctrl-border);flex:none;align-self:center}
192
+ .signoff-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}
193
+ .signoff-count{flex:none;color:var(--mut);font-size:11px;cursor:default}
194
+ /* Always visible, never tooltip-gated. Two different populations are on screen at once — per-row
195
+ ELEMENT counts and a ledger-LINE total — and a human who adds the rows up will not get the total.
196
+ A hover-only disclaimer is optimistic that anyone finds it. */
197
+ .signoff-caption{margin:8px 0 14px;color:var(--mut);font-size:11px;line-height:1.4}
198
+ .signoff-caption[hidden]{display:none}
199
+ .signoff-actions{display:flex;justify-content:flex-end;gap:8px;flex:none}
200
+ .signoff-actions button[hidden]{display:none}
132
201
  /* 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}
202
+ /* Above EVERY surface it can be shown over, the sign-off overlay (z-index 90) included: a tooltip
203
+ that renders behind the thing it is describing is worse than no tooltip, because the control still
204
+ advertises one. Raise this whenever a higher surface is added. */
205
+ #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
206
  #tooltip.show{opacity:1}
135
207
  #app{display:flex;flex:1;min-height:0}
136
208
  #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 +215,13 @@ button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
143
215
  .opts label em{margin-left:auto;color:var(--mut);font-style:normal;font-size:11px}
144
216
  .opts .sw{width:12px;height:12px;border-radius:3px;flex:0 0 12px;border:1px solid var(--ctrl-border)}
145
217
  .opts label.textlayer{opacity:.55;cursor:default}
218
+ /* A row whose facet value has no canonical key (#805 Phase D slice D1). buildFacet sets
219
+ `aria-disabled` on the checkbox — NOT the `disabled` property, which would take it out of the tab
220
+ order and hide the refusal from Instructor; see the comment there. This is presentation only, and
221
+ deliberately reuses button:disabled's own .5/cursor:default rather than inventing a third muted-row
222
+ treatment beside .textlayer (.55) and .facet.dim (.4). */
223
+ .opts label.novalue{opacity:.5;cursor:default}
224
+ input[type=checkbox][aria-disabled="true"]{cursor:default}
146
225
  /* Fully custom checkbox — the native unchecked widget is a white/grey square that breaks the dark baseline. */
147
226
  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
227
  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 +244,11 @@ input:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
165
244
  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
245
  [data-theme="light"] input[type=checkbox]{background:var(--bg)}
167
246
  [data-theme="light"] .opts label.textlayer{opacity:.7}
247
+ /* .novalue gets the same lift, and for the same reason .textlayer needed one: opacity does not
248
+ composite symmetrically across grounds, so .5 that reads as "quiet" on the dark panel reads as
249
+ "barely there" on the light one. This is the row LEAST able to afford that — it is the one
250
+ carrying an explanation of why it cannot be ticked. */
251
+ [data-theme="light"] .opts label.novalue{opacity:.65}
168
252
  .hint{color:var(--mut);font-size:11px;line-height:1.5}
169
253
  /* #count is the footer's only child since #603 took the Fit/Zoom buttons out of the rail, so the
170
254
  flex row that used to wrap around them is gone with them — as are #count's width:100% and
@@ -285,15 +369,22 @@ body.publication-blocked #empty{position:static;flex:1}
285
369
  <span id="src" class="stat"></span>
286
370
  <span class="sp"></span>
287
371
  <span id="saved" class="stat"></span>
372
+ <span id="saveRequiredStatus" class="stat required-step" role="status" aria-live="polite" tabindex="-1" hidden>Ready — press Save filter</span>
288
373
  <button id="save" data-command-id="filter.save" class="primary" disabled>Save filter</button>
289
374
  </header>
290
375
  <div id="app">
291
376
  <aside id="panel">
292
377
  <section id="modes">
293
378
  <h2>Match on</h2>
294
- <label data-command-id="filter.match-on"><input type="checkbox" name="dim" value="layer" checked /> Layer</label>
295
- <label data-command-id="filter.match-on"><input type="checkbox" name="dim" value="thickness" /> Thickness</label>
296
- <label data-command-id="filter.match-on"><input type="checkbox" name="dim" value="color" /> Color</label>
379
+ <!-- The id sits on the INPUT, not on the wrapping <label>. Instructor's `activate()` (the `?`
380
+ sheet's Enter) queries for the carrier and then calls `.focus()` on it — and a <label> is
381
+ not focusable, so a label carrier silently failed to take the user to the control and fell
382
+ back to describing it. `accessibleNameOf` reads a wrapping label for an input, so the
383
+ control still announces "Layer"; nothing is lost by moving the id inward, and the hover
384
+ path is unchanged because `Commands.resolve` walks UP from whatever is hovered. -->
385
+ <label><input type="checkbox" name="dim" value="layer" data-command-id="filter.match-on" checked /> Layer</label>
386
+ <label><input type="checkbox" name="dim" value="thickness" data-command-id="filter.match-on" /> Thickness</label>
387
+ <label><input type="checkbox" name="dim" value="color" data-command-id="filter.match-on" /> Color</label>
297
388
  <p class="hint">Checked criteria must all match (AND).</p>
298
389
  </section>
299
390
  <section class="facet" id="facet-layers">
@@ -358,6 +449,30 @@ body.publication-blocked #empty{position:static;flex:1}
358
449
  <button class="eall primary" id="eyeAddAll" data-command-id="filter.eyedropper-add">Add all to filter</button>
359
450
  </div>
360
451
 
452
+ <!-- The exclusion sign-off confirm step. Only ever opened for a revision read that has something
453
+ switched OFF on a dimension it is matching on: those are the values whose every matching element
454
+ the completion proof may later dismiss as a group, so this is where a human takes that decision
455
+ on the record. Nothing in the list is interactive — to change the list, Cancel and re-tick in the
456
+ panel, which is the one place selection is edited.
457
+ The list is GROUPED by dimension with a visible heading per group, which is why the old sr-only
458
+ list label is gone: each group's <ul> is labelled by its own <h3>, which says more, not less. -->
459
+ <div id="signoffOverlay" hidden>
460
+ <div id="signoffPanel" role="dialog" aria-modal="true" aria-labelledby="signoffTitle" aria-describedby="signoffDesc">
461
+ <h2 id="signoffTitle">Confirm what this read will dismiss</h2>
462
+ <p class="signoff-desc" id="signoffDesc">These values are switched off in your filter, so this read treats every element matching them as not steel — dismissed as a group, with no line-by-line reason. Values left on can’t be dismissed this way.</p>
463
+ <p class="signoff-total" id="signoffTotal" role="status"></p>
464
+ <div class="signoff-notice" id="signoffNotice" role="status" hidden></div>
465
+ <div class="signoff-list" id="signoffList"></div>
466
+ <p class="signoff-caption" id="signoffCaption">Row counts are elements, not split by page role. The total above is lines this read may dismiss.</p>
467
+ <div class="signoff-actions">
468
+ <button id="signoffCancel" data-command-id="filter.signoff-cancel">Cancel</button>
469
+ <button id="signoffApprove" class="primary" data-command-id="filter.signoff-approve">Approve these exclusions</button>
470
+ <button id="signoffClose" data-command-id="filter.signoff-close" hidden>Close</button>
471
+ <button id="signoffReload" class="primary" data-command-id="filter.signoff-reload" hidden>Reload page</button>
472
+ </div>
473
+ </div>
474
+ </div>
475
+
361
476
  <!-- The Instructor seam. Classic, parser-inserted and BEFORE this page's own script on
362
477
  purpose: classic scripts run synchronously in document order while modules are deferred, so
363
478
  window.Commands is guaranteed to exist by the time anything below reads it.
@@ -370,12 +485,15 @@ body.publication-blocked #empty{position:static;flex:1}
370
485
  <script>window.InstructorReporter.mount({ surface: 'steel-filter' });</script>
371
486
 
372
487
  <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';
488
+ import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, liveOverlayElements, bgRect, textFontSize, applySelToFilter, hasUnsupportedSingleSheetFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, dismissibleFacetValues, FACET_DIMS, FACET_DIM_BY_CONTROL, MODE_ORDER, facetKey, NOTE_TEXT } from './steel-filter-core.js';
374
489
 
375
490
  const APP_ID = new URLSearchParams(location.search).get('app') || '';
376
491
  // Workspaces use a project-keyed contract; an empty project id is the app-keyed workflow surface.
377
492
  const PROJECT = new URLSearchParams(location.search).get('project') || '';
378
493
  let revisionRequest = new URLSearchParams(location.search).get('revisionRequest') || '';
494
+ // Monotonic ownership for async Save results. The id alone cannot distinguish A→empty (A's own
495
+ // completion) from A→B→empty (B arrived and was then cleared while A was still in flight).
496
+ let revisionCheckpointGeneration = 0;
379
497
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
380
498
  const CONTRACT_QS = PROJECT ? (PROJECT_QS + '&quietMissing=1') : PROJECT_QS;
381
499
  const SVGNS = 'http://www.w3.org/2000/svg';
@@ -389,6 +507,7 @@ const overlay = document.getElementById('overlay');
389
507
  const bgImg = svg.querySelector('image.bg');
390
508
  const countEl = document.getElementById('count');
391
509
  const savedEl = document.getElementById('saved');
510
+ const saveRequiredStatus = document.getElementById('saveRequiredStatus');
392
511
  const saveBtn = document.getElementById('save');
393
512
 
394
513
  let C = null; // the full contract
@@ -403,6 +522,8 @@ let conflicted = false; // latched once a save is refused, so a second click do
403
522
  let sheets = []; // normalizeFilter(F).sheets — per-sheet geometry
404
523
  let active = 0; // index into sheets
405
524
  let parseWarned = false; // latch, so a broken stream cannot spam the console
525
+ let checkpointSaveBlocked = false; // a half-completed checkpoint must reload before it can be retried safely
526
+ let saveInFlight = false; // parent checkpoint polling must not re-enable Save during the queued write
406
527
 
407
528
  function setSaved(state){
408
529
  // The state→(class, label) map is `statChip` in steel-filter-core.js, where it is table-tested.
@@ -420,7 +541,7 @@ function setSaved(state){
420
541
  if(actionable){
421
542
  savedEl.setAttribute('role', 'button');
422
543
  savedEl.setAttribute('tabindex', '0');
423
- savedEl.setAttribute('aria-label', text + ' — show what changed');
544
+ savedEl.setAttribute('aria-label', text + (state === 'signoff-blocked' ? ' — show why the approval was refused' : ' — show what changed'));
424
545
  } else {
425
546
  savedEl.removeAttribute('role'); savedEl.removeAttribute('tabindex'); savedEl.removeAttribute('aria-label');
426
547
  }
@@ -455,10 +576,20 @@ function setSaved(state){
455
576
  let lastBanner; // the last DOCUMENT message, so the header chip can re-open a bar the user dismissed
456
577
  function showChangedBanner(message, opts){
457
578
  const kind = (opts && opts.kind) || 'document';
458
- const old = document.getElementById('conflictBanner'); if(old) old.remove();
579
+ const dismissible = !opts || opts.dismissible !== false;
580
+ const requiredRecovery = !!(opts && opts.requiredRecovery);
581
+ const old = document.getElementById('conflictBanner');
582
+ // A failed required checkpoint disables Save, so Reload is the only way forward. A later SSE
583
+ // reconnect/disconnect notice must not replace that action with a dismissible channel message.
584
+ if(old && old.dataset.requiredRecovery === 'true' && !requiredRecovery) return;
585
+ if(old) old.remove();
459
586
  if(kind === 'document') lastBanner = message;
460
587
  const bar = document.createElement('div');
461
588
  bar.id = 'conflictBanner';
589
+ bar.dataset.requiredRecovery = String(requiredRecovery);
590
+ bar.setAttribute('role', 'alert');
591
+ bar.setAttribute('aria-live', 'assertive');
592
+ bar.setAttribute('aria-atomic', 'true');
462
593
  // The bar keeps its saturated blue skin in BOTH themes — it is an alert, and it earns its prominence
463
594
  // by not being the page's own surface. Its SHADOW is themed, because that one is not a choice: an
464
595
  // 18px black glow thrown up a white page is the artifact, not the emphasis.
@@ -470,6 +601,7 @@ function showChangedBanner(message, opts){
470
601
  || 'This model changed somewhere else since you opened it — your save didn’t go through. '
471
602
  + 'Reload and reapply your changes.';
472
603
  const reload = document.createElement('button');
604
+ reload.setAttribute('data-command-id', 'filter.reload');
473
605
  reload.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
474
606
  reload.textContent = '↻ Reload';
475
607
  // No local draft in this surface, so a plain reload is already safe (unlike the steel editor, whose
@@ -482,6 +614,8 @@ function showChangedBanner(message, opts){
482
614
  // prompt remains the thing that stops silent data loss.
483
615
  reload.onclick = () => { if(kind === 'document') dirty = false; location.reload(); };
484
616
  const dismiss = document.createElement('button');
617
+ dismiss.setAttribute('data-command-id', 'filter.dismiss-message');
618
+ dismiss.setAttribute('aria-label', 'Dismiss message');
485
619
  dismiss.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
486
620
  dismiss.textContent = '✕';
487
621
  // Dismissing hides the bar but must not erase the FACT that the view is behind — otherwise the only
@@ -498,8 +632,11 @@ function showChangedBanner(message, opts){
498
632
  if(kind !== 'document') return;
499
633
  if(!savedEl.classList.contains('conflict') && !savedEl.classList.contains('err')) setSaved('stale');
500
634
  };
501
- bar.appendChild(msg); bar.appendChild(reload); bar.appendChild(dismiss);
635
+ bar.appendChild(msg); bar.appendChild(reload); if(dismissible) bar.appendChild(dismiss);
502
636
  document.body.appendChild(bar);
637
+ // A required checkpoint failure disables Save and leaves Reload as the only recovery. Announce the
638
+ // alert above, then put keyboard focus on that remaining action instead of stranding it on Save.
639
+ if(!dismissible) setTimeout(() => reload.focus(), 0);
503
640
  }
504
641
  // `.stat.conflict` ships `cursor:pointer` and, until now, nothing behind it — a control that looks clickable
505
642
  // and does nothing. Back it: clicking the cyan chip re-opens the document bar it belongs to. (In the 'Save
@@ -507,11 +644,108 @@ function showChangedBanner(message, opts){
507
644
  // no other route exists at all.) Keyboard-reachable because setSaved gives the actionable states
508
645
  // role=button + tabindex; a control only a mouse can reach is half a control.
509
646
  function reopenBanner(){ if(savedEl.classList.contains('conflict')) showChangedBanner(lastBanner); }
510
- savedEl.onclick = reopenBanner;
647
+ // One cyan chip, two explanations — route to whichever state it is actually carrying, or the chip
648
+ // becomes a control that re-opens the wrong thing.
649
+ function reopenChipExplanation(){ if(signoffOutcome) reopenSignOffProblem(); else reopenBanner(); }
650
+ savedEl.onclick = reopenChipExplanation;
511
651
  savedEl.addEventListener('keydown', e => {
512
- if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenBanner(); }
652
+ if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenChipExplanation(); }
513
653
  });
514
- function markDirty(){ dirty = true; saveBtn.disabled = false; setSaved('dirty'); }
654
+ function markDirty(){
655
+ dirty = true; saveBtn.disabled = checkpointSaveBlocked; setSaved('dirty');
656
+ if(revisionRequest) syncRequiredSaveCue();
657
+ }
658
+
659
+ function setRequiredSaveCue(checkpoint, ready){
660
+ saveBtn.classList.toggle('needs-save', ready);
661
+ saveRequiredStatus.hidden = !checkpoint;
662
+ saveRequiredStatus.textContent = ready ? 'Ready — press Save filter' : 'Select drawing lines first';
663
+ if(checkpoint){
664
+ saveBtn.setAttribute('aria-describedby', 'saveRequiredStatus');
665
+ saveBtn.setAttribute('data-tip', ready
666
+ ? 'Required next step: save this Drawing Filter, then return to the terminal AI that prepared it and tell it to continue'
667
+ : 'Select at least one drawing line in the filter before saving');
668
+ if(ready) saveBtn.removeAttribute('data-blocked-reason');
669
+ else saveBtn.setAttribute('data-blocked-reason', 'Select at least one drawing line in the Drawing Filter before saving.');
670
+ } else {
671
+ saveBtn.removeAttribute('aria-describedby');
672
+ saveBtn.removeAttribute('data-tip');
673
+ saveBtn.removeAttribute('data-blocked-reason');
674
+ }
675
+ }
676
+
677
+ function syncRequiredSaveCue(){
678
+ if(saveInFlight){ setRequiredSaveCue(false, false); saveBtn.disabled = true; return; }
679
+ if(checkpointSaveBlocked){ setRequiredSaveCue(false, false); saveBtn.disabled = true; return; }
680
+ const checkpoint = !!revisionRequest && !!C && !!F && !!sel && !conflicted;
681
+ const ready = checkpoint && sheets.some(sheet => (sheet.elements || []).some(el => matchesActive(el, mode, sel)));
682
+ setRequiredSaveCue(checkpoint, ready);
683
+ // The checkpoint always explains the next action, but only a non-empty selection can be saved.
684
+ // A valid prepared filter may already be ready; otherwise the first facet edit re-evaluates it.
685
+ if(checkpoint) saveBtn.disabled = !ready;
686
+ else saveBtn.disabled = !dirty && !conflicted;
687
+ }
688
+
689
+ // A checkpoint Save is two writes: first the exact Filter, then the request's "filter saved" receipt.
690
+ // Freeze every selection control across BOTH awaits so a click cannot change `sel` after the request body
691
+ // was serialized and then be incorrectly cleared by the successful response. Navigation outside this
692
+ // iframe remains available; only the editor whose snapshot is in flight becomes inert.
693
+ function setFilterEditingLocked(locked){
694
+ const app = document.getElementById('app');
695
+ const eye = document.getElementById('eye');
696
+ // The eyedropper is intentionally portalled outside #app so it can float over the canvas. Close it
697
+ // and lock that separate surface too; otherwise an already-open Add button can mutate `sel` after
698
+ // the contract body was serialized while the checkpoint receipt is still pending.
699
+ if(locked) closeEye();
700
+ // Save and the sign-off dialog are TWO independent lock owners. On a checkpoint refusal the
701
+ // `finally` below releases Save while the dialog deliberately stays open; clearing inert there
702
+ // exposed the whole editor behind an aria-modal surface. Leave modal-owned inert in place and let
703
+ // restoreSignoffBackground() restore the exact pre-dialog state when the dialog actually closes.
704
+ const signoff = document.getElementById('signoffOverlay');
705
+ const signoffOwnsLock = !!signoff && !signoff.hidden;
706
+ app.inert = !!locked || signoffOwnsLock;
707
+ eye.inert = !!locked || signoffOwnsLock;
708
+ if(locked) app.setAttribute('aria-busy', 'true');
709
+ else app.removeAttribute('aria-busy');
710
+ if(locked) eye.setAttribute('aria-busy', 'true');
711
+ else eye.removeAttribute('aria-busy');
712
+ }
713
+
714
+ // Same-origin parent bridge: polling may complete, fail, or clear a checkpoint while this editor has
715
+ // unsaved facet changes. Update only the checkpoint state and URL; never reload the document away.
716
+ window.__floRevisionCheckpoint = {
717
+ setRequest(value){
718
+ const nextRequest = String(value || '');
719
+ if(nextRequest !== revisionRequest){
720
+ revisionCheckpointGeneration += 1;
721
+ // The sign-off list belongs to the exact checkpoint that opened it. Keeping it visible after
722
+ // polling advances to another request would let an old list be approved against the new read
723
+ // when the layer names happen to match.
724
+ retireSignOffForCheckpointChange();
725
+ checkpointSaveBlocked = false;
726
+ // Reload-only recovery belongs to the exact checkpoint that failed. If polling advances,
727
+ // replaces, or clears that request, remove its stale alert before the new checkpoint can enable
728
+ // Save; otherwise the screen simultaneously says “Reload is the only way forward” and offers a
729
+ // working Save button. Preserve ordinary unsaved filter state for the new request.
730
+ const recovery = document.getElementById('conflictBanner');
731
+ if(recovery && recovery.dataset.requiredRecovery === 'true'){
732
+ recovery.remove();
733
+ lastBanner = undefined;
734
+ // `conflicted` belongs to checkpoint A's refused conditional write. Carrying it into B makes
735
+ // B look usable while every Save silently reopens A's vanished warning. Retire the latch with
736
+ // the exact required-recovery banner; an ordinary external-edit conflict remains untouched.
737
+ conflicted = false;
738
+ setSaved(dirty ? 'dirty' : '');
739
+ }
740
+ }
741
+ revisionRequest = nextRequest;
742
+ const url = new URL(location.href);
743
+ if(revisionRequest) url.searchParams.set('revisionRequest', revisionRequest);
744
+ else url.searchParams.delete('revisionRequest');
745
+ history.replaceState(null, '', url.pathname + url.search);
746
+ syncRequiredSaveCue();
747
+ },
748
+ };
515
749
 
516
750
  // ── Live updates: reacting to a write that did not come from this tab ──
517
751
  //
@@ -815,11 +1049,18 @@ function initFromFilter(){
815
1049
  // Facets are GLOBAL — one selection for every sheet. The producer (skill step 1b) MUST aggregate
816
1050
  // the UNION of layers/thicknesses/colors across all sheets here; a facet value present on a sheet
817
1051
  // 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);
1052
+ buildFacet('layers', F.layers || [], it => it.name);
1053
+ // Labelled from the CANONICAL width, not the raw one: 0.123 and 0.124 are one value now, and a row
1054
+ // labelled "0.123 pt" that governs both would name a width the human is not deciding about. Layers
1055
+ // and colours keep their raw text — case-folding a hex does not make it a different colour, and the
1056
+ // row should still read as the drawing set recorded it.
1057
+ //
1058
+ // Through `thicknessLabel`, which handles the two ways a row can have no canonical width — see it.
1059
+ buildFacet('thicknesses', F.thicknesses || [], it => thicknessLabel(it.w));
1060
+ buildFacet('colors', F.colors || [], it => it.hex);
821
1061
  buildSheetSwitcher();
822
1062
  setSheet(active);
1063
+ syncRequiredSaveCue();
823
1064
  }
824
1065
 
825
1066
  // ── sheet switcher ──────────────────────────────────────────────────────────────────────────────
@@ -1023,20 +1264,249 @@ function hasRasterContext(){ return !!((sheets[active] && sheets[active].page) |
1023
1264
 
1024
1265
  function setOf(facet){ return facet === 'layers' ? sel.layers : facet === 'thicknesses' ? sel.thicknesses : sel.colors; }
1025
1266
 
1026
- function buildFacet(facet, items, valueKey, label, selValue){
1267
+ const FACET_NOUN = { layers: 'layer', thicknesses: 'thickness', colors: 'colour' };
1268
+
1269
+ /**
1270
+ * ONE sentence for a row whose value is not a value for its dimension — the hover tip, the
1271
+ * screen-reader description and Instructor's blocked reason are the same words, because three
1272
+ * wordings of one refusal is three things to keep in step.
1273
+ *
1274
+ * It says the tick will be CLEARED, not merely that the value is invalid: a stored `on: true` on such
1275
+ * a row is discarded on the next Save (the value can never enter the selection), and a human who is
1276
+ * told only "isn't valid" would not expect their saved flag to change underneath them.
1277
+ */
1278
+ 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.';
1279
+ /** The other way a picked value is unusable: it is well-formed, but this filter lists no row for it,
1280
+ * so nothing could persist it. Distinct copy, because the fix is different — the drawing set's
1281
+ * control lists are incomplete, not its values malformed. */
1282
+ 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.';
1283
+ let noValueSeq = 0;
1284
+
1285
+ /**
1286
+ * How a thickness reads on screen: the CANONICAL width, because that is the value being decided —
1287
+ * 0.123 and 0.124 are one value now, and a row labelled "0.123 pt" governing both names a width
1288
+ * nobody is choosing about.
1289
+ *
1290
+ * Two fallbacks, and they are different. A width that is not a NUMBER still has something to show, so
1291
+ * it shows that: the row is already refused by its dimming and its tooltip, and the label's remaining
1292
+ * job is to say WHICH row is being refused. A width that is absent entirely has nothing to show, and
1293
+ * "undefined pt" is not a value — it says the row is broken without saying anything the human can act
1294
+ * on. (Both were live: the first was caught by a real browser pass, the second by review, because
1295
+ * every test fixture had a `w` of some kind.)
1296
+ *
1297
+ * There is a THIRD case, and it is deliberately NOT handled here: `NaN` and `Infinity` are numbers, so
1298
+ * `facetKey` returns them and this renders "NaN pt" as an ordinary, tickable row. That is consistent
1299
+ * on purpose — the ledger's predicate selects on them too, so a row the panel refused would disagree
1300
+ * with the audit — and it is harmless downstream, because `isDismissibleFacetValue` refuses them and
1301
+ * the census `keyOf` refuses them, so such a value can never authorise a dismissal. It is also not
1302
+ * reachable from a stored contract: JSON carries neither literal. Making the panel reject them would
1303
+ * require a panel-only key rule, which is the producer/consumer split this whole slice removes.
1304
+ */
1305
+ function thicknessLabel(w){
1306
+ const key = facetKey('thickness', w);
1307
+ if(key !== undefined) return key + ' pt';
1308
+ return w === undefined || w === null ? 'No thickness recorded' : w + ' pt';
1309
+ }
1310
+ /** dim -> control name. DERIVED from the shared descriptor, never retyped: a hand-maintained second
1311
+ * copy of the mapping is the exact defect this slice exists to remove, one file over. */
1312
+ const FACET_CONTROL_OF = Object.fromEntries(MODE_ORDER.map(dim => [dim, FACET_DIMS[dim].control]));
1313
+
1314
+ /**
1315
+ * Which dimensions a picked element OFFERS a row for — APPLICABILITY, which is a different question
1316
+ * from whether the value can be added.
1317
+ *
1318
+ * Conflating the two hid exactly the refusal this slice exists to surface: requiring a usable
1319
+ * canonical key here meant a line with `w: "bad"` simply had no Thickness row, so nothing was
1320
+ * refused, nothing was explained, and "Add all" silently took two values of three.
1321
+ *
1322
+ * Thickness is INAPPLICABLE to text, and to a stroke whose canonical width is not above zero — a
1323
+ * hairline has no meaningful width and the Filter shows no `0 pt` row to add it to, so hiding it is
1324
+ * honest. A width that is not a NUMBER is a different case: the element HAS a stroke, so the row is
1325
+ * offered and then refused, with the reason attached.
1326
+ *
1327
+ * `NaN` and a negative width fall on the INAPPLICABLE side, because `width > 0` is false for both.
1328
+ * That is the same answer `eyedropperAdd`'s own `hasStroke` gives, so the popover never offers a row
1329
+ * the adder would skip — but unlike a malformed width it is hidden rather than explained. Left as is:
1330
+ * neither is reachable from a stored contract (JSON carries no `NaN`), and the alternative is a
1331
+ * fourth state on a popover that already has three.
1332
+ */
1333
+ function eyeOffers(el, dim){
1334
+ if(dim !== 'thickness') return true;
1335
+ if(el.kind === 'text') return false;
1336
+ const width = facetKey('thickness', el.w);
1337
+ return width === undefined || width > 0;
1338
+ }
1339
+ function eyeAddableDims(el){
1340
+ return ['layer', 'thickness', 'color'].filter(dim => eyeOffers(el, dim) && eyeAddable(el, dim));
1341
+ }
1342
+
1343
+ /**
1344
+ * Can this picked value actually be added — meaning, will it SURVIVE a save?
1345
+ *
1346
+ * Two conditions, and the second is easy to miss. The value must have a canonical key, and the filter
1347
+ * must carry a CONTROL ROW for it: `applySelToFilter` writes `on` flags onto rows and nothing else, so
1348
+ * a key with no row is silently dropped the moment the contract is written. Accepting one put a value
1349
+ * in the selection, changed the canvas and the "N selected" readout, and then left Save disabled —
1350
+ * a visible edit with no route to persistence and no warning, which `beforeunload` cannot even catch
1351
+ * because nothing was ever marked dirty.
1352
+ *
1353
+ * The producer is supposed to make this impossible (see the aggregate-the-union note in
1354
+ * `initFromFilter`), so a missing row is a producer bug — and refusing it loudly is how that bug
1355
+ * becomes visible instead of becoming a lost edit.
1356
+ */
1357
+ function eyeAddable(el, dim){
1358
+ const key = facetKey(dim, el[FACET_DIMS[dim].elementKey]);
1359
+ if(key === undefined) return false;
1360
+ return (F[FACET_DIMS[dim].control] || []).some(it => facetRowKey(FACET_DIMS[dim].control, it) === key);
1361
+ }
1362
+
1363
+ /**
1364
+ * THE one way this page reads a control row's facet value — the shared canonicaliser, indexed through
1365
+ * the shared descriptor (#805 Phase D slice D1).
1366
+ *
1367
+ * Every producer and consumer of the selection Set goes through it: this page's checkbox state,
1368
+ * All/None and the eyedropper, and core's `selFromFilter` / `matchesActive` / `applySelToFilter`. A
1369
+ * raw value read anywhere in that chain is not a near miss — a Set holding `#abc123` asked for
1370
+ * `#ABC123` answers "no", so the row renders ticked and Save writes it OFF, with no error and nothing
1371
+ * on screen to notice. `undefined` means the row's value is not a value for its dimension at all.
1372
+ */
1373
+ function facetRowKey(facet, it){
1374
+ const dim = FACET_DIM_BY_CONTROL[facet];
1375
+ return facetKey(dim, it[FACET_DIMS[dim].rowKey]);
1376
+ }
1377
+
1378
+ /**
1379
+ * Would Save write a different `on` than this facet's ROWS currently hold?
1380
+ *
1381
+ * The same expression `applySelToFilter` uses for those rows, deliberately — asking "did the
1382
+ * selection Set move" instead misses every edit that changes a persisted flag without changing the
1383
+ * Set: a stored tick on an unselectable row (which Save clears), and a row with no `on` at all
1384
+ * (which Save writes out).
1385
+ *
1386
+ * Named for what it measures, and NOT `saveWouldChange`: Save also persists `filter.mode`,
1387
+ * `F.sheets` and `F.active`, none of which this sees. Those are covered elsewhere — the mode
1388
+ * checkboxes mark dirty unconditionally, and switching sheets is navigation rather than an edit
1389
+ * (see `setSheet`). A name promising totality would invite the next caller to rely on one.
1390
+ */
1391
+ function facetOnWouldChange(facet){
1392
+ const s = setOf(facet);
1393
+ return (F[facet] || []).some(it => {
1394
+ const key = facetRowKey(facet, it);
1395
+ return it.on !== (key !== undefined && s.has(key));
1396
+ });
1397
+ }
1398
+
1399
+ /**
1400
+ * Tell the facet's bulk controls what they can actually do.
1401
+ *
1402
+ * `#eyeAddAll` was taught to say when it must drop a value; `all`/`none` run over the SAME
1403
+ * unselectable rows, are used far more, and said nothing — click "all", watch two of three rows tick,
1404
+ * and the control that half-failed offers no explanation. The refusal was reachable only by hovering
1405
+ * the row, not the control that just declined to act on it.
1406
+ *
1407
+ * The labels stay "all"/"none" — they are 4-character controls in a 300px panel and there is nowhere
1408
+ * to put a longer word — so the honesty rides on the tooltip and on `data-blocked-reason`, which is
1409
+ * what Instructor reads. When NOTHING in the list can be moved, they refuse outright.
1410
+ */
1411
+ function syncFacetBulk(facet){
1412
+ const items = F[facet] || [];
1413
+ const usable = items.filter(it => facetRowKey(facet, it) !== undefined).length;
1414
+ for(const attr of ['data-all', 'data-none']){
1415
+ const button = document.querySelector(`[${attr}="${facet}"]`);
1416
+ if(!button) continue;
1417
+ if(usable === items.length){
1418
+ button.removeAttribute('aria-disabled');
1419
+ button.removeAttribute('data-blocked-reason');
1420
+ button.removeAttribute('data-tip');
1421
+ continue;
1422
+ }
1423
+ const verb = attr === 'data-all' ? 'ticks' : 'unticks';
1424
+ const reason = usable === 0
1425
+ ? `No ${FACET_NOUN[facet]} in this list has a value the filter can use, so this does nothing. ${NO_VALUE_REASON(facet)}`
1426
+ : `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.`;
1427
+ if(usable === 0) button.setAttribute('aria-disabled', 'true'); else button.removeAttribute('aria-disabled');
1428
+ button.setAttribute('data-blocked-reason', reason);
1429
+ button.setAttribute('data-tip', reason);
1430
+ }
1431
+ }
1432
+
1433
+ function buildFacet(facet, items, label){
1434
+ const dim = FACET_DIM_BY_CONTROL[facet];
1027
1435
  const box = document.querySelector(`#facet-${facet} .opts`);
1028
1436
  box.replaceChildren();
1029
1437
  for(const it of items){
1030
- const val = it[valueKey];
1438
+ const val = it[FACET_DIMS[dim].rowKey];
1439
+ const key = facetRowKey(facet, it);
1031
1440
  const isText = facet === 'layers' && it.drawable === false;
1032
1441
  const wrap = document.createElement('label');
1033
- wrap.setAttribute('data-command-id', 'filter.facet-toggle');
1034
- if(isText) wrap.className = 'textlayer';
1442
+ // The no-value case is tested BEFORE `isText` on purpose: a layer row can be both undrawable and
1443
+ // wrong-typed, and if .textlayer won it would render as an ordinary muted row with a checkbox that
1444
+ // silently refuses to stay ticked and no explanation — this slice's own defect, relocated.
1445
+ //
1446
+ // The tip rides on the LABEL, never on the input: a disabled control does not reliably fire
1447
+ // pointerover, so a data-tip on the checkbox would simply never render. The label wraps the row.
1448
+ if(key === undefined){
1449
+ wrap.className = 'novalue';
1450
+ wrap.setAttribute('data-tip', NO_VALUE_REASON(facet));
1451
+ } else if(isText) wrap.className = 'textlayer';
1035
1452
  const cb = document.createElement('input');
1036
1453
  cb.type = 'checkbox';
1037
- cb.checked = setOf(facet).has(selValue(it));
1454
+ // The id sits on the CHECKBOX, not on the <label> wrapping the row, and the difference is
1455
+ // reachability rather than pedantry. Instructor's `activate()` finds the carrier by selector and
1456
+ // calls `.focus()` on it; a <label> is not focusable, so from the `?` sheet "Include a value"
1457
+ // could never take the user to the control and fell back to merely describing it. On the input it
1458
+ // focuses, and `focusFor` — which resolves upward through `closest('… input …')` — then reads the
1459
+ // very state this row goes out of its way to expose: `aria-disabled` and `data-blocked-reason`.
1460
+ // The row still announces its layer/width/colour, because `accessibleNameOf` names a form control
1461
+ // from its wrapping label. Hovering is unaffected: `Commands.resolve` walks up from the hovered
1462
+ // node, and the checkbox is what a pointer lands on. (`vector.show-kind` keeps the label carrier
1463
+ // for now — a different surface, and not this slice's to change.)
1464
+ cb.setAttribute('data-command-id', 'filter.facet-toggle');
1465
+ cb.checked = key !== undefined && setOf(facet).has(key);
1038
1466
  cb.value = String(val);
1039
- cb.addEventListener('change', () => { const s = setOf(facet); cb.checked ? s.add(selValue(it)) : s.delete(selValue(it)); markDirty(); apply(); });
1467
+ // syncFacetChecks(), not just this one box: two rows whose values canonicalise the same (a
1468
+ // `#ABC123` beside a `#abc123`) are ONE selection value, so the sibling must move with it rather
1469
+ // than sit stale until the next rebuild. A no-op on every filter our own extractor produces.
1470
+ // `aria-disabled`, NOT the `disabled` property, and the difference is the whole point.
1471
+ //
1472
+ // A truly disabled input is out of the tab order and fires no pointer events, so nothing can
1473
+ // reach it: Instructor's `focusFor` resolves UPWARD from the hovered/focused element
1474
+ // (`closest('button, …, input, …')` in web/instructor.js), and from a `<label>` carrier it cannot
1475
+ // descend into the box. `disabled` here meant the state was set and no reader existed — a record
1476
+ // nobody could read, which is this epic's own failure shape in miniature. `aria-disabled` keeps
1477
+ // the control focusable and hoverable, so `focusFor` lands ON it and reads exactly the two things
1478
+ // it looks for: `target.getAttribute('aria-disabled') === 'true'` and `data-blocked-reason`.
1479
+ //
1480
+ // It also fixes the modality gap: a `data-tip` renders on pointerover only, so a keyboard or
1481
+ // screen-reader user got nothing. `aria-describedby` points at a real node carrying the same
1482
+ // sentence, and the row stays reachable by Tab to hear it.
1483
+ //
1484
+ // The cost is that a click still toggles the box natively, so the handler puts it back. Refusing
1485
+ // visibly beats refusing silently — and the reason is one hover, one Tab or one `?` away.
1486
+ if(key === undefined){
1487
+ const why = document.createElement('span');
1488
+ why.className = 'sr-only';
1489
+ why.id = 'novalue-' + facet + '-' + noValueSeq++;
1490
+ why.textContent = NO_VALUE_REASON(facet);
1491
+ cb.setAttribute('aria-disabled', 'true');
1492
+ cb.setAttribute('aria-describedby', why.id);
1493
+ cb.setAttribute('data-blocked-reason', NO_VALUE_REASON(facet));
1494
+ // Snap the box back, and mark dirty when the row's STORED flag disagrees with what Save will
1495
+ // write. Otherwise the refusal copy promises "saving will clear its tick" on a page whose Save
1496
+ // button nothing can enable.
1497
+ cb.addEventListener('change', () => { cb.checked = false; if(facetOnWouldChange(facet)) markDirty(); });
1498
+ // Appended to the LIST, not to the row. A <label> wrapping an input contributes its text to that
1499
+ // input's accessible NAME, and `.sr-only` clips a node visually without removing it from the
1500
+ // accname computation - so parking the sentence inside `wrap` made the checkbox announce the
1501
+ // whole refusal as its name, then `aria-describedby` read it out a second time, with the value
1502
+ // the user is actually looking at arriving last. `aria-describedby` resolves document-wide, so
1503
+ // a sibling works and announces once, as a description.
1504
+ box.appendChild(why);
1505
+ }
1506
+ else cb.addEventListener('change', () => { const s = setOf(facet); cb.checked ? s.add(key) : s.delete(key); syncFacetChecks(); markDirty(); apply(); });
1507
+ // NOTE: the per-row handler always marks dirty — a click on a live row IS an edit, even when the
1508
+ // resulting flag matches what was stored (the user re-ticked what they just unticked). Only the
1509
+ // bulk controls need `saveWouldChange`, because only they can run over rows they cannot move.
1040
1510
  wrap.appendChild(cb);
1041
1511
  if(facet === 'layers'){
1042
1512
  const sw = document.createElement('span'); sw.className = 'sw';
@@ -1048,9 +1518,16 @@ function buildFacet(facet, items, valueKey, label, selValue){
1048
1518
  wrap.appendChild(sw);
1049
1519
  }
1050
1520
  wrap.appendChild(document.createTextNode(' ' + label(it) + ' '));
1051
- const c = document.createElement('em'); c.textContent = it.count; wrap.appendChild(c);
1521
+ const c = document.createElement('em'); c.textContent = it.count;
1522
+ // The count spans the WHOLE drawing set — schedule and detail sheets included — while the canvas
1523
+ // stat chip counts only what is shown on THIS sheet. Two numbers that count different things are
1524
+ // on screen together, so the one that is not obvious carries the explanation. data-tip, never
1525
+ // title=. (The sign-off step says the same thing about the same number.)
1526
+ 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.');
1527
+ wrap.appendChild(c);
1052
1528
  box.appendChild(wrap);
1053
1529
  }
1530
+ syncFacetBulk(facet);
1054
1531
  }
1055
1532
 
1056
1533
  function syncFacetChecks(){
@@ -1059,8 +1536,8 @@ function syncFacetChecks(){
1059
1536
  const cbs = document.querySelectorAll(`#facet-${facet} input[type=checkbox]`);
1060
1537
  cbs.forEach((cb, i) => {
1061
1538
  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);
1539
+ const key = facetRowKey(facet, it);
1540
+ cb.checked = key !== undefined && setOf(facet).has(key);
1064
1541
  });
1065
1542
  }
1066
1543
  }
@@ -1093,13 +1570,34 @@ document.querySelectorAll('input[name=dim]').forEach(cb => cb.addEventListener('
1093
1570
  mode = canonicalMode([...document.querySelectorAll('input[name=dim]:checked')].map(c => c.value));
1094
1571
  markDirty(); apply();
1095
1572
  }));
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)));
1573
+ // KNOWING EQUIVALENT MUTANT (both lines): removing the `aria-disabled` guard turns no test red. It is
1574
+ // set only when NO row in the list has a usable key, and `setAllFacet` skips exactly those rows — so
1575
+ // the handler is a provable no-op in the only state the guard fires in. Kept because a control that
1576
+ // says it will do nothing should not run its handler, and recorded here so the next person reading a
1577
+ // sweep can tell it from an untested branch. The gate a user can observe is the `aria-disabled` and
1578
+ // the reason set by `syncFacetBulk`, both of which ARE tested.
1579
+ document.querySelectorAll('[data-all]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.all, true); }));
1580
+ document.querySelectorAll('[data-none]').forEach(b => b.addEventListener('click', () => { if(b.getAttribute('aria-disabled') !== 'true') setAllFacet(b.dataset.none, false); }));
1098
1581
  function setAllFacet(facet, on){
1099
1582
  const s = setOf(facet);
1100
1583
  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();
1584
+ // CANONICAL keys, exactly as the per-row handler and the eyedropper add them. Adding a raw value
1585
+ // here was the concrete regression this slice exists to prevent: All ticks the box, Save writes OFF.
1586
+ // A row with no canonical key is skipped — it is not selectable at all, and its checkbox is disabled.
1587
+ // An All that alters nothing must not claim an unsaved edit: on a list whose rows are ALL
1588
+ // unselectable, an unconditional markDirty() made All and None produce the identical outcome — no
1589
+ // visible change plus an "Unsaved ●" chip — which is exactly the report a user cannot tell a working
1590
+ // control from a broken one by.
1591
+ //
1592
+ // But "did the SET move" is the wrong question, and asking it hid two real edits. A row whose value
1593
+ // has no canonical key carries a stored `on` that Save is about to CLEAR — the refusal copy promises
1594
+ // exactly that — and a row with no `on` at all carries a load-time default Save is about to write
1595
+ // explicitly. Neither moves the Set, so neither enabled Save, and on an all-unselectable facet the
1596
+ // promise "saving will clear its tick" had no route to a save at all.
1597
+ //
1598
+ // So the question is the honest one: would Save write a different `on` than the row holds now?
1599
+ for(const it of items){ const key = facetRowKey(facet, it); if(key !== undefined){ on ? s.add(key) : s.delete(key); } }
1600
+ syncFacetChecks(); if(facetOnWouldChange(facet)) markDirty(); apply();
1103
1601
  }
1104
1602
 
1105
1603
  // --- eyedropper: pick a line/label -> popover, + Add each / Add all ---
@@ -1109,25 +1607,80 @@ function openEyedropper(clientX, clientY, el){
1109
1607
  eyeEl = el;
1110
1608
  const body = document.getElementById('eyeBody');
1111
1609
  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>`));
1610
+ // A picked element whose value is not a value for its dimension cannot be added — `eyedropperAdd`
1611
+ // skips it. The checkbox in the panel REFUSES VISIBLY for the same value, so a + Add that quietly
1612
+ // did nothing would be the same refusal on two surfaces with only one of them honest.
1613
+ const addable = (dim) => eyeAddable(el, dim);
1614
+ const dropped = ['layer', 'thickness', 'color'].filter(dim => eyeOffers(el, dim) && !addable(dim));
1615
+ const whyBlocked = (dim) => facetKey(dim, el[FACET_DIMS[dim].elementKey]) === undefined
1616
+ ? NO_VALUE_REASON(FACET_CONTROL_OF[dim]) : NO_ROW_REASON(FACET_CONTROL_OF[dim]);
1617
+ rows.push(eyeRow('Layer', el.layer, 'layer', `<span class="sw" style="background:${safeColor(layerColor[el.layer])}"></span>`, addable('layer'), whyBlocked('layer')));
1618
+ // Offered when applicable, refused when unusable — the same two-step as layer and colour.
1619
+ if(eyeOffers(el, 'thickness')) rows.push(eyeRow('Thickness', thicknessLabel(el.w), 'thickness', '', addable('thickness'), whyBlocked('thickness')));
1620
+ rows.push(eyeRow('Color', el.color, 'color', `<span class="sw" style="background:${safeColor(el.color)}"></span>`, addable('color'), whyBlocked('color')));
1115
1621
  body.innerHTML = rows.join('');
1116
- body.querySelectorAll('button[data-add]').forEach(b => b.onclick = () => { eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEye(); });
1622
+ body.querySelectorAll('button[data-add]:not([aria-disabled])').forEach(b => b.onclick = () => { eyedropperAdd(sel, el, b.dataset.add); syncFacetChecks(); markDirty(); apply(); closeEye(); });
1623
+ // The Add-all control tells the truth about what it is about to do — including refusing outright
1624
+ // when the pick offers nothing this filter can express.
1625
+ const addAll = document.getElementById('eyeAddAll');
1626
+ const addableCount = eyeAddableDims(el).length;
1627
+ addAll.textContent = addableCount === 0 ? 'Add all to filter'
1628
+ : dropped.length ? 'Add the ' + addableCount + ' usable value' + (addableCount === 1 ? '' : 's')
1629
+ : 'Add all to filter';
1630
+ if(addableCount === 0){
1631
+ addAll.setAttribute('aria-disabled', 'true');
1632
+ addAll.setAttribute('data-blocked-reason', whyBlocked(dropped[0]));
1633
+ addAll.setAttribute('data-tip', whyBlocked(dropped[0]));
1634
+ } else {
1635
+ addAll.removeAttribute('aria-disabled');
1636
+ addAll.removeAttribute('data-blocked-reason');
1637
+ if(dropped.length) addAll.setAttribute('data-tip', whyBlocked(dropped[0]));
1638
+ else addAll.removeAttribute('data-tip');
1639
+ }
1117
1640
  eye.classList.add('show');
1118
1641
  const w = eye.offsetWidth || 220, h = eye.offsetHeight || 160;
1119
1642
  eye.style.left = Math.min(clientX + 8, window.innerWidth - w - 8) + 'px';
1120
1643
  eye.style.top = Math.min(clientY + 8, window.innerHeight - h - 8) + 'px';
1121
1644
  }
1122
- function eyeRow(k, v, which, swatch){
1645
+ function eyeRow(k, v, which, swatch, addable, reason){
1123
1646
  // data-tip, never title=: .v ellipsizes, so this row NEEDS a tooltip to show a long layer name in
1124
1647
  // full — and a native title= would draw it as the light OS bubble, the one browser default this
1125
1648
  // 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>`;
1649
+ //
1650
+ // `aria-disabled` rather than `disabled`, for the same reason the facet checkbox uses it: a
1651
+ // disabled button is unreachable by hover, Tab and Instructor alike, so the refusal would carry no
1652
+ // explanation on any modality. The click handler is simply not bound to it.
1653
+ const why = reason || NO_VALUE_REASON(FACET_CONTROL_OF[which]);
1654
+ const blocked = addable ? '' : ` aria-disabled="true" data-blocked-reason="${esc(why)}" data-tip="${esc(why)}"`;
1655
+ 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
1656
  }
1128
1657
  function closeEye(){ eye.classList.remove('show'); eyeEl = null; }
1129
1658
  document.getElementById('eyeClose').onclick = closeEye;
1130
- document.getElementById('eyeAddAll').onclick = () => { if(eyeEl){ eyedropperAdd(sel, eyeEl, 'all'); syncFacetChecks(); markDirty(); apply(); } closeEye(); };
1659
+ // "Add all" is the THIRD surface this refusal has to be honest on, and it was the one left dishonest:
1660
+ // the per-dimension + Add buttons refuse visibly while this one stayed enabled and quietly added two
1661
+ // of three — or, for an element with nothing addable, closed the popover having changed nothing and
1662
+ // raised an "Unsaved ●" chip anyway. That is verbatim the failure `setAllFacet` above exists to fix.
1663
+ //
1664
+ // So it is gated on whether ANY offered dimension is addable, it says which one it is dropping when it
1665
+ // cannot take them all, and it marks dirty only when it actually added something.
1666
+ document.getElementById('eyeAddAll').onclick = () => {
1667
+ if(eyeEl && eyeAddableDims(eyeEl).length){
1668
+ // Per DIMENSION, never `'all'`. `eyedropperAdd`'s own `'all'` adds every value with a canonical
1669
+ // key, and it cannot know which of them this filter lists a row for — so it would add exactly the
1670
+ // unsaveable value the button has just said it is dropping. Adding what was advertised, and only
1671
+ // that, is what makes the label true.
1672
+ for(const dim of eyeAddableDims(eyeEl)) eyedropperAdd(sel, eyeEl, dim);
1673
+ // The SAME question setAllFacet asks, for the same reason: adding a value that is already ticked
1674
+ // changes nothing, and a pick with nothing addable changes nothing at all — neither is an edit.
1675
+ syncFacetChecks(); if(['layers','thicknesses','colors'].some(facetOnWouldChange)) markDirty(); apply();
1676
+ }
1677
+ // KNOWING EQUIVALENT MUTANT: dropping the `eyeAddableDims(...).length` guard turns no test red,
1678
+ // because `eyedropperAdd` skips every unusable value anyway and `saveWouldChange` then reports no
1679
+ // edit — the call is a provable no-op. It is kept as defence in depth and to state the intent, and
1680
+ // recorded here so the next person reading a sweep can tell it from an untested branch. The gate
1681
+ // that a user can actually observe is the `aria-disabled` + reason set in `openEyedropper`.
1682
+ closeEye();
1683
+ };
1131
1684
 
1132
1685
  // --- pan/zoom via viewBox; a click (no drag) on an element opens the eyedropper ---
1133
1686
  let base = { x:0, y:0, w:1000, h:1000 }, vb = { ...base }, drag = null;
@@ -1167,7 +1720,7 @@ document.getElementById('fit2').onclick = fit;
1167
1720
  document.getElementById('zoomsteel2').onclick = zoomSteel;
1168
1721
 
1169
1722
  // --- save: write the selection + mode onto C.filter and PUT the contract ---
1170
- saveBtn.onclick = save;
1723
+ saveBtn.onclick = () => { void beginSave(); };
1171
1724
  // Serialize THIS tab's writes, as the steel editor does. Without it the page conflicts with ITSELF:
1172
1725
  // markDirty() re-enables Save while a save is in flight, so a second click sent a second PUT carrying the
1173
1726
  // SAME If-Match tag — one won, the other came back 412 and latched a conflict caused by nobody but the user.
@@ -1178,6 +1731,556 @@ saveBtn.onclick = save;
1178
1731
  let writeQueue = Promise.resolve();
1179
1732
  const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
1180
1733
  function save(){ return queueWrite(saveNow); }
1734
+ function blockRequiredCheckpointSave(message){
1735
+ checkpointSaveBlocked = true;
1736
+ setSaved('err');
1737
+ setRequiredSaveCue(false, false);
1738
+ saveBtn.disabled = true;
1739
+ showChangedBanner(message, { dismissible:false, requiredRecovery:true });
1740
+ }
1741
+
1742
+ /* ── the exclusion sign-off confirm step ────────────────────────────────────────────
1743
+ A value switched OFF on a dimension the filter matches on is one whose every matching element the
1744
+ completion proof may dismiss as a group, with no line-by-line reason. So for a revision read, Save
1745
+ first shows the human exactly that list — grouped by dimension — and asks them to approve it; the
1746
+ ordered {dim, value} pairs ride out with the Save and the server records the approval against them.
1747
+ Nothing dismissible means nothing is being dismissed wholesale, so there is no decision to record
1748
+ and the step is skipped entirely rather than shown empty.
1749
+
1750
+ Generalised from layers alone in #805 Phase D. On a FLATTENED drawing set — no optional-content
1751
+ groups, every element on one synthetic layer name — the layer facet carries no information at all
1752
+ and this step could dismiss nothing, which is why line weight is now here too. */
1753
+ let signoffValues = []; // the ordered [{dim, value}] currently displayed and about to be submitted
1754
+ let pendingSignOff = null; // handed to saveNow for exactly one checkpoint POST
1755
+ let signoffOutcome = null; // a refusal code, for the notice below
1756
+ let signoffBusy = false; // a write is in flight: dismissal is locked
1757
+ let signoffPreview = null; // the server's reply: { manifestHash, controlsHash, potentialLines }
1758
+ let signoffPreviewState = 'idle'; // 'idle' | 'pending' | 'ok' | 'failed'
1759
+ let signoffPreviewSeq = 0; // ONE in-flight preview; a stale reply is ignored, never rendered
1760
+ const signoffOverlay = document.getElementById('signoffOverlay');
1761
+ const signoffPanel = document.getElementById('signoffPanel');
1762
+ const signoffList = document.getElementById('signoffList');
1763
+ const signoffTotal = document.getElementById('signoffTotal');
1764
+ const signoffCaption = document.getElementById('signoffCaption');
1765
+ const signoffNotice = document.getElementById('signoffNotice');
1766
+ const signoffCancel = document.getElementById('signoffCancel');
1767
+ const signoffApprove = document.getElementById('signoffApprove');
1768
+ const signoffCloseBtn = document.getElementById('signoffClose');
1769
+ const signoffReload = document.getElementById('signoffReload');
1770
+ const SIGNOFF_APPROVE_LABEL = 'Approve these exclusions';
1771
+ /* Long enough that a slow fold on a 120,000-element set still lands, short enough that a hung request
1772
+ does not leave the modal waiting forever — §4.3b requires the modal not to block on one. A timeout
1773
+ resolves to the FAILED state, which is a real state with a way out, not a spinner nobody can leave. */
1774
+ const SIGNOFF_PREVIEW_TIMEOUT_MS = 30_000;
1775
+
1776
+ /** The visible heading for each dimension's group, in MODE_ORDER.
1777
+ * "Line weight", not "Thickness": this is a structural-steel product, where "thickness" reads as
1778
+ * PLATE thickness. On the one screen where a human authorises dismissing elements, the drawn-line
1779
+ * meaning has to be unambiguous. (The panel's own checkbox still says "Thickness"; flagged.) */
1780
+ const SIGNOFF_GROUP_LABEL = { thickness: 'Line weight', layer: 'Layer', color: 'Color' };
1781
+
1782
+ /** What each row's count actually counts — per dimension, because they are not the same population.
1783
+ * The extractor never counts a text span into `width_counts`, so a line-weight count is drawn
1784
+ * geometry only, while a layer or colour count includes text and circles. Every one of them ends by
1785
+ * pointing at the total, because the two numbers are not reconcilable by arithmetic and a human who
1786
+ * adds the rows up must not read the difference as a bug. */
1787
+ const SIGNOFF_COUNT_TIP = {
1788
+ thickness: 'Every line and circle drawn at this weight across the whole drawing set — text is not counted here, and this is not the same population as the total above.',
1789
+ layer: 'Every element on this layer across the whole drawing set — lines, text and circles included — not the same population as the total above.',
1790
+ color: 'Every element in this colour across the whole drawing set — lines, text and circles included — not the same population as the total above.',
1791
+ };
1792
+
1793
+ /** What the human is told when an approval cannot proceed.
1794
+ *
1795
+ * `saved` is load-bearing and is why this is a table rather than two strings. The three server
1796
+ * refusals arrive AFTER the contract PUT has committed — that is what the checkpoint route is for —
1797
+ * so their copy truthfully opens by saying the filter edit is safe. The preview failure happens
1798
+ * BEFORE the PUT, where the opposite is true, and telling that human their changes were saved would
1799
+ * be a plain lie on the one screen that cannot afford one. */
1800
+ const SIGNOFF_PROBLEMS = {
1801
+ 'steel-exclusion-signoff-stale': {
1802
+ saved: true,
1803
+ title: 'The exclusion list changed since you approved it',
1804
+ 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 what this read would really dismiss and approve that.',
1805
+ },
1806
+ 'steel-exclusion-preview-stale': {
1807
+ saved: true,
1808
+ title: 'This drawing set was re-scanned while you were reviewing',
1809
+ body: 'Your filter changes were saved. The counts you were shown describe an older scan of this drawing set, so the approval was refused rather than recorded against evidence you did not see — reload and approve what the current scan shows.',
1810
+ },
1811
+ 'steel-census-scope-missing': {
1812
+ saved: true,
1813
+ title: 'This read can’t record an approval yet',
1814
+ body: 'Your filter changes were saved. This request’s drawing scan was made before whole-set approval existed and covers only the model sheets — ask your terminal AI to re-read this revision, then reload and approve the list.',
1815
+ },
1816
+ // ── the PREVIEW's refusals. Every one of these happens BEFORE the contract PUT, so every one says
1817
+ // the changes are not saved — which is why they cannot simply reuse the entries above even where
1818
+ // the server code is the same word. `steel-census-scope-missing` is the case that forced this
1819
+ // table into existence: collapsing every preview failure into the generic entry below told the
1820
+ // human to "press Save again", which re-previews, fails identically, and loops forever, while the
1821
+ // sentence that would actually help was already written three entries up and unreachable.
1822
+ 'preview:steel-census-scope-missing': {
1823
+ saved: false,
1824
+ title: 'This read can’t work out what it would dismiss yet',
1825
+ body: 'Your filter changes have NOT been saved. This request’s drawing scan was made before whole-set approval existed and covers only the model sheets — ask your terminal AI to re-read this revision, then reload.',
1826
+ },
1827
+ 'preview:steel-manifest-missing': {
1828
+ saved: false,
1829
+ title: 'This read’s drawing scan is missing',
1830
+ body: 'Your filter changes have NOT been saved. The server no longer holds a coherent scan of this drawing set — ask your terminal AI to re-scan this revision, then reload.',
1831
+ },
1832
+ 'preview:steel-manifest-unrepresentable': {
1833
+ saved: false,
1834
+ title: 'This read’s drawing scan is incomplete',
1835
+ body: 'Your filter changes have NOT been saved. One sheet in this scan does not record what it contains, so nothing can say what excluding a value would dismiss — ask your terminal AI to re-scan this revision, then reload.',
1836
+ },
1837
+ 'preview:steel-manifest-ledger-unbound': {
1838
+ saved: false,
1839
+ title: 'This scan and this filter describe different drawing sets',
1840
+ body: 'Your filter changes have NOT been saved. The scan on the server no longer matches the filter on this page, so no count of what would be dismissed can be trusted — ask your terminal AI to re-scan this revision, then reload.',
1841
+ },
1842
+ 'preview:steel-preview-controls-stale': {
1843
+ saved: false,
1844
+ title: 'This page is showing an out-of-date filter',
1845
+ body: 'Your filter changes have NOT been saved. The controls on this page are not the ones the current scan published, so approving them would approve a different list — reload to see what is really there.',
1846
+ },
1847
+ 'preview:steel-preview-not-pending': {
1848
+ saved: false,
1849
+ title: 'This read is no longer waiting for a filter',
1850
+ body: 'Your filter changes have NOT been saved. This read has moved on or been closed, so there is nothing here to approve — reload to see where it got to.',
1851
+ },
1852
+ 'steel-exclusion-preview-unavailable': {
1853
+ // The ONLY refusal that happens BEFORE the contract PUT. Everything about how it is presented
1854
+ // follows from that: its copy says the changes were not saved, and closing it must not latch the
1855
+ // "Approval needed" chip, because there is nothing approved-or-not yet — the edit is simply
1856
+ // still unsaved, and the chip that says so is the one the user needs.
1857
+ saved: false,
1858
+ title: 'FloLess couldn’t work out what this read would dismiss',
1859
+ body: 'Your filter changes have NOT been saved. Approving without those figures would record a decision against evidence nobody was shown, so nothing was written — close this and press Save again.',
1860
+ },
1861
+ };
1862
+
1863
+ /**
1864
+ * A refusal the SERVER named and this page has no authored copy for, held beside the table rather than
1865
+ * written into it (see the checkpoint arm in `saveNow` for why). At most one at a time: it belongs to
1866
+ * the attempt that produced it, and the next attempt clears it with everything else.
1867
+ */
1868
+ let relayedRefusal = null;
1869
+
1870
+ /** The copy for one refusal — authored where this page has it, relayed from the server where not. */
1871
+ function signoffProblem(code){
1872
+ return (code && Object.prototype.hasOwnProperty.call(SIGNOFF_PROBLEMS, code)) ? SIGNOFF_PROBLEMS[code] : relayedRefusal;
1873
+ }
1874
+
1875
+ /**
1876
+ * The count shown beside one dismissible value: `filter.<facet>[].count`.
1877
+ *
1878
+ * Every element carrying that value across the drawing set, NOT split by page role, and NOT the same
1879
+ * population as the ledger lines the total above counts. Labelled and tooltipped for exactly that,
1880
+ * because the honest number is the one the human is deciding against.
1881
+ *
1882
+ * Takes the count ONCE per canonical value, never a sum across rows. Summing was right while each row
1883
+ * carried its own partial tally, and became wrong the moment `mergeWholeSetLayerCensus` started
1884
+ * stamping the GROUP's whole-set count onto every row of a canonical group: two rows for one value
1885
+ * then each reported the whole population, and adding them doubled it. That number is what a human
1886
+ * reads at the moment they authorise a wholesale dismissal, so an inflated one is exactly the kind of
1887
+ * wrong this surface cannot afford.
1888
+ *
1889
+ * Matched on the CANONICAL key, not the raw row value — the same fold `dismissibleFacetValues` used
1890
+ * to decide the row is dismissible at all. Matching raw would silently find no count for a
1891
+ * hand-edited `#ABC123` row whose approved value is `#abc123`, and render "element count unknown"
1892
+ * over a value carrying thousands of elements.
1893
+ *
1894
+ * `Number.isFinite` still gates: a junk count is not a count, and `null` renders as "element count
1895
+ * unknown" rather than a number nobody can trust.
1896
+ */
1897
+ function facetElementCount(dim, value){
1898
+ const control = FACET_DIMS[dim].control, key = FACET_DIMS[dim].rowKey;
1899
+ for(const row of (F && F[control]) || []){
1900
+ if(row && facetKey(dim, row[key]) === value && Number.isFinite(row.count)) return row.count;
1901
+ }
1902
+ return null;
1903
+ }
1904
+
1905
+ /** How one dismissible value reads on its row. Thickness through the same `thicknessLabel` the panel
1906
+ * uses, so the modal and the checkbox name the same value the same way. */
1907
+ function signoffValueLabel(dim, value){
1908
+ return dim === 'thickness' ? thicknessLabel(value) : String(value);
1909
+ }
1910
+
1911
+ function setSignoffMode(problem){
1912
+ const failed = !!problem;
1913
+ signoffNotice.hidden = !failed;
1914
+ signoffList.hidden = failed;
1915
+ signoffTotal.hidden = failed;
1916
+ signoffCaption.hidden = failed;
1917
+ signoffCancel.hidden = failed; signoffApprove.hidden = failed;
1918
+ signoffCloseBtn.hidden = !failed;
1919
+ // Reload is offered only where the work is already SAVED. On a pre-PUT refusal the human still has
1920
+ // unsaved ticks, and reloading throws them away — the `beforeunload` guard would fire, but inside the
1921
+ // shell's iframe that is the native browser prompt `__floGuard` exists to avoid. Close, then Save
1922
+ // again, is the recovery that cannot lose anything, and it is what that copy already says.
1923
+ signoffReload.hidden = !failed || !(signoffProblem(problem) && signoffProblem(problem).saved);
1924
+ if(!failed) return;
1925
+ // Neither refusal can be cleared by pressing Approve again, so the approve pair is REPLACED rather
1926
+ // than left on screen as a false affordance.
1927
+ const copy = signoffProblem(problem);
1928
+ signoffNotice.textContent = '';
1929
+ const heading = document.createElement('b'); heading.textContent = copy.title;
1930
+ const body = document.createElement('p'); body.textContent = copy.body;
1931
+ signoffNotice.append(heading, body);
1932
+ // Approve held focus when it was pressed, and it has just been HIDDEN — leaving focus on a hidden
1933
+ // control drops it on <body>. Reload is the only action that can make this checkpoint retryable, so
1934
+ // put focus there; Close remains available only to dismiss the explanation.
1935
+ signoffReload.focus();
1936
+ }
1937
+
1938
+ let signoffCoveredSurfaces = [];
1939
+ function coverSignoffBackground(){
1940
+ if(signoffCoveredSurfaces.length) return;
1941
+ signoffCoveredSurfaces = ['app', 'eye'].map((id) => document.getElementById(id)).filter(Boolean).map((element) => ({
1942
+ element,
1943
+ hadInert: element.hasAttribute('inert'),
1944
+ ariaHidden: element.getAttribute('aria-hidden'),
1945
+ }));
1946
+ for(const { element } of signoffCoveredSurfaces){
1947
+ element.setAttribute('inert', '');
1948
+ element.setAttribute('aria-hidden', 'true');
1949
+ }
1950
+ }
1951
+ function restoreSignoffBackground(){
1952
+ for(const { element, hadInert, ariaHidden } of signoffCoveredSurfaces){
1953
+ // The Save transaction may still own this lock when polling retires the dialog's checkpoint.
1954
+ // Release only the dialog's share; saveNow.finally performs the last unlock after both writes.
1955
+ if(!hadInert && !saveInFlight) element.removeAttribute('inert');
1956
+ else element.setAttribute('inert', '');
1957
+ if(ariaHidden === null) element.removeAttribute('aria-hidden');
1958
+ else element.setAttribute('aria-hidden', ariaHidden);
1959
+ }
1960
+ signoffCoveredSurfaces = [];
1961
+ }
1962
+
1963
+ /**
1964
+ * The magnitude, and its three states.
1965
+ *
1966
+ * A CEILING, never a promise — "up to", never "will". Before the proof exists the server cannot know
1967
+ * how many lines will actually be dismissed: a later `member` or `mixed` attestation, or simply an
1968
+ * absent one, reduces it under the ALL rule. What it can compute exactly is the maximum this approval
1969
+ * authorises.
1970
+ *
1971
+ * The pending and failed sentences carry no digits at all, which is what "render no total" protects:
1972
+ * a wrong magnitude here is worse than none, because the magnitude IS the decision being taken.
1973
+ */
1974
+ function renderSignoffTotal(){
1975
+ if(signoffPreviewState === 'ok' && signoffPreview){
1976
+ const lines = (signoffPreview.potentialLines.model || 0) + (signoffPreview.potentialLines.evidence || 0);
1977
+ signoffTotal.textContent = '';
1978
+ const strong = document.createElement('b');
1979
+ strong.textContent = 'Up to ' + lines.toLocaleString();
1980
+ signoffTotal.append(strong, document.createTextNode(' lines may be dismissed as a group.'));
1981
+ return;
1982
+ }
1983
+ signoffTotal.textContent = signoffPreviewState === 'pending'
1984
+ ? 'Working out how many lines this may dismiss…'
1985
+ : '';
1986
+ }
1987
+
1988
+ /** Approve is inert while the figure it is approving against has not arrived.
1989
+ *
1990
+ * `aria-disabled`, never the native `disabled` property — this page already uses that distinction
1991
+ * twice (the All/None controls, the eyedropper's Add buttons) so a refused control stays hoverable
1992
+ * and tabbable for the `data-tip` that explains WHY. A natively disabled button silently swallows
1993
+ * both. The focus trap keys off the `.disabled` property, so an aria-disabled Approve correctly
1994
+ * stays inside it. */
1995
+ function setSignoffApproveGate(){
1996
+ const waiting = signoffPreviewState === 'pending';
1997
+ if(waiting){
1998
+ signoffApprove.setAttribute('aria-disabled', 'true');
1999
+ signoffApprove.setAttribute('data-tip', 'Waiting for the count of what this read may dismiss.');
2000
+ } else {
2001
+ signoffApprove.removeAttribute('aria-disabled');
2002
+ signoffApprove.removeAttribute('data-tip');
2003
+ }
2004
+ }
2005
+
2006
+ /**
2007
+ * Ask the server what the PROPOSED ticks would dismiss.
2008
+ *
2009
+ * It has to be a preview rather than a figure off the manifest GET, because this modal opens BEFORE
2010
+ * the contract PUT: at this moment the proposed ticks exist only in browser memory and the server's
2011
+ * authoritative filter still describes the PREVIOUS selection. A number derived from that would be
2012
+ * about a different decision.
2013
+ *
2014
+ * The reply also carries the two hashes the approval is BOUND to — the manifest it was taken against
2015
+ * and the controls the human was shown a magnitude for — so a failed preview is not merely a missing
2016
+ * number: there is no approval to submit at all. That is why the failure state replaces the approve
2017
+ * pair rather than leaving an Approve button that would be refused.
2018
+ */
2019
+ async function runSignoffPreview(){
2020
+ const seq = ++signoffPreviewSeq;
2021
+ let previewRefusal = 'steel-exclusion-preview-unavailable';
2022
+ signoffPreview = null;
2023
+ signoffPreviewState = 'pending';
2024
+ renderSignoffTotal();
2025
+ setSignoffApproveGate();
2026
+ const body = { mode: F.mode, layers: [], thicknesses: [], colors: [] };
2027
+ for(const dim of MODE_ORDER){
2028
+ const d = FACET_DIMS[dim];
2029
+ body[d.control] = ((F && F[d.control]) || []).map(row => ({ [d.rowKey]: row[d.rowKey], on: row.on === true }));
2030
+ }
2031
+ const controller = new AbortController();
2032
+ const timer = setTimeout(() => controller.abort(), SIGNOFF_PREVIEW_TIMEOUT_MS);
2033
+ try {
2034
+ const res = await fetch(`/api/projects/${encodeURIComponent(PROJECT)}/revision-requests/${encodeURIComponent(revisionRequest)}/exclusion-preview`, {
2035
+ method: 'POST', headers: { 'content-type': 'application/json' },
2036
+ body: JSON.stringify(body), signal: controller.signal,
2037
+ });
2038
+ if(!res.ok){
2039
+ // The server's own CODE, not just its status. Each preview refusal has a different recovery and
2040
+ // the server already chose the right one; collapsing them into the generic failure below threw
2041
+ // that away — and for a model-pages-only census it produced a loop, telling the human to press
2042
+ // Save again when only their terminal AI can fix it.
2043
+ let refusal = null; try { refusal = await res.json(); } catch(_){ refusal = null; }
2044
+ const named = refusal && refusal.code && SIGNOFF_PROBLEMS['preview:' + refusal.code] ? 'preview:' + refusal.code : null;
2045
+ throw Object.assign(new Error('exclusion preview refused: ' + res.status), { signoffCode: named });
2046
+ }
2047
+ const payload = await res.json();
2048
+ if(seq !== signoffPreviewSeq) return; // a newer open superseded this one
2049
+ // The reply is CHECKED, not assumed, and the check is here rather than at the point of use.
2050
+ // `renderSignoffTotal` runs after this function's try/catch, so a missing `potentialLines` threw
2051
+ // out of the async function as an unhandled rejection: state stayed 'ok', the total kept reading
2052
+ // "Working out…", the approve gate was never released, and the dialog became a dead end escapable
2053
+ // only by Cancel. Fail-closed, but SILENTLY — which is the one thing the fail-closed rule forbids.
2054
+ // A malformed reply is a failed preview, and the failed state already says what to do about it.
2055
+ const counts = payload && payload.potentialLines;
2056
+ const usable = !!payload && typeof payload.manifestHash === 'string' && typeof payload.controlsHash === 'string'
2057
+ && !!counts && Number.isFinite(counts.model) && Number.isFinite(counts.evidence);
2058
+ if(!usable) throw new Error('exclusion preview reply is missing the figures the approval binds to');
2059
+ signoffPreview = payload;
2060
+ signoffPreviewState = 'ok';
2061
+ } catch(e){
2062
+ if(seq !== signoffPreviewSeq) return;
2063
+ console.error('exclusion preview failed', e);
2064
+ signoffPreviewState = 'failed';
2065
+ // A named refusal keeps its own sentence; a network drop, a timeout or an unrecognised code falls
2066
+ // to the generic one, which is the honest answer for "we do not know why".
2067
+ previewRefusal = (e && e.signoffCode) || 'steel-exclusion-preview-unavailable';
2068
+ } finally {
2069
+ clearTimeout(timer);
2070
+ }
2071
+ if(seq !== signoffPreviewSeq) return;
2072
+ renderSignoffTotal();
2073
+ setSignoffApproveGate();
2074
+ // No figures means no approval to submit — the two binding hashes come from this reply. Say so, and
2075
+ // offer the actions that can actually help, instead of an Approve the server would refuse.
2076
+ if(signoffPreviewState === 'failed'){ signoffOutcome = previewRefusal; setSignoffMode(signoffOutcome); }
2077
+ }
2078
+
2079
+ function openSignOff(values){
2080
+ signoffValues = values;
2081
+ // A NEW Save attempt starts clean. Without this a refusal from a previous attempt outlived it:
2082
+ // `setSignoffMode(null)` only hides the notice, so `closeSignOff` would latch "Approval needed" for
2083
+ // a refusal that no longer existed, and the header chip would re-open copy describing a failure the
2084
+ // user had already recovered from.
2085
+ signoffOutcome = null;
2086
+ relayedRefusal = null;
2087
+ signoffList.textContent = '';
2088
+ for(const dim of MODE_ORDER){
2089
+ const rows = values.filter(row => row.dim === dim);
2090
+ // Never rendered empty — the same rule that skips the whole modal when nothing is dismissible.
2091
+ if(!rows.length) continue;
2092
+ const section = document.createElement('section');
2093
+ section.className = 'signoff-group'; section.setAttribute('data-dim', dim);
2094
+ const heading = document.createElement('h3');
2095
+ heading.className = 'signoff-group-heading';
2096
+ heading.id = 'signoffGroup-' + dim;
2097
+ heading.textContent = SIGNOFF_GROUP_LABEL[dim];
2098
+ const list = document.createElement('ul');
2099
+ list.className = 'signoff-rows';
2100
+ list.setAttribute('aria-labelledby', heading.id);
2101
+ for(const entry of rows){
2102
+ const label = signoffValueLabel(dim, entry.value);
2103
+ const count = facetElementCount(dim, entry.value);
2104
+ const row = document.createElement('li'); row.className = 'signoff-row';
2105
+ row.setAttribute('data-dim', dim); row.setAttribute('data-value', String(entry.value));
2106
+ if(dim === 'color'){
2107
+ // The swatch renders DRAWING DATA, not chrome — the one non-baseline colour on this surface,
2108
+ // inside a bordered chip so a white or near-white value is still visible on the dark ground.
2109
+ const sw = document.createElement('span'); sw.className = 'sw';
2110
+ sw.style.background = safeColor(entry.value);
2111
+ row.appendChild(sw);
2112
+ }
2113
+ const name = document.createElement('span'); name.className = 'signoff-name';
2114
+ // data-tip, never title=: .signoff-name ellipsizes, so a long layer name needs the themed tooltip.
2115
+ name.textContent = label; name.setAttribute('data-tip', label);
2116
+ const shown = document.createElement('span'); shown.className = 'signoff-count';
2117
+ shown.textContent = count === null ? 'element count unknown' : count.toLocaleString() + ' element' + (count === 1 ? '' : 's');
2118
+ shown.setAttribute('data-tip', SIGNOFF_COUNT_TIP[dim]);
2119
+ row.append(name, shown);
2120
+ list.appendChild(row);
2121
+ }
2122
+ section.append(heading, list);
2123
+ signoffList.appendChild(section);
2124
+ }
2125
+ setSignoffMode(null);
2126
+ coverSignoffBackground();
2127
+ signoffOverlay.hidden = false;
2128
+ void runSignoffPreview();
2129
+ // Cancel takes focus, not Approve: a stray Enter must not fire the consequential action before the
2130
+ // list has been read.
2131
+ signoffCancel.focus();
2132
+ }
2133
+
2134
+ function closeSignOff(){
2135
+ if(signoffOverlay.hidden) return;
2136
+ signoffOverlay.hidden = true;
2137
+ restoreSignoffBackground();
2138
+ signoffValues = [];
2139
+ // Abandon any preview still in flight, so its reply cannot repaint a closed dialog or re-arm a
2140
+ // refusal the user has already dismissed.
2141
+ signoffPreviewSeq += 1;
2142
+ signoffPreviewState = 'idle';
2143
+ signoffPreview = null;
2144
+ setSignoffApproveGate();
2145
+ // A refusal is not resolved by dismissing its explanation. Leave the header carrying the state, as
2146
+ // a control that brings the explanation back — the same cyan "non-default, click to act" chip the
2147
+ // page already uses for a write conflict.
2148
+ //
2149
+ // ONLY for a refusal that happened after the contract PUT committed. The pre-PUT preview failure
2150
+ // wrote nothing at all: the edit is still unsaved, Save is still enabled, and the modal's own copy
2151
+ // says to press it again — so replacing the "Unsaved" chip with "Approval needed" would hide from
2152
+ // the user that they still have unsaved work, which is the opposite of what that chip is for.
2153
+ //
2154
+ // …and a refusal that does NOT latch the chip is DISCHARGED here, not merely un-latched. Leaving it
2155
+ // set made the header's re-open route a dead click: `reopenChipExplanation` routes on
2156
+ // `signoffOutcome` being truthy, so the chip would say "Unsaved", the click would resolve to a
2157
+ // refusal, and nothing would appear. (Found by re-reviewing the fix that introduced it — the guard
2158
+ // and the router have to agree about what "there is a refusal" means, and one place is where that
2159
+ // agreement lives.) Discharging is also simply true: nothing was written, so there is no state to
2160
+ // come back to, and the user's next action is Save again, which opens a fresh modal anyway.
2161
+ const latchesChip = !!(signoffOutcome && signoffProblem(signoffOutcome) && signoffProblem(signoffOutcome).saved);
2162
+ if(latchesChip) setSaved('signoff-blocked'); else signoffOutcome = null;
2163
+ // Focus must never be dropped on <body>. Save is DISABLED the instant a save succeeds and a
2164
+ // disabled control cannot take focus, so the fallback is the layer list the user came from — which
2165
+ // is also where they would go next to change what is ticked. (A real browser pass caught this:
2166
+ // returning focus to Save is right on Cancel and wrong on the success path.)
2167
+ // `:not([aria-disabled])`, and then ANY facet row: the first layer row can now be an unselectable
2168
+ // one, and a row that refuses input is not somewhere to leave the user. `:not(.dim)` too — a facet
2169
+ // whose dimension is unchecked carries `pointer-events:none; opacity:.4`, so a box inside it is
2170
+ // focusable but visually and pointer-inert, which is a worse landing spot than it looks. The mode
2171
+ // checkboxes are the last resort — always present, never dimmed — because the rule is never to drop
2172
+ // focus on <body>.
2173
+ const back = saveBtn.disabled
2174
+ ? (document.querySelector('#facet-layers:not(.dim) .opts input:not([aria-disabled])')
2175
+ || document.querySelector('.facet:not(.dim) .opts input:not([aria-disabled])')
2176
+ || document.querySelector('input[name=dim]'))
2177
+ : saveBtn;
2178
+ if(back) back.focus();
2179
+ }
2180
+
2181
+ /** Retire a checkpoint-owned decision surface when polling replaces that checkpoint. */
2182
+ function retireSignOffForCheckpointChange(){
2183
+ const wasVisible = !signoffOverlay.hidden;
2184
+ signoffOverlay.hidden = true;
2185
+ restoreSignoffBackground();
2186
+ signoffValues = [];
2187
+ pendingSignOff = null;
2188
+ signoffOutcome = null;
2189
+ // The SAME preview teardown `closeSignOff` performs, and for a sharper reason here: a retired
2190
+ // checkpoint's preview is answering a question about a manifest that is no longer this request's.
2191
+ // Without the sequence bump its reply would repaint a dialog that has been retired, and could
2192
+ // re-arm an approve gate for figures nobody will be shown. `relayedRefusal` goes with it — it
2193
+ // belongs to the attempt being retired.
2194
+ signoffPreviewSeq += 1;
2195
+ signoffPreviewState = 'idle';
2196
+ signoffPreview = null;
2197
+ relayedRefusal = null;
2198
+ setSignoffApproveGate();
2199
+ // A dismissed refusal is hidden but still checkpoint-owned: closeSignOff deliberately preserves
2200
+ // signoffOutcome so its status chip can reopen the explanation. A replacement must retire that state
2201
+ // too, without moving focus when no dialog is currently on screen.
2202
+ if(!wasVisible) return;
2203
+ // The replacement request's cue is painted later in the same turn. Move focus after that paint so
2204
+ // a keyboard user does not remain parked on a control inside the now-hidden dialog.
2205
+ setTimeout(() => {
2206
+ const target = saveBtn.disabled ? saveRequiredStatus : saveBtn;
2207
+ if(target && !target.hidden) target.focus();
2208
+ }, 0);
2209
+ }
2210
+
2211
+ function setSignoffBusy(busy){
2212
+ signoffBusy = busy;
2213
+ signoffCancel.disabled = busy; signoffApprove.disabled = busy;
2214
+ signoffApprove.textContent = busy ? 'Saving…' : SIGNOFF_APPROVE_LABEL;
2215
+ }
2216
+
2217
+ async function approveSignOff(){
2218
+ if(signoffBusy) return;
2219
+ // The gate the `aria-disabled` attribute advertises, enforced. An attribute alone is a claim; this
2220
+ // is the refusal, and it exists because `aria-disabled` deliberately leaves the control clickable
2221
+ // so its tooltip can explain itself.
2222
+ if(signoffApprove.getAttribute('aria-disabled') === 'true') return;
2223
+ if(signoffPreviewState !== 'ok' || !signoffPreview) return;
2224
+ setSignoffBusy(true);
2225
+ // The ordered pairs the confirm step displayed, the mode they were computed under, and the two
2226
+ // hashes binding them to the manifest and the controls this human was shown a magnitude for —
2227
+ // never a hash of the list itself, so the browser does not have to reproduce the server's canonical
2228
+ // JSON, and never the full control list, so the assertion stays specific to what was shown.
2229
+ pendingSignOff = {
2230
+ mode: F.mode,
2231
+ dismissed: signoffValues.map(row => ({ dim: row.dim, value: row.value })),
2232
+ manifestHash: signoffPreview.manifestHash,
2233
+ controlsHash: signoffPreview.controlsHash,
2234
+ };
2235
+ signoffOutcome = null;
2236
+ try { await save(); } finally { setSignoffBusy(false); pendingSignOff = null; }
2237
+ // A checkpoint refusal keeps the modal open and explains itself. Anything else (a 412 conflict, a
2238
+ // 428, a dropped connection) is a document-level failure the page's own chip and banner already
2239
+ // explain — duplicating that inside the modal would fork one failure into two stories.
2240
+ if(signoffOutcome) setSignoffMode(signoffOutcome); else closeSignOff();
2241
+ }
2242
+
2243
+ /** Bring the refusal explanation back — the chip is the only route once the dialog is dismissed.
2244
+ * No `saved` guard is needed here, deliberately: `closeSignOff` discharges any refusal that did not
2245
+ * latch the chip, so a still-set `signoffOutcome` IS one the chip is carrying. One rule, one place. */
2246
+ function reopenSignOffProblem(){
2247
+ if(!signoffOutcome) return;
2248
+ coverSignoffBackground();
2249
+ signoffOverlay.hidden = false;
2250
+ setSignoffMode(signoffOutcome);
2251
+ }
2252
+ signoffApprove.onclick = () => { void approveSignOff(); };
2253
+ signoffCancel.onclick = () => { if(!signoffBusy) closeSignOff(); };
2254
+ signoffCloseBtn.onclick = closeSignOff;
2255
+ signoffReload.onclick = () => location.reload();
2256
+ signoffOverlay.addEventListener('pointerdown', (e) => { if(e.target === signoffOverlay && !signoffBusy) closeSignOff(); });
2257
+ signoffPanel.addEventListener('keydown', (e) => {
2258
+ if(e.key === 'Escape' && !signoffBusy){ e.preventDefault(); closeSignOff(); return; }
2259
+ if(e.key !== 'Tab') return;
2260
+ // A real trap over the VISIBLE actions — the two hidden ones belong to the other state. An
2261
+ // aria-disabled Approve deliberately stays IN the trap: it is reachable so its tooltip can be read.
2262
+ const stops = [signoffCancel, signoffApprove, signoffCloseBtn, signoffReload].filter((b) => !b.hidden && !b.disabled);
2263
+ if(!stops.length) return;
2264
+ const first = stops[0], last = stops[stops.length - 1];
2265
+ if(e.shiftKey && document.activeElement === first){ e.preventDefault(); last.focus(); }
2266
+ else if(!e.shiftKey && document.activeElement === last){ e.preventDefault(); first.focus(); }
2267
+ });
2268
+
2269
+ /** Save's entry point: write the live selection onto the filter, then confirm the dismissals first. */
2270
+ async function beginSave(){
2271
+ // `!sel` (not just `!F`) for the same reason saveNow checks it — an empty state can carry a truthy
2272
+ // filter with nothing rendered.
2273
+ if(!C || !F || !sel) return;
2274
+ if(conflicted){ showChangedBanner(); return; }
2275
+ applySelToFilter(F, sel, mode);
2276
+ // Only a revision read records an approval, and only when something is actually being dismissed.
2277
+ // THE shared definition, never a second one: the same function the server's digest, the audit's
2278
+ // shorthand predicate and the `facet-census` coverage check all read.
2279
+ const values = revisionRequest ? dismissibleFacetValues(F) : [];
2280
+ if(!values.length){ pendingSignOff = null; await save(); return; }
2281
+ openSignOff(values);
2282
+ }
2283
+
1181
2284
  async function saveNow(){
1182
2285
  // `!sel` (not just `!F`) is the honest gate: an empty state can carry a truthy `filter` with nothing
1183
2286
  // rendered, and applySelToFilter would then dereference a null `sel` and throw uncaught.
@@ -1188,6 +2291,9 @@ async function saveNow(){
1188
2291
  // A second click while already conflicted must NOT silently re-fire a request we know will fail —
1189
2292
  // just re-surface the explanation.
1190
2293
  if(conflicted){ showChangedBanner(); return; }
2294
+ saveInFlight = true;
2295
+ setFilterEditingLocked(true);
2296
+ setRequiredSaveCue(false, false);
1191
2297
  saveBtn.disabled = true; setSaved('saving');
1192
2298
  // Name this write BEFORE sending it, deliberately: the server broadcasts before it replies, so the echo
1193
2299
  // can reach our own listener while this `await` is still pending — and an id we did not yet know would
@@ -1195,26 +2301,42 @@ async function saveNow(){
1195
2301
  // only runs with `dirty` true, so an unnamed echo takes the BANNER arm and accuses the AI of updating the
1196
2302
  // filter the user was in the middle of saving, while never adopting the new etag.
1197
2303
  const mid = newMutationId(CRYPTO); claimMutation(mid);
2304
+ // The parent can update `revisionRequest` while either fetch is in flight. One click must finish
2305
+ // the same checkpoint it started, so capture the id once and use it for both requests.
2306
+ const checkpointRequest = revisionRequest;
2307
+ const checkpointGeneration = revisionCheckpointGeneration;
1198
2308
  try {
1199
2309
  const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
1200
2310
  // TOTAL, as of P1c: a write with no precondition is refused (428). No tag means we read through the
1201
2311
  // BAKED fallback (the GET tags only store-backed documents) — this app has no draft yet — so the
1202
2312
  // honest precondition is `If-None-Match: *`, "I believe this store is empty".
1203
2313
  if(serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
1204
- if(revisionRequest) headers['x-floless-filter-request'] = revisionRequest;
2314
+ if(checkpointRequest) headers['x-floless-filter-request'] = checkpointRequest;
1205
2315
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C) });
1206
2316
  if(res.status === 428){ // a writer here sent no precondition — a bug in our code, not a user error.
1207
2317
  // NOT the conflict copy: nothing else wrote, so "changed somewhere else" would be a lie. This bar
1208
2318
  // is Reload-only (no overwrite button), which is already the right shape for a 428.
1209
2319
  releaseMutation(mid);
1210
2320
  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.');
2321
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
2322
+ if(checkpointRequest){
2323
+ 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.');
2324
+ } else {
2325
+ setSaved('err'); saveBtn.disabled = false; syncRequiredSaveCue();
2326
+ showChangedBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
2327
+ }
1213
2328
  return;
1214
2329
  }
1215
2330
  if(res.status === 412){
1216
2331
  releaseMutation(mid);
1217
- conflicted = true; setSaved('conflict'); saveBtn.disabled = false; showChangedBanner(); return;
2332
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
2333
+ conflicted = true;
2334
+ if(checkpointRequest){
2335
+ blockRequiredCheckpointSave('This Drawing Filter changed before the required save could finish. Reload the Drawing Filter, review the selections, and press Save filter again.');
2336
+ } else {
2337
+ setSaved('conflict'); saveBtn.disabled = false; syncRequiredSaveCue(); showChangedBanner();
2338
+ }
2339
+ return;
1218
2340
  }
1219
2341
  if(!res.ok){ releaseMutation(mid); throw new Error(await res.text()); }
1220
2342
  // NOTE the asymmetry, and that it is deliberate: success does NOT release the id. The echo for this
@@ -1222,20 +2344,93 @@ async function saveNow(){
1222
2344
  // external change and reload itself the instant the user saved. The id is consumed by that echo, or
1223
2345
  // dropped when the write fails, or discarded when the SSE channel closes (nothing can echo after that).
1224
2346
  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}),
2347
+ if(checkpointRequest && PROJECT && serverEtag){
2348
+ const body = { etag: serverEtag };
2349
+ // Built in `approveSignOff` from what the confirm step actually displayed and what the preview
2350
+ // actually returned — assembled there rather than here so this write cannot invent an approval
2351
+ // the human never saw.
2352
+ if(pendingSignOff) body.exclusionSignOff = pendingSignOff;
2353
+ const checkpoint = await fetch(`/api/projects/${encodeURIComponent(PROJECT)}/revision-requests/${encodeURIComponent(checkpointRequest)}/filter-saved`, {
2354
+ method:'POST', headers:{'content-type':'application/json'}, body:JSON.stringify(body),
1228
2355
  });
1229
- if(!checkpoint.ok) throw new Error(await checkpoint.text());
1230
- revisionRequest = '';
1231
- history.replaceState(null, '', location.pathname + PROJECT_QS);
2356
+ if(!checkpoint.ok){
2357
+ let payload = null; try { payload = await checkpoint.json(); } catch(_){ payload = null; }
2358
+ const code = payload && payload.code;
2359
+ // Keyed on the CODE, at ANY status, with a default arm — not on `409 && a code we authored`.
2360
+ // `/filter-saved` can refuse twelve ways and only three had authored copy, so the other nine
2361
+ // fell through to a bare `throw`: the modal closed exactly as it does on success while the
2362
+ // contract PUT had already committed, and the server's own recovery sentence — including the
2363
+ // one the design wrote for an over-cap approval, "leave more values switched on" — was
2364
+ // delivered to the console and nobody else. The default arm is the load-bearing half: a code
2365
+ // added server-side later must not silently rejoin that path. (pr-review-toolkit, finding 1.)
2366
+ //
2367
+ // The relayed copy is held BESIDE the table, never written into it. `code` comes off the wire,
2368
+ // and `table[code] = …` with a key of `__proto__` sets the object's PROTOTYPE rather than an
2369
+ // own property — the same hazard `canonicalJson` carries a null-prototype guard for. A
2370
+ // separate slot also keeps the authored table what it says it is: the copy this page wrote.
2371
+ if(code && !SIGNOFF_PROBLEMS[code] && payload && typeof payload.error === 'string'){
2372
+ relayedRefusal = {
2373
+ saved: true,
2374
+ title: 'This approval could not be recorded',
2375
+ body: 'Your filter changes were saved. ' + payload.error,
2376
+ };
2377
+ }
2378
+ if(SIGNOFF_PROBLEMS[code] || relayedRefusal){
2379
+ // The contract PUT has ALREADY committed by the time this route is called — that is what
2380
+ // it is for. So the user's edit is not lost and no rollback is attempted (one would be an
2381
+ // unsafe write against a document they may have edited further); only the checkpoint and
2382
+ // the approval are withheld, and the modal says exactly that.
2383
+ // The contract IS saved, so 'Unsaved' would be a lie — but so is a bare 'saved ✓' on a read
2384
+ // that cannot proceed. Remember the refusal so closing the dialog leaves a chip that names
2385
+ // the state and re-opens the explanation, instead of a dead end that looks finished.
2386
+ if(revisionRequest === checkpointRequest){
2387
+ signoffOutcome = code;
2388
+ dirty = false;
2389
+ checkpointSaveBlocked = true;
2390
+ setRequiredSaveCue(false, false);
2391
+ saveBtn.disabled = true;
2392
+ setSaved('signoff-blocked');
2393
+ }
2394
+ return;
2395
+ }
2396
+ throw new Error(payload ? (payload.error || JSON.stringify(payload)) : 'the Drawing Filter checkpoint was refused');
2397
+ }
2398
+ if(revisionRequest === checkpointRequest){
2399
+ revisionRequest = '';
2400
+ history.replaceState(null, '', location.pathname + PROJECT_QS);
2401
+ }
1232
2402
  }
1233
- dirty = false; setSaved('saved');
2403
+ // A newer request can become the required checkpoint after BOTH of A's writes succeeded. A's
2404
+ // success is real, but it cannot satisfy B or turn off B's required Save cue. Leave the editor's
2405
+ // existing dirty state intact so the user is still told exactly what the new checkpoint needs.
2406
+ const checkpointAdvanced = checkpointRequest && revisionCheckpointGeneration !== checkpointGeneration;
2407
+ const ownBroadcastClear = checkpointAdvanced && !revisionRequest
2408
+ && revisionCheckpointGeneration === checkpointGeneration + 1;
2409
+ if(checkpointAdvanced && !ownBroadcastClear){ setSaved(dirty ? 'dirty' : ''); syncRequiredSaveCue(); return; }
2410
+ dirty = false; setSaved('saved'); syncRequiredSaveCue();
1234
2411
  } catch(e){
1235
2412
  // The id is deliberately KEPT here. No response arrived, so we do not know whether the write landed —
1236
2413
  // and if it did, it broadcast, and releasing would make that echo look external and blame the AI for the
1237
2414
  // user's own save. A retained id costs nothing (see releaseMutation).
1238
- console.error('filter save failed', e); setSaved('err'); saveBtn.disabled = false;
2415
+ console.error('filter save failed', e);
2416
+ // A newer checkpoint can arrive while either write for the old one is in flight. The old failure
2417
+ // remains diagnostic in the console, but it must not latch the newer request into reload-only
2418
+ // recovery or replace its Ready cue with a stale error.
2419
+ if(checkpointRequest && revisionRequest !== checkpointRequest){ setSaved(dirty ? 'dirty' : ''); return; }
2420
+ setSaved('err');
2421
+ if(checkpointRequest){
2422
+ // The contract PUT may already have succeeded while the checkpoint POST failed. Retrying with
2423
+ // the old ETag would only produce another refusal, so stop the Ready pulse and give one safe,
2424
+ // explicit recovery action instead of inviting an endless click loop.
2425
+ blockRequiredCheckpointSave('FloLess couldn’t complete this required Drawing Filter save. Reload the Drawing Filter, review the selections, and press Save filter again.');
2426
+ } else {
2427
+ saveBtn.disabled = false;
2428
+ showChangedBanner('FloLess couldn’t save that Drawing Filter change. Reload and try again.');
2429
+ }
2430
+ } finally {
2431
+ saveInFlight = false;
2432
+ setFilterEditingLocked(false);
2433
+ syncRequiredSaveCue();
1239
2434
  }
1240
2435
  }
1241
2436
  window.addEventListener('beforeunload', e => { if(dirty){ e.preventDefault(); e.returnValue = ''; } });
@@ -1245,7 +2440,7 @@ window.addEventListener('beforeunload', e => { if(dirty){ e.preventDefault(); e.
1245
2440
  // backstop so an intentional close doesn't re-trigger the native prompt.
1246
2441
  window.__floGuard = {
1247
2442
  isDirty: () => dirty,
1248
- save: async () => { await save(); return !dirty; },
2443
+ save: async () => { await beginSave(); return !dirty; },
1249
2444
  discard: () => { dirty = false; },
1250
2445
  };
1251
2446
 
@@ -1273,6 +2468,22 @@ window.__filterTest = {
1273
2468
  sheetOptionTexts: () => sheetOptions().map(o => o.textContent),
1274
2469
  pick: (i) => { const el = nodes[i].el; openEyedropper(Math.round(window.innerWidth / 2), 200, el); return el; },
1275
2470
  addAll: () => document.getElementById('eyeAddAll').click(),
2471
+ // Exclusion sign-off state, so a real browser pass can assert the control and the {dim, value} list
2472
+ // it SUBMITS, not only that a modal appeared. `signoffValues` is the submitted list itself — names
2473
+ // alone stopped being enough the moment a line weight could authorise a dismissal.
2474
+ signoffOpen: () => !signoffOverlay.hidden,
2475
+ signoffValues: () => signoffValues.map(row => ({ dim: row.dim, value: row.value })),
2476
+ signoffGroups: () => [...signoffList.querySelectorAll('.signoff-group')].map(group => ({
2477
+ dim: group.getAttribute('data-dim'),
2478
+ heading: group.querySelector('.signoff-group-heading').textContent,
2479
+ rows: [...group.querySelectorAll('.signoff-row')].map(row => row.textContent),
2480
+ })),
2481
+ signoffRows: () => [...signoffList.querySelectorAll('.signoff-row')].map(row => row.textContent),
2482
+ signoffTotal: () => signoffTotal.textContent,
2483
+ signoffPreviewState: () => signoffPreviewState,
2484
+ signoffApproveGated: () => signoffApprove.getAttribute('aria-disabled') === 'true',
2485
+ signoffNotice: () => (signoffNotice.hidden ? null : signoffNotice.textContent),
2486
+ signoffActions: () => [...document.querySelectorAll('.signoff-actions button')].filter(b => !b.hidden).map(b => b.textContent),
1276
2487
  };
1277
2488
 
1278
2489
  // Themed tooltips (replaces native title=) — one shared element, shown on data-tip hover after a short