@floless/app 0.123.2 → 0.124.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.
@@ -498,7 +498,15 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
498
498
  #moreMenu button:disabled{opacity:.4;cursor:default;background:transparent}
499
499
  #moreMenu button.on{color:var(--brand)}
500
500
  button:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
501
- #srcStat{max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
501
+ /* Provenance is an at-a-glance marker, not a second sheet selector: a muted label plus one short bold
502
+ value, the way the header's other stat chips read (Members 6, Axes Global), with the full caption in
503
+ data-tip. Capping the value holds the whole chip to 173px even on a name that overruns (master's ran
504
+ to 240px), which is what keeps a 1920 window's button bank on one row — the header is flex-wrap:wrap,
505
+ so it still wraps below ~1870px, and sooner the longer the value. `b` needs
506
+ inline-block for max-width to apply at all, and vertical-align:bottom to hold its baseline with the
507
+ sibling chips (overflow:hidden makes an inline-block's bottom edge its own baseline). */
508
+ #srcStat{white-space:nowrap}
509
+ #srcStat b{display:inline-block;max-width:130px;overflow:hidden;text-overflow:ellipsis;vertical-align:bottom}
502
510
  #detailNewForm input#dnName{margin:2px 0 10px}
503
511
  #dnDrop{border:1px dashed #475569;border-radius:8px;background:#0b1220;min-height:88px;display:flex;align-items:center;justify-content:center;gap:12px;text-align:center;color:var(--mut);cursor:pointer;padding:12px;font-size:12px}
504
512
  #dnDrop:hover{border-color:var(--brand);color:var(--text)} #dnDrop.has{border-style:solid;border-color:var(--brand)}
@@ -879,6 +887,14 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
879
887
  #m3dRefsBody .refdet input[type=text]{height:24px;font-size:11px}
880
888
  #m3dRefsBody .refdet .dnote{color:var(--mut);font-size:11px;line-height:1.45}
881
889
  #m3dRefsBody .refdet .dwarn{color:#fbbf24;font-size:11px;line-height:1.45}
890
+ /* The Stage D measurement block. IT IS NOT A .dwarn, and that distinction is the point: `.dwarn` is
891
+ amber, and amber in this panel already means "something looks wrong with this reference" (it is
892
+ 1000× too big, it is a long way from your model). A measurement is a neutral READING — dressing it in
893
+ the warning colour would tell the user their measurement was a problem, and would leave nothing louder
894
+ for the caution that lives INSIDE it. So the block is neutral and contained, and only the caution
895
+ within it is amber. Every value here is already in use two rules up (--line, #0b1220 from .lockrow's
896
+ track); no new token enters the baseline. */
897
+ #m3dRefsBody .refdet .dmeas{border:1px solid var(--line);border-radius:6px;background:#0b1220;padding:6px;display:flex;flex-direction:column;gap:6px}
882
898
  #m3dRefsBody .refdet .lockrow{display:flex;align-items:center;gap:0;color:var(--text);font-size:11px;background:transparent;border:0;padding:2px 0;cursor:pointer;box-shadow:none}
883
899
  #m3dRefsBody .refdet .lockrow .mck{position:relative;width:26px;height:14px;margin-right:9px;border-radius:7px;border:1px solid var(--line);background:#0b1220;flex:none;transition:background-color .15s,border-color .15s}
884
900
  #m3dRefsBody .refdet .lockrow .mck::after{content:'';position:absolute;top:1px;left:1px;width:10px;height:10px;border-radius:50%;background:#64748b;transition:transform .15s,background-color .15s}
@@ -949,6 +965,40 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
949
965
  #riSays b{color:var(--mut);font-weight:600}
950
966
  #riVerdict{display:none;margin-top:10px;padding:8px 10px;border:1px solid #713f12;border-radius:7px;color:#fbbf24;font-size:11.5px;line-height:1.55}
951
967
  #riVerdict button{margin-top:7px}
968
+ /* ── The storey / type picker (S2 Stage C) — load ONE FLOOR of a building you cannot afford whole.
969
+ A section INSIDE the confirm stage rather than a fourth stage: that stage already means "here are
970
+ the facts, add it?", and this makes it "here are the facts, choose a part, add it" — still the same
971
+ question with a refinement, not a new one. A fourth stage would also charge every large file an
972
+ extra click, which is precisely the file this exists to help.
973
+ The grouping chrome is #m3dLegend's `.cat-hdr`/`.cat-label`/`.cat-tog`, widened above rather than
974
+ re-declared, and the rows reuse `.reftree`'s bounded-scroll recipe. NO SCROLLBAR CSS IS NEEDED —
975
+ the page's global `*{scrollbar-width…}` (line 6) and `*::-webkit-scrollbar*` rules already reach
976
+ any new container. NO CHECKBOX CSS EITHER: `input[type=checkbox]` is fully themed above
977
+ (unchecked box, :checked, indeterminate, :focus-visible, forced-colors). */
978
+ #riPickToggle{margin-top:10px}
979
+ #refImportModal .reftree{max-height:168px;overflow:auto;border:1px solid var(--line);border-radius:7px;background:var(--bg);padding:3px 2px;margin-bottom:8px}
980
+ #refImportModal .ripick-row{display:flex;align-items:center;gap:6px;padding:2px 4px;border-radius:5px;font-size:11.5px;color:var(--text);cursor:pointer;user-select:none}
981
+ #refImportModal .ripick-row:hover{background:#33415580}
982
+ #refImportModal .ripick-row .rpname{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}
983
+ #refImportModal .ripick-row .rpcount{flex:none;color:var(--mut);font-variant-numeric:tabular-nums;font-size:10px}
984
+ /* The storey-less row. NOT a disabled checkbox — a disabled control says "you may not do this yet",
985
+ and the truth is that the reader cannot express it at all, so there is no control to disable. */
986
+ #refImportModal .ripick-row--fixed{cursor:default}
987
+ #refImportModal .ripick-row--fixed:hover{background:none}
988
+ #refImportModal .ripick-row .rpfixed{flex:none;width:14px;text-align:center;color:var(--mut)}
989
+ #refImportModal .ripick-row .rpnote{flex:none;color:var(--mut);font-size:10px}
990
+ #riPickNote,#riNoBreak{color:var(--mut);font-size:11px;line-height:1.5;margin:8px 0}
991
+ /* The live count's two loud states, in the tokens this file already uses — #riVerdict's amber and
992
+ #riDropErr's red. No new colour is introduced by this feature. */
993
+ #riConfirmErr{display:none;margin-top:10px;color:#fca5a5;font-size:11.5px;line-height:1.5}
994
+ /* Two ids, deliberately: `#riElements.warn` alone is specificity (1,1,0) and loses to
995
+ `#refImportModal .rirow .pv` (1,2,0) above, so the colour was authored and never rendered. An
996
+ independent QA pass found it by reading the computed colour — asserting the class name, which
997
+ is what this session's own E2E did, passes with the pixel still wrong. */
998
+ #refImportModal #riElements.warn{color:#fbbf24} #refImportModal #riElements.refuse{color:#fca5a5}
999
+ #riFootNote{display:none;flex:1;align-self:center;font-size:11px;line-height:1.4;text-align:left}
1000
+ #riFootNote.warn{color:#fbbf24} #riFootNote.refuse{color:#fca5a5}
1001
+ #riInsert[disabled]{opacity:.5;cursor:not-allowed}
952
1002
  /* ── Favourites tab (#m3dFavBody) — the Views-tab row/search recipe. No create button (★ lives in the
953
1003
  Inspector); a kind-filter + search header, per-row kind swatch + portability badge + row-click-to-arm. ── */
954
1004
  #favHeadRow{display:flex;align-items:stretch;gap:6px;margin-bottom:6px;flex:none}
@@ -1007,19 +1057,31 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1007
1057
  #m3dLegend .lmode{display:flex;border:1px solid var(--line);border-radius:6px;overflow:hidden;height:24px;margin-bottom:6px;flex:none}
1008
1058
  #m3dLegend .lmode button{flex:1;border:0;background:transparent;color:var(--mut);font-size:11px;cursor:pointer}
1009
1059
  #m3dLegend .lmode button.on{background:var(--brand);color:#fff}
1010
- #m3dLegend .cat-hdr{display:flex;align-items:center;gap:6px;padding:3px 4px;border-radius:5px;cursor:pointer;user-select:none;white-space:nowrap}
1011
- #m3dLegend .cat-hdr:hover{background:#33415580}
1060
+ /* WIDENED, NOT DUPLICATED, to reach the import modal's storey/type picker (S2 Stage C) — the same
1061
+ technique the `.psethd`/`.psetbody` rules above needed for #m3dRefsBody, and for the same reason:
1062
+ these are scoped to #m3dLegend, which is not an ancestor of #refImportModal. The picker is the
1063
+ identical shape (a header standing for several rows, with a tri-state toggle), so it gets the
1064
+ identical chrome rather than a second copy that drifts. */
1065
+ #m3dLegend .cat-hdr,#refImportModal .cat-hdr{display:flex;align-items:center;gap:6px;padding:3px 4px;border-radius:5px;cursor:pointer;user-select:none;white-space:nowrap}
1066
+ #m3dLegend .cat-hdr:hover,#refImportModal .cat-hdr:hover{background:#33415580}
1067
+ /* …but NOT in the import modal, where only the nested toggle acts. In #m3dLegend the whole header
1068
+ collapses its group, so the pointer and the hover fill are honest there; borrowing them here would
1069
+ promise a click that does nothing. Placed AFTER the rule it overrides — same specificity, so source
1070
+ order is what decides, and an earlier copy silently lost. */
1071
+ #refImportModal .cat-hdr{cursor:default}
1072
+ #refImportModal .cat-hdr:hover{background:none}
1073
+ #refImportModal .cat-tog{cursor:pointer}
1012
1074
  #m3dLegend .cat-hdr.empty .cat-label,#m3dLegend .cat-hdr.empty .cat-count{opacity:.55}
1013
1075
  #m3dLegend .cat-hdr.drop-target{outline:1px solid var(--brand);background:rgba(59,130,246,.18)}
1014
1076
  #m3dLegend .cat-chevron{font-size:10px;color:var(--mut);width:12px;flex:none;text-align:center}
1015
- #m3dLegend .cat-tog{font-size:12px;width:14px;flex:none;cursor:pointer;line-height:1;text-align:center}
1016
- #m3dLegend .cat-tog[data-state=on]{color:var(--brand)} #m3dLegend .cat-tog[data-state=off]{color:var(--mut)} #m3dLegend .cat-tog[data-state=mixed]{color:#64748b}
1077
+ #m3dLegend .cat-tog,#refImportModal .cat-tog{font-size:12px;width:14px;flex:none;cursor:pointer;line-height:1;text-align:center;background:none;border:0;padding:0}
1078
+ #m3dLegend .cat-tog[data-state=on],#refImportModal .cat-tog[data-state=on]{color:var(--brand)} #m3dLegend .cat-tog[data-state=off],#refImportModal .cat-tog[data-state=off]{color:var(--mut)} #m3dLegend .cat-tog[data-state=mixed],#refImportModal .cat-tog[data-state=mixed]{color:#64748b}
1017
1079
  /* `min-width:0` + ellipsis because a flex item that cannot shrink below its content OVERFLOWS the row
1018
1080
  rather than truncating, and `.cat-hdr` is `white-space:nowrap`. The legend's own categories were
1019
1081
  always short enough to hide this; the reference tree's disambiguated headers ("Wall · IFCWALL…")
1020
1082
  are the first labels long enough to test it. Same recipe as `.refname` directly above. */
1021
- #m3dLegend .cat-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:12px;color:var(--text)}
1022
- #m3dLegend .cat-count{font-size:10px;color:var(--mut);font-variant-numeric:tabular-nums}
1083
+ #m3dLegend .cat-label,#refImportModal .cat-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:12px;color:var(--text)}
1084
+ #m3dLegend .cat-count,#refImportModal .cat-count{font-size:10px;color:var(--mut);font-variant-numeric:tabular-nums}
1023
1085
  #m3dLegend .lrow.typed{padding-left:20px}
1024
1086
  #m3dLegend .cat-hdr.sub{padding-left:20px} /* a nested (middle) category, e.g. Dimensions → Base-plate */
1025
1087
  #m3dLegend .lrow.sub{padding-left:34px} /* a row inside a nested category — indented one level deeper */
@@ -1111,9 +1173,12 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1111
1173
  <b>Steel Model</b>
1112
1174
  <div id=viewToggle role=group aria-label="Canvas view"><button id=vt2d class="seg on" aria-pressed=true data-tip="Plan view (2D overlay)">2D</button><button id=vt3d class=seg aria-pressed=false data-tip="3D model view">3D</button></div>
1113
1175
  <!-- Plan switcher. See the .plan-* rules for why this is not a <select>. Unlike the sibling page's sheet
1114
- switcher it is NOT hidden for a single plan: this control is the ONLY place the current sheet name
1115
- appears in this editor, so hiding it for a one-plan model would delete information rather than a
1116
- dead control. (An earlier version of this comment justified that by claiming the sibling can hide
1176
+ switcher it is NOT hidden for a single plan: this control is the only place the name of the plan you
1177
+ are LOOKING AT appears, so hiding it for a one-plan model would delete information rather than a
1178
+ dead control. (#srcStat is not a second one: it names the READ, and only ever with C.source.name or
1179
+ the read date — never C.source.sheet, which is why the header can never appear to name the plan you
1180
+ are on. A read that recorded ONLY a sheet shows no chip at all.)
1181
+ (An earlier version of this comment justified that by claiming the sibling can hide
1117
1182
  because the sheet is also named on its #src readout. That is false — #src renders `C.source.name`,
1118
1183
  the source FILE's name — and the sibling really does leave a lone sheet unnamed on screen. The
1119
1184
  decision here stands on its own; it does not need a claim about the other page.) -->
@@ -1474,8 +1539,25 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1474
1539
  <div id=riConfirmStage style="display:none">
1475
1540
  <div id=riSays></div>
1476
1541
  <div class=rirow><span class=pn>Schema</span><span class=pv id=riSchema>—</span></div>
1477
- <div class=rirow><span class=pn>Objects</span><span class=pv id=riElements>—</span></div>
1542
+ <!-- "ESTIMATED objects", and it reads `population` — not `probe.elements`, which counts elements
1543
+ placed directly in the spatial structure and is a DIFFERENT, smaller number (measured: 10 for
1544
+ a file whose read returns 16, and 5,878 for one that returns 17,460). This row sits directly
1545
+ above a limit stated in objects, so the two have to be the same kind of number. `aria-live` is
1546
+ on the VALUE alone so ticking a storey re-announces the count, not the label. -->
1547
+ <div class=rirow><span class=pn data-tip="How many objects FloLess expects to load, read from the file's own storey and type summary before anything is drawn. The real count can differ a little once the file is read.">Estimated objects</span><span class=pv id=riElements aria-live=polite>—</span></div>
1478
1548
  <div class=rirow><span class=pn>File size</span><span class=pv id=riBytes>—</span></div>
1549
+ <!-- ── The picker. Hidden entirely unless the file offers a real choice (more than one storey or
1550
+ more than one type); collapsed unless the file is big enough for the choice to matter, so a
1551
+ 13-object model still imports in two clicks. -->
1552
+ <button type=button id=riPickToggle class=pilllink style="display:none" aria-expanded=false aria-controls=riPick>Load only part of this file ▸</button>
1553
+ <div id=riPick style="display:none">
1554
+ <div id=riPickNote style="display:none"></div>
1555
+ <div class=cat-hdr id=riStoreyHdr><span class=cat-label>Storeys</span><span class=cat-count id=riStoreyCount></span><button type=button class=cat-tog id=riStoreyAll data-state=on data-tip="Select or clear every storey"></button></div>
1556
+ <div class=reftree id=riStoreyList></div>
1557
+ <div class=cat-hdr id=riTypeHdr><span class=cat-label>Types</span><span class=cat-count id=riTypeCount></span><button type=button class=cat-tog id=riTypeAll data-state=on data-tip="Select or clear every type"></button></div>
1558
+ <div class=reftree id=riTypeList></div>
1559
+ </div>
1560
+ <div id=riNoBreak style="display:none"></div>
1479
1561
  <!-- NO SIZE ROW HERE, and that is a decision rather than an omission. The only pre-tessellation
1480
1562
  measurement available is `probe.bbox`, which its own manifest calls APPROXIMATE — measured, it
1481
1563
  spans every cartesian point the file places, not the geometry: for the Motebello lift shaft it
@@ -1484,9 +1566,17 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1484
1566
  is in, from the rendered bounds; the bbox is used ONLY for the position hint below, which is
1485
1567
  labelled a probability and phrased as one. -->
1486
1568
  <div id=riVerdict role=status></div>
1569
+ <!-- The confirm stage's OWN error slot. Without it a refusal had to fall back to `riStage('drop')`,
1570
+ which swaps the whole body out — so a message saying "choose fewer storeys" destroyed the
1571
+ picker it was pointing at. -->
1572
+ <div id=riConfirmErr role=alert></div>
1487
1573
  </div>
1488
1574
  </div>
1489
1575
  <div class=rifoot>
1576
+ <!-- The count again, in the footer, because the picker pushes the row above out of view on a file
1577
+ with twelve storeys and sixteen types — and the number is the whole reason the control is
1578
+ comprehensible. Shown only when it is amber or red; silence is the ok state. -->
1579
+ <div id=riFootNote role=status></div>
1490
1580
  <button id=riCancel>Cancel</button>
1491
1581
  <button id=riInsert class=primary style="display:none" data-tip="Add this model as a reference. It is never part of your steel.">Add reference</button>
1492
1582
  </div>
@@ -1496,7 +1586,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1496
1586
  <div id=ciBody>
1497
1587
  <!-- stage: dropzone -->
1498
1588
  <div id=ciDropStage>
1499
- <div id=ciDrop data-tip="Click to browse, or drag an IFC file here"><span id=ciDropTxt>Drop an IFC file here, or click to browse</span></div>
1589
+ <div id=ciDrop data-tip="Click to browse, or drag an IFC file here"><span>Drop an IFC file here, or click to browse</span></div>
1500
1590
  <input id=ciFile type=file accept=".ifc,.ifczip" hidden>
1501
1591
  <div class=hint style="margin-top:10px">Design a connection in IDEA StatiCa, Tekla or any tool, export IFC, and drop it here to place it in your model. The file stays on your machine.</div>
1502
1592
  <div class=gerr id=ciDropErr style="display:none"></div>
@@ -1567,6 +1657,12 @@ const APP_ID = new URLSearchParams(location.search).get('app') || '';
1567
1657
  // /api/contract call; the contract-request (Ask AI) bodies carry `project` for slice-4 context.
1568
1658
  const PROJECT = new URLSearchParams(location.search).get('project') || '';
1569
1659
  const PROJECT_QS = PROJECT ? ('?project=' + encodeURIComponent(PROJECT)) : '';
1660
+ // READS ONLY, and only when project-scoped — the same split steel-filter.html already makes, for the
1661
+ // same reason. A project with no model yet is an expected state, not a failure, but a 404 makes the
1662
+ // browser log its own red "Failed to load resource" that no JS handling can suppress; 204 says the
1663
+ // same thing silently. Never on the app-keyed URL, whose 404 carries the publication-ownership codes
1664
+ // the empty states below branch on, and never on the PUT — a write wants the ordinary refusal.
1665
+ const CONTRACT_QS = PROJECT ? (PROJECT_QS + '&quietMissing=1') : PROJECT_QS;
1570
1666
  // ── The browser draft's identity, and the contract type this page can render (unit 5, P1c-3) ──
1571
1667
  // The one contract type this editor renders. A contract with NO `type` is legacy steel v1 — the server's
1572
1668
  // own validator says so and falls back to exactly this (contract-schema.ts, validateContract), so
@@ -1943,7 +2039,14 @@ async function boot() {
1943
2039
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
1944
2040
  import('./steel-model-v2-commands.js'), import('./steel-model-v2-client-validation.js'),
1945
2041
  ]);
1946
- const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
2042
+ const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + CONTRACT_QS);
2043
+ // 204 = the project-scoped "nothing stored yet", the quiet twin of the generic 404 below. It carries
2044
+ // no body and no code, so it routes straight to the same empty state rather than through the
2045
+ // publication-code branches, which only an app-keyed read can produce.
2046
+ if (res.status === 204) {
2047
+ showEmpty('⊞', 'No model for', 'Read a structural drawing first — ask your terminal AI to run the workflow, then open this editor again.', APP_ID);
2048
+ return;
2049
+ }
1947
2050
  if (!res.ok) {
1948
2051
  if (res.status === 404) {
1949
2052
  // TWO different 404s, and telling them apart is the whole point of this branch.
@@ -4130,7 +4233,7 @@ function gridSvg(){
4130
4233
  geo.v.forEach((l,i)=>{s+=`<line class="gridln${gsel('gv:'+i)}" data-gv="${i}" x1="${l.x}" y1="${l.lo}" x2="${l.x}" y2="${l.hi}"/><line class="gridhit gv" data-gv="${i}" x1="${l.x}" y1="${l.lo}" x2="${l.x}" y2="${l.hi}" data-tip="Grid ${esc(l.label)} — ${gTip}"></line>`;});
4131
4234
  geo.h.forEach((l,i)=>{s+=`<line class="gridln${gsel('gh:'+i)}" data-gh="${i}" x1="${l.lo}" y1="${l.y}" x2="${l.hi}" y2="${l.y}"/><line class="gridhit gh" data-gh="${i}" x1="${l.lo}" y1="${l.y}" x2="${l.hi}" y2="${l.y}" data-tip="Grid ${esc(l.label)} — ${gTip}"></line>`;});
4132
4235
  (geo.lines||[]).forEach((l,i)=>{s+=`<line class="gridln${gsel('gl:'+(l.id!=null?l.id:i))}" data-gl="${i}" x1="${l.a[0]}" y1="${l.a[1]}" x2="${l.b[0]}" y2="${l.b[1]}"/><line class="gridhit gl" data-gl="${i}" x1="${l.a[0]}" y1="${l.a[1]}" x2="${l.b[0]}" y2="${l.b[1]}" data-tip="Grid ${esc(l.label)} — ${gTip}"></line>`;});
4133
- const bub=(x,y,lb,ax,i,end)=>`<g class=gridbubg data-${ax}="${i}" data-end="${end}" data-tip="Grid ${esc(lb)} — drag to move or adjust · dbl-click to rename · click to select"><circle class=gridbub data-bx="${x}" data-by="${y}" cx="${x}" cy="${y}" r="${R}"/><text class=gridtx data-bx="${x}" data-by="${y}" x="${x}" y="${y}" style="font-size:${F}px">${esc(lb)}</text></g>`;
4236
+ const bub=(x,y,lb,ax,i,end)=>`<g class=gridbubg data-${ax}="${i}" data-end="${end}" data-tip="Grid ${esc(lb)} — drag to move or adjust · dbl-click to rename · click to select"><circle class=gridbub cx="${x}" cy="${y}" r="${R}"/><text class=gridtx x="${x}" y="${y}" style="font-size:${F}px">${esc(lb)}</text></g>`;
4134
4237
  geo.v.forEach((l,i)=>{s+=bub(l.x,l.lo,l.label,'gv',i,0)+bub(l.x,l.hi,l.label,'gv',i,1);});
4135
4238
  geo.h.forEach((l,i)=>{s+=bub(l.lo,l.y,l.label,'gh',i,0)+bub(l.hi,l.y,l.label,'gh',i,1);});
4136
4239
  (geo.lines||[]).forEach((l,i)=>{s+=bub(l.a[0],l.a[1],l.label,'gl',i,0)+bub(l.b[0],l.b[1],l.label,'gl',i,1);});
@@ -4472,7 +4575,9 @@ let lastCmd=null;
4472
4575
  function setLastCmd(label,run){lastCmd={label,run};}
4473
4576
  function anyToolActive(){
4474
4577
  if(dimMode||dimChain||dimSplitMode||geoMode||csaxisMode||gridMode||gridPick||gridLinePick||dimStyleMode||mode==='add'||picking||cmTool||qdPick)return true; // 2D tools armed (cmTool = Move/Copy; qdPick = the F7 grid station pick)
4475
- if(view3d&&window.Steel3DView){if(window.Steel3DView.clipMode&&window.Steel3DView.clipMode())return true;const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))return true;} // 3D dim/clip armed
4578
+ if(view3d&&window.Steel3DView){if(window.Steel3DView.clipMode&&window.Steel3DView.clipMode())return true;
4579
+ if(window.Steel3DView.refMeasureState&&window.Steel3DView.refMeasureState().armed)return true; // the reference measure owns the left-click too, so Space/Enter must not re-invoke the last command over it
4580
+ const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))return true;} // 3D dim/clip armed
4476
4581
  return false;
4477
4582
  }
4478
4583
  function repeatLast(){if(lastCmd){lastCmd.run();if(typeof toast==='function')toast('↻ '+lastCmd.label);}}
@@ -4862,8 +4967,13 @@ async function connModifyRequest(j){
4862
4967
  const onMember=j.main?' on member '+j.main:'';
4863
4968
  const label=j.kind==='custom'&&j.name?' ("'+j.name+'")':'';
4864
4969
  const instruction='Modify the '+kindName+' connection "'+j.id+'"'+label+onMember+' (sheet '+((P&&P.sheet)||'?')+') — adjust, replace or move it per my request.';
4970
+ // `project` like both sibling producers (detailRequest, Ask AI): without it the relay composes an
4971
+ // APP-keyed GET/PUT, so in a workspace project the AI reads the wrong store — and if that app store
4972
+ // is empty the GET falls through to the baked publication, which carries no ETag, at which point the
4973
+ // instruction's own "If-None-Match: * when there was no ETag" rule has it CREATE an app-scoped
4974
+ // contract while the user's project document is never touched.
4865
4975
  try{const res=await fetch('/api/contract-request',{method:'POST',headers:{'content-type':'application/json'},
4866
- body:JSON.stringify({appId:APP_ID,instruction,intent:'modify',target:{sheet:(P&&P.sheet)||undefined,ids:[j.id,j.main].filter(Boolean)}})});
4976
+ body:JSON.stringify({appId:APP_ID,project:PROJECT||undefined,instruction,intent:'modify',target:{sheet:(P&&P.sheet)||undefined,ids:[j.id,j.main].filter(Boolean)}})});
4867
4977
  toast(res.ok?'Change queued for your terminal AI session':'Could not queue the request');
4868
4978
  }catch(_){toast('Could not queue the request');}
4869
4979
  }
@@ -5012,7 +5122,7 @@ function panel(){
5012
5122
  const _rb=document.getElementById('csRepickB');if(_rb)_rb.onclick=()=>{if(_d3.repickFrame3d)_d3.repickFrame3d();};
5013
5123
  return;}
5014
5124
  if(csaxisMode){p.innerHTML=`<span class=badge>Set local axes</span>
5015
- <div class=hint id=csHint style="margin-top:8px">${csDraft?'Click the <b>second</b> point — the local-X direction. Y follows at 90°.':'Click the <b>origin</b> point to start.'}</div>
5125
+ <div class=hint style="margin-top:8px">${csDraft?'Click the <b>second</b> point — the local-X direction. Y follows at 90°.':'Click the <b>origin</b> point to start.'}</div>
5016
5126
  <div class=hint style="margin-top:8px">Two clicks define the frame; snaps to member ends &amp; grid (<b>Alt</b> off). <b>Esc</b> cancels.</div>`;return;}
5017
5127
  if(cmTool){const nsel=selIds.size;
5018
5128
  p.innerHTML=`<span class=badge>${cmTool==='move'?'Move':(cmArrayMode?'Copy array':'Copy')}</span>
@@ -6572,7 +6682,7 @@ function disarmCm(){cmTool=null;cmArrayMode=false;cmDraft=null;cmHudClose();cmPr
6572
6682
  if(window.Steel3DView&&window.Steel3DView.cmClear3d)window.Steel3DView.cmClear3d();} // drop the 3D-side pick/preview too
6573
6683
  function armCm(tool,array){ // re-arming the same config toggles the tool off — works in 2D and (on the working plane) in 3D
6574
6684
  if(cmTool===tool&&cmArrayMode===!!array){disarmCm();render();return;}
6575
- if(view3d&&window.Steel3DView){const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))window.Steel3DView.toggleDimTool();if(window.Steel3DView.disarmFrame3d)window.Steel3DView.disarmFrame3d();} // the 3D dim tool + the local frame share the left-click — disarm both
6685
+ if(view3d&&window.Steel3DView){const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))window.Steel3DView.toggleDimTool();if(window.Steel3DView.disarmFrame3d)window.Steel3DView.disarmFrame3d();if(window.Steel3DView.armRefMeasure3d){window.Steel3DView.armRefMeasure3d(null);refMeasureClear();}} // the 3D dim tool + the local frame share the left-click — disarm both
6576
6686
  if(!selIds.size){toast('Select members first, then '+(tool==='move'?'Move':'Copy'));return;}
6577
6687
  if(mode==='add'){mode='sel';setMode();if(window.Steel3DView&&window.Steel3DView.drClear3d)window.Steel3DView.drClear3d();}
6578
6688
  if(dimMode){dimMode=false;setDimMode();}
@@ -7111,7 +7221,7 @@ function setMode(){document.body.classList.toggle('add',mode==='add');document.g
7111
7221
  if(mode!=='add'){drawDraft=null;drawPrevClear();cmHudClose();if(view3d&&window.Steel3DView&&window.Steel3DView.drClear3d)window.Steel3DView.drClear3d();}} // leaving Add-member drops the in-progress start + preview, closes any open typed-entry HUD, and clears the 3D draw start (else a stale Add token could revalidate on re-arm — Codex)
7112
7222
  document.getElementById('mAdd').onclick=()=>{if(dimMode){dimMode=false;setDimMode();}if(csaxisMode){csaxisMode=false;setCsMode();}if(cmTool)disarmCm();if(qdPick){qdPick=null;setQdPickCls();}
7113
7223
  if(gridMode||gridPick||gridLinePick){if(gridLinePick&&gridLinePick.line)gridLinePick.line.remove();gridMode=false;gridPick=false;gridLinePick=null;gridSetPickClass();} // arming Add leaves the grid panel — same mutual exclusion Move/Copy already enforces. In 3D addActive() consumes the click AHEAD of the grid pick, so without this the Add gesture would run while the grid button + hint still claimed an armed pick (the A shortcut routes through this same handler)
7114
- if(view3d&&window.Steel3DView){const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))window.Steel3DView.toggleDimTool();if(window.Steel3DView.disarmFrame3d)window.Steel3DView.disarmFrame3d();} // the 3D dim tool + the local frame share the left-click — disarm both when entering add mode
7224
+ if(view3d&&window.Steel3DView){const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))window.Steel3DView.toggleDimTool();if(window.Steel3DView.disarmFrame3d)window.Steel3DView.disarmFrame3d();if(window.Steel3DView.armRefMeasure3d){window.Steel3DView.armRefMeasure3d(null);refMeasureClear();}} // the 3D dim tool + the local frame share the left-click — disarm both when entering add mode
7115
7225
  selDimIds.clear();dimStyleMode=false;mode=(mode==='add'?'sel':'add');if(mode==='add')selIds.clear();else if(window.Steel3DView&&window.Steel3DView.drClear3d)window.Steel3DView.drClear3d();snapOnlyClear2d();setMode();render();setLastCmd('Add member',()=>{if(mode!=='add'){if(dimMode){dimMode=false;setDimMode();}mode='add';selIds.clear();setMode();render();}});}; // entering add/sel disarms the Dimension + set-axes tools + the Dimension style pane + drops any dim selection + reverts a snap override; leaving add clears the 3D draw draft
7116
7226
  document.getElementById('dimB').onclick=()=>{if(csaxisMode){csaxisMode=false;setCsMode();}if(qdPick){qdPick=null;setQdPickCls();}dimMode=!dimMode;setDimMode();render();setLastCmd('Dimension',()=>{if(!dimMode){dimMode=true;setDimMode();render();}});};
7117
7227
  document.getElementById('csSetB').onclick=()=>{csaxisMode=!csaxisMode;setCsMode();render();};
@@ -7390,6 +7500,20 @@ addEventListener('keydown',e=>{
7390
7500
  if(e.key==='Escape'&&selDimIds.size){if(dimSplitMode){dimSplitMode=false;snapClear();render();}else{selDimIds.clear();render();}return;} // Esc on a selected dim: end split mode → else deselect
7391
7501
  if(e.key==='Escape'&&view3d&&mode==='add'){if(cmHudIsOpen()){cmHudClose();return;}if(window.Steel3DView&&window.Steel3DView.drEscape&&window.Steel3DView.drEscape())return;} // 3D draw: Esc closes an open typed-entry HUD first, then drops the in-progress start pick, then exits add mode (falls through below)
7392
7502
  if(e.key==='Escape'&&!view3d&&mode==='add'&&drawDraft){drawDraft=null;drawPrevClear();render();return;} // 2D Add-member: 1st Esc drops the in-progress start point (2nd falls through below → exits the tool), like the Dimension tool
7503
+ // Esc while typing the true distance leaves the BOX, and stops there. Without this the press falls all
7504
+ // the way to the catch-all below — which is not guarded by `inForm` — and clears the user's member
7505
+ // selection as the answer to "I have finished typing", which is not a thing they asked for.
7506
+ if(e.key==='Escape'&&_ae&&_ae.id==='refMeasureTrue'){e.preventDefault();e.stopImmediatePropagation();if(_ae.blur)_ae.blur();return;}
7507
+ // The reference measure's Esc, owned HERE and not in the 3D layer — the same split the grid-line pick
7508
+ // documents on both sides. This handler is bound at parse time and the 3D view binds its own inside
7509
+ // init(), so this one runs FIRST: were the measure handled there, the catch-all one line below would
7510
+ // already have cleared the user's member selection by the time it stepped the measure back, and one Esc
7511
+ // would do two things. `stopImmediatePropagation` because the press is fully consumed here.
7512
+ // Three stages, resolved inside refMeasureEscape: drop the second pick → drop the result → exit the tool.
7513
+ if(e.key==='Escape'&&view3d&&!inForm&&window.Steel3DView&&window.Steel3DView.refMeasureEscape&&window.Steel3DView.refMeasureEscape()){
7514
+ e.preventDefault();e.stopImmediatePropagation();
7515
+ if(refMeasure&&!(window.Steel3DView.refMeasureKept&&window.Steel3DView.refMeasureKept()))refMeasure=null; // the stage that dropped the RESULT drops the card with it
7516
+ renderRefsTab();return;}
7393
7517
  if(e.key==='Escape'){if(geoMode){geoMode=null;setGeo();render();return;}if(mode==='add'){mode='sel';setMode();}picking=false;pickKind='profile';pickEnd=null;selIds.clear();selGridIds.clear();render();return;}
7394
7518
  if((e.key==='Delete'||e.key==='Backspace')&&view3d&&window.Steel3DView.selectedClips&&window.Steel3DView.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)
7395
7519
  if((e.key==='Delete'||e.key==='Backspace')&&view3d&&sel3dDimIds.size&&!selIds.size&&!inForm){e.preventDefault();[...sel3dDimIds].forEach(id=>view3dApi.onDeleteDim3d(id));return;} // 3D: Delete removes ALL selected 3D dims — only when no member is selected
@@ -8038,6 +8162,11 @@ const view3dApi={
8038
8162
  if(gridAddFreeLine(toDisp(a),toDisp(b),null,GRID_LINE_MIN_DISP)){pushUndo(pv);gridCancelLinePick();render();refresh3DGrid();}else panel();}, // rejected (too short) → keep the pick armed and let the user retry the 2nd point, same as 2D
8039
8163
  onGridLinePickStep:()=>panel(), // first point placed in 3D → repaint the panel hint ("Pick the second point")
8040
8164
  onGridLinePickCancel:()=>gridCancelLinePick(), // Esc in the 3D view cancels the pick (grid mode stays)
8165
+ // S2 Stage D — the reference measure. The 3D layer owns the PICK; the editor owns the RESULT, which is
8166
+ // why the second click hands the two points over here instead of storing them there.
8167
+ onRefMeasure:(refId,a,b,mm)=>{refMeasure={refId,a,b,mm,typed:''};refSelectedId=refId;renderRefsTab();},
8168
+ onRefMeasureStep:()=>renderRefsTab(), // repaint so the panel's armed affordance can't drift from the tool
8169
+ onRefMeasureCancel:()=>{const v=window.Steel3DView;if(v&&v.armRefMeasure3d)v.armRefMeasure3d(null);refMeasureClear();},
8041
8170
  onSnapOnlyChanged:()=>updSnapStat(), // keep the header snap-override chip honest for every 3D-side clear (tool disarm etc.)
8042
8171
  onDeleteDim3d:(id)=>{if(!canWriteModel())return;C.dims3d=(C.dims3d||[]).filter(x=>x.id!==id);sel3dDimIds.delete(id);scheduleSave();refreshDims3d();},
8043
8172
  onSelectDim3d:(id,mods)=>{ // Ctrl/Shift multi-select (same as parts); selecting a dim is exclusive with member/2D-dim/clip selection
@@ -9009,6 +9138,20 @@ const refLoading=new Set(); // ids with a geometry fetch in flight — the
9009
9138
  const refFailed=new Map(); // id -> why its geometry could not be fetched (see loadReferenceGeometry)
9010
9139
  const refEmpty=new Set(); // ids the reader answered for, with nothing drawable in the answer
9011
9140
  let refSelectedId=null; // the reference the panel has expanded (and the 3D layer has selected)
9141
+ /**
9142
+ * THE STAGE D MEASUREMENT, AND IT IS NOT MODEL DATA. `{refId,a,b,mm,typed}` or null.
9143
+ *
9144
+ * Deliberately a module variable rather than a key on `C`: a measurement is a question the user asked, not
9145
+ * a fact about the building. Nothing in save(), snapshot(), restoreSaved() or the schema knows it exists,
9146
+ * so a measure that is never accepted leaves the serialized contract byte-identical — the bargain this
9147
+ * whole feature is sold on, pinned by server/reference-measure-scale.test.ts.
9148
+ *
9149
+ * `typed` rides along for a duller reason: renderRefsTab() rebuilds the whole tab, and several ordinary
9150
+ * acts reach it (an opacity release, a snap toggle, geometry finishing its fetch, refEdit itself). Without
9151
+ * somewhere outside the DOM to keep it, a half-typed "6" would be destroyed by an event the user did not
9152
+ * connect to their typing.
9153
+ */
9154
+ let refMeasure=null;
9012
9155
  /**
9013
9156
  * The INDEX of the one object drilled into inside `refSelectedId`, or null.
9014
9157
  *
@@ -9235,11 +9378,193 @@ function refEdit(id,patch){
9235
9378
  const v=window.Steel3DView;
9236
9379
  if(v){if(patch.display&&v.setReferenceDisplay)v.setReferenceDisplay(id,refDisp(r));
9237
9380
  if(patch.placement&&v.setReferencePlacement)v.setReferencePlacement(id,r.placement||null);}
9381
+ // A MEASUREMENT DOES NOT SURVIVE THE SCALE IT WAS TAKEN AT (S2 Stage D). Its card says the distance is
9382
+ // "at this reference's scale right now", and the accept multiplies by the scale then applied — so a
9383
+ // scale changed by ANY other route in between makes both the sentence false and the arithmetic wrong.
9384
+ // The Scale box is one row above the card and is deliberately not suppressed while measuring, so this is
9385
+ // reachable in three clicks. Placed HERE because refEdit is the single write path: a guard in the card
9386
+ // could be walked around by the box, and one in the box could be walked around by the next writer.
9387
+ // SCALE ONLY — a change of `origin` translates the reference, and a distance is translation-invariant, so
9388
+ // "move it next to your model" must not throw a measurement away for no reason.
9389
+ if(patch.placement&&patch.placement.scale!==undefined&&refMeasure&&refMeasure.refId===id){
9390
+ refMeasure=null;if(v&&v.clearRefMeasure3d)v.clearRefMeasure3d();} // set directly, not via refMeasureClear() — the renderRefsTab below is the one repaint this needs
9238
9391
  scheduleSave();renderRefsTab();
9239
9392
  }
9240
9393
 
9394
+ // ── S2 Stage D: measure a distance on a reference, then set its scale from it ─────────────────────
9395
+ //
9396
+ // The two points come from the 3D layer's armed pick (`armRefMeasure3d`), which snaps to THAT reference's
9397
+ // own points and to nothing else. The reason is arithmetic, not taste: `xrefMatrix` builds
9398
+ // translate(origin)·rotZ·scale(s), so a distance between two points INSIDE the reference is s·|p₁−p₂| and
9399
+ // scales by the factor — while a distance from the reference to our steel, or to a second reference, is
9400
+ // not a quantity `placement.scale` governs at all. Letting a foreign point in would compute a factor from
9401
+ // something the factor does not move, and the resulting scale would be silently wrong.
9402
+
9403
+ /** Arm the two-point measure against one reference, opening its row so the result has somewhere to land. */
9404
+ function refMeasureArm(id){
9405
+ const r=refById(id);if(!r){toast('That reference is no longer in this model');return;}
9406
+ const v=window.Steel3DView;
9407
+ // `view3d` IS THE CONDITION. Steel3DView.armRefMeasure3d exists as soon as the module loads, in either
9408
+ // view, so testing for the method alone was a branch that could never fire for the reason it named —
9409
+ // and would have armed a pick against a canvas nobody is looking at.
9410
+ if(!view3d||!v||!v.armRefMeasure3d){toast('Switch to the 3D view to measure a reference');return;}
9411
+ // Both entry points are already gated on there being geometry; this is the guard that survives a refactor
9412
+ // of either of them, and it distinguishes "still loading" from "there is nothing here" the way the move
9413
+ // command's sibling refusal does.
9414
+ // THE REASON IS ALREADY KNOWN — say it. refFailed carries why the fetch failed and refEmpty means the
9415
+ // reader answered with nothing drawable; collapsing both into "there is no geometry yet" tells a user
9416
+ // whose file failed to load exactly what a user whose file is legitimately empty is told.
9417
+ if(!refGeom.has(id)){
9418
+ toast(refLoading.has(id)?'Still reading its geometry — try again in a moment'
9419
+ :refFailed.has(id)?('Its geometry could not be read — '+refFailed.get(id))
9420
+ :refEmpty.has(id)?'This file has nothing drawable in it to measure'
9421
+ :'There is no geometry to measure yet');
9422
+ return;}
9423
+ refMeasureClear();
9424
+ // OPENING THE ROW IS ALL THREE OF THE ROW HANDLER'S MOVES, not just the first. `refSelectedObjIdx` is an
9425
+ // INDEX into the selected reference's object array, so setting `refSelectedId` alone would leave an index
9426
+ // taken inside reference A pointing into reference B — the exact failure refRemove's comment names.
9427
+ refSelectedId=id;refSelectedObjIdx=null;
9428
+ if(v.selectReference)v.selectReference(id);
9429
+ // SAID, NOT SILENTLY FIXED. Un-hiding would be a persisted display write the user did not ask for; §10.3
9430
+ // already establishes that a hidden reference still snaps, so the tool works — it is only the looking
9431
+ // that does not.
9432
+ if(refDisp(r).visible===false)toast('“'+r.name+'” is hidden — show it to see what you are measuring');
9433
+ v.armRefMeasure3d(id);
9434
+ renderRefsTab();panel();
9435
+ }
9436
+ /** Is the two-point measure armed against THIS reference right now? (Independent of a result existing.) */
9437
+ function refMeasureArmedOn(id){
9438
+ const v=window.Steel3DView;
9439
+ return !!(v&&v.refMeasureState&&v.refMeasureState().refId===id);
9440
+ }
9441
+ /**
9442
+ * The measurement lives in ONE reference's detail block, so it must not outlive that block being open.
9443
+ *
9444
+ * Three ordinary acts move `refSelectedId` without touching the tool: clicking the measured row again
9445
+ * (the handler TOGGLES), clicking a different reference's row, and inserting a new reference. Each left
9446
+ * the tool armed and the dashed segment drawn while the chip read "Measured - see the panel" and the
9447
+ * panel had no card — the dead-control shape dropRefMeasure3d exists to prevent, arrived at from the
9448
+ * other side. Called from every site that assigns refSelectedId.
9449
+ */
9450
+ function refMeasureFollowSelection(){
9451
+ const v=window.Steel3DView;
9452
+ const armedOn=v&&v.refMeasureState?v.refMeasureState().refId:null;
9453
+ const held=refMeasure?refMeasure.refId:null;
9454
+ for(const id of new Set([armedOn,held])){if(id&&id!==refSelectedId)refMeasureDropFor(id);}
9455
+ }
9456
+ /** Drop the measurement and the segment drawn for it. The ONLY thing a cancelled measure changes. */
9457
+ function refMeasureClear(){
9458
+ const had=!!refMeasure;refMeasure=null;
9459
+ const v=window.Steel3DView;if(v&&v.clearRefMeasure3d)v.clearRefMeasure3d();
9460
+ if(had)renderRefsTab();
9461
+ }
9462
+ /**
9463
+ * Disarm the tool AND drop any result, when this reference stops being a thing you can measure.
9464
+ *
9465
+ * One helper rather than the same three lines at every call site, because the sites that need it are the
9466
+ * ones easiest to forget: removing the reference, re-reading its geometry, and — the one a first cut
9467
+ * missed — the tool being armed with no result yet, where a `refMeasure`-only guard sees nothing to clean
9468
+ * up and leaves the chip reading "Click the first point on this reference" over a dead id whose every
9469
+ * click is a silent no-op.
9470
+ */
9471
+ function refMeasureDropFor(id){
9472
+ const v=window.Steel3DView;
9473
+ const armed=!!(v&&v.refMeasureState&&v.refMeasureState().refId===id);
9474
+ if(!armed&&!(refMeasure&&refMeasure.refId===id))return;
9475
+ if(v&&v.armRefMeasure3d)v.armRefMeasure3d(null);
9476
+ refMeasureClear();
9477
+ // ALWAYS repaint. refMeasureClear only does so when a MEASUREMENT existed, and disarming with no result is
9478
+ // the ordinary case — pressing the button a second time to stop. Without this the button went on reading
9479
+ // "Measuring - click to stop" over a tool that was no longer armed: the same lie the armed affordance was
9480
+ // added to stop telling, in the other direction. Caught in the browser pass.
9481
+ renderRefsTab();
9482
+ }
9483
+ /** The measured distance in the editor's own length format, plus the millimetres the input takes bare. */
9484
+ function refMeasureWords(mm){return fmtFtIn(mm/304.8*12)+' ('+Math.round(mm).toLocaleString('en-US')+' mm)';}
9485
+ /**
9486
+ * What typing this value would do — SHARED by the live caution and the accept, so the number the caution
9487
+ * names and the number the button applies can never be two different numbers. Returns null when the typed
9488
+ * value is not a positive finite length.
9489
+ *
9490
+ * IT COMPOSES WITH THE SCALE ALREADY APPLIED, and that is the whole arithmetic. `refMeasure.mm` is the
9491
+ * distance AS DRAWN — the snap points come off `matrixWorld`, which already includes `placement.scale` —
9492
+ * so the factor that makes the drawn distance equal the true one is `true/measured`, applied ON TOP of
9493
+ * what is there. Comparing against the file's own size instead is the bug `refScaleAdvice`'s comment
9494
+ * records on the other offer for this same field: the advice survived being taken, and a second click gave
9495
+ * 0.000001.
9496
+ */
9497
+ function refMeasuredScaleOf(r,typed){
9498
+ if(!r||!refMeasure||refMeasure.refId!==r.id)return null; // not this reference's measurement - no offer to make
9499
+ const gc=GC();
9500
+ const trueMm=(gc&&gc.parseLen)?gc.parseLen(typed):NaN;
9501
+ const measured=refMeasure.mm;
9502
+ // A REASON, NOT A BARE null — the caller had four causes collapsed into one message. `trueMm>0` is
9503
+ // redundant against a VALID contract (a positive applied scale turns a non-positive typed distance
9504
+ // into a non-positive `next`, refused below) and is kept anyway: it stops being redundant exactly when
9505
+ // `placement.scale` is itself negative, which the schema forbids and a hand-edited file can carry.
9506
+ if(!(measured>0))return {bad:'measured'};
9507
+ if(!isFinite(trueMm)||!(trueMm>0))return {bad:'typed'};
9508
+ const applied=((r.placement&&r.placement.scale)||1);
9509
+ const next=applied*(trueMm/measured);
9510
+ // And THIS is the case worth naming rather than blaming the typing: a negative applied scale means a
9511
+ // perfectly good 6m is reported as not-a-length, and the user retypes it forever while the real fault
9512
+ // sits in the Scale box above.
9513
+ if(!isFinite(next)||!(next>0))return {bad:'scale'};
9514
+ const times=next>applied?next/applied:applied/next;
9515
+ return {applied,next,times,bigger:next>applied,
9516
+ timesWords:times>=1000?Math.round(times).toLocaleString('en-US')+'×':(Math.round(times*10)/10)+'×'};
9517
+ }
9518
+ /**
9519
+ * Turn "this is really 6 m" into a scale, through the SAME write every other scale edit uses.
9520
+ *
9521
+ * AN ABSURD FACTOR IS CAUTIONED, NOT REFUSED. A first cut hard-blocked anything outside [1e-6,1e6]; design
9522
+ * review overturned it on two grounds that both hold. The Scale box four rows up accepts any positive
9523
+ * number, so a gate here would be a second policy for one field. And it is recoverable in the way I had
9524
+ * assumed it was not — `snapshot()` does not capture `reference_models`, but the Scale box still shows the
9525
+ * value, so typing 1 back in IS the undo. What is left is a live warning, which is the honest shape: the
9526
+ * typed distance is the one quantity in this interaction the user actually knows.
9527
+ */
9528
+ function refApplyMeasuredScale(id,typed){
9529
+ if(!canWriteModel())return;
9530
+ const r=refById(id);if(!r)return;
9531
+ const t=refMeasuredScaleOf(r,typed);
9532
+ if(!t||t.bad){
9533
+ toast(!t?'There is no measurement to set a scale from — measure two points first'
9534
+ :t.bad==='scale'?('“'+r.name+'” has a scale of '+((r.placement&&r.placement.scale))+', which is not a positive number — fix the Scale box first')
9535
+ :t.bad==='measured'?'That measurement has no length — measure two different points'
9536
+ :"That does not look like a length — try something like 6m, 20', or 6096");
9537
+ return;}
9538
+ // THE LOCK IS REFUSED BY `refEdit`, not by a branch of its own here — its toast is the one the Scale box
9539
+ // produces for the same act on the same field, and a second locked-state pattern for one field in one
9540
+ // panel is the drift.
9541
+ refEdit(id,{placement:{scale:t.next}});
9542
+ // …and THIS is the load-bearing line: refEdit refused the write, so the measurement must survive for the
9543
+ // user to unlock and press again rather than re-measure. Written as one guarded return over a shared
9544
+ // call, because the same thing spelled as two branches each ending in an identical refEdit reads as an
9545
+ // accident and the next simplifier collapses it — deleting this behaviour silently.
9546
+ if(refDisp(r).locked)return;
9547
+ // ASSERT THE WRITE, do not assume it. refEdit returns void and reports only the lock refusal, by
9548
+ // inference; every other refusal inside it (today canWriteModel(), which merely returns) would reach
9549
+ // the full success path — measurement discarded, tool disarmed, a toast claiming a scale was set that
9550
+ // was not. Reading the field back costs one line and turns that whole class into a visible failure.
9551
+ const written=(r.placement||{}).scale;
9552
+ if(written!==t.next){toast('Could not set the scale on “'+r.name+'” — nothing was changed');return;}
9553
+ refMeasureClear();
9554
+ const v=window.Steel3DView;if(v&&v.armRefMeasure3d)v.armRefMeasure3d(null); // the job is done — give the left-click back
9555
+ toast('Scale set — “'+r.name+'” now matches what you measured.');
9556
+ }
9557
+
9241
9558
  // ── The References tab ────────────────────────────────────────────────────────────────────────────
9242
- function renderRefsTab(){const host=document.getElementById('m3dRefsBody');if(!host)return;host.replaceChildren();
9559
+ function renderRefsTab(){const host=document.getElementById('m3dRefsBody');if(!host)return;
9560
+ // WAS THE USER TYPING THE TRUE DISTANCE? This function replaces the whole tab, and several ordinary acts
9561
+ // reach it while the Stage D card is open — an opacity release, a lock toggle, geometry arriving for ANY
9562
+ // reference, a second measurement, refEdit itself. The typed TEXT survives on `refMeasure.typed`; what
9563
+ // does not survive on its own is the caret, and losing that mid-number is the difference between a
9564
+ // control that stutters and one that works.
9565
+ const _ae=document.activeElement;
9566
+ const _keepCaret=_ae&&_ae.id==='refMeasureTrue'?{start:_ae.selectionStart,end:_ae.selectionEnd}:null;
9567
+ host.replaceChildren();
9243
9568
  const head=document.createElement('div');head.id='refHeadRow';
9244
9569
  const add=document.createElement('button');add.type='button';add.id='refAddBtn';add.textContent='+ Add a reference model';
9245
9570
  add.dataset.tip='Overlay an architect’s or engineer’s IFC to build against. It is never part of your steel.';
@@ -9251,6 +9576,11 @@ function renderRefsTab(){const host=document.getElementById('m3dRefsBody');if(!h
9251
9576
  e.textContent='No reference models yet — add somebody else’s IFC to see it beside your steel and snap to it. It never enters your BOM, an export, or the lock.';
9252
9577
  host.appendChild(e);return;}
9253
9578
  for(const r of all){host.appendChild(buildRefRow(r));if(r.id===refSelectedId)host.appendChild(buildRefDetail(r));}
9579
+ // …and put the caret back where it was. Done here rather than in buildRefMeasureCard because focus only
9580
+ // takes on a node that is IN the document, and the card is not attached until the loop above runs.
9581
+ if(_keepCaret){const el=document.getElementById('refMeasureTrue');
9582
+ if(el&&el.focus){el.focus();
9583
+ try{if(el.setSelectionRange)el.setSelectionRange(_keepCaret.start,_keepCaret.end);}catch(e){console.warn('[reference] could not restore the caret in the measure box',e);}}}
9254
9584
  }
9255
9585
 
9256
9586
  function buildRefRow(r){
@@ -9308,12 +9638,16 @@ function buildRefRow(r){
9308
9638
  row.appendChild(zoom);
9309
9639
 
9310
9640
  const dots=Object.assign(document.createElement('span'),{className:'refdots',textContent:'⋯'});
9311
- dots.setAttribute('role','button');dots.dataset.tip='More — move it next to your model, reload, remove';
9641
+ // The tip ENUMERATES the menu, so adding an item without touching it leaves the anchor advertising a
9642
+ // menu that no longer exists. (Caught in the browser pass: Stage D's item shipped while this still read
9643
+ // "move it next to your model, reload, remove".)
9644
+ dots.setAttribute('role','button');dots.dataset.tip='More — measure a distance, move it next to your model, reload, remove';
9312
9645
  dots.addEventListener('click',e=>{e.stopPropagation();openRefRowMenu(r,dots);});
9313
9646
  row.appendChild(dots);
9314
9647
 
9315
9648
  row.addEventListener('click',()=>{
9316
9649
  refSelectedId=refSelectedId===r.id?null:r.id;
9650
+ refMeasureFollowSelection(); // this handler TOGGLES, so one click can collapse the measured row
9317
9651
  refSelectedObjIdx=null; // picking a WHOLE reference from the row leaves no object drilled into — same rule the 3D layer's `selectReference` follows, so the two surfaces cannot disagree
9318
9652
  if(window.Steel3DView&&window.Steel3DView.selectReference)window.Steel3DView.selectReference(refSelectedId);
9319
9653
  renderRefsTab();panel();});
@@ -9479,11 +9813,49 @@ function buildRefDetail(r){
9479
9813
  refEdit(r.id,{placement:{scale:v}});});
9480
9814
  sRow.appendChild(sc);wrap.appendChild(sRow);
9481
9815
 
9816
+ // THE SECOND DOOR INTO THE MEASURE (S2 Stage D). The ⋯ item is where a user browsing what a reference can
9817
+ // do finds it; this is where a user staring at a Scale value they know is wrong is already looking, so
9818
+ // the offer belongs at the point of pain too — in the same ghost weight as the two fix buttons below.
9819
+ // Gated on there being geometry, the same rule and the same reason as the ⋯ item.
9820
+ if(refGeom.has(r.id)){
9821
+ // THE BUTTON REPORTS THE TOOL'S STATE, and a second press turns it off. Without this, Clear left the
9822
+ // panel looking exactly like the never-armed state while every canvas click was still being eaten by
9823
+ // the measure, and there was no way to put the left-click back except Esc or arming something else.
9824
+ const armedNow=refMeasureArmedOn(r.id);
9825
+ const mb=document.createElement('button');mb.type='button';mb.className='ghost'+(armedNow?' on':'');mb.id='refMeasureBtn';
9826
+ mb.style.marginTop='6px';mb.textContent=armedNow?'Measuring — click to stop':'Measure a distance →';
9827
+ mb.setAttribute('aria-pressed',String(armedNow));
9828
+ mb.dataset.tip=armedNow?'Stop measuring and give the left-click back to selecting.':REF_MEASURE_TIP;
9829
+ mb.addEventListener('click',()=>{if(refMeasureArmedOn(r.id))refMeasureDropFor(r.id);else refMeasureArm(r.id);});
9830
+ wrap.appendChild(mb);
9831
+ // IN PROSE, NOT IN A TOOLTIP — the same treatment and the same gating as the Ctrl+click drill note
9832
+ // above, for the reason that note states: a tooltip is hover-driven and reaches neither a keyboard nor a
9833
+ // screen-reader user, and a two-click canvas gesture is precisely the thing they cannot discover by
9834
+ // hovering. The half of this flow after the result — the box and both buttons — is ordinary form chrome
9835
+ // and is fully reachable; the picking half is not, which is the same gap the Dimension tool and the
9836
+ // grid-line pick already have and is not Stage D's to close.
9837
+ wrap.appendChild(Object.assign(document.createElement('div'),{className:'dnote',
9838
+ textContent:'Pick two points on this reference in the 3D view to measure the distance between them, then tell us what that distance should really be.'}));
9839
+ }
9840
+
9841
+ // EVIDENCE BEATS A GUESS. Both offers write `placement.scale`, and `refScaleAdvice` is a span-similarity
9842
+ // heuristic while a measurement is a distance the user knows. Putting "Scale ×0.001" beside "you measured
9843
+ // 6,096 mm" asks them to adjudicate between the two, and the guess can win. Suppressed only for the
9844
+ // reference that HAS the measurement, and only while it is on screen: taking or clearing it restores the
9845
+ // advisory, recomputed against whatever scale is then applied — which is refScaleAdvice's own behaviour,
9846
+ // so this needs no dismissed-flag of its own.
9847
+ // ARMED **OR** HOLDING A RESULT. Keying on the result alone left the guess live through the whole of
9848
+ // the armed-with-first-point state — with its Scale x1000 button one row above the card, one click
9849
+ // from changing the very scale the half-finished pick was taken at. That is the window the stale-pick
9850
+ // bug lived in, and suppressing the offer is half of closing it.
9851
+ const measuring=!!(refMeasure&&refMeasure.refId===r.id)||refMeasureArmedOn(r.id);
9852
+ if(refMeasure&&refMeasure.refId===r.id)wrap.appendChild(buildRefMeasureCard(r));
9853
+
9482
9854
  // The scale advisory, on a measurement that can bear it: `spanMm` is computed server-side from the
9483
9855
  // vertices the reader actually returned. The pre-insert modal deliberately offers none, because
9484
9856
  // before tessellation the only number available is the reader's bbox, which spans everything the file
9485
9857
  // MENTIONS (74 m for a 3.6 m shaft) and would offer to permanently mis-scale a correct reference.
9486
- const scale=refScaleAdvice(r.id);
9858
+ const scale=measuring?null:refScaleAdvice(r.id);
9487
9859
  if(scale){
9488
9860
  const w=Object.assign(document.createElement('div'),{className:'dwarn'});
9489
9861
  w.textContent='This looks about '+scale.words+' your model. If the file states the wrong units, this is the usual fix.';
@@ -9506,6 +9878,74 @@ function buildRefDetail(r){
9506
9878
  return wrap;
9507
9879
  }
9508
9880
 
9881
+ /**
9882
+ * What the two clicks measured, and the one question that turns it into a scale (S2 Stage D).
9883
+ *
9884
+ * IT SITS IN THE DETAIL BLOCK, not over the canvas, because it is a RECORD rather than a hint: it has to
9885
+ * survive the second click while the user composes an answer. A card that follows the cursor is a moving
9886
+ * target the instant the mouse leaves it, and it would have to carry a text input — which either follows
9887
+ * the cursor too (unworkable) or snaps to a fixed spot, at which point it is a worse-positioned panel.
9888
+ * The canvas keeps the half the panel cannot show: the dashed segment stays drawn with its value on it,
9889
+ * and the cursor readout carries the running distance while the second point is still being aimed.
9890
+ * This is also where `placement.scale` already lives — Scale is one row up and the heuristic advisory
9891
+ * occupies the very slot below — so the number the user just set is where they would look for it.
9892
+ */
9893
+ function buildRefMeasureCard(r){
9894
+ const box=Object.assign(document.createElement('div'),{className:'dmeas'});
9895
+ box.id='refMeasureCard';
9896
+ const head=document.createElement('div');head.className='drow';
9897
+ head.appendChild(Object.assign(document.createElement('span'),{className:'dlab',textContent:'Measured'}));
9898
+ head.appendChild(Object.assign(document.createElement('span'),{id:'refMeasureVal',
9899
+ textContent:refMeasureWords(refMeasure.mm)+', at this reference’s scale right now'}));
9900
+ box.appendChild(head);
9901
+
9902
+ const row=document.createElement('div');row.className='drow';
9903
+ row.appendChild(Object.assign(document.createElement('span'),{className:'dlab',textContent:'Really'}));
9904
+ const inp=document.createElement('input');inp.type='text';inp.id='refMeasureTrue';
9905
+ inp.style.cssText='flex:1;min-width:0';inp.placeholder='e.g. 6m, 20\', 6096';
9906
+ inp.value=refMeasure.typed||''; // survives a rebuild — see refMeasure's doc comment
9907
+ inp.setAttribute('aria-label','What should that distance really be?');
9908
+ // ASCII apostrophe in the EXAMPLE, deliberately: parseLen's regex matches ' and not the typographic ’,
9909
+ // so a tip that showed the pretty one would teach a character the parser rejects.
9910
+ inp.dataset.tip='What that distance really is. 20\' feet, 6m metres, a bare number millimetres.';
9911
+ row.appendChild(inp);box.appendChild(row);
9912
+
9913
+ // THE CAUTION IS LIVE AND IT DOES NOT BLOCK — see refApplyMeasuredScale for why a hard gate was dropped.
9914
+ const warn=Object.assign(document.createElement('div'),{className:'dwarn',id:'refMeasureWarn'});
9915
+ warn.style.display='none';box.appendChild(warn);
9916
+ const reflect=()=>{
9917
+ refMeasure.typed=inp.value; // keep it OUTSIDE the DOM, so a re-render cannot eat it
9918
+ const t=refMeasuredScaleOf(r,inp.value);
9919
+ // The factor the caution is about to name, left where a test can read it. Without it the only way to
9920
+ // check that the caution and the button agree is to recompute — which is what the test claiming to
9921
+ // compare them was actually doing, so a caution that doubled its own number went unnoticed.
9922
+ warn.dataset.next=(t&&!t.bad&&isFinite(t.next))?String(t.next):'';
9923
+ // CLEARED, NOT JUST HIDDEN. An independent QA pass read this element's text after it had been hidden
9924
+ // and reported the feature as computing wrong ratios — because a hidden node still carrying 'about
9925
+ // 1,000x smaller' from three keystrokes ago is a false statement waiting for anything to show it. The
9926
+ // arithmetic was right; the leftover was not.
9927
+ if(!t||t.bad||!(t.times>=10)){warn.textContent='';warn.style.display='none';return;}
9928
+ warn.textContent='That would make this reference about '+t.timesWords+' '+(t.bigger?'bigger':'smaller')+
9929
+ ' than it is now. Double-check you picked the right two points and typed the right units.';
9930
+ warn.style.display='';};
9931
+ inp.addEventListener('input',reflect);
9932
+
9933
+ const btns=document.createElement('div');btns.className='drow';
9934
+ const set=document.createElement('button');set.type='button';set.className='ghost';set.id='refMeasureSet';
9935
+ set.textContent='Set scale from this';
9936
+ set.dataset.tip='Set this reference’s scale so your two points measure exactly what you typed.';
9937
+ set.addEventListener('click',()=>refApplyMeasuredScale(r.id,inp.value));
9938
+ inp.addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();refApplyMeasuredScale(r.id,inp.value);}});
9939
+ const clr=document.createElement('button');clr.type='button';clr.className='ghost';clr.id='refMeasureClearBtn';
9940
+ clr.textContent='Clear';clr.dataset.tip='Discard this measurement — nothing has been saved.';
9941
+ clr.addEventListener('click',()=>refMeasureClear());
9942
+ // NO LOCKED SPECIAL-CASE, deliberately — refEdit already refuses a placement patch on a locked reference
9943
+ // with its own toast, which is exactly how the sibling Scale box behaves. See refApplyMeasuredScale.
9944
+ btns.append(set,clr);box.appendChild(btns);
9945
+ reflect(); // a restored `typed` gets its caution back with it
9946
+ return box;
9947
+ }
9948
+
9509
9949
  // ── The drilled-into reference object (S2 Stage A) ────────────────────────────────────────────────
9510
9950
  //
9511
9951
  // Ctrl+click one object inside a reference and this is what the Inspect panel shows: what the FILE says
@@ -10215,6 +10655,15 @@ function unitWords(declared){
10215
10655
  * general-purpose nudge after a manual drag.)
10216
10656
  */
10217
10657
  const REF_MOVE_LABEL='Move it next to your model';
10658
+ /**
10659
+ * The measure's label and its one-sentence explanation, in ONE place for exactly the reason above: there
10660
+ * are two doors into this tool — the ⋯ item and the ghost button beside the Scale box — and the same
10661
+ * action wearing two independently-edited labels is a drift waiting to happen. (Both are deliberately
10662
+ * kept: the ⋯ item is where a user browsing what a reference CAN do finds it, and the panel button is
10663
+ * where a user staring at a Scale value they know is wrong is already looking.)
10664
+ */
10665
+ const REF_MEASURE_LABEL='Measure a distance on it';
10666
+ const REF_MEASURE_TIP='Pick two points on this reference, tell us what that distance really is, and we’ll scale it to match.';
10218
10667
  /**
10219
10668
  * Shift a reference so its centre lands ON THE MODEL — the fix the Motebello measurement earned.
10220
10669
  *
@@ -10250,6 +10699,11 @@ function openRefRowMenu(r,anchorEl){closeRefRowMenu();
10250
10699
  const m=document.createElement('div');m.id='refRowMenu';m.className='m3dmenu open';m.setAttribute('role','menu');
10251
10700
  const mk=(label,fn,danger)=>{const b=document.createElement('button');b.type='button';b.textContent=label;if(danger)b.className='mdanger';b.setAttribute('role','menuitem');b.addEventListener('click',()=>{closeRefRowMenu();fn();});return b;};
10252
10701
  m.append(mk('Zoom to it',()=>{if(window.Steel3DView)window.Steel3DView.frameReference(r.id);}));
10702
+ // Offered only where there is something to measure — the same rule the move item follows below, and for
10703
+ // the same stated reason: an enabled item that can do nothing but toast a refusal is a worse answer than
10704
+ // no item. (refMeasureArm keeps its own refusal anyway; a guard that lives only in the caller is one
10705
+ // refactor from being gone.)
10706
+ if(refGeom.has(r.id))m.append(mk(REF_MEASURE_LABEL,()=>refMeasureArm(r.id)));
10253
10707
  // OFFERED ONLY WHEN THERE IS SOMETHING TO BE NEXT TO. Loading a reference before modelling any steel is
10254
10708
  // a normal first move, and in that state this command can do nothing but toast a refusal — an enabled
10255
10709
  // item that always fails is a worse answer than no item. Omitted rather than disabled, which is how
@@ -10259,6 +10713,11 @@ function openRefRowMenu(r,anchorEl){closeRefRowMenu();
10259
10713
  if(nativeModelBounds())m.append(mk(REF_MOVE_LABEL,()=>refMoveToOrigin(r.id)));
10260
10714
  m.append(mk('Reload its geometry',()=>{
10261
10715
  if(refDisp(r).locked){toast('“'+r.name+'” is locked — unlock it to reload it');return;} // the lock freezes reload, as the schema says
10716
+ // A MEASUREMENT OF THIS REFERENCE DOES NOT SURVIVE ITS GEOMETRY BEING RE-READ. The dashed
10717
+ // segment is drawn at world points taken off the OLD tessellation, so keeping it would leave a
10718
+ // line — and a number the panel invites you to scale from — floating beside geometry it no
10719
+ // longer describes. Same reasoning the tree's positional group keys are dropped two lines down.
10720
+ refMeasureDropFor(r.id);
10262
10721
  refGeom.delete(r.id);refFailed.delete(r.id);refEmpty.delete(r.id);refUnresolved.delete(r.id);
10263
10722
  // The tree's group keys are POSITIONAL ('2:1' is the second storey's second type), so a
10264
10723
  // re-read that adds, drops or reorders anything makes them address different groups. Dropped
@@ -10296,6 +10755,9 @@ async function refRemove(r){
10296
10755
  refGeom.delete(r.id);refUnresolved.delete(r.id);refFailed.delete(r.id);refEmpty.delete(r.id);
10297
10756
  refTreeOpen.delete(r.id);refTreeGroups.delete(r.id);refTreeQuery.delete(r.id); // the tree goes with the reference
10298
10757
  if(refSelectedId===r.id){refSelectedId=null;refSelectedObjIdx=null;} // the object drilled into goes with the reference it was inside — leaving the index behind would point the panel into a reference that no longer exists
10758
+ // …and so does a measurement of it, for the same reason one rung down: the dashed segment and the offer
10759
+ // to scale from it would outlive the thing they describe, and the offer's write target no longer exists.
10760
+ refMeasureDropFor(r.id);
10299
10761
  pushReferences();renderRefsTab();panel();
10300
10762
  }catch(_){toast('Could not remove that reference');}
10301
10763
  }
@@ -10347,11 +10809,246 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10347
10809
  if(!view3d){toast('Switch to the 3D view to add a reference model');return;}
10348
10810
  riStop(); // a previous attempt's in-flight probe must not answer into this one
10349
10811
  riSha=null;riName='';riVerdict=null;riProbeCentre=null;riErr('');ri$('riDrop').classList.remove('drag');
10812
+ riBuildPick(null); // and the picker, so a cancelled file's storeys never show under a new name
10350
10813
  riStage('drop');ri$('refImportModal').style.display='flex';}
10351
10814
  window.openRefImport=openRefImport;
10352
10815
  function riClose(){riStop();riClearSoft();ri$('refImportModal').style.display='none';}
10353
10816
 
10354
10817
  const RI_MAX_BYTES=150*1024*1024; // mirrors MAX_BYTES in server/reference-import.ts (pinned by the parity test)
10818
+ // Mirrors MAX_OBJECTS / WARN_OBJECTS in server/reference-import.ts (pinned by the same parity test).
10819
+ // MIRRORED rather than fetched because the picker re-judges the total on every checkbox: a round
10820
+ // trip per tick is not a control. The SERVER still owns the decision — it refuses the insert on its
10821
+ // own count, twice — so this copy only ever tells the user what is about to happen.
10822
+ // DECLARED SEPARATELY, one `const` each. The parity test reads these as source text and matches
10823
+ // `const NAME = …`, so a single statement with two declarators hides the second one from the guard
10824
+ // entirely — which is a mirror that silently stops being checked.
10825
+ const REF_MAX_OBJECTS=20000;
10826
+ const REF_WARN_OBJECTS=11000;
10827
+
10828
+ // ── The storey / type picker (S2 Stage C) ───────────────────────────────────────────────────────
10829
+ // `null` on either axis means "everything", which is NOT the same as a Set holding every name: the
10830
+ // former omits the key from the request and reads the whole file, the latter narrows to a list. That
10831
+ // distinction is the whole feature — see riBuildFilter.
10832
+ let riProbeRows=null; // {storeys, types} as the probe reported them, or null
10833
+ let riPopulation=null; // the whole-file estimate, or null when the bridge offered no breakdown
10834
+ // Sets hold the file's OWN spelling of each name, never a normalised one. The reader matches
10835
+ // case-insensitively, so lower-casing them worked — and quietly wrote "basement" onto the
10836
+ // contract for a file that says "BASEMENT". The stored filter is meant to be what `probe`
10837
+ // reported; a real browser pass caught it, no unit test could have. Exact matching is also
10838
+ // correct here because every name in a Set came from the very rows being compared against.
10839
+ let riStoreyPick=null,riTypePick=null; // Set of chosen names, or null for "all"
10840
+
10841
+ /** Rows a filter can actually name. The storey-less row is excluded: no filter value reaches it. */
10842
+ const riSelectable=rows=>(rows||[]).filter(r=>r&&r.name!==null);
10843
+
10844
+ /**
10845
+ * The estimate for the current selection — the SAME rule as the server's `selectedPopulation`.
10846
+ *
10847
+ * A `min` of two independent sums, and therefore a heuristic rather than a bound: the two axes
10848
+ * intersect, and two separate breakdowns cannot express an intersection. Measured on a real file, a
10849
+ * storey with 7 and a type with 6 share ZERO objects while this returns 6. That is why nothing in the
10850
+ * UI states this number as a fact about the combination — see riPickNote.
10851
+ */
10852
+ function riEstimate(){
10853
+ if(!riProbeRows)return null;
10854
+ if(riStoreyPick===null&&riTypePick===null)return riPopulation;
10855
+ const sumOf=(rows,want)=>{
10856
+ if(!rows||want===null)return null;
10857
+ const hit=rows.filter(r=>r.name!==null&&want.has(r.name));
10858
+ // NOTHING MATCHED IS NO ESTIMATE, NOT ZERO — the same rule the server applies, for the same
10859
+ // reason: zero would read as "this selection is tiny" when it means "we cannot tell".
10860
+ return hit.length?hit.reduce((n,r)=>n+r.elements,0):null;
10861
+ };
10862
+ const sums=[sumOf(riProbeRows.storeys,riStoreyPick),sumOf(riProbeRows.types,riTypePick)].filter(n=>n!==null);
10863
+ return sums.length?Math.min(...sums):null;
10864
+ }
10865
+ const riVerdictOf=n=>(!Number.isFinite(n)?null:n>REF_MAX_OBJECTS?'refuse':n>=REF_WARN_OBJECTS?'warn':'ok');
10866
+
10867
+ /**
10868
+ * What to send with the insert — `undefined` for "the whole file".
10869
+ *
10870
+ * ALL-CHECKED COLLAPSES TO OMITTING THE KEY rather than listing every name, and that is not merely
10871
+ * tidier: an explicit full list is a filter, so it would make the server demand a `selected` receipt
10872
+ * and would run the estimate through the min-heuristic for a case that is exactly known. Omitting is
10873
+ * also the only spelling the reader reads as "unfiltered" — an empty list means "select nothing".
10874
+ */
10875
+ function riBuildFilter(){
10876
+ if(riStoreyPick===null&&riTypePick===null)return undefined; // untouched: the whole file
10877
+ const f={};
10878
+ if(riStoreyPick!==null)f.storeys=[...riStoreyPick];
10879
+ if(riTypePick!==null)f.ifcTypes=[...riTypePick];
10880
+ // AN EMPTIED PICK IS SENT AS EMPTY, NOT DROPPED. Returning `undefined` here would say "the whole
10881
+ // file" for a user who had just cleared every row — the one inference the route refuses outright,
10882
+ // reimplemented on this side of the wire. The server answers it with `reference-empty-filter`;
10883
+ // relying on the Add button being disabled would make a UI state the only guard against reading a
10884
+ // whole building. (Code review.)
10885
+ return f;
10886
+ }
10887
+
10888
+ /** Has the user narrowed an axis to nothing? The server refuses this; the button refuses it sooner. */
10889
+ const riEmptyPick=()=>(riStoreyPick!==null&&riStoreyPick.size===0)||(riTypePick!==null&&riTypePick.size===0);
10890
+
10891
+ /** One list of checkboxes. `pick` is null for "all", so a fresh render starts every row checked. */
10892
+ function riRenderRows(host,rows,pick,onToggle){
10893
+ host.replaceChildren();
10894
+ for(const r of rows||[]){
10895
+ if(r.name===null){
10896
+ // NOT A DISABLED CHECKBOX. A disabled control says "you may not do this yet"; the truth is that
10897
+ // the reader skips unnamed-storey rows entirely, so no filter value can ever select these and
10898
+ // there is no control to disable. They load only while the storey axis is untouched — which is
10899
+ // what the note says, and it is re-derived on every render rather than toggled.
10900
+ const row=document.createElement('div');row.className='ripick-row ripick-row--fixed';
10901
+ row.dataset.tip='Not assigned to any storey in the file, so a storey filter can never pick these out on their own. They load only while every storey is selected.';
10902
+ const dash=document.createElement('span');dash.className='rpfixed';dash.setAttribute('aria-hidden','true');dash.textContent='—';
10903
+ const nm=document.createElement('span');nm.className='rpname';nm.textContent='Not on any storey';
10904
+ const ct=document.createElement('span');ct.className='rpcount';ct.textContent=r.elements.toLocaleString();
10905
+ const note=document.createElement('span');note.className='rpnote';
10906
+ note.textContent=pick===null?'Included':'Excluded — can’t be selected';
10907
+ row.append(dash,nm,ct,note);host.appendChild(row);
10908
+ continue;
10909
+ }
10910
+ const row=document.createElement('label');row.className='ripick-row';
10911
+ const cb=document.createElement('input');cb.type='checkbox';
10912
+ cb.checked=pick===null||pick.has(r.name);
10913
+ cb.addEventListener('change',()=>onToggle(r.name,cb.checked));
10914
+ const nm=document.createElement('span');nm.className='rpname';nm.textContent=r.name;
10915
+ const ct=document.createElement('span');ct.className='rpcount';ct.textContent=r.elements.toLocaleString();
10916
+ row.append(cb,nm,ct);host.appendChild(row);
10917
+ }
10918
+ }
10919
+
10920
+ /** Repaint everything the selection governs: both lists, both toggles, the count and the button. */
10921
+ function riPaintPick(refocus){
10922
+ if(!riProbeRows)return;
10923
+ const sRows=riSelectable(riProbeRows.storeys),tRows=riSelectable(riProbeRows.types);
10924
+ riRenderRows(ri$('riStoreyList'),riProbeRows.storeys,riStoreyPick,(name,on)=>{
10925
+ if(riStoreyPick===null)riStoreyPick=new Set(sRows.map(r=>r.name));
10926
+ on?riStoreyPick.add(name):riStoreyPick.delete(name);
10927
+ if(riStoreyPick.size===sRows.length)riStoreyPick=null; // back to "all" — omit the key entirely
10928
+ riPaintPick({host:'riStoreyList',name});
10929
+ });
10930
+ riRenderRows(ri$('riTypeList'),riProbeRows.types,riTypePick,(name,on)=>{
10931
+ if(riTypePick===null)riTypePick=new Set(tRows.map(r=>r.name));
10932
+ on?riTypePick.add(name):riTypePick.delete(name);
10933
+ if(riTypePick.size===tRows.length)riTypePick=null;
10934
+ riPaintPick({host:'riTypeList',name});
10935
+ });
10936
+ const state=(pick,total)=>pick===null?'on':pick.size===0?'off':pick.size===total?'on':'mixed';
10937
+ const sTog=ri$('riStoreyAll'),tTog=ri$('riTypeAll');
10938
+ for(const [tog,pick,total] of [[sTog,riStoreyPick,sRows.length],[tTog,riTypePick,tRows.length]]){
10939
+ const st=state(pick,total);
10940
+ tog.dataset.state=st;tog.textContent=st==='on'?'☑':st==='off'?'☐':'▣';
10941
+ tog.setAttribute('aria-label',(st==='on'?'Clear':'Select')+' every '+(tog===sTog?'storey':'type'));
10942
+ }
10943
+ // Put the keyboard back where it was. The rows are rebuilt wholesale, so the element that fired the
10944
+ // change event no longer exists; without this a keyboard user is thrown to the top of the modal on
10945
+ // every single tick. Matched by NAME rather than index because a repaint can reorder nothing today
10946
+ // but would silently mis-focus if it ever did.
10947
+ if(refocus){
10948
+ const host=ri$(refocus.host);
10949
+ for(const l of host.querySelectorAll('label.ripick-row')){
10950
+ if(l.querySelector('.rpname')?.textContent===refocus.name){l.querySelector('input')?.focus();break;}
10951
+ }
10952
+ }
10953
+ ri$('riStoreyCount').textContent=sRows.length+' in this file';
10954
+ ri$('riTypeCount').textContent=tRows.length+' in this file';
10955
+ // THE STANDING NOTE, present exactly while both axes are narrowed. It says what the mechanic IS
10956
+ // rather than predicting a number: the estimate here is a min of two independent sums and can be
10957
+ // far above the truth (measured 6 where the real intersection was 0), so a sentence built on it
10958
+ // would state a wrong count as fact.
10959
+ const both=riStoreyPick!==null&&riTypePick!==null;
10960
+ const note=ri$('riPickNote');
10961
+ note.textContent=both?'Storeys and types narrow together — an object has to match BOTH to load, so picking from each can give you far fewer objects than either one alone.':'';
10962
+ note.style.display=both?'block':'none';
10963
+ riPaintCount();
10964
+ }
10965
+
10966
+ /** The live count, its two loud states, and the button they govern. */
10967
+ function riPaintCount(){
10968
+ // `riEstimate()` needs the rows; when there is no picker there are none, so the whole-file
10969
+ // population is the estimate. Reading `riEstimate()` unconditionally printed "—" over the correct
10970
+ // number for a file whose breakdown has one half present and the other missing — a state
10971
+ // `readPopulation` documents as reachable. (Second review round.)
10972
+ const n=riProbeRows?riEstimate():riPopulation;
10973
+ const v=riVerdictOf(n),empty=riEmptyPick();
10974
+ const canPick=!!riProbeRows;
10975
+ const el=ri$('riElements'),foot=ri$('riFootNote'),add=ri$('riInsert');
10976
+ el.classList.remove('warn','refuse');foot.classList.remove('warn','refuse');
10977
+ // THE REFUSAL DOES NOT OUTLIVE THE FIX. Staying on the confirm stage exists so the user can act on
10978
+ // "choose fewer storeys" — so the red sentence has to clear as they do, or they watch the live
10979
+ // count fall to a safe number underneath a message still quoting the old one.
10980
+ {const e=ri$('riConfirmErr');if(e.style.display!=='none'){e.textContent='';e.style.display='none';}}
10981
+ el.textContent=n===null?'—':'~'+n.toLocaleString();
10982
+ let msg='';
10983
+ if(empty){
10984
+ el.classList.add('refuse');
10985
+ msg='Nothing is selected, so there would be nothing to load. Tick at least one storey or type.';
10986
+ }else if(v==='refuse'){
10987
+ el.classList.add('refuse');
10988
+ // THE REMEDY MUST BE ONE THEY HAVE. With no picker on screen there is nothing to uncheck, and the
10989
+ // first version of this branch hard-blocked the user with an instruction they could not follow —
10990
+ // the same client/server mismatch `pickerCanExist` exists to remove, in the other direction.
10991
+ msg='About '+n.toLocaleString()+' objects — over FloLess’s limit of '+REF_MAX_OBJECTS.toLocaleString()+' for one reference. '
10992
+ +(canPick?'Uncheck some storeys or types to bring it under.'
10993
+ :'This file doesn’t offer storeys or types to load part of it, so it can only be exported smaller.');
10994
+ }else if(v==='warn'){
10995
+ el.classList.add('warn');
10996
+ msg='About '+n.toLocaleString()+' objects — this will take a while to load and may feel slow to navigate.';
10997
+ }
10998
+ foot.textContent=msg;
10999
+ if(msg)foot.classList.add(empty||v==='refuse'?'refuse':'warn'); // never tag a note that is not shown
11000
+ foot.style.display=msg?'block':'none';
11001
+ // DISABLED, not merely warned. The server refuses both of these anyway — this only saves the user
11002
+ // the upload and the wait before being told.
11003
+ const blocked=empty||v==='refuse';
11004
+ add.disabled=blocked;
11005
+ add.dataset.tip=blocked
11006
+ ?(empty?'Tick at least one storey or type first'
11007
+ :canPick?'This selection is over the limit — uncheck some rows'
11008
+ :'This file is over the limit and cannot be loaded in parts')
11009
+ :'Add this model as a reference. It is never part of your steel.';
11010
+ }
11011
+
11012
+ /**
11013
+ * Build the picker for a freshly probed file — or explain, in the same slot, why there is none.
11014
+ *
11015
+ * TWO INDEPENDENT QUESTIONS. Does the control EXIST (is there a real choice to make)? And is it OPEN
11016
+ * (is the file big enough for that choice to matter)? Conflating them either hides the option on a
11017
+ * small-but-many-storeyed file or charges every 13-object model an extra decision.
11018
+ */
11019
+ function riBuildPick(probe){
11020
+ riProbeRows=null;riStoreyPick=null;riTypePick=null;
11021
+ const tog=ri$('riPickToggle'),box=ri$('riPick'),none=ri$('riNoBreak');
11022
+ tog.style.display='none';box.style.display='none';none.style.display='none';
11023
+ ri$('riStoreyList').replaceChildren();ri$('riTypeList').replaceChildren();
11024
+ ri$('riInsert').disabled=false;
11025
+ ri$('riFootNote').style.display='none';ri$('riFootNote').textContent='';
11026
+ ri$('riElements').classList.remove('warn','refuse');
11027
+ {const e=ri$('riConfirmErr');e.textContent='';e.style.display='none';}
11028
+ if(!probe)return;
11029
+ // NULL IS NOT EMPTY. No breakdown means the user's IFC reader could not answer — never that the
11030
+ // file has no storeys — so the slot says so instead of showing an empty picker they cannot use.
11031
+ if(probe.storeys===null||probe.types===null){
11032
+ none.textContent='This file doesn’t say how many storeys or types it contains — that usually means an older IFC reader. FloLess can only load it whole.';
11033
+ none.style.display='block';
11034
+ riPaintCount(); // no picker is not "no judgement": the count is still judged, from riPopulation
11035
+ return;
11036
+ }
11037
+ riProbeRows={storeys:probe.storeys,types:probe.types};
11038
+ const sRows=riSelectable(probe.storeys),tRows=riSelectable(probe.types);
11039
+ // NO CHOICE, NO CONTROL. One storey and one type cannot be split into anything, and a picker that
11040
+ // can only select everything is furniture.
11041
+ if(sRows.length<=1&&tRows.length<=1){riPaintCount();return;}
11042
+ tog.style.display='';
11043
+ const big=riPopulation!==null&&riPopulation>=REF_WARN_OBJECTS;
11044
+ riSetPickOpen(big);
11045
+ riPaintPick();
11046
+ }
11047
+ function riSetPickOpen(open){
11048
+ ri$('riPick').style.display=open?'block':'none';
11049
+ ri$('riPickToggle').setAttribute('aria-expanded',open?'true':'false');
11050
+ ri$('riPickToggle').textContent=open?'Load only part of this file ▾':'Load only part of this file ▸';
11051
+ }
10355
11052
  function riReadFile(f){ if(!f||riBusy)return;riErr('');
10356
11053
  if(!/\.(ifc|ifczip)$/i.test(f.name||'')){riErr('Not an IFC file — expected .ifc or .ifczip.');return;}
10357
11054
  if(f.size>RI_MAX_BYTES){riErr('“'+f.name+'” is '+fileSizeWords(f.size)+'; the limit for a reference model is 150 MB. Try exporting just the part of the model you need to see.');return;}
@@ -10379,6 +11076,12 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10379
11076
  // response already on the wire lands anyway — so the id is what actually stops a cancelled
10380
11077
  // file's facts being written under a different file's name.
10381
11078
  if(mine!==riRun)return;
11079
+ // CLEARED PER ATTEMPT, HERE — not only in openRefImport. Both failure paths leave the modal open
11080
+ // at the drop stage, so a second file dropped after one fails never calls openRefImport again.
11081
+ // `riSha`/`riVerdict` survive that only because they are overwritten unconditionally below;
11082
+ // the picker state would not be, if the next file's breakdown is absent and riBuildPick returns
11083
+ // early. File A's storeys would then ride file B's sha, and the reader would select nothing.
11084
+ riProbeRows=null;riStoreyPick=null;riTypePick=null;riPopulation=null;
10382
11085
  riClearSoft();
10383
11086
  if(!res.ok||!d.ok){riStage('drop');riErr(d.error||'Could not read that file.');return;}
10384
11087
  riSha=d.sha;riVerdict=d.verdict||null;
@@ -10389,7 +11092,13 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10389
11092
  says.append(b,document.createTextNode(said?unitWords(said):'nothing about its units'),
10390
11093
  document.createTextNode('. FloLess has already applied that — you should not need to rescale it.'));
10391
11094
  ri$('riSchema').textContent=(d.probe&&d.probe.schema)||'—';
10392
- ri$('riElements').textContent=String((d.probe&&d.probe.elements)||0);
11095
+ // THE READ POPULATION, not `probe.elements` — those count different things and the second is
11096
+ // smaller (measured 10 against a 16-object read, 5,878 against 17,460). This row sits above a
11097
+ // limit stated in objects, so the two must be the same kind of number. `riBuildPick` then
11098
+ // overwrites it with the live figure whenever a picker exists.
11099
+ riPopulation=typeof d.population==='number'?d.population:null;
11100
+ ri$('riElements').textContent=riPopulation===null?'—':'~'+riPopulation.toLocaleString();
11101
+ riBuildPick(d.probe);
10393
11102
  // KB below a megabyte. `Math.max(1, …)` reported a 7.6 KB file as "1 MB" — a small lie, but the
10394
11103
  // number sits directly above a limit stated in MB, so it made the two unreadable together.
10395
11104
  ri$('riBytes').textContent=fileSizeWords(d.bytes||0);
@@ -10447,6 +11156,7 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10447
11156
  // the same reason the offer is (the bbox spans everything the file places) — the panel's own offer
10448
11157
  // re-does it exactly once the real bounds exist.
10449
11158
  const riNative=nativeModelCentre();
11159
+ const riFilterBody=riBuildFilter(); // computed ONCE — it was called twice in one expression
10450
11160
  const riOriginShift=takeOrigin&&riProbeCentre?riProbeCentre.map((v,i)=>riNative[i]-v):null;
10451
11161
  riStage('prog');riProg('Reading the geometry…','Still reading — a whole building takes a moment.');
10452
11162
  try{
@@ -10456,7 +11166,11 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10456
11166
  // the reference rather than by a debounced PUT afterwards. Applying it in the presentation
10457
11167
  // block left it outside the point of no return: a closed tab or a save conflict would leave
10458
11168
  // the server holding the site coordinates the user had just asked to move away from.
10459
- body:JSON.stringify({sha:riSha,name:riName,...(takeOrigin&&riOriginShift?{placement:{origin:riOriginShift}}:{})})});
11169
+ // The chosen SUBSET rides the insert alongside the placement, and for the same reason: it is
11170
+ // part of what the user decided in this modal, so it belongs inside the point of no return
11171
+ // rather than in a PUT afterwards. `undefined` here means the whole file — never an empty list,
11172
+ // which the reader would read as "select nothing".
11173
+ body:JSON.stringify({sha:riSha,name:riName,...(riFilterBody?{filter:riFilterBody}:{}),...(takeOrigin&&riOriginShift?{placement:{origin:riOriginShift}}:{})})});
10460
11174
  d=await res.json().catch(()=>({}));
10461
11175
  if(mine!==riRun){
10462
11176
  // Cancelled while this was in flight. The server refuses to commit for a client that has gone
@@ -10470,13 +11184,27 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10470
11184
  return;
10471
11185
  }
10472
11186
  riClearSoft();
10473
- if(!res.ok||!d.ok){riStage('drop');riErr(d.error||'Could not add that reference.');return;}
11187
+ if(!res.ok||!d.ok){
11188
+ // STAY ON CONFIRM for the refusals the picker itself can fix. `riStage('drop')` swaps the whole
11189
+ // body back to the dropzone, so telling somebody to "choose fewer storeys or types" would
11190
+ // remove every control that lets them. The other failures still go back — there is nothing to
11191
+ // act on in this stage for a vanished upload or a contract conflict.
11192
+ // `reference-filter-unconfirmed` belongs here too: its whole remedy is to try again, and
11193
+ // dropping to the dropzone would throw away the twelve storeys the user had just ticked.
11194
+ const actionable=d.code==='reference-too-many-objects'||d.code==='reference-filter-unmatched'
11195
+ ||d.code==='reference-empty-filter'||d.code==='reference-filter-unconfirmed';
11196
+ if(actionable&&riStageNow!=='drop'){
11197
+ riStage('confirm');
11198
+ const e=ri$('riConfirmErr');e.textContent=d.error||'Could not add that reference.';e.style.display='block';
11199
+ }else{riStage('drop');riErr(d.error||'Could not add that reference.');}
11200
+ return;
11201
+ }
10474
11202
  adoptReferenceWrite(d.etag);
10475
11203
  if(!Array.isArray(C.reference_models))C.reference_models=[];
10476
11204
  C.reference_models.push(d.reference);
10477
11205
  refGeom.set(d.reference.id,refGeomFrom(d)); // the same normaliser the geometry route's arrival uses — one shape, one spelling
10478
11206
  hadDrill=refSelectedObjIdx!==null; // …before this line drops it; the presentation half below needs to know
10479
- refSelectedId=d.reference.id;refSelectedObjIdx=null;
11207
+ refSelectedId=d.reference.id;refMeasureFollowSelection();refSelectedObjIdx=null;
10480
11208
  inserted=d.reference;
10481
11209
  }catch(e){
10482
11210
  // Aborted: no response at all, so we cannot know whether the write landed. Same reasoning as
@@ -10507,6 +11235,12 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10507
11235
  // throw away whatever else the inspector was in the middle of. (Codex review, both halves.)
10508
11236
  if(hadDrill)panel();
10509
11237
  toast('Added “'+inserted.name+'” as a reference'+(d.dropped?' ('+d.dropped+' object'+(d.dropped===1?'':'s')+' had nothing to draw)':''));
11238
+ // A PARTIAL MATCH IS NOT A CLEAN SUCCESS. The reference really was added, so this is a toast
11239
+ // rather than an error — but a user who picked three storeys and got two must be told, or the
11240
+ // server carrying `unmatched` on the response reaches nobody and the fix is wire-only.
11241
+ if(Array.isArray(d.unmatched)&&d.unmatched.length){
11242
+ toast('But nothing matched '+d.unmatched.map(function(u){return '“'+u+'”';}).join(', ')+' — that part of the file may have been renamed.');
11243
+ }
10510
11244
  }catch(e){
10511
11245
  console.error('[reference] added, but the view could not be updated',e);
10512
11246
  toast('Added “'+inserted.name+'” — reload the view to see it');
@@ -10519,6 +11253,12 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
10519
11253
  // leaving the invisible one is the version of that rule that does not hold. (UX review, #580.)
10520
11254
  ri$('riBackdrop').onclick=()=>{if(riStageNow!=='prog')riClose();};
10521
11255
  ri$('riInsert').onclick=riInsert;
11256
+ ri$('riPickToggle').onclick=()=>riSetPickOpen(ri$('riPick').style.display==='none');
11257
+ // The tri-state header toggle: `null` (all) and a full Set are the same selection but not the
11258
+ // same REQUEST — null omits the key — so clearing goes to an empty Set and selecting goes back
11259
+ // to null, never to a Set holding every name.
11260
+ ri$('riStoreyAll').onclick=()=>{riStoreyPick=riStoreyPick===null?new Set():null;riPaintPick();};
11261
+ ri$('riTypeAll').onclick=()=>{riTypePick=riTypePick===null?new Set():null;riPaintPick();};
10522
11262
  ri$('riDrop').onclick=()=>ri$('riFile').click();
10523
11263
  ri$('riDrop').onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();ri$('riFile').click();}};
10524
11264
  ri$('riFile').onchange=e=>{const f=e.target.files&&e.target.files[0];e.target.value='';riReadFile(f);};
@@ -13138,16 +13878,48 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
13138
13878
  const msg=fails.length?('SELFTEST FAIL: '+fails.join(' | ')):'SELFTEST PASS (frame + snap + transform + brace math)';
13139
13879
  console[fails.length?'error':'log'](msg);try{toast(msg);}catch(_){}
13140
13880
  })();}
13141
- // --- provenance caption: show contract.source when present (read from <name> · <sheet> · <read_at>) ---
13881
+ // --- provenance chip: contract.source (name/sheet/read_at) → "Source <file>", full caption in the tooltip ---
13882
+ // contract.source is authored by the terminal AI that read the drawing, so a source that is PRESENT but
13883
+ // unusable is a real upstream bug, not an empty state. An ABSENT one stays silent — a hand-built model
13884
+ // legitimately has none — but anything else warns, so a reader that drifts its shape is not mistaken for
13885
+ // "this model was never read from a drawing". console.warn, not error: the E2E gate reads the error channel
13886
+ // and a malformed contract must not spend it. (silent-failure review; same rule as normBrace above.)
13142
13887
  (function(){
13143
- const src=C.source;if(!src||typeof src!=='object')return;
13144
- const parts=[];
13145
- if(src.name)parts.push('read from '+src.name);
13146
- if(src.sheet)parts.push(src.sheet);
13147
- if(src.read_at){try{const d=new Date(src.read_at);if(!isNaN(d.getTime()))parts.push(d.toLocaleDateString());}catch{/* skip unparseable date */}}
13148
- if(!parts.length)return;
13149
- const el=document.getElementById('srcStat');if(!el)return;
13150
- el.textContent=parts.join(' · ');el.dataset.tip=parts.join(' · ');el.style.display=''; // title = full provenance (the chip itself truncates with ellipsis)
13888
+ const src=C.source;if(src==null)return; // no provenance recorded — the legitimate empty state
13889
+ // Each call states its OWN consequence: a refused field still leaves a chip, a refused source does not.
13890
+ const warn=(why,got)=>{console.warn('steel-editor: contract.source '+why,got);};
13891
+ if(typeof src!=='object'||Array.isArray(src)){warn('is not an object — the provenance chip stays hidden',src);return;}
13892
+ // Never coerce: every field here is drawing-derived, and an object reaching String() paints the literal
13893
+ // "[object Object]" into the header — the same reason planLabel refuses it. A non-string is not a value.
13894
+ // Refusing it WARNS, because partial drift is the likelier kind: a reader that starts emitting epoch-ms
13895
+ // for read_at, or a number for sheet, would otherwise have that one field vanish from the tooltip with
13896
+ // everything else still rendering, and nothing anywhere to notice. Absent — missing, null, or the empty
13897
+ // string a serializer writes for "unknown" — is silent; 0, false and objects are drift and are not.
13898
+ const str=(v,k)=>{if(v==null||v==='')return'';if(typeof v==='string'&&v.trim())return v.trim();warn('carried a '+k+' that is not a usable string — that field is left out of the chip',v);return'';};
13899
+ const name=str(src.name,'name'),sheet=str(src.sheet,'sheet'),stamp=str(src.read_at,'read_at');
13900
+ const parts=[];let day='';
13901
+ if(name)parts.push('read from '+name);
13902
+ if(sheet)parts.push(sheet);
13903
+ // No try/catch: new Date(<string>) never throws — it returns Invalid Date, which isNaN already catches.
13904
+ // Requiring a STRING also keeps read_at 0/null/true out; each of those is a VALID Date of 1 Jan 1970,
13905
+ // so a looser guard would stamp the chip with an epoch date nobody's drawing was read on.
13906
+ if(stamp){const d=new Date(stamp);if(isNaN(d.getTime()))warn('carried an unreadable read_at — the date is left out of the chip',src.read_at);else{day=d.toLocaleDateString(undefined,{timeZone:'UTC'});parts.push(day);}}
13907
+ if(!parts.length){warn('recorded no name, sheet or readable date — the provenance chip stays hidden',src);return;}
13908
+ const el=document.getElementById('srcStat');
13909
+ if(!el){warn('cannot render — #srcStat is missing from the header',null);return;}
13910
+ // The value must be one that CANNOT go stale, because this block runs once at boot and nothing re-runs
13911
+ // it on setPlan(). The file and the read date are fixed for the life of the page; source.sheet is not.
13912
+ // It is the single sheet the drawing was READ from, while plans[] holds many and C.active is restored
13913
+ // from localStorage — so a multi-sheet model opens on S-202 with the chip stamped S-201, in a row of
13914
+ // live per-sheet stats (Members, Dup, Axes) where that reads as "current". So the sheet NEVER heads this
13915
+ // chip, not even as a last resort: a source with no file and no readable date has recorded no stale-proof
13916
+ // identity, and a readout that is wrong is worse than one that is absent (see the per-sheet counts
13917
+ // above). That is the same call as the {path, sha256} case just above — hide, and say why. The sheet
13918
+ // still reaches the tooltip whenever anything else earns the chip, where "read from …" dates it.
13919
+ const val=name||day;
13920
+ if(!val){warn('recorded only a sheet, which cannot head this chip without reading as the plan you are on — the provenance chip stays hidden',src);return;}
13921
+ el.textContent='Source ';el.append(Object.assign(document.createElement('b'),{textContent:val}));
13922
+ el.dataset.tip=parts.join(' · ');el.style.display='';
13151
13923
  })();
13152
13924
  // --- Ask AI: send instruction + optional screenshots → POST /api/contract-request ---
13153
13925
  // The server records a tweak-contract request; the terminal AI picks it up async and PUTs