@floless/app 0.112.1 → 0.113.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,9 +28,53 @@ button{background:#334155;color:var(--text);border:1px solid #475569;border-radi
28
28
  button:hover{background:#475569} button:disabled{opacity:.5;cursor:default}
29
29
  button.primary{background:var(--brand);border-color:var(--brand);color:#fff} button.primary:hover{background:#2f6fe0}
30
30
  button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
31
- select{background:#0f172a;color:var(--text);border:1px solid #475569;border-radius:6px;padding:5px 8px;font:13px system-ui;cursor:pointer}
32
- select:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
33
- header select#sheetSel{font-weight:600;min-width:200px;max-width:320px}
31
+ /* Sheet switcher — a themed combobox, NOT a native <select>.
32
+ A <select>'s CLOSED state takes styling fine; its arrow and its option list do not. Those are drawn
33
+ by the OS, so they come up as a light panel against this dark theme no matter what the rule says —
34
+ the browser default the "style every control" rule exists to stop. The trigger/popover/option
35
+ vocabulary mirrors the app's shared .wf-combo (web/app.css): the same control, re-expressed in THIS
36
+ page's tokens and scale, because this standalone page does not load app.css. */
37
+ .sheet-combo{position:relative;display:inline-flex}
38
+ /* Explicit, and load-bearing: this page has no global [hidden] rule, and the author `display` above
39
+ beats the UA's own [hidden] rule by ORIGIN, so without this `sheetCombo.hidden = true` would quietly
40
+ do nothing. Higher specificity than `.sheet-combo` above, so no !important is needed. */
41
+ .sheet-combo[hidden]{display:none}
42
+ /* Darker than the page's action buttons on purpose (they are #334155): this reads as a FIELD you pick
43
+ from rather than a button you press — the distinction the native <select> used to carry for free. */
44
+ /* appearance:none is inert here — the background/border rules below already de-nativize the button in
45
+ every engine we ship to — but it is stated rather than assumed: `appearance: auto` on this control is
46
+ the exact signature the QA pass matched on when it caught the <select>, and leaving it reading `auto`
47
+ would make the next such pass re-raise a defect that is gone. NOT the same case as the checkbox
48
+ below, whose appearance:none is load-bearing (drop it and a white native box comes back). */
49
+ .sheet-trigger{display:inline-flex;align-items:center;gap:6px;min-width:200px;max-width:320px;-webkit-appearance:none;appearance:none;background:var(--bg);border:1px solid #475569;border-radius:6px;padding:5px 8px;font:600 13px system-ui}
50
+ .sheet-trigger:hover,.sheet-trigger.open{background:var(--bg);border-color:var(--brand)}
51
+ .sheet-trigger-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}
52
+ .sheet-caret{color:var(--mut);flex:none;transition:transform .15s}
53
+ .sheet-trigger.open .sheet-caret{transform:rotate(180deg)}
54
+ /* Panel treatment matched to #eye below (8px radius, 0 8px 24px) — this page's own popover idiom, not
55
+ app.css's larger one, so the two PANEL popovers on this surface read as one family. (#tooltip keeps
56
+ the smaller cross-page treatment on purpose — it is the same control on four surfaces.) */
57
+ .sheet-popover{position:absolute;top:calc(100% + 4px);left:0;min-width:100%;width:max-content;max-width:400px;background:var(--panel);border:1px solid var(--line);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);z-index:60;animation:sheet-in .14s ease-out}
58
+ /* NOT the same case as .sheet-combo[hidden] above, and the asymmetry is worth naming: .sheet-popover
59
+ declares no `display`, so the UA [hidden] rule already applies unopposed and this is redundant TODAY.
60
+ It stays as insurance — the moment anyone gives this panel a `display`, its absence becomes the same
61
+ silent-inert-`hidden` bug the rule 15 lines up exists to prevent. */
62
+ .sheet-popover[hidden]{display:none}
63
+ @keyframes sheet-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}
64
+ .sheet-list{overflow-y:auto;max-height:260px;padding:4px} /* a scroll container — themed by the global * scrollbar rules above */
65
+ /* A <div role=option>, not a <button> — deliberately NOT focusable, as the shared .wf-option is. Focus
66
+ must stay on the trigger for aria-activedescendant to mean anything, and a focusable row also left
67
+ focus on <body> when the row was clicked and then hidden. So this needs its own cursor/font. */
68
+ .sheet-option{display:block;width:100%;cursor:pointer;background:transparent;border:none;border-left:2px solid transparent;border-radius:4px;padding:6px 8px;text-align:left;font:13px system-ui;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
69
+ .sheet-option:hover,.sheet-option.highlighted{background:#334155}
70
+ /* Left-border accent for the current sheet — the shared .wf-option.selected convention, not a tick glyph. */
71
+ .sheet-option.selected{border-left-color:var(--brand);color:var(--brand)}
72
+ /* Mirrors app.css's .sr-only. Needed here because this page does not load app.css, and the sheet
73
+ switcher has no VISIBLE label beside it the way the workflow/project pickers do. */
74
+ .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}
75
+ /* Themed tooltip — replaces native title= so no light OS tooltip leaks onto the dark theme. */
76
+ #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:0 8px 22px rgba(0,0,0,.5);opacity:0;transition:opacity .12s}
77
+ #tooltip.show{opacity:1}
34
78
  #app{display:flex;flex:1;min-height:0}
35
79
  #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}
36
80
  #panel h2{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);margin:0 0 8px;display:flex;align-items:center;justify-content:space-between}
@@ -75,7 +119,27 @@ footer{margin-top:auto;display:flex;align-items:center;gap:6px;flex-wrap:wrap;bo
75
119
  <body>
76
120
  <header>
77
121
  <b>Steel filter</b>
78
- <select id="sheetSel" title="Switch framing-plan sheet" style="display:none"></select>
122
+ <!-- Ships hidden: a single-sheet set is not a choice, and buildSheetSwitcher() reveals it only when
123
+ there is more than one sheet. See the .sheet-* rules for why this is not a <select>. -->
124
+ <div class="sheet-combo" id="sheetCombo" hidden>
125
+ <!-- aria-labelledby (label + VALUE), never aria-label: aria-label would OVERRIDE the button's own
126
+ text, so a screen reader would announce the control's purpose and never say which sheet is
127
+ open — a regression against the <select>, which announced its selected option for free. This
128
+ is the shared control's shape (`aria-labelledby="wf-label wf-trigger-label"`, web/index.html);
129
+ the label span is visually hidden only because this header, unlike the workflow/project
130
+ spine, has no room for a visible one. -->
131
+ <span id="sheetComboLabel" class="sr-only">Framing-plan sheet</span>
132
+ <button id="sheetTrigger" class="sheet-trigger" type="button" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-controls="sheetPopover" aria-labelledby="sheetComboLabel sheetTriggerLabel" data-tip="Switch framing-plan sheet">
133
+ <span class="sheet-trigger-label" id="sheetTriggerLabel"></span>
134
+ <svg class="sheet-caret" width="10" height="6" viewBox="0 0 10 6" aria-hidden="true"><path fill="currentColor" d="M0 0l5 6 5-6z"/></svg>
135
+ </button>
136
+ <!-- role=listbox sits on the element aria-controls POINTS AT, as in the shared control. With the
137
+ role on the inner scroller instead, the trigger carried aria-activedescendant naming an option
138
+ inside a listbox it did not declare it controlled — the APG relationship, broken. -->
139
+ <div id="sheetPopover" class="sheet-popover" role="listbox" aria-labelledby="sheetComboLabel" hidden>
140
+ <div class="sheet-list" id="sheetList"></div>
141
+ </div>
142
+ </div>
79
143
  <span id="src" class="stat"></span>
80
144
  <span class="sp"></span>
81
145
  <span id="saved" class="stat"></span>
@@ -116,7 +180,20 @@ footer{margin-top:auto;display:flex;align-items:center;gap:6px;flex-wrap:wrap;bo
116
180
  <div id="empty">
117
181
  <div>
118
182
  <p>No filter data yet.</p>
119
- <p class="hint" style="margin-top:8px;max-width:340px">Your terminal AI reads the drawing once (PyMuPDF) and bakes its layers, thicknesses and colours here. Use <b>Re-read &amp; re-bake ▸</b> on the canvas, then reload.</p>
183
+ <!-- "then reload" is GONE, and #441 is what earned that: until it landed, the pre-read verb
184
+ (server/steel-prepass-route.ts) broadcast nothing at all, so this hint could only tell the user
185
+ to refresh by hand. It now announces itself as `pre-read`.
186
+ The chain is looser than "this control updates the view", and the promise is worded for the
187
+ chain rather than the control: Re-read & re-bake POSTs /api/rebake, which QUEUES a request for
188
+ the terminal AI. The AI then writes — through the pre-read verb, or through the contract route
189
+ for a project that holds no contract yet (the verb 404s on that case by design, saying the
190
+ first write goes through the contract route). Both of those broadcast, so "once it's done"
191
+ holds either way.
192
+ What does NOT reach this page: a write the verb REFUSES (it has many such returns, none of
193
+ which broadcast) — that failure is the AI's to report, in the terminal where the user asked
194
+ for it — and a re-bake whose result is canonically equal to what is already stored, where
195
+ there is nothing new to show. -->
196
+ <p class="hint" style="margin-top:8px;max-width:340px">Your terminal AI reads the drawing once (PyMuPDF) and bakes its layers, thicknesses and colours here. Use <b>Re-read &amp; re-bake ▸</b> on the canvas — this view updates on its own once it’s done.</p>
120
197
  </div>
121
198
  </div>
122
199
  <div id="zoombar"><button id="fit2">Fit</button><button id="zoomsteel2">Steel</button></div>
@@ -129,7 +206,7 @@ footer{margin-top:auto;display:flex;align-items:center;gap:6px;flex-wrap:wrap;bo
129
206
  </div>
130
207
 
131
208
  <script type="module">
132
- import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, bgRect, applySelToFilter, normalizeFilter } from './steel-filter-core.js';
209
+ import { matchesActive, modeDims, canonicalMode, selFromFilter, eyedropperAdd, countShown, bgRect, applySelToFilter, normalizeFilter, liveUpdateAction, statChip, newMutationId, sheetLabel, NOTE_TEXT } from './steel-filter-core.js';
133
210
 
134
211
  const APP_ID = new URLSearchParams(location.search).get('app') || '';
135
212
  // Workspaces: project-keyed contract (see steel-editor.html). Empty = legacy app-keyed URLs.
@@ -160,13 +237,28 @@ let serverEtag = null; // the server's tag for the contract we loaded
160
237
  let conflicted = false; // latched once a save is refused, so a second click does not re-fire it
161
238
  let sheets = []; // normalizeFilter(F).sheets — per-sheet geometry
162
239
  let active = 0; // index into sheets
240
+ let parseWarned = false; // latch, so a broken stream cannot spam the console
163
241
 
164
242
  function setSaved(state){
165
- savedEl.className = 'stat ' + (state || '');
166
- savedEl.innerHTML = state === 'dirty' ? 'Unsaved <b>●</b>' : state === 'saved' ? 'Saved <b>✓</b>'
167
- : state === 'err' ? 'Save failed <b>✕</b>'
168
- // Not an error: the user's selection is fine, the model simply moved under them.
169
- : state === 'conflict' ? 'Save conflict' : '';
243
+ // The state→(class, label) map is `statChip` in steel-filter-core.js, where it is table-tested.
244
+ const { cls, text, badge } = statChip(state);
245
+ savedEl.className = 'stat ' + cls;
246
+ // Assembled from DOM nodes, not innerHTML: the nested <b> is what the .stat.* rules colour, and
247
+ // building it this way keeps the chip free of an HTML sink.
248
+ savedEl.replaceChildren();
249
+ if(text) savedEl.append(text);
250
+ if(badge){ const b = document.createElement('b'); b.textContent = badge; savedEl.append(b); }
251
+ // Only the cyan states DO anything when clicked (they re-open a dismissed bar), so only they are
252
+ // exposed as a control. A plain status chip must not be focusable — that would put a tab stop with no
253
+ // action behind it into the header, the mirror image of the dead affordance this fixes.
254
+ const actionable = cls === 'conflict';
255
+ if(actionable){
256
+ savedEl.setAttribute('role', 'button');
257
+ savedEl.setAttribute('tabindex', '0');
258
+ savedEl.setAttribute('aria-label', text + ' — show what changed');
259
+ } else {
260
+ savedEl.removeAttribute('role'); savedEl.removeAttribute('tabindex'); savedEl.removeAttribute('aria-label');
261
+ }
170
262
  }
171
263
 
172
264
  /**
@@ -179,8 +271,27 @@ function setSaved(state){
179
271
  */
180
272
  // `message` is optional so the 428 (stale-page) case reuses this bar rather than forking a second one —
181
273
  // same bar, same tokens, one thing to learn. Defaults to the write-conflict copy.
182
- function showConflictBanner(message){
274
+ //
275
+ // Renamed from showConflictBanner (it now also carries "the AI updated this" and "live updates
276
+ // disconnected", neither of which is a conflict) — the bar was always the generic "something changed
277
+ // underneath you, here is the way out" component; only its default copy is conflict-specific.
278
+ // `opts.kind` says what the bar is ABOUT, and three behaviours hang off it:
279
+ // 'document' (default) — the stored model changed or a save was refused. Its copy always tells the user
280
+ // their edits are at stake, so ↻ Reload may discard them, and dismissing leaves
281
+ // the "Out of date" chip behind as the remaining trace.
282
+ // 'channel' — the live-update stream itself is in trouble. NOTHING is known to have changed,
283
+ // so this must not stamp "Out of date" on a page that may be perfectly current,
284
+ // must not be re-opened by a chip describing a document state, and must NOT
285
+ // silently discard edits: its copy never warned about them, so the browser's own
286
+ // unload prompt stays armed as the backstop.
287
+ // Review found all three wired the wrong way round: one shared handler cleared `dirty` for every caller, so
288
+ // clicking ↻ Reload on "Live updates disconnected" — a bar the user never asked for, whose copy mentions no
289
+ // edits — silently threw their toggles away, unrecoverably (this surface keeps no draft).
290
+ let lastBanner; // the last DOCUMENT message, so the header chip can re-open a bar the user dismissed
291
+ function showChangedBanner(message, opts){
292
+ const kind = (opts && opts.kind) || 'document';
183
293
  const old = document.getElementById('conflictBanner'); if(old) old.remove();
294
+ if(kind === 'document') lastBanner = message;
184
295
  const bar = document.createElement('div');
185
296
  bar.id = 'conflictBanner';
186
297
  bar.style.cssText = 'position:fixed;bottom:0;left:0;right:0;z-index:50;display:flex;align-items:center;gap:10px;'
@@ -195,23 +306,274 @@ function showConflictBanner(message){
195
306
  reload.textContent = '↻ Reload';
196
307
  // No local draft in this surface, so a plain reload is already safe (unlike the steel editor, whose
197
308
  // restoreSaved() would re-overlay the conflicting draft).
198
- reload.onclick = () => location.reload();
309
+ //
310
+ // Clearing `dirty` keeps the native "Leave site?" dialog off the screen, and a DOCUMENT bar has earned
311
+ // that: its copy states the edits are at stake and asks the user to reload and reapply them, so stacking
312
+ // the browser's grey confirm on top of our themed bar re-asks a question they just answered. A CHANNEL
313
+ // bar has NOT earned it — see the note above showChangedBanner — so there `dirty` stands and the browser
314
+ // prompt remains the thing that stops silent data loss.
315
+ reload.onclick = () => { if(kind === 'document') dirty = false; location.reload(); };
199
316
  const dismiss = document.createElement('button');
200
317
  dismiss.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
201
318
  dismiss.textContent = '✕';
202
- dismiss.onclick = () => bar.remove();
319
+ // Dismissing hides the bar but must not erase the FACT that the view is behind — otherwise the only
320
+ // trace is gone and the next Save fails with a 412 the user has no way to have anticipated. It must
321
+ // not overwrite a MORE specific state either: 'Save conflict'/'Save failed' each name a refused write,
322
+ // which is strictly more informative. 'Unsaved ●' is safe to replace — the enabled Save button already
323
+ // carries that signal, and staleness is the part the user cannot otherwise see.
324
+ dismiss.onclick = () => {
325
+ bar.remove();
326
+ // Only a DOCUMENT bar leaves a trace, and only when the chip is not already carrying a more specific
327
+ // state: 'Save conflict'/'Save failed' each name a refused write, which beats "Out of date". 'Unsaved ●'
328
+ // is safe to replace — the enabled Save button already carries that signal, and staleness is the part
329
+ // the user cannot otherwise see.
330
+ if(kind !== 'document') return;
331
+ if(!savedEl.classList.contains('conflict') && !savedEl.classList.contains('err')) setSaved('stale');
332
+ };
203
333
  bar.appendChild(msg); bar.appendChild(reload); bar.appendChild(dismiss);
204
334
  document.body.appendChild(bar);
205
335
  }
336
+ // `.stat.conflict` ships `cursor:pointer` and, until now, nothing behind it — a control that looks clickable
337
+ // and does nothing. Back it: clicking the cyan chip re-opens the document bar it belongs to. (In the 'Save
338
+ // conflict' state pressing Save also re-shows it, so this is the ONLY route only from 'Out of date' — where
339
+ // no other route exists at all.) Keyboard-reachable because setSaved gives the actionable states
340
+ // role=button + tabindex; a control only a mouse can reach is half a control.
341
+ function reopenBanner(){ if(savedEl.classList.contains('conflict')) showChangedBanner(lastBanner); }
342
+ savedEl.onclick = reopenBanner;
343
+ savedEl.addEventListener('keydown', e => {
344
+ if(e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar'){ e.preventDefault(); reopenBanner(); }
345
+ });
206
346
  function markDirty(){ dirty = true; saveBtn.disabled = false; setSaved('dirty'); }
207
347
 
348
+ // ── Live updates: reacting to a write that did not come from this tab ──
349
+ //
350
+ // The `filter` block this page renders is rewritten from outside all the time: the terminal AI's contract
351
+ // PUT, the pre-read verb, both arms of the rollback route, the revision-read commit and its staged confirm,
352
+ // and the v1→v2 migration commit. Each of those broadcasts `contract-changed` on /api/events — and this
353
+ // page listened to none of them, so it showed its boot-time snapshot until somebody thought to refresh.
354
+ //
355
+ // DELIBERATELY NO COUNT, and no "every write" claim either. Both are traps this comment has already fallen
356
+ // into once each: #442 shipped an absolute "every one of those broadcasts" that was false, and the fix for
357
+ // it shipped a tally that was also wrong. `server/mutation-id.ts` owns the number and explains why it is a
358
+ // liability (it has been wrong twice in that file alone); the writes that stay silent include the
359
+ // project-creation seed in POST /api/projects, a refused pre-read, and a re-bake that changes nothing.
360
+ //
361
+ // And `verify:change-reasons` is NOT the arbiter of that list, though an earlier draft here said it was: it
362
+ // matches only the `contractChangedWithReason` builder, so the contract PUT — the writer this page sees
363
+ // most — never appears in its tally, and its per-file expectations are a fixed allow-list that a brand-new
364
+ // writer would not join on its own. It is authoritative for token↔sentence correspondence, nothing wider.
365
+ //
366
+ // The DECISION (ours vs. external, reload vs. banner) is `liveUpdateAction` in steel-filter-core.js,
367
+ // where it is unit-tested; everything here is wiring.
368
+ const ownWrites = []; // ids of this tab's own writes, so we can tell our own echo from a real change
369
+ const OWN_WRITES_MAX = 32; // a backstop, not a working limit — see releaseMutation on why a stray id is harmless
370
+ /** `self.crypto` access can itself throw in hardened embeddings, so resolve it defensively once; the tier
371
+ * selection and all three fallbacks live in newMutationId (core), where they are tested. */
372
+ const CRYPTO = (() => { try { return self.crypto; } catch(_){ return null; } })();
373
+ function claimMutation(id){ ownWrites.push(id); while(ownWrites.length > OWN_WRITES_MAX) ownWrites.shift(); }
374
+ /**
375
+ * Drop an id whose write the server DEMONSTRABLY refused (428/412/non-2xx) — those return before the
376
+ * broadcast, so nothing will ever echo that id.
377
+ *
378
+ * Deliberately NOT called when the request produced no response at all, and not on success:
379
+ * - success — the echo for that write is usually still in flight (the server broadcasts before it
380
+ * replies), so releasing would make the tab read its OWN echo as external.
381
+ * - a thrown fetch — the outcome is UNKNOWN: the write may well have landed and broadcast. Releasing
382
+ * there un-names a write that then comes back looking external, and the user gets "The AI updated this
383
+ * filter" for their own save — the exact false accusation the CHANGE_LEAD table exists to stop.
384
+ *
385
+ * A retained id is harmless, which is what makes that trade safe, and an earlier version of this comment
386
+ * had it backwards: a stray id can only be matched by a frame carrying that same id, and no other writer
387
+ * ever sends it (rollback/revision-read/migration send none). So it cannot suppress anybody else's event —
388
+ * it can only sit there until the next echo's `drop` sweeps it or the FIFO evicts it.
389
+ */
390
+ function releaseMutation(id){ const i = ownWrites.indexOf(id); if(i >= 0) ownWrites.splice(i, 1); }
391
+
392
+ /**
393
+ * The sentence each reason token becomes on screen (unit 5, P7g — the mechanism #439 added for the editor).
394
+ *
395
+ * "The AI updated this filter" is flatly FALSE for a rollback or a v1→v2 conversion, both of which the
396
+ * user just performed themselves, and naming the wrong actor is worse than naming none: it sends someone
397
+ * looking for a change nobody made. This page is a second consumer of the same frames, so it needs the
398
+ * same table — without it, the defect that change removed would simply reappear one surface over.
399
+ *
400
+ * Word for word the editor's `CHANGE_LEAD`, deliberately: one event, one sentence, and a user may well
401
+ * have both surfaces open on the same model. Only the FALLBACK differs, naming this surface's own noun.
402
+ * The token is the server's and internal; the SENTENCE is ours — nothing off the wire is ever rendered,
403
+ * so a frame cannot put copy on screen.
404
+ *
405
+ * NULL PROTOTYPE, deliberately: a plain object literal answers `CHANGE_LEAD['constructor']` with a
406
+ * FUNCTION, so a frame carrying `reason:"constructor"` would concatenate "function Object() { [native
407
+ * code] }" into the bar. With no prototype there is nothing to inherit, and every unknown token —
408
+ * malformed, hostile, or merely from a newer server than this tab — falls through to the generic sentence.
409
+ */
410
+ const CHANGE_LEAD = Object.assign(Object.create(null), {
411
+ 'rollback': 'This model was rolled back',
412
+ // Phase ONE of the read whose phase two announces itself as `revision-read` — hence "started", which is
413
+ // the editor's own word for it. The sentence is about the READ rather than about this view on purpose:
414
+ // `filter` is only the part of that verb's output which lands here (it also writes the datum and
415
+ // registration fields, and on v1 the per-sheet grid), and the verb's own header warns against the
416
+ // flattering "one small block" description this comment previously repeated.
417
+ 'pre-read': 'The AI started reading a drawing set into this model',
418
+ 'revision-read': 'The AI read a revised drawing set into this model',
419
+ 'migration': 'This project was converted to the 3D model',
420
+ });
421
+
422
+ // A one-shot note handed to the NEXT load, so a populated view repainting under the user is explained
423
+ // instead of reading as a glitch. Scoped per app+project: two filter views must not read each other's note.
424
+ const NOTE_KEY = 'flo-filter-note:' + APP_ID + ':' + PROJECT;
425
+ /** Read-and-clear, so a note can never outlive the reload that wrote it (e.g. when the reload lands on a
426
+ * boot that bails early) and resurface on some unrelated later load. */
427
+ function takeUpdateNote(){
428
+ try { const had = sessionStorage.getItem(NOTE_KEY) === '1'; if(had) sessionStorage.removeItem(NOTE_KEY); return had; }
429
+ catch(_){ return false; } // private-mode/blocked storage: the note is a nicety, never a requirement
430
+ }
431
+ function showUpdateNote(){
432
+ // Only over an EMPTY chip. boot() awaits a fetch that can carry multi-megabyte rasters, and the mode
433
+ // checkboxes are live throughout, so the user can earn 'Unsaved ●' (or dismiss a bar into 'Out of date')
434
+ // before this runs — and overwriting either would hide real pending work behind a cosmetic note, which is
435
+ // exactly what the retire-timer below guards against. Guarding the timer but not the assignment left the
436
+ // same hole open at the other end.
437
+ if(savedEl.textContent !== '') return;
438
+ setSaved('note');
439
+ // Retire it after a beat — but never step on a state the user has EARNED in the meantime: four seconds
440
+ // is long enough to tick a facet, and clearing an 'Unsaved ●' chip would hide real pending work.
441
+ setTimeout(() => { if(savedEl.textContent === NOTE_TEXT) setSaved(''); }, 4000);
442
+ }
443
+
444
+ let seenConnected = false; // the stream's opening frame arrived once; a SECOND one means it reconnected
445
+ let booting = true; // boot()'s contract fetch is still in flight
446
+ let missedDuringBoot = false;
447
+ /** The channel is not delivering and cannot recover on its own — say so rather than leaving the user on a
448
+ * view they believe is live. 'channel' kind: nothing is known to have changed (see showChangedBanner). */
449
+ function liveUpdatesLost(message){ showChangedBanner(message, { kind: 'channel' }); }
450
+
451
+ function initLiveUpdates(){
452
+ // Both no-EventSource exits announce themselves. Silence here would leave the page with no listener at
453
+ // all while looking identical to a working one — the user would wait for an update no code is left to
454
+ // deliver.
455
+ if(typeof EventSource === 'undefined'){ liveUpdatesLost('This browser can’t receive live updates — reload to see changes made elsewhere.'); return; }
456
+ let es;
457
+ try { es = new EventSource('/api/events'); }
458
+ catch(_){ liveUpdatesLost('Live updates unavailable — reload to see changes made elsewhere.'); return; }
459
+ es.onmessage = (e) => {
460
+ let m;
461
+ try { m = JSON.parse(e.data); }
462
+ catch {
463
+ // Unreachable in practice (frames are JSON.stringify output and SSE never dispatches a partial
464
+ // frame), but latched-warn once if it ever happens: this surface would otherwise go permanently deaf
465
+ // to that class of frame leaving no trace anywhere.
466
+ if(!parseWarned){ parseWarned = true; console.warn('steel-filter: unparseable SSE frame — ignoring'); }
467
+ return;
468
+ }
469
+ const a = liveUpdateAction(m, {
470
+ appId: APP_ID, project: PROJECT, ownWrites, dirty,
471
+ // "a filter is RENDERED", not "a `filter` key exists" — `sel` is set only by initFromFilter(), so it
472
+ // is false in every empty state, including a truthy-but-elementless filter block.
473
+ hasDocument: !!sel,
474
+ seenConnected,
475
+ });
476
+ if(a.act === 'ignore') return;
477
+ if(a.act === 'connected'){ seenConnected = true; return; }
478
+ if(a.act === 'gap'){
479
+ // The stream reconnected, so any write during the gap is lost with no replay. We cannot know whether
480
+ // one happened, only that we would not have seen it — so resync rather than assume.
481
+ if(dirty && sel) liveUpdatesLost('Live updates reconnected — reload to be sure you’re seeing the latest.');
482
+ else if(booting) missedDuringBoot = true;
483
+ else { dirty = false; location.reload(); } // no note: nothing is KNOWN to have changed, so claiming an update would be a guess
484
+ return;
485
+ }
486
+ if(a.act === 'own-echo'){
487
+ ownWrites.splice(0, a.drop);
488
+ // Adopt the tag the server minted for our own write, so a PUT that succeeded while its response was
489
+ // lost cannot leave `serverEtag` stale and 412 the user's next save against their own change.
490
+ if(a.adoptEtag) serverEtag = a.adoptEtag;
491
+ return;
492
+ }
493
+ if(a.act === 'banner'){
494
+ // Deliberately NOT the conflict copy: nothing was refused here, so "your save didn't go through"
495
+ // would be a plain lie. The lead names WHAT happened rather than guessing WHO did it; an absent or
496
+ // unrecognised token falls through to the generic sentence, which is correct for the plain contract
497
+ // PUT (the one writer that usually IS the terminal AI, and which deliberately sends no reason).
498
+ //
499
+ // Read INSIDE this branch, as the editor does: if resolving the lead could ever throw, doing it
500
+ // above the `if` would take the RELOAD path down with it, leaving the tab neither bannering nor
501
+ // reloading — silently deaf to external writes, with the error swallowed by the event loop.
502
+ const lead = (typeof a.reason === 'string' && CHANGE_LEAD[a.reason]) || 'The AI updated this filter';
503
+ showChangedBanner(lead + ' — reload to see it (you have unsaved edits).');
504
+ return;
505
+ }
506
+ // A frame landing while boot()'s fetch is in flight must NOT reload: that throws away an in-flight
507
+ // request and, with writes arriving in a burst, can restart boot faster than it completes — a page that
508
+ // never finishes rendering, with no banner and no chip to explain it. Record it; boot() decides once,
509
+ // from a settled state.
510
+ if(booting){ missedDuringBoot = true; return; }
511
+ // Nothing to lose: reload straight into the new version so the user never has to think about
512
+ // refreshing. `dirty` is cleared first because this arm IS reachable with unsaved-but-unsaveable
513
+ // toggles (the empty state — `dirty && !sel`), and leaving the flag set would put the browser's own
514
+ // "Leave site?" confirm on screen with no user gesture behind it; cancel that and the page sits on the
515
+ // stale empty state forever, which is the very defect this listener exists to remove.
516
+ dirty = false;
517
+ // Leave a note for the next load ONLY when there was already something on screen — on the empty state
518
+ // the panel and drawing appearing IS the explanation, and a chip firing in the same instant is noise.
519
+ if(sel) try { sessionStorage.setItem(NOTE_KEY, '1'); } catch(_){ /* never block the reload over a nicety */ }
520
+ location.reload();
521
+ };
522
+ es.onerror = () => {
523
+ // A transient drop auto-reconnects (readyState CONNECTING) and is deliberately NOT surfaced here — the
524
+ // recovery is detected instead, by the duplicate `connected` frame that reconnect delivers (see
525
+ // liveUpdateAction). That matters because CONNECTING is the COMMON failure (a cut socket) while CLOSED
526
+ // is the rare one, so treating only CLOSED as newsworthy would leave the ordinary case silent.
527
+ if(es.readyState === EventSource.CLOSED){
528
+ // Nothing can echo over a dead channel, so held ids are unmatchable; dropping them is tidiness, not a
529
+ // correctness fix (a retained id cannot suppress another writer's event — see releaseMutation).
530
+ ownWrites.length = 0;
531
+ console.warn('steel-filter: SSE channel closed — live updates paused');
532
+ // A lapsed subscription reaches exactly here: /api/events sits behind the 402 gate, and a non-200
533
+ // fails the connection outright. Naming reload as the fix would be incomplete in that case — the
534
+ // reload 402s too — so the copy stays neutral about the cause rather than promising a fix.
535
+ liveUpdatesLost('Live updates disconnected — reload to resume change detection.');
536
+ }
537
+ };
538
+ }
539
+
208
540
  async function boot(){
541
+ try { await bootOnce(); }
542
+ finally {
543
+ booting = false;
544
+ // A write landed while the fetch was in flight, so what we just rendered may already be a version
545
+ // behind. Reload ONCE, from a settled state — bounded, unlike reloading mid-flight, because each pass
546
+ // only re-arms if another write arrives during the next one.
547
+ if(missedDuringBoot){ missedDuringBoot = false; dirty = false; location.reload(); }
548
+ }
549
+ }
550
+
551
+ async function bootOnce(){
209
552
  if(!APP_ID){ showEmpty('No app specified.'); return; }
553
+ // Listen BEFORE the fetch, and before every early return below. The editor installs its listener at the
554
+ // END of boot() and gets away with it because each of its early exits calls a showEmpty() that replaces
555
+ // the whole <body>; ours leaves the page live and interactive, so the same placement would have left the
556
+ // "No filter data yet." state — the one the pre-read pass exists to fill in, and the single most
557
+ // valuable update this listener can deliver — as the one state that never updates itself.
558
+ initLiveUpdates();
559
+ const note = takeUpdateNote();
210
560
  let res;
211
561
  try { res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + CONTRACT_QS); }
212
562
  catch(e){ showEmpty('Could not reach the server.'); return; }
213
- if(res.status === 204){ showEmpty(); return; }
214
- if(!res.ok){ showEmpty(); return; }
563
+ // 204 and 404 are both "no contract stored yet", which IS the ordinary pre-bake state: a project read
564
+ // asks for 204 (quietMissing), an app-keyed read gets 404. Neither is an error, and both must keep the
565
+ // bake hint — an E2E caught an earlier version of this treating 404 as a failure, which put an error
566
+ // headline on the most common empty state there is and hid the one instruction that helps.
567
+ if(res.status === 204 || res.status === 404){ showEmpty(); return; }
568
+ // Anything else IS a failure, and saying which one matters: a bare showEmpty() presented a 402
569
+ // (subscription lapsed) or a 500 as "No filter data yet" — indistinguishable from a project simply
570
+ // awaiting its first bake — leaving the user, and anyone reading their console, nothing to go on.
571
+ if(!res.ok){
572
+ console.error('steel-filter: contract read failed (' + res.status + ')');
573
+ showEmpty(res.status === 402 ? 'Your FloLess subscription needs attention — sign in again to load this drawing.'
574
+ : 'Couldn’t load this drawing’s filter data (error ' + res.status + ').');
575
+ return;
576
+ }
215
577
  C = await res.json();
216
578
  serverEtag = res.headers.get('ETag'); // echoed back on save so a stale write is refused, not silently applied
217
579
  F = C && C.filter;
@@ -221,11 +583,20 @@ async function boot(){
221
583
  document.getElementById('empty').classList.remove('show');
222
584
  document.getElementById('src').textContent = (C.source && C.source.name) ? ('· ' + C.source.name) : '';
223
585
  initFromFilter();
586
+ // Only once there is actually a rendered view to explain — see takeUpdateNote.
587
+ if(note) showUpdateNote();
224
588
  }
225
589
 
226
590
  function showEmpty(msg){
227
591
  const e = document.getElementById('empty');
228
- if(msg) e.querySelector('p').textContent = msg;
592
+ if(msg){
593
+ e.querySelector('p').textContent = msg;
594
+ // The hint below explains how a filter gets BAKED ("your terminal AI reads the drawing once…"). Under an
595
+ // error headline — "Could not reach the server.", a 402, "No app specified." — that answers a question
596
+ // nobody asked and implies the thing is merely pending, so it goes away with the good news.
597
+ const hint = e.querySelector('.hint');
598
+ if(hint) hint.style.display = 'none';
599
+ }
229
600
  e.classList.add('show');
230
601
  }
231
602
 
@@ -246,17 +617,146 @@ function initFromFilter(){
246
617
  buildFacet('layers', F.layers || [], 'name', it => it.name, it => it.name);
247
618
  buildFacet('thicknesses', F.thicknesses || [], 'w', it => it.w + ' pt', it => it.w);
248
619
  buildFacet('colors', F.colors || [], 'hex', it => it.hex, it => it.hex);
249
- // sheet switcher (mirror the editor's planSel) — hidden for a single-sheet set
250
- const sheetSel = document.getElementById('sheetSel');
251
- sheetSel.innerHTML = sheets.map((s, i) => {
252
- const lbl = (s.sheet || ('Sheet ' + (i + 1))) + (s.title ? (' · ' + s.title) : '');
253
- return `<option value="${i}">${esc(lbl)}</option>`;
254
- }).join('');
255
- sheetSel.style.display = sheets.length > 1 ? '' : 'none';
256
- sheetSel.onchange = e => setSheet(+e.target.value);
620
+ buildSheetSwitcher();
257
621
  setSheet(active);
258
622
  }
259
623
 
624
+ // ── sheet switcher ──────────────────────────────────────────────────────────────────────────────
625
+ //
626
+ // A themed combobox rather than a <select>: see the .sheet-* CSS for why the native control cannot be
627
+ // made to obey the dark baseline. This is the app's shared .wf-combo control (web/index.html +
628
+ // web/aware.js), ported to this standalone page — deliberately the SAME control, not a lookalike.
629
+ //
630
+ // Not ported (the list is open-ended, not a closed set of two — an earlier version of this comment
631
+ // claimed two and was quietly hiding a third divergence that turned out to be an accessibility bug):
632
+ // · no SEARCH field — the workflow and project pickers face dozens of rows, a framing-plan set faces
633
+ // a handful, and an input that grabs focus on open would put a control with nothing to do between
634
+ // the user and the list. With no input to host them, focus stays on the trigger and the TRIGGER
635
+ // carries aria-activedescendant — the WAI-ARIA select-only shape, hence role=combobox on a <button>.
636
+ // · no per-row action or dirty-dot chrome — a sheet is a read-only place to look, not an entity you own.
637
+ // · opens ON the current row (openSheets highlights `active`); the shared control opens with no
638
+ // highlight and merely scrolls the selection into view. A short list has somewhere obvious to start.
639
+ const sheetCombo = document.getElementById('sheetCombo');
640
+ const sheetTrigger = document.getElementById('sheetTrigger');
641
+ const sheetTriggerLabel = document.getElementById('sheetTriggerLabel');
642
+ const sheetPopover = document.getElementById('sheetPopover');
643
+ const sheetList = document.getElementById('sheetList');
644
+ let sheetHi = -1; // index of the keyboard-highlighted row while open; -1 = none
645
+
646
+ function sheetOptions(){ return [...sheetList.children]; }
647
+
648
+ function buildSheetSwitcher(){
649
+ // Rebuilding under an open popover would strand `sheetHi` and aria-activedescendant on rows that no
650
+ // longer exist. Unreachable today (this runs once, from boot, and every external write is a full
651
+ // reload) — but it is one call, and it stops the trap the day this page re-renders in place.
652
+ closeSheets(false);
653
+ sheetList.replaceChildren();
654
+ sheets.forEach((s, i) => {
655
+ // A <div role=option>, NOT a <button>: focus has to stay on the trigger for aria-activedescendant
656
+ // to mean anything, and a focusable row also dropped focus onto <body> when it was clicked and then
657
+ // hidden. Matches the shared .wf-option, which is a div for the same reason.
658
+ const o = document.createElement('div');
659
+ o.className = 'sheet-option';
660
+ o.id = 'sheet-opt-' + i; // the target aria-activedescendant points at
661
+ o.setAttribute('role', 'option');
662
+ o.setAttribute('aria-selected', 'false');
663
+ o.dataset.i = String(i);
664
+ // textContent, never innerHTML: a sheet name and title are read off the drawing, so they are data.
665
+ o.textContent = sheetLabel(s, i);
666
+ // The row ellipsizes inside a 400px panel, so a long "S-202 · Second Floor Framing At El 118'-6""
667
+ // is clipped with no way to read the rest. The <select> this replaced had no such problem — its OS
668
+ // panel auto-sized to its content — so without this the port REGRESSES what a user can read. Same
669
+ // reasoning as eyeRow's .v below, which was converted in this very change; it just has to be applied
670
+ // in both places. (Harmlessly redundant when the label fits.)
671
+ o.setAttribute('data-tip', o.textContent);
672
+ o.addEventListener('click', () => { closeSheets(true); setSheet(i); });
673
+ sheetList.appendChild(o);
674
+ });
675
+ // One sheet is not a choice — the same rule the <select> carried, moved onto the wrapper.
676
+ sheetCombo.hidden = sheets.length <= 1;
677
+ }
678
+
679
+ /** Point the control at whatever sheet is now active — called from setSheet, so a programmatic switch
680
+ * (the test seam, a restored `active`) moves the label and the selected-row accent exactly as a click
681
+ * does. (Accent, not a tick — see the .sheet-option.selected rule.) */
682
+ function syncSheetSwitcher(){
683
+ const label = sheets.length ? sheetLabel(sheets[active], active) : '';
684
+ sheetTriggerLabel.textContent = label;
685
+ // The trigger ellipsizes at 320px too, so the closed state needs the same escape hatch as the rows.
686
+ // This REPLACES the static "Switch framing-plan sheet" tip: the caret and the listbox already say
687
+ // what the control does, and the accessible name (aria-labelledby) still carries the purpose — so the
688
+ // one thing the tooltip can add that nothing else does is the part that got clipped.
689
+ if(label) sheetTrigger.setAttribute('data-tip', label);
690
+ for(const o of sheetOptions()){
691
+ const on = Number(o.dataset.i) === active;
692
+ o.classList.toggle('selected', on);
693
+ o.setAttribute('aria-selected', on ? 'true' : 'false');
694
+ }
695
+ // A switch that lands while the popover is OPEN must move the highlight with it. Without this the
696
+ // keyboard highlight and aria-activedescendant stay on the previously-active row, so the next Enter
697
+ // re-picks the row the user just navigated away from.
698
+ if(!sheetPopover.hidden) highlightSheet(active);
699
+ }
700
+
701
+ function highlightSheet(i){
702
+ const opts = sheetOptions(); if(!opts.length) return;
703
+ sheetHi = Math.max(0, Math.min(opts.length - 1, i)); // clamp, so Up on the first row parks rather than wrapping
704
+ opts.forEach((o, n) => o.classList.toggle('highlighted', n === sheetHi));
705
+ const hi = opts[sheetHi];
706
+ hi.scrollIntoView({ block: 'nearest' });
707
+ // DOM focus never leaves the trigger, so the highlighted row is announced through it.
708
+ sheetTrigger.setAttribute('aria-activedescendant', hi.id);
709
+ }
710
+
711
+ function openSheets(){
712
+ if(!sheetPopover.hidden) return;
713
+ sheetPopover.hidden = false;
714
+ sheetTrigger.classList.add('open');
715
+ sheetTrigger.setAttribute('aria-expanded', 'true');
716
+ highlightSheet(active); // open ON the current sheet, so ↓ steps to the next one rather than to the top
717
+ }
718
+ function closeSheets(focusTrigger){
719
+ if(sheetPopover.hidden) return;
720
+ sheetPopover.hidden = true;
721
+ sheetTrigger.classList.remove('open');
722
+ sheetTrigger.setAttribute('aria-expanded', 'false');
723
+ sheetTrigger.removeAttribute('aria-activedescendant'); // must not survive the close — it would name a row nothing is showing
724
+ sheetOptions().forEach(o => o.classList.remove('highlighted'));
725
+ sheetHi = -1;
726
+ if(focusTrigger) sheetTrigger.focus();
727
+ }
728
+
729
+ sheetTrigger.addEventListener('click', () => { sheetPopover.hidden ? openSheets() : closeSheets(false); });
730
+ sheetTrigger.addEventListener('keydown', e => {
731
+ if(sheetPopover.hidden){
732
+ if(e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' '){ e.preventDefault(); openSheets(); }
733
+ return;
734
+ }
735
+ if(e.key === 'ArrowDown'){ e.preventDefault(); highlightSheet(sheetHi + 1); }
736
+ else if(e.key === 'ArrowUp'){ e.preventDefault(); highlightSheet(sheetHi - 1); }
737
+ else if(e.key === 'Home'){ e.preventDefault(); highlightSheet(0); }
738
+ else if(e.key === 'End'){ e.preventDefault(); highlightSheet(sheetOptions().length - 1); }
739
+ else if(e.key === 'Enter' || e.key === ' '){ e.preventDefault(); const i = sheetHi; closeSheets(true); if(i >= 0) setSheet(i); }
740
+ else if(e.key === 'Escape'){ e.preventDefault(); closeSheets(true); }
741
+ // Tab must still MOVE — close on the way out rather than swallowing it, or the popover is left
742
+ // orphaned over a control the user has already left.
743
+ else if(e.key === 'Tab'){ closeSheets(false); }
744
+ });
745
+ // An open popover closes on a press anywhere outside it.
746
+ //
747
+ // pointerdown, not click, so the popover goes at the START of a press: the canvas begins a pan on
748
+ // pointerdown, and a click-based listener would leave the panel hanging over the drawing for the whole
749
+ // drag. (An earlier version of this comment justified it by claiming setPointerCapture means a canvas
750
+ // press "never produces a click" — measured in the browser, that is FALSE: the click still fires and
751
+ // still bubbles to document. The real reason is the timing above, not a missing event.)
752
+ //
753
+ // Capture phase is declared defence, not a fact about today's code: nothing on the canvas path calls
754
+ // stopPropagation(), so bubble would behave identically right now. It costs nothing and means a future
755
+ // stopPropagation() on the canvas can never strand the popover open.
756
+ document.addEventListener('pointerdown', e => {
757
+ if(!sheetPopover.hidden && !sheetCombo.contains(e.target)) closeSheets(false);
758
+ }, true);
759
+
260
760
  // Render one framing-plan sheet; facets/sel/mode are global and persist across sheets.
261
761
  // Switching sheets is NAVIGATION, not a document edit — it deliberately does not markDirty() (an
262
762
  // estimator pages through framing plans constantly; a false "unsaved changes" prompt on read-only
@@ -281,7 +781,7 @@ function setSheet(i){
281
781
  base = { x: 0, y: 0, w: pg.w, h: pg.h }; vb = { ...base }; setVB();
282
782
  apply();
283
783
  closeEye();
284
- const ss = document.getElementById('sheetSel'); if(ss) ss.value = String(active);
784
+ syncSheetSwitcher();
285
785
  }
286
786
 
287
787
  function buildOverlay(){
@@ -405,7 +905,10 @@ function openEyedropper(clientX, clientY, el){
405
905
  eye.style.top = Math.min(clientY + 8, window.innerHeight - h - 8) + 'px';
406
906
  }
407
907
  function eyeRow(k, v, which, swatch){
408
- return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" title="${esc(v)}">${esc(v)}</span><button data-add="${which}">+ Add</button></div>`;
908
+ // data-tip, never title=: .v ellipsizes, so this row NEEDS a tooltip to show a long layer name in
909
+ // full — and a native title= would draw it as the light OS bubble, the one browser default this
910
+ // surface still leaked. The themed #tooltip handler at the foot of this file renders it.
911
+ return `<div class="erow"><span class="k">${k}</span>${swatch}<span class="v" data-tip="${esc(v)}">${esc(v)}</span><button data-add="${which}">+ Add</button></div>`;
409
912
  }
410
913
  function closeEye(){ eye.classList.remove('show'); eyeEl = null; }
411
914
  document.getElementById('eyeClose').onclick = closeEye;
@@ -452,18 +955,36 @@ document.getElementById('zoomsteel2').onclick = zoomSteel;
452
955
 
453
956
  // --- save: write the selection + mode onto C.filter and PUT the contract ---
454
957
  saveBtn.onclick = save;
455
- async function save(){
456
- if(!C || !F) return;
958
+ // Serialize THIS tab's writes, as the steel editor does. Without it the page conflicts with ITSELF:
959
+ // markDirty() re-enables Save while a save is in flight, so a second click sent a second PUT carrying the
960
+ // SAME If-Match tag — one won, the other came back 412 and latched a conflict caused by nobody but the user.
961
+ // Review found that race had teeth beyond a spurious banner: an older response landing last could clear
962
+ // `dirty` and show 'Saved ✓' while newer edits were still unsaved, and from there the next external write
963
+ // treats the page as clean and silently reloads those edits away. Queued, each PUT sees the tag the previous
964
+ // one produced, so the second save succeeds instead of racing.
965
+ let writeQueue = Promise.resolve();
966
+ const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
967
+ function save(){ return queueWrite(saveNow); }
968
+ async function saveNow(){
969
+ // `!sel` (not just `!F`) is the honest gate: an empty state can carry a truthy `filter` with nothing
970
+ // rendered, and applySelToFilter would then dereference a null `sel` and throw uncaught.
971
+ if(!C || !F || !sel) return;
457
972
  applySelToFilter(F, sel, mode); // global facet on-flags + mode
458
973
  F.sheets = sheets; F.active = active;
459
974
  delete F.page; delete F.elements; delete F.steelBbox; // migrate legacy single-sheet shape forward
460
975
  C.filter = F;
461
976
  // A second click while already conflicted must NOT silently re-fire a request we know will fail —
462
977
  // just re-surface the explanation.
463
- if(conflicted){ showConflictBanner(); return; }
978
+ if(conflicted){ showChangedBanner(); return; }
464
979
  saveBtn.disabled = true; setSaved('');
980
+ // Name this write BEFORE sending it, deliberately: the server broadcasts before it replies, so the echo
981
+ // can reach our own listener while this `await` is still pending — and an id we did not yet know would
982
+ // read as somebody else's write. NOT a self-reload, as an earlier version of this comment claimed: save()
983
+ // only runs with `dirty` true, so an unnamed echo takes the BANNER arm and accuses the AI of updating the
984
+ // filter the user was in the middle of saving, while never adopting the new etag.
985
+ const mid = newMutationId(CRYPTO); claimMutation(mid);
465
986
  try {
466
- const headers = { 'content-type': 'application/json' };
987
+ const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
467
988
  // TOTAL, as of P1c: a write with no precondition is refused (428). No tag means we read through the
468
989
  // BAKED fallback (the GET tags only store-backed documents) — this app has no draft yet — so the
469
990
  // honest precondition is `If-None-Match: *`, "I believe this store is empty".
@@ -472,18 +993,29 @@ async function save(){
472
993
  if(res.status === 428){ // a writer here sent no precondition — a bug in our code, not a user error.
473
994
  // NOT the conflict copy: nothing else wrote, so "changed somewhere else" would be a lie. This bar
474
995
  // is Reload-only (no overwrite button), which is already the right shape for a 428.
996
+ releaseMutation(mid);
475
997
  console.error('save refused 428 — a first-party writer sent no precondition; this is a FloLess bug');
476
998
  setSaved('err'); saveBtn.disabled = false;
477
- showConflictBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
999
+ showChangedBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
478
1000
  return;
479
1001
  }
480
1002
  if(res.status === 412){
481
- conflicted = true; setSaved('conflict'); saveBtn.disabled = false; showConflictBanner(); return;
1003
+ releaseMutation(mid);
1004
+ conflicted = true; setSaved('conflict'); saveBtn.disabled = false; showChangedBanner(); return;
482
1005
  }
483
- if(!res.ok) throw new Error(await res.text());
1006
+ if(!res.ok){ releaseMutation(mid); throw new Error(await res.text()); }
1007
+ // NOTE the asymmetry, and that it is deliberate: success does NOT release the id. The echo for this
1008
+ // very write is usually still in flight, so releasing here would make the tab read its OWN echo as an
1009
+ // external change and reload itself the instant the user saved. The id is consumed by that echo, or
1010
+ // dropped when the write fails, or discarded when the SSE channel closes (nothing can echo after that).
484
1011
  const t = res.headers.get('ETag'); if(t) serverEtag = t;
485
1012
  dirty = false; setSaved('saved');
486
- } catch(e){ console.error('filter save failed', e); setSaved('err'); saveBtn.disabled = false; }
1013
+ } catch(e){
1014
+ // The id is deliberately KEPT here. No response arrived, so we do not know whether the write landed —
1015
+ // and if it did, it broadcast, and releasing would make that echo look external and blame the AI for the
1016
+ // user's own save. A retained id costs nothing (see releaseMutation).
1017
+ console.error('filter save failed', e); setSaved('err'); saveBtn.disabled = false;
1018
+ }
487
1019
  }
488
1020
  window.addEventListener('beforeunload', e => { if(dirty){ e.preventDefault(); e.returnValue = ''; } });
489
1021
  // #170: same-origin bridge so the parent (aware.js) can show ITS styled confirm modal on close
@@ -500,6 +1032,13 @@ window.__floGuard = {
500
1032
  // and inspect state deterministically without fragile sub-pixel clicks on thin SVG strokes.
501
1033
  window.__filterTest = {
502
1034
  ready: () => !!F,
1035
+ dirty: () => dirty,
1036
+ // Live-update state, so a real browser pass can assert the WIRING (not only the visible outcome) —
1037
+ // whether an own-write echo was actually consumed, and whether its tag was adopted.
1038
+ ownWrites: () => [...ownWrites],
1039
+ serverEtag: () => serverEtag,
1040
+ chip: () => savedEl.textContent,
1041
+ banner: () => document.getElementById('conflictBanner')?.querySelector('span')?.textContent ?? null,
503
1042
  mode: () => mode,
504
1043
  sel: () => ({ layers: [...sel.layers], thicknesses: [...sel.thicknesses], colors: [...sel.colors] }),
505
1044
  shown: () => countShown((sheets[active] && sheets[active].elements) || [], mode, sel),
@@ -507,10 +1046,32 @@ window.__filterTest = {
507
1046
  sheetCount: () => sheets.length,
508
1047
  activeSheet: () => active,
509
1048
  setSheet: (i) => setSheet(i),
1049
+ // Sheet-switcher state, so a real browser pass can assert the control rather than only the render.
1050
+ sheetOpen: () => !sheetPopover.hidden,
1051
+ sheetTriggerText: () => sheetTriggerLabel.textContent,
1052
+ sheetOptionTexts: () => sheetOptions().map(o => o.textContent),
510
1053
  pick: (i) => { const el = nodes[i].el; openEyedropper(Math.round(window.innerWidth / 2), 200, el); return el; },
511
1054
  addAll: () => document.getElementById('eyeAddAll').click(),
512
1055
  };
513
1056
 
1057
+ // Themed tooltips (replaces native title=) — one shared element, shown on data-tip hover after a short
1058
+ // delay, positioned below the control, clamped to the viewport, and flipped ABOVE when it would
1059
+ // overflow the bottom. The same handler vector-editor.html and steel-editor.html carry (page-global in
1060
+ // both): this page having its own variant is how three surfaces end up with three tooltip behaviours.
1061
+ // Adding it here is what lets this file drop out of verify-no-title's exclusion list — and
1062
+ // verify-no-title.test.ts now pins that a page using data-tip actually ships something to render it.
1063
+ // (Nothing enforces the three copies stay identical; if they drift, that guard still holds the floor.)
1064
+ (function(){ const tip=document.createElement('div'); tip.id='tooltip'; document.body.appendChild(tip); let t=null;
1065
+ function show(el){ const txt=el.getAttribute('data-tip'); if(!txt) return; tip.textContent=txt; tip.classList.add('show');
1066
+ const r=el.getBoundingClientRect(), tw=tip.offsetWidth, th=tip.offsetHeight;
1067
+ let x=Math.max(6,Math.min(r.left+r.width/2-tw/2, innerWidth-tw-6)), y=r.bottom+6; if(y+th>innerHeight-6) y=r.top-th-6;
1068
+ tip.style.left=x+'px'; tip.style.top=y+'px'; }
1069
+ function hide(){ clearTimeout(t); tip.classList.remove('show'); }
1070
+ document.addEventListener('pointerover', e=>{ const el=e.target.closest('[data-tip]'); if(!el) return; clearTimeout(t); t=setTimeout(()=>show(el),400); });
1071
+ document.addEventListener('pointerout', e=>{ if(e.target.closest('[data-tip]')) hide(); });
1072
+ document.addEventListener('pointerdown', hide, true); // a click hides the tip immediately
1073
+ })();
1074
+
514
1075
  boot();
515
1076
  </script>
516
1077
  </body>