@floless/app 0.140.0 → 0.141.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.
@@ -5,7 +5,7 @@ import { mountModelLightingPanel } from './model-viewport-lighting.js';
5
5
  import { createRevitEditorAdapter, revitRenderPlan } from './model-editor-revit-adapter.js';
6
6
  import {
7
7
  buildRevitClassificationTree, filterRevitPropertyGroups, groupRevitProperties,
8
- revitExplorerTabs, revitPropertyEncodingLabel,
8
+ renderRevitNoModelState, revitExplorerTabs, revitInitialAuthority, revitNoModelCopy, revitPropertyEncodingLabel,
9
9
  } from './model-revit-module.js';
10
10
  import { createRevitViewport } from './model-viewport-revit-adapter.js';
11
11
  import { mountModelOrientationOverlay } from './model-orientation-overlay.js';
@@ -753,7 +753,7 @@ function mountSharedModelTools() {
753
753
  }
754
754
 
755
755
  function authorityButtons(state) {
756
- const host = $('authorityChoices'); host.replaceChildren(); const available = ['draft', 'approved'].filter((key) => state[key]); const initial = state.draft ? 'draft' : 'approved';
756
+ const host = $('authorityChoices'); host.replaceChildren(); const available = ['draft', 'approved'].filter((key) => state[key]); const initial = revitInitialAuthority(state);
757
757
  window.__revitInstructorState = { ...(window.__revitInstructorState || {}), authority: initial };
758
758
  for (const key of available) { const button = document.createElement('button'); button.type = 'button'; button.dataset.commandId = 'revit.authority'; button.dataset.commandInstanceLabel = key; button.textContent = key === 'draft' ? 'Working model' : 'Approved model'; button.setAttribute('aria-pressed', String(key === initial)); button.addEventListener('click', async () => { if (button.getAttribute('aria-pressed') === 'true') return; try { if (!await loadRevision(state, key)) return; await activateSpatialForRevision(state, state[key]); host.querySelectorAll('button').forEach((item) => item.setAttribute('aria-pressed', String(item === button))); window.__revitInstructorState = { ...(window.__revitInstructorState || {}), authority: key }; window.__instructor?.notifyChanged(); } catch (error) { toast(error.message); } }); host.append(button); }
759
759
  return initial;
@@ -767,6 +767,21 @@ async function boot() {
767
767
  orientation: $('modelViewCube'), axes: $('modelWorldAxes'), explorer: $('modelExplorer'),
768
768
  pointerDock: $('modelBottomDock'), inspector: $('inspectorPanel'), statusHud: $('modelSpatialHud'),
769
769
  });
770
+ window.__revitInstructorState = { selected: selectedId, authority: null };
771
+ // Read the project before creating any WebGL context: a project with no revision yet (its RVT is
772
+ // importing, stopped importing, or was never added) is an ordinary state with nothing to render.
773
+ await json('/api/editor/session', { method: 'POST' });
774
+ const state = (await json(`/api/editor/revit-projects/${encodeURIComponent(projectId)}`)).state;
775
+ $('modelName').textContent = state.projectName || projectId;
776
+ $('sourceName').textContent = state.source?.filename || state.pendingSource?.filename || 'No RVT source';
777
+ if (!revitInitialAuthority(state)) {
778
+ const copy = revitNoModelCopy(state);
779
+ // A published source with no revision behind it is not one of the ordinary states: stay loud.
780
+ if (!copy) throw new Error('This project lists an RVT file, but no model was saved from it, so there is nothing to open. On the Source tab, choose the RVT again to rebuild the model.');
781
+ $('editorRoot').dataset.modelState = 'empty';
782
+ renderRevitNoModelState($('loadingState'), copy);
783
+ return;
784
+ }
770
785
  mountPanels();
771
786
  viewport = createRevitViewport({ canvas: $('modelCanvas'),
772
787
  // A big model takes a few seconds to convert, and the first moment shows nothing happening
@@ -786,12 +801,7 @@ async function boot() {
786
801
  // every mode, so reading it reports a picture the user is not looking at.
787
802
  outline: () => viewport.outlineState?.() ?? null,
788
803
  realistic: () => viewport.realisticState?.() ?? null };
789
- window.__revitInstructorState = { selected: selectedId, authority: null };
790
- await json('/api/editor/session', { method: 'POST' });
791
- const state = (await json(`/api/editor/revit-projects/${encodeURIComponent(projectId)}`)).state;
792
804
  projectContract = await json(`/api/contract/revit-model?project=${encodeURIComponent(projectId)}&quietMissing=1`);
793
- $('modelName').textContent = state.projectName || projectId;
794
- $('sourceName').textContent = state.source?.filename || 'No RVT source';
795
805
  const authority = authorityButtons(state); await loadRevision(state, authority); await activateSpatialForRevision(state, state[authority]); mountSharedModelTools();
796
806
  const releasePointerCoordinates = viewport.onPointerWorld((renderPoint) => {
797
807
  if (!renderPoint || !spatialTools) { $('modelCursorCoordinates').textContent = 'X — · Y — · Z — mm'; return; }
@@ -1412,7 +1412,7 @@ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stro
1412
1412
  .chip.user{border-color:#1d4ed8;color:#93c5fd}
1413
1413
  [data-theme="light"] .chip.user{color:#1d4ed8}
1414
1414
  tr.confrow{cursor:pointer} .conf-expand{color:var(--mut);font-size:12px;line-height:1.6;background:var(--sunken)}
1415
- .ftab td .combo{padding:4px 6px} .ftab .rea{color:var(--mut);font-size:12px} .ftab .vcell{white-space:nowrap}
1415
+ .ftab td .combo{padding:4px 6px}
1416
1416
  .ftab-inp{background:var(--field);color:var(--text);border:1px solid var(--ctrl-border);border-radius:4px;padding:4px 6px;width:100%;font:13px var(--ui)}
1417
1417
  .ftab-inp:focus{outline:none;border-color:var(--brand)}
1418
1418
  .ftab .cdel{padding:3px 7px;font-size:11px} .ftab .csrc{white-space:nowrap}
@@ -2528,6 +2528,8 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2528
2528
  for why the same declarations also load in the shell. -->
2529
2529
  <script src="commands.js"></script>
2530
2530
  <script src="commands-steel.js"></script>
2531
+ <!-- An Esc this editor leaves unused closes the shell's editor overlay (#1571); mounted after the keydown ladder. -->
2532
+ <script src="overlay-escape.js"></script>
2531
2533
  <script type="importmap">{"imports":{"three":"./vendor/three.module.js","three/addons/":"./vendor/","three-bvh-csg":"./vendor/three-bvh-csg.module.js"}}</script>
2532
2534
  <script type="module" src="./steel-3d-view.js"></script>
2533
2535
  <!-- grid-core is an ES module; the editor's classic script reaches it via window.GridCore (set before
@@ -12688,6 +12690,14 @@ document.getElementById('undoB').onclick=doUndo;
12688
12690
  document.getElementById('redoB').onclick=doRedo;
12689
12691
  document.getElementById('dragMoveB').onclick=()=>{setDragMove(!dragMoveOn);toast(dragMoveOn?'Drag to move/copy: ON — drag moves, Ctrl+drag copies':'Drag to move/copy: OFF — a click only selects');};
12690
12692
  setDragMove(dragMoveOn); // reflect the persisted state on load (body class + pill)
12693
+ /* #1571: an Esc this editor leaves unused closes the shell's editor overlay (web/overlay-escape.js). That reads
12694
+ preventDefault() as "this Esc was mine", but most rungs of the ladder below act without it. So the ladder's LAST
12695
+ rung says when it found nothing to act on (escLadderIdle), and the listener bound right after the ladder marks
12696
+ every other Esc that reached it as used — with OverlayEscape.markUsed, NOT preventDefault, which the 3D view's
12697
+ listeners also read. A rung that stops immediate propagation stops that listener and the forwarder mounted after
12698
+ it too, so it needs no mark. */
12699
+ let escLadderIdle=false;
12700
+ addEventListener('keydown',e=>{if(e.key==='Escape')escLadderIdle=false;});
12691
12701
  addEventListener('keydown',e=>{
12692
12702
  // #planTrigger is named explicitly because it USED to be covered for free: the plan switcher was a
12693
12703
  // select element, so focusing it matched the tag test and suppressed every !inForm shortcut below. It is now a
@@ -12761,8 +12771,9 @@ addEventListener('keydown',e=>{
12761
12771
  e.preventDefault();e.stopImmediatePropagation();
12762
12772
  if(refMeasure&&!(window.Steel3DView.refMeasureKept&&window.Steel3DView.refMeasureKept()))refMeasure=null; // the stage that dropped the RESULT drops the card with it
12763
12773
  renderRefsTab();return;}
12764
- if(e.key==='Escape'){if(geoMode){geoMode=null;setGeo();render();return;}if(mode==='add'){mode='sel';setMode();}
12765
- if(view3d)return; // the later-mounted 3D CAD arbiter owns the final selection-Escape rung
12774
+ if(e.key==='Escape'){if(geoMode){geoMode=null;setGeo();render();return;}const leftAdd=mode==='add';if(leftAdd){mode='sel';setMode();}
12775
+ if(view3d){escLadderIdle=!leftAdd;return;} // the later-mounted 3D CAD arbiter owns the final selection-Escape rung (it marks what it uses)
12776
+ escLadderIdle=!leftAdd&&!picking&&!selIds.size&&!selGridIds.size; // nothing to cancel and nothing to deselect: the Esc goes up to the overlay (#1571)
12766
12777
  picking=false;pickKind='profile';pickEnd=null;modelSelection.clearMembers();modelSelection.clearGrids();render();return;}
12767
12778
  if((e.key==='Delete'||e.key==='Backspace')&&view3d&&modelEditor.steel.selectedClips&&modelEditor.steel.selectedClips().length&&!selIds.size&&!sel3dDimIds.size&&!selDimIds.size&&!inForm){e.preventDefault();window.Steel3DView.deleteSelectedClips();return;} // 3D: Del removes the selected clip plane(s)/box(es) — only when nothing else is selected (clip selection is exclusive)
12768
12779
  if((e.key==='Delete'||e.key==='Backspace')&&view3d&&sel3dDimIds.size&&!selIds.size&&!inForm){e.preventDefault();const V=window.Steel3DView;[...sel3dDimIds].forEach(id=>V&&V.removeMeasureById?V.removeMeasureById(id):view3dApi.onDeleteDim3d(id));return;} // 3D: Delete removes ALL selected 3D dims through the shared measure session — only when no member is selected
@@ -12822,6 +12833,11 @@ addEventListener('keydown',e=>{
12822
12833
  if(selIds.size||selDimIds.size||selGridIds.size)clearWholeReferenceSelection();
12823
12834
  render();}
12824
12835
  else if(k==='s'){e.preventDefault();persist();(window.flushContract?window.flushContract():Promise.resolve()).then(()=>toast('Saved ✓')).catch(()=>toast('Save failed'));}}); // edits autosave; Ctrl+S just flushes now (no browser "save page" dialog)
12836
+ // #1571, the other half of escLadderIdle above: an Esc the ladder acted on is marked used, so the forwarder mounted
12837
+ // next leaves it alone. Order is load-bearing: both must bind AFTER the ladder and BEFORE the 3D view's own window
12838
+ // keydown (bound later, inside its init(), and marking what it uses itself).
12839
+ addEventListener('keydown',e=>{if(e.key==='Escape'&&!escLadderIdle&&window.OverlayEscape)window.OverlayEscape.markUsed(e);});
12840
+ window.OverlayEscape&&window.OverlayEscape.mount();
12825
12841
  // The 2D view band (#1428): the same pair as #m3dFit/#m3dFitSel, on the plan's own framing. Fit is
12826
12842
  // also Home; Zoom to selected is also Alt+Z / Shift+Space, and with nothing selected it frames the whole
12827
12843
  // plan, exactly as the 3D pair does with an empty selection — so neither button is ever disabled.
@@ -13125,6 +13141,7 @@ document.addEventListener('click',e=>{if(selFly.classList.contains('open')&&!sel
13125
13141
  const back=reviewFlyKind==='needs-review'?'reviewStat':reviewFlyKind==='registration'?'regStat':'untrackedStat',t=document.getElementById(back);
13126
13142
  const mine=rf.contains(document.activeElement)||document.activeElement===t;
13127
13143
  closeReviewFly();
13144
+ if(window.OverlayEscape)window.OverlayEscape.markUsed(e); // this Esc closed the list, so it must not also close the editor overlay (#1571) — a mark only the overlay reads, so the ladder and the 3D view still see it as before
13128
13145
  if(!mine)return;
13129
13146
  e.stopPropagation();e.preventDefault();
13130
13147
  if(t)t.focus();},true);
@@ -76,6 +76,38 @@ export function facetKey(dim, value) {
76
76
  throw new Error(`facetKey: unknown dimension ${JSON.stringify(dim)}`);
77
77
  }
78
78
 
79
+ /**
80
+ * WHICH ROWS of a facet's control list describe this element's value on that dimension — every index
81
+ * into `filter[FACET_DIMS[dim].control]` whose canonical key matches, in list order. Empty when none do.
82
+ *
83
+ * Hover info needs this to light up the very checkbox a user is about to untick, and it lives HERE
84
+ * rather than in the page because it is the same canonical-key comparison the whole selection chain
85
+ * turns on. Matching by RAW value is the defect `facetRowKey`'s note describes: a `#ABC123` row beside an
86
+ * element whose colour reads `#abc123` is ONE value, and a raw comparison would light nothing while the
87
+ * filter treats them as the same.
88
+ *
89
+ * ALL of them, not the first. Two rows can canonicalise to one key (`#ABC123` and `#abc123`), and the
90
+ * panel moves both checkboxes together (`syncFacetChecks`); lighting only the first pointed at one of two
91
+ * boxes that are about to change (review finding).
92
+ *
93
+ * Empty covers two different cases on purpose, because the caller does the same thing with both: the
94
+ * element carries no value for this dimension (`facetKey` returns undefined), and the value is well
95
+ * formed but the filter lists no row for it. `NaN` is left to `===`, so this answers exactly what
96
+ * `eyeAddable`'s own `.some(...)` answers.
97
+ */
98
+ export function facetRowIndicesFor(filter, dim, el) {
99
+ const desc = FACET_DIMS[dim];
100
+ // LOUD for the same reason as `facetKey`: the CONTROL name ('colors') instead of the dimension would
101
+ // quietly light nothing on every hover, which reads as "this line is on no listed colour".
102
+ if (!desc) throw new Error(`facetRowIndicesFor: unknown dimension ${JSON.stringify(dim)}`);
103
+ const key = facetKey(dim, el ? el[desc.elementKey] : undefined);
104
+ if (key === undefined) return [];
105
+ const rows = (filter && filter[desc.control]) || [];
106
+ const hits = [];
107
+ rows.forEach((it, i) => { if (facetKey(dim, it[desc.rowKey]) === key) hits.push(i); });
108
+ return hits;
109
+ }
110
+
79
111
  /**
80
112
  * Is this CANONICAL key a value a human could meaningfully have been shown and excluded?
81
113
  *
@@ -161,10 +193,16 @@ export function selFromFilter(filter) {
161
193
  // Sets hold CANONICAL keys, never raw row values — see `matchesActive`. A row whose value is not a
162
194
  // value for its dimension contributes nothing: it could never have matched an element the ledger
163
195
  // accepts, so admitting it would only let the panel show a tick with no consequence.
196
+ //
197
+ // A layer FloLess did not read (`notRead`, #990) contributes nothing either, whatever `on` it stored:
198
+ // no line behind it was read, so a tick kept from before it was flagged would render ticked while
199
+ // selecting nothing. Save (`applySelToFilter`) therefore writes it OFF: the state a first read already
200
+ // gives every such layer, since a withheld layer never carries a steel token (#1579).
164
201
  const keys = (dim, rows, dflt) => {
165
202
  const out = new Set();
166
203
  for (const row of rows) {
167
204
  if (!onOr(row, dflt(row))) continue;
205
+ if (dim === 'layer' && row.notRead === true) continue;
168
206
  const key = facetKey(dim, row[FACET_DIMS[dim].rowKey]);
169
207
  if (key !== undefined) out.add(key);
170
208
  }
@@ -207,6 +245,77 @@ export function eyedropperAdd(sel, el, which) {
207
245
  return sel;
208
246
  }
209
247
 
248
+ /**
249
+ * Is a picked element's value on ONE dimension currently ticked? Compared on the canonical key, the
250
+ * same one `eyedropperAdd` adds and `matchesActive` reads, so the popover's Add-or-Remove choice can
251
+ * never disagree with what the checkbox in the panel shows.
252
+ *
253
+ * A value with no canonical key is never selected — it cannot enter the Set at all — so it stays an
254
+ * + Add, and the popover's existing refusal explains why that Add cannot act.
255
+ */
256
+ export function eyedropperHas(sel, el, dim) {
257
+ const desc = FACET_DIMS[dim];
258
+ if (!desc) throw new Error(`eyedropperHas: unknown dimension ${JSON.stringify(dim)}`);
259
+ const key = facetKey(dim, el ? el[desc.elementKey] : undefined);
260
+ return key !== undefined && sel[desc.control].has(key);
261
+ }
262
+
263
+ /**
264
+ * Eyedropper, the other direction: untick a picked element's value on ONE dimension.
265
+ *
266
+ * Why it exists at all: a line the filter is SHOWING always has its value on the dimension being
267
+ * matched on already ticked — and the popover used to offer only + Add, a no-op, for exactly the value
268
+ * a user picked the line to get rid of. (A switched-off line, pickable with Hover info since #1527, is
269
+ * the reverse case: + Add is what brings it back.)
270
+ *
271
+ * One dimension per call, and deliberately no `'all'`. Adding everything a line carries is how a
272
+ * filter is BUILT from an example; removing everything it carries would also untick, say, a black
273
+ * that every beam on the sheet shares, and nothing on the popover could show that blast radius
274
+ * before it happened.
275
+ */
276
+ export function eyedropperRemove(sel, el, dim) {
277
+ const desc = FACET_DIMS[dim];
278
+ if (!desc) throw new Error(`eyedropperRemove: unknown dimension ${JSON.stringify(dim)}`);
279
+ const key = facetKey(dim, el ? el[desc.elementKey] : undefined);
280
+ if (key !== undefined) sel[desc.control].delete(key);
281
+ return sel;
282
+ }
283
+
284
+ /**
285
+ * EVERY reason one element is switched off under this mode and selection — a list, never a first
286
+ * match (#1527). Empty exactly when `matchesActive` is true.
287
+ *
288
+ * TOTAL over the criteria: it walks `MODE_ORDER`, the same list `FACET_DIMS` is keyed by, so a criterion
289
+ * added there is enumerated here without anyone remembering to (a test pins the two lists as one).
290
+ * Each entry is `{ dim, reason }`:
291
+ * - `'unticked'` — the element has a value on a criterion ticked under Match on, the filter lists a
292
+ * row for it, and that row is not ticked. The only reason a + Add can clear.
293
+ * - `'no-row'` — the value is well formed but the filter lists no row for it, so it can never be
294
+ * ticked (and would be dropped on save).
295
+ * - `'no-value'` — the element carries no value the criterion can match: the wrong type, or a
296
+ * thickness on a text run or a zero-width hairline, which `eyedropperAdd` refuses to add.
297
+ * With NOTHING ticked under Match on every element is off, and the one entry is
298
+ * `{ dim: null, reason: 'no-criterion' }`.
299
+ */
300
+ export function switchOffBlockers(el, mode, sel, filter) {
301
+ const dims = modeDims(mode);
302
+ if (!dims.length) return [{ dim: null, reason: 'no-criterion' }];
303
+ const out = [];
304
+ for (const dim of MODE_ORDER) {
305
+ if (!dims.includes(dim)) continue;
306
+ const d = FACET_DIMS[dim];
307
+ const key = facetKey(dim, el ? el[d.elementKey] : undefined);
308
+ // `matchesActive` counts a ticked key as a match whatever it is, so this must too — including a
309
+ // `0` width that `eyedropperAdd` would never have put there itself.
310
+ if (key !== undefined && sel[d.control].has(key)) continue;
311
+ const unaddable = key === undefined || (dim === 'thickness' && (!(key > 0) || (el && el.kind === 'text')));
312
+ if (unaddable) out.push({ dim, reason: 'no-value' });
313
+ else if (!facetRowIndicesFor(filter, dim, el).length) out.push({ dim, reason: 'no-row' });
314
+ else out.push({ dim, reason: 'unticked' });
315
+ }
316
+ return out;
317
+ }
318
+
210
319
  /** Count how many elements are visible under the current mode + selection. */
211
320
  export function countShown(elements, mode, sel) {
212
321
  let n = 0;
@@ -255,7 +364,22 @@ const TEXT_DEFAULT_FONT = 10;
255
364
  const MIN_HORIZONTAL_ADVANCE = 0.1;
256
365
 
257
366
  /**
258
- * The `font-size` for one text element, from its bounding box and its string.
367
+ * The span's own font size as the producer recorded it (`element.size`), or 0 when there is none.
368
+ * Contracts extracted before the producer recorded it carry no `size`; so does a hand-edited one. Only a
369
+ * finite positive number counts: anything else is "not recorded", never a size of 0.
370
+ */
371
+ const recordedFontSize = (size) => (typeof size === 'number' && Number.isFinite(size) && size > 0 ? size : 0);
372
+
373
+ /**
374
+ * The `font-size` for one text element: the PDF's own size when the producer recorded it, and otherwise
375
+ * an estimate from its bounding box and its string.
376
+ *
377
+ * THE RECORDED SIZE WINS, unfloored, because it is the truth the box can only approximate: the drawing is
378
+ * meant to read at the sizes it was plotted at, and the box estimate below is wrong in a way no rule on
379
+ * the box can fix. A label set along a diagonal member has an axis-aligned box inflated on BOTH sides,
380
+ * so its short side is not its glyph height either. On the real Take 5 sheet every label is 9.36 or
381
+ * 18.84 pt Arial, and the estimate drew HSS6x6x3/8 at 40.4 (4.3x) and W10x33 at 29.3 (3.1x) beside
382
+ * horizontal labels that measured exactly right. What follows is the fallback for contracts without it.
259
383
  *
260
384
  * The producer records a bbox and the text, never a rotation, so the writing direction has to be
261
385
  * INFERRED. For horizontal text the run advances along X, so the box's HEIGHT is the glyph height —
@@ -290,20 +414,154 @@ const MIN_HORIZONTAL_ADVANCE = 0.1;
290
414
  * constant far enough to catch it would start shrinking narrow horizontal text, which is the worse
291
415
  * failure (unreadable labels on every drawing, to fix a rare one).
292
416
  */
293
- export function textFontSize(bbox, text) {
294
- // Junk coerces to 0 rather than NaN, so a malformed bbox lands on the default below instead of
295
- // poisoning the comparison (NaN fails every test, which would silently mean "horizontal").
296
- const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
297
- const b = Array.isArray(bbox) ? bbox : [];
298
- const w = num(b[2]) - num(b[0]);
299
- const h = num(b[3]) - num(b[1]);
300
- const glyphs = (text == null ? '' : String(text)).trim().length;
301
- const vertical = glyphs > 1 && w > 0 && w < h && w < h * glyphs * MIN_HORIZONTAL_ADVANCE;
302
- const side = vertical ? w : h;
417
+ export function textFontSize(bbox, text, size) {
418
+ const recorded = recordedFontSize(size);
419
+ if (recorded) return recorded;
420
+ const [w, h] = textSides(bbox);
421
+ const side = textIsVertical(bbox, text) ? w : h;
303
422
  // `|| TEXT_DEFAULT_FONT` for a zero/unmeasurable side, then the floor — the two-step the page shipped.
304
423
  return Math.max(TEXT_MIN_FONT, side || TEXT_DEFAULT_FONT);
305
424
  }
306
425
 
426
+ /**
427
+ * Junk coerces to 0 rather than NaN, so a malformed bbox lands on the defaults above instead of
428
+ * poisoning the comparisons (NaN fails every test, which would silently mean “horizontal”).
429
+ */
430
+ const textNum = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
431
+
432
+ /**
433
+ * Is this run drawn ROTATED — i.e. is its recorded box's SHORT side the glyph height? The whole
434
+ * discriminator textFontSize documents above, lifted out because the drawn-run geometry below needs the
435
+ * same answer and a second copy of this test would be free to drift from the one that sizes the glyphs.
436
+ */
437
+ export function textIsVertical(bbox, text) {
438
+ const [w, h] = textSides(bbox);
439
+ const glyphs = (text == null ? '' : String(text)).trim().length;
440
+ return glyphs > 1 && w > 0 && w < h && w < h * glyphs * MIN_HORIZONTAL_ADVANCE;
441
+ }
442
+
443
+ /**
444
+ * The recorded box, NORMALISED to `[left, top, right, bottom]` in the drawing's y-down space, or null
445
+ * when the box does not have four finite numeric corners. A box describes the same rectangle whichever
446
+ * corner it was recorded from. So the glyph size, the rotation test and the anchor the page mounts the
447
+ * run at (`textDraw`) read it from here, and so do the hit index's recorded rectangle (`textRect` in
448
+ * steel-filter-hit.js) and the halo (`paintHot`): no two of them can disagree about which rectangle a
449
+ * label occupies.
450
+ *
451
+ * Read raw, they disagreed twice (#1538 review findings). A rotated `[0,100,10,0]` had a negative
452
+ * height, so it was judged horizontal and sized at the 8-unit floor instead of its 10-unit glyph width.
453
+ * And a reversed `[300,510,420,495]` was anchored at its raw `bbox[3]` — its TOP edge — so the page
454
+ * painted its glyphs at y 480..495, wholly outside the y 495..510 box the hit test and the halo use,
455
+ * and a pointer on the visible label read nothing.
456
+ *
457
+ * Only a box with FOUR finite numbers is normalised — the same admission rule the hit index has always
458
+ * had. A corner that is missing, non-finite or not a number is not an edge, and must never become one:
459
+ * coercing it to 0 and normalising against that 0 moved `[100,200]` to x 0 at font-size 200 (Codex
460
+ * review, round 4). Such a box is read exactly as the page always read it (`textSides`, `textDraw`).
461
+ *
462
+ * `max - min` is exactly `|a - b|` in floating point, so the sides measure what they always did. The
463
+ * producer emits normalised boxes (a PyMuPDF `Rect * Matrix`, server/steel-filter-prepass.ts), so on a
464
+ * real drawing nothing read through here moves.
465
+ *
466
+ * @returns {[number, number, number, number] | null}
467
+ */
468
+ export function textBox(bbox) {
469
+ if (!Array.isArray(bbox)) return null;
470
+ const [x0, y0, x1, y1] = bbox;
471
+ if (!Number.isFinite(x0) || !Number.isFinite(y0) || !Number.isFinite(x1) || !Number.isFinite(y1)) return null;
472
+ return [Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1)];
473
+ }
474
+
475
+ /**
476
+ * The box's `[width, height]`: measured on the normalised box when there is one. Otherwise they are read
477
+ * exactly as the page always read them, raw and signed, with junk coerced to 0. That is the only reading
478
+ * that sizes a malformed box as it always was (`[100,200]` at the 8-unit floor), and a negative side it
479
+ * produces is never judged rotated.
480
+ */
481
+ const textSides = (bbox) => {
482
+ const r = textBox(bbox);
483
+ if (r) return [r[2] - r[0], r[3] - r[1]];
484
+ const b = Array.isArray(bbox) ? bbox : [];
485
+ return [textNum(b[2]) - textNum(b[0]), textNum(b[3]) - textNum(b[1])];
486
+ };
487
+
488
+ /**
489
+ * The average glyph advance, as a fraction of the font size, used to ESTIMATE how wide a run is drawn.
490
+ * There are no text metrics here — this module is pure, and the hit index is built before anything is
491
+ * laid out — so the width of a run has to be guessed from its glyph count. 0.5 deliberately guesses
492
+ * LOW (mixed-case sans text averages nearer 0.55), because the estimate becomes a hit rectangle:
493
+ * falling short loses the hover on the last glyph or two of a label, while overshooting steals the
494
+ * pointer from whatever is drawn just past it — a leader line, which is the failure #1527's first
495
+ * attempt at this shipped and had to back out.
496
+ */
497
+ const GLYPH_ADVANCE = 0.5;
498
+
499
+ /**
500
+ * The string the view actually paints for a text element — the page's own `el.text || ''`, lifted so
501
+ * that expression exists once.
502
+ *
503
+ * It matters because the run rectangle is measured from the glyph COUNT. Counting
504
+ * `String(text).trim().length` instead made `text: false` five glyphs wide and `text: 0` one, for
505
+ * elements the page paints as empty: a rectangle at distance 0 throughout, filed and haloed, for
506
+ * glyphs nobody can see (review finding). `textFontSize` keeps its own `String(text)` count on
507
+ * purpose — it predates this, it only ever picks an axis, and changing it would move the size of
508
+ * every run on every drawing to fix a rectangle that is now simply not created.
509
+ *
510
+ * A truthy non-string is CONVERTED, not passed through. A contract may carry `text: 1` for a grid
511
+ * bubble -- nothing type-checks `elements[].text` -- and handing that back unchanged made `textDraw`
512
+ * call `.trim()` on a number, which threw while building the overlay and took the whole sheet down
513
+ * with it (Codex review). `text || ''` is still what decides EMPTY, so `false` and `0` paint nothing
514
+ * exactly as the page always had it.
515
+ */
516
+ export const textString = (text) => (text ? String(text) : '');
517
+
518
+ /**
519
+ * WHERE the page draws one text element: the anchor it mounts the run at, the font-size it uses, and
520
+ * the rectangle the glyphs therefore occupy (`run`, null when there are no glyphs to draw).
521
+ *
522
+ * THE ONE source of that geometry. The view mounts the run from `x`/`baseline`/`size`; the hit index
523
+ * files a ROTATED run's `run` as a second rectangle beside the recorded bbox, and the hover halo draws
524
+ * it — so what a user points at is by construction what was drawn there. Deriving it twice is what
525
+ * #1538 is about: a rotated run's recorded box is tall and narrow while its glyphs run sideways OUT of
526
+ * it, so hit testing the recorded box alone reads nothing over most of a label the user can plainly see.
527
+ *
528
+ * The anchor is the NORMALISED box's bottom-left corner (`textBox`). An SVG `<text>` stands on its
529
+ * baseline and rises from it, so in this y-down space the bottom edge is where the glyphs stand, and
530
+ * they are painted up INTO the recorded box. For a box recorded top-left to bottom-right — every box
531
+ * the producer emits — that is exactly the page's long-standing raw anchor, `x = bbox[0]` and
532
+ * `y = bbox[3] || bbox[1]`, so nothing on a real drawing moves. What moves is a box recorded the other
533
+ * way round: the raw anchor sat on its TOP edge and painted the label wholly above its own box, where
534
+ * neither the hit test nor the halo was. Anchoring from the normalised box makes the recorded box
535
+ * contain an unrotated run by construction (operator ruling on #1542, 2026-09-24), which is what lets
536
+ * the hit test trust that box instead of clamping an estimate against it.
537
+ *
538
+ * The one normalised spelling that also moves is a box whose bottom edge is exactly 0 and whose top is
539
+ * negative: the raw `||` read that 0 as missing and fell through to the top edge — the same defect, on
540
+ * a box lying above the sheet's origin, which the producer does not emit.
541
+ *
542
+ * A box WITHOUT four finite numeric corners has no normalised form (`textBox`) and is anchored exactly
543
+ * as the page always anchored it: `x = bbox[0]`, `y = bbox[3] || bbox[1]`, the `||` on the raw entries
544
+ * and then coerced (coercing first moved a box whose `bbox[3]` is the STRING '0', which is truthy to the
545
+ * page). The hit index cannot file such a box, so nothing it answers depends on where this puts it.
546
+ *
547
+ * A HORIZONTAL run's estimated width is capped at its recorded width, which for such a run already
548
+ * spans the glyphs: the estimate is only ever needed where the recording does not describe the drawn
549
+ * run, and left uncapped it reaches past the last glyph onto the linework beside it. A recorded width
550
+ * of 0 or less measures nothing, so it caps nothing.
551
+ */
552
+ export function textDraw(bbox, text, fontSize) {
553
+ const b = Array.isArray(bbox) ? bbox : [];
554
+ const box = textBox(b);
555
+ const x = box ? box[0] : textNum(b[0]);
556
+ const baseline = box ? box[3] : textNum(b[3] || b[1]);
557
+ const size = textFontSize(b, text, fontSize);
558
+ const glyphs = textString(text).trim().length;
559
+ const [recorded] = textSides(b);
560
+ let width = glyphs * size * GLYPH_ADVANCE;
561
+ if (!textIsVertical(b, text) && recorded > 0) width = Math.min(width, recorded);
562
+ return { x, baseline, size, width, run: glyphs ? [x, baseline - size, x + width, baseline] : null };
563
+ }
564
+
307
565
  /**
308
566
  * Write the live selection + mode back onto the filter block's `on` flags so it persists on the
309
567
  * contract (what Save PUTs, and what the reader reads). Mutates and returns `filter`.
@@ -320,7 +578,9 @@ export function applySelToFilter(filter, sel, mode) {
320
578
  const d = FACET_DIMS[dim];
321
579
  for (const row of filter[d.control] || []) {
322
580
  const key = facetKey(dim, row[d.rowKey]);
323
- row.on = key !== undefined && sel[d.control].has(key);
581
+ // A not-read layer row (#1579) is written OFF even when a readable twin with the same name
582
+ // selects the value: selFromFilter keeps the ROW out, and this keeps it out row by row.
583
+ row.on = key !== undefined && !(dim === 'layer' && row.notRead === true) && sel[d.control].has(key);
324
584
  }
325
585
  }
326
586
  return filter;
@@ -574,3 +834,29 @@ export function dismissibleFacetValues(filter) {
574
834
  }
575
835
  return out;
576
836
  }
837
+
838
+ /**
839
+ * The note Hover info shows when some curves on the sheet cannot be read along their whole length
840
+ * (#1550), or null when there is nothing to say. `coarse` is the hit index's count of curves it had to
841
+ * trace with fewer straight pieces than they need -- pointing at parts of those can read nothing,
842
+ * more of them once zoomed in (where the pointer's reach shrinks), so the user must be told rather than left to conclude the line is not there.
843
+ *
844
+ * `canIdentify` is whether a click on an empty spot can ask the original drawing (#1528): that is the
845
+ * one recovery that names the exact line, so it is offered whenever it exists. The Filters panel, which
846
+ * lists every value on the sheet, always is.
847
+ *
848
+ * Pure, so the singular/plural wording and both recoveries are table-tested without a page.
849
+ */
850
+ export function coarseCurveNote(coarse, canIdentify) {
851
+ const n = Number.isSafeInteger(coarse) && coarse > 0 ? coarse : 0;
852
+ if (!n) return null;
853
+ const one = n === 1;
854
+ const title = one ? '1 curve can’t be read everywhere' : `${n.toLocaleString('en-US')} curves can’t be read everywhere`;
855
+ const why = one
856
+ ? 'Hover info could not trace it in full, because it is very large or this sheet has a great many large curves, so pointing at parts of it may read nothing, especially zoomed in.'
857
+ : 'Hover info could not trace them in full, because they are very large or this sheet has a great many large curves, so pointing at parts of them may read nothing, especially zoomed in.';
858
+ const next = canIdentify
859
+ ? 'Click the spot to ask the original drawing what is there, or find the value in the Filters panel.'
860
+ : 'Find the value in the Filters panel instead.';
861
+ return { title, body: `${why} ${next}` };
862
+ }