@floless/app 0.123.0 → 0.123.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -92,6 +92,48 @@
92
92
  input[type=radio]:checked{border-color:var(--brand)}
93
93
  input[type=radio]:checked::before{transform:scale(1)}
94
94
  input[type=radio]:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
95
+ /* Checkboxes go the SAME route, and the comment above understated the problem when it called the
96
+ per-container `.gck input` / `.m3dmenu label input` rules an escape hatch that worked: every one of
97
+ them was `accent-color` plus a width, which fixes the STRETCH but not the colour — accent-color
98
+ tints only the CHECKED fill, so an UNCHECKED box stayed the UA widget, a solid white square on this
99
+ #070a0f page. Rebuilt here the way steel-filter.html:90 already builds its global checkbox (brand
100
+ fill, white tick, 3px radius) using the same ::before construction as the radio directly above.
101
+ The tick is a fixed 9px, NOT a percentage: the box is `display:inline-grid` with `place-content:
102
+ center`, so its track is sized by this very item and a percentage width resolves to 0 — measured at
103
+ 6x, every checked box painted a solid brand square with no check in it. A guard cannot catch that
104
+ (it reads declarations, and `width:62%` is one), so the size is stated outright. */
105
+ input[type=checkbox]{appearance:none;-webkit-appearance:none;width:14px;height:14px;flex:none;padding:0;
106
+ border:1px solid #475569;border-radius:3px;background:#0f172a;cursor:pointer;display:inline-grid;place-content:center;
107
+ transition:border-color .12s,background-color .12s}
108
+ input[type=checkbox]::before{content:'';width:9px;height:9px;background:#fff;transform:scale(0);transition:transform .12s ease;
109
+ clip-path:polygon(14% 44%,0 65%,50% 100%,100% 16%,80% 0%,43% 62%)}
110
+ input[type=checkbox]:checked{background:var(--brand);border-color:var(--brand)}
111
+ input[type=checkbox]:checked::before{transform:scale(1)}
112
+ input[type=checkbox]:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
113
+ /* INDETERMINATE. `appearance:none` deletes the platform's mixed-state dash along with the box, and
114
+ only `:checked` reveals the tick — so a checkbox the editor has explicitly put in the mixed state
115
+ rendered identically to an unchecked one, quietly reporting "no" where the truth is "the selection
116
+ disagrees". This page really does drive it: dimBg (line ~5012) when selected dimensions differ on
117
+ label backgrounds, and the per-end `_ck` TOS-default boxes (~5297) when members mix default and
118
+ custom. Same fill as :checked, with the ::before clipped to a bar instead of a tick. Declared on
119
+ every surface, not just this one, so the next page to set .indeterminate inherits it rather than
120
+ re-learning this. (Raised by the Codex review on #592.) */
121
+ input[type=checkbox]:indeterminate{background:var(--brand);border-color:var(--brand)}
122
+ input[type=checkbox]:indeterminate::before{transform:scale(1);clip-path:none;height:2px;border-radius:1px}
123
+ /* FORCED COLORS (Windows High Contrast). The OS overrides every authored colour, so the custom box's
124
+ fill and its clipped ::before both collapse to system colours and the states stop being tellable
125
+ apart. Hand the platform its own widget back: in that mode the UA control is the accessible one,
126
+ and the white-on-dark leak this whole rule exists to fix cannot arise, because the OS — not this
127
+ stylesheet — is choosing the colours. `revert` rolls each declaration back to the UA origin, which
128
+ also drops the generic `select,input{width:100%}` above for these two controls.
129
+ NOTE for the guard: verify-native-controls deliberately cannot see inside a conditional @media, so
130
+ this block neither satisfies nor weakens it — the unconditional rules above are still what it
131
+ reads. (Raised by the Codex review on #592.) */
132
+ @media (forced-colors: active){
133
+ input[type=checkbox],input[type=radio]{appearance:revert;-webkit-appearance:revert;width:revert;height:revert;
134
+ border:revert;background:revert;display:revert;padding:revert}
135
+ input[type=checkbox]::before,input[type=radio]::before{content:none}
136
+ }
95
137
  input[type=number]{-moz-appearance:textfield;appearance:textfield}
96
138
  input[type=number]::-webkit-outer-spin-button,input[type=number]::-webkit-inner-spin-button{-webkit-appearance:none;margin:0}
97
139
  .row{margin:8px 0} .danger{background:#7f1d1d;border-color:#991b1b} .danger:hover{background:#991b1b}
@@ -187,7 +229,7 @@
187
229
  .tfchip:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
188
230
  .tfchip.tfdim{border-style:dashed}
189
231
  .defck{display:inline-flex;align-items:center;gap:4px;font-size:10px;text-transform:uppercase;letter-spacing:.05em;color:var(--mut);cursor:pointer}
190
- .defck input{width:auto;margin:0;cursor:pointer;accent-color:var(--brand)}
232
+ .defck input{margin:0;cursor:pointer} /* size + theming now come from the global input[type=checkbox] rule; `width:auto` had to go — on an appearance:none box it collapses the control to nothing */
191
233
  input:disabled{opacity:.55;cursor:default}
192
234
  .badge{display:block;background:var(--brand);color:#fff;text-align:center;font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:5px;border-radius:6px;margin-bottom:10px}
193
235
  .pick{color:var(--brand)!important}
@@ -505,6 +547,39 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
505
547
  #panel .pintog.on .mck::after{transform:translateX(12px);background:var(--brand)}
506
548
  #panel .pintog svg{margin-right:4px;color:#22d3ee;flex:none} /* the pin glyph carries the dim accent, matching the on-canvas markers */
507
549
  #panel .pintog:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
550
+ /* ── The drilled-into reference object (S2 Stage A): somebody else's IFC element, read-only.
551
+ Property SETS are accordions because one object can carry several of them and a dozen-plus rows each
552
+ — measured on the Motebello sample: 2 sets and 15 values on its heaviest object, 31 sets and 271
553
+ values across its 19 (docs/superpowers/specs/2026-08-03-reference-objects-stage-a-qa.md). Dumping
554
+ that into a 240px rail on select is unreadable. The chevron / aria-expanded / aria-controls /
555
+ brand-tinted-open recipe is #moreMenu's (.msec-hdr), reused rather than reinvented — same glyph too.
556
+ NO inner scroller: the panel is already `overflow:auto` and inherits the global themed scrollbar, so
557
+ a bespoke fixed-height box here would be one more thing to theme and test for nothing. */
558
+ #panel .robjname{font-size:13px;color:var(--text);font-weight:600;overflow-wrap:anywhere;margin:0 0 2px}
559
+ #panel .psetgrp{border-top:1px solid var(--line)}
560
+ /* The property-set accordion. #m3dRefsBody is named alongside #panel because the reference object
561
+ tree (S2 Stage B) reuses this exact header in the References legend, which is a SIBLING of #panel —
562
+ scoped to #panel alone the header fell through to the global `button{}` pill: grey fill, rounded
563
+ border, a chevron that never turned and a count that was not muted. Same markup, same look, both
564
+ places. */
565
+ #panel .psethd,#m3dRefsBody .psethd{display:flex;align-items:center;gap:6px;width:100%;background:transparent;border:0;border-radius:0;box-shadow:none;color:var(--text);font:600 11px system-ui;padding:5px 2px;cursor:pointer;text-align:left}
566
+ #panel .psethd:hover,#m3dRefsBody .psethd:hover{color:var(--text);background:#33415580}
567
+ #panel .psethd[aria-expanded=true],#m3dRefsBody .psethd[aria-expanded=true]{color:var(--brand)}
568
+ #panel .psethd:focus-visible,#m3dRefsBody .psethd:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
569
+ #panel .psethd .chev,#m3dRefsBody .psethd .chev{color:var(--mut);font-size:10px;width:10px;flex:none;transition:transform .15s}
570
+ #panel .psethd[aria-expanded=true] .chev,#m3dRefsBody .psethd[aria-expanded=true] .chev{transform:rotate(90deg);color:var(--brand)}
571
+ #panel .psethd .psn,#m3dRefsBody .psethd .psn{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
572
+ #panel .psethd .psc,#m3dRefsBody .psethd .psc{flex:none;color:var(--mut);font-weight:400;font-variant-numeric:tabular-nums}
573
+ #panel .psetbody,#m3dRefsBody .psetbody{display:none;padding:2px 0 8px 16px}
574
+ #panel .psetbody.open,#m3dRefsBody .psetbody.open{display:block}
575
+ /* Label ABOVE value, not beside it: an IFC property name ("NominalRenderingHeight") and its value
576
+ ("0055SFt0000001150") can BOTH be long, so the label-left/value-right recipe this panel uses
577
+ elsewhere either truncates or wraps into a ragged mess at this width. */
578
+ #panel .psrow{display:flex;flex-direction:column;gap:1px;margin:0 0 7px}
579
+ #panel .psrow .psk{font-size:10px;color:var(--mut);overflow-wrap:anywhere;line-height:1.35}
580
+ #panel .psrow .psv{font-size:12px;color:var(--text);overflow-wrap:anywhere;line-height:1.4}
581
+ #panel .psrow .psv.psnone{color:var(--mut)} /* the file recorded the property with NO value */
582
+ #panel .psrow .psv.psempty{color:var(--mut);font-style:italic} /* …with an EMPTY value, which is a different fact */
508
583
  #dimEditPop .dimEditTog:hover{border-color:var(--brand);color:var(--text)}
509
584
  #dimEditPop .dimEditTog.on{border-color:var(--brand);background:rgba(59,130,246,.18);color:var(--text)}
510
585
  #dimEditPop .dimEditTog.pin.on{border-color:#22d3ee;background:rgba(34,211,238,.16);color:var(--text)}
@@ -540,7 +615,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
540
615
  .gerr{color:#fca5a5;font-size:11px;margin-top:3px}
541
616
  .gbtns{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px} .gbtns button{margin:0}
542
617
  .gck{display:flex;align-items:center;gap:8px;color:var(--text);cursor:pointer;font-size:12px;padding:2px 0}
543
- .gck input{accent-color:var(--brand);cursor:pointer;margin:0;width:14px;height:14px;flex:none} /* beat the panel's generic full-width input rule */
618
+ .gck input{cursor:pointer;margin:0;width:14px;height:14px;flex:none} /* beat the panel's generic full-width input rule */
544
619
  /* F11 generated views modal — baseline modal/tabs/inputs, sized for batch selection without crowding the 240px Views pane. */
545
620
  #viewGenModal{z-index:60} /* the 3D toolbar is z:59; this modal must fully cover it, while later-appended toasts at z:60 and the z:80 tooltip still win */
546
621
  #viewGenModal .mpanel{width:min(640px,92vw)}
@@ -556,7 +631,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
556
631
  #vgList .vggroup{padding:5px 7px 3px;color:var(--mut);font-size:10px;text-transform:uppercase;letter-spacing:.07em}
557
632
  #vgList .vgrow{display:flex;align-items:center;gap:9px;padding:6px 8px;border-radius:5px;cursor:pointer}
558
633
  #vgList .vgrow:hover{background:#33415580}
559
- #vgList .vgrow input{accent-color:var(--brand);width:14px;height:14px;margin:0;flex:none}
634
+ #vgList .vgrow input{width:14px;height:14px;margin:0;flex:none}
560
635
  #vgList .vgaxis{width:18px;color:var(--mut);font-size:10px;font-weight:700}
561
636
  #vgList .vgname{color:var(--text);font-size:12px}
562
637
  #vgList .vgempty{padding:28px 16px;text-align:center;color:var(--mut);font-size:12px;line-height:1.5}
@@ -664,7 +739,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
664
739
  .m3dmenu hr{border:0;border-top:1px solid var(--line);margin:4px 0}
665
740
  .m3dmenu label{display:flex;align-items:center;gap:7px;padding:7px 12px;color:var(--text);font-size:12px;cursor:pointer;white-space:nowrap}
666
741
  .m3dmenu label:hover{background:#334155}
667
- .m3dmenu label input{margin:0;width:auto;accent-color:var(--brand);cursor:pointer} /* width:auto — don't inherit the global input{width:100%}; keeps the checkbox tight against its label (View / Plane / Work toggles) */
742
+ .m3dmenu label input{margin:0;cursor:pointer} /* the global input[type=checkbox] rule now sets the box size, so this no longer inherits input{width:100%} and no longer needs `width:auto` — which on an appearance:none box would collapse it (View / Plane / Work toggles) */
668
743
  .m3dmenu .wpprow{display:flex;gap:4px;align-items:center;padding:4px 12px}
669
744
  .m3dmenu .wpprow button{width:auto;flex:none;padding:4px 8px;border:1px solid var(--line);border-radius:5px}
670
745
  .m3dmenu .wpprow input{width:74px;height:24px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:5px;padding:0 6px;font:12px system-ui}
@@ -688,7 +763,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
688
763
  #propPop .pprow:hover{background:#334155}
689
764
  #propPop .pprow.dis{opacity:.5;cursor:default}
690
765
  #propPop .pprow.dis:hover{background:transparent}
691
- #propPop .pprow input{margin:0;accent-color:var(--brand);cursor:pointer;flex:none;width:auto} /* width:auto beats the editor's global input{width:100%} that would otherwise stretch the checkbox across the row */
766
+ #propPop .pprow input{margin:0;cursor:pointer;flex:none} /* the global input[type=checkbox] rule sizes the box, so the old `width:auto` (which would now collapse it) is gone */
692
767
  #propPop .pprow .pn{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
693
768
  #propPop .pprow .pv{color:var(--mut);font-variant-numeric:tabular-nums;max-width:44%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:right}
694
769
  #propPop .pprow .pv.varies{font-style:italic}
@@ -696,7 +771,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
696
771
  #propPop .ppfoot{border-top:1px solid var(--line);padding:8px 10px;display:flex;flex-direction:column;gap:6px}
697
772
  #propPop .ppfoot .seg2{margin-top:0}
698
773
  #propPop .ppfoot label{display:flex;align-items:center;gap:7px;color:var(--text);cursor:pointer;font-size:11px}
699
- #propPop .ppfoot label input{margin:0;accent-color:var(--brand);cursor:pointer;flex:none;width:auto}
774
+ #propPop .ppfoot label input{margin:0;cursor:pointer;flex:none}
700
775
  /* Connection read-only mode: no labeling, so hide the label footer + Clear-all; rows aren't clickable. */
701
776
  #propPop.connmode .ppfoot{display:none}
702
777
  #propPop.connmode #ppClear{display:none}
@@ -780,7 +855,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
780
855
  than a new hue being invented. ── */
781
856
  #refHeadRow{display:flex;align-items:stretch;gap:6px;margin-bottom:6px;flex:none}
782
857
  #refAddBtn{flex:1;min-width:0;height:28px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
783
- #m3dRefsBody .refempty,#m3dRefsBody .refhint{color:var(--mut);font-size:11px;line-height:1.5;padding:6px 4px}
858
+ #m3dRefsBody .refempty{color:var(--mut);font-size:11px;line-height:1.5;padding:6px 4px}
784
859
  #m3dRefsBody .refrow{display:flex;align-items:center;gap:6px;padding:3px 4px;border-radius:5px;cursor:pointer;user-select:none;white-space:nowrap}
785
860
  #m3dRefsBody .refrow:hover{background:#33415580}
786
861
  #m3dRefsBody .refrow.sel{box-shadow:inset 2px 0 0 var(--brand);background:rgba(59,130,246,.16);padding-left:2px}
@@ -821,6 +896,36 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
821
896
  #m3dRefsBody .refdet .seg2 button{font-size:11px;padding:0}
822
897
  #m3dRefsBody .refdet .seg2 .swc{flex:1;width:auto;height:100%;border:0;border-radius:0;min-width:0}
823
898
  #m3dRefsBody .refdet .seg2 .swc.on{box-shadow:inset 0 0 0 2px var(--brand)}
899
+ /* ── The object tree (S2 Stage B) — what is INSIDE one reference, storey → IFC type.
900
+ Grouping chrome is #m3dLegend's own `.cat-hdr`/`.cat-hdr.sub`/`.cat-chevron`/`.cat-count`, which
901
+ already exists for exactly this two-level shape (Dimensions → Base-plate); the rows sit at the
902
+ `.lrow.sub` indent. New here: the bounded scroll box, the row, the filter box and the cap notice.
903
+ The accordion HEADER is `.psethd`/`.psetbody`, whose rules had to be widened to name #m3dRefsBody —
904
+ they were scoped to #panel, which is a sibling of this panel, not an ancestor.
905
+ THE BOX IS BOUNDED, and that is a deliberate departure from the property panel's "no inner
906
+ scroller" rule: that reasoning ("one more thing to theme and test for nothing") holds at 31 sets
907
+ and does not hold at 17,460 objects, which would otherwise push every control above it off screen.
908
+ Same recipe as #ciList / #vgList, so it inherits the global themed scrollbar and adds no CSS. */
909
+ #m3dRefsBody .reftree{max-height:min(38vh,300px);overflow:auto;border:1px solid var(--line);border-radius:7px;background:var(--bg);padding:3px 2px}
910
+ /* The tree's own filter. It does NOT reuse #propPop's `.ppsearch` — that recipe is scoped to #propPop
911
+ and cannot reach this panel, so naming it here would be a class that styles nothing. The global
912
+ `select,input` rule already makes it dark, and `#m3dRefsBody .refdet input[type=text]` above already
913
+ sizes it (and outranks this rule, so height/font are deliberately not restated here). What neither
914
+ gives it is room for its text against the global `padding:6px`, or the branded focus ring that every
915
+ other input in this file has and that CLAUDE.md requires. */
916
+ #m3dRefsBody .reftreesearch{padding:4px 0 6px}
917
+ #m3dRefsBody .reftreesearch input{padding:0 8px}
918
+ #m3dRefsBody .reftreesearch input:focus{outline:none;border-color:var(--brand)}
919
+ #m3dRefsBody .reftreesearch input::placeholder{color:var(--mut)}
920
+ #m3dLegend .refobjrow{display:flex;align-items:center;gap:6px;padding:2px 4px 2px 34px;border-radius:5px;cursor:pointer;user-select:none;white-space:nowrap;font-size:11px;color:var(--text)}
921
+ #m3dLegend .refobjrow:hover{background:#33415580}
922
+ #m3dLegend .refobjrow:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
923
+ #m3dLegend .refobjrow.sel{box-shadow:inset 2px 0 0 var(--brand);background:rgba(59,130,246,.16)}
924
+ #m3dLegend .refobjrow.flash{background:rgba(59,130,246,.12)} /* "you just navigated here" — the same flash tint .lrow/.vwrow use, held longer (900ms) because the tree may also have scrolled */
925
+ #m3dLegend .refobjrow .ronm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis}
926
+ #m3dLegend .refobjrow .rord{flex:none;color:var(--mut);font-size:10px;font-variant-numeric:tabular-nums}
927
+ #m3dRefsBody .reftree .cat-hdr:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
928
+ #m3dRefsBody .refcap{color:var(--mut);font-size:10px;padding:4px 4px 4px 34px;line-height:1.4}
824
929
  #m3dRefsBody .refdet .colrow{display:flex;align-items:center;gap:6px}
825
930
  #m3dRefsBody .refdet .colrow .seg2{flex:1;min-width:0}
826
931
  /* ── Reference-model import modal (#refImportModal) — the #connImportModal recipe, under its own ids.
@@ -909,7 +1014,11 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
909
1014
  #m3dLegend .cat-chevron{font-size:10px;color:var(--mut);width:12px;flex:none;text-align:center}
910
1015
  #m3dLegend .cat-tog{font-size:12px;width:14px;flex:none;cursor:pointer;line-height:1;text-align:center}
911
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}
912
- #m3dLegend .cat-label{flex:1;font-size:12px;color:var(--text)}
1017
+ /* `min-width:0` + ellipsis because a flex item that cannot shrink below its content OVERFLOWS the row
1018
+ rather than truncating, and `.cat-hdr` is `white-space:nowrap`. The legend's own categories were
1019
+ always short enough to hide this; the reference tree's disambiguated headers ("Wall · IFCWALL…")
1020
+ 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)}
913
1022
  #m3dLegend .cat-count{font-size:10px;color:var(--mut);font-variant-numeric:tabular-nums}
914
1023
  #m3dLegend .lrow.typed{padding-left:20px}
915
1024
  #m3dLegend .cat-hdr.sub{padding-left:20px} /* a nested (middle) category, e.g. Dimensions → Base-plate */
@@ -1358,7 +1467,10 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1358
1467
  <div id=riDropErr role=alert></div>
1359
1468
  <input id=riFile type=file accept=".ifc,.ifczip" style="display:none">
1360
1469
  </div>
1361
- <div id=riProgStage style="display:none"><div id=riProgTxt>Reading the file…</div></div>
1470
+ <!-- The spinner is `connImportModal`'s own `.ci-prog`/`.ci-spin` (see the CSS above), reused rather
1471
+ than re-invented: this stage sat as static text for up to six seconds before its honest
1472
+ "still working" message appeared, which reads as hung next to the sibling modal that spins. -->
1473
+ <div id=riProgStage style="display:none"><div class=ci-prog><span class=ci-spin aria-hidden=true></span><span id=riProgTxt>Reading the file…</span></div></div>
1362
1474
  <div id=riConfirmStage style="display:none">
1363
1475
  <div id=riSays></div>
1364
1476
  <div class=rirow><span class=pn>Schema</span><span class=pv id=riSchema>—</span></div>
@@ -4802,11 +4914,83 @@ function syncV2SelectionNotice(p){
4802
4914
  else if(m&&canonical){mark('tosA',!Number.isFinite(canonical.from?.z?.known));mark('tosB',!Number.isFinite(canonical.to?.z?.known));}
4803
4915
  }
4804
4916
  }
4917
+ /**
4918
+ * Does something else own the panel or the selection right now?
4919
+ *
4920
+ * The reference object is the LOWEST-PRIORITY thing this panel can show. It beats the two "there is
4921
+ * nothing to say" notices below it (`NO_PLAN_VIEW`, the read-only note) — for a drilled-into object
4922
+ * there IS something to say, and it is true — but it must lose to everything the user explicitly did.
4923
+ *
4924
+ * The dispatch cannot simply be moved below those takeovers: they sit BELOW the two notices, which is
4925
+ * correct for them (a v2 document cannot reach them) and would put the reference branch back under
4926
+ * `NO_PLAN_VIEW`, where the whole feature was unreachable. So the ORDER stays and this predicate carries
4927
+ * the rule instead — the same shape `dimStyleMode` already uses one line further down.
4928
+ *
4929
+ * Two classes, and both were missed by the first cut (Codex review):
4930
+ * a SELECTION of ours — including 3D dimensions and clip planes, which are deleted by the same
4931
+ * Delete key that would then be acting on something the panel is not describing;
4932
+ * a MODE the user armed — the 3D local frame, Dimension, Dimension style, Set local axes, Move/Copy.
4933
+ * Each of those renders instructions into this panel, and the reference object was swallowing them
4934
+ * whole: drill in, arm the frame, and the frame's own prompts never appeared.
4935
+ *
4936
+ * `gridMode` is deliberately NOT here: it is dispatched above the reference branch already.
4937
+ *
4938
+ * WHICH of the two it is matters, so this returns the kind rather than a boolean. A SELECTION of ours
4939
+ * clears the reference outright — that is what `clickSelect` already does when a click lands on one of
4940
+ * our members, and anything less is worse than nothing: the independent QA pass found that releasing to
4941
+ * a whole-reference selection left all nineteen objects LIT at the exact moment the user selected their
4942
+ * own steel, which draws more attention to the reference than the drill did. A MODE only drops the
4943
+ * drill; arming the Dimension tool is not a statement about which reference you care about.
4944
+ */
4945
+ function refPanelPreempted(){
4946
+ if(selIds.size||selDimIds.size||selGridIds.size||sel3dDimIds.size)return 'selection';
4947
+ const v=window.Steel3DView;
4948
+ if(view3d&&v&&v.selectedClips&&v.selectedClips().length)return 'selection';
4949
+ if(dimStyleMode||dimMode||csaxisMode||cmTool)return 'mode';
4950
+ if(view3d&&v&&v.frameArmed&&v.frameArmed())return 'mode';
4951
+ return null;
4952
+ }
4805
4953
  function panel(){
4806
4954
  const p=document.getElementById('panel');
4807
4955
  if(MODEL_V2)queueMicrotask(()=>syncV2SelectionNotice(p));
4808
4956
  if(!selDimIds.size||!dimsVisible)dimSplitMode=false;document.body.classList.toggle('dimsplit',dimSplitMode); // split mode is meaningless without a (visible) dim selected — also disarms when dims are hidden
4809
4957
  if(gridMode){renderGridPanel(p);return;}
4958
+ // FIRST after the grid takeover, and ABOVE the two "there is nothing to say" panels below — because for
4959
+ // a drilled-into reference object there IS something to say, and it is true. A reference model is
4960
+ // model-level: it does not belong to a plan view and it does not depend on our own model being
4961
+ // editable, so both of the notices below answer a question the user did not ask. Sitting under
4962
+ // NO_PLAN_VIEW in particular made the whole feature UNREACHABLE on a document whose only views are
4963
+ // elevations or sections — you could drill in, the object would highlight, and the panel would go on
4964
+ // saying "No editable plan view". (Codex review.)
4965
+ //
4966
+ // The grid panel stays above it: that one is a mode the user explicitly entered and must be able to leave.
4967
+ //
4968
+ // ANYTHING THAT SELECTS SOMETHING OF OURS TAKES THE PANEL BACK — the same rule, in the same place, as
4969
+ // `dimStyleMode` three lines below, and for the same reason: there are far too many ways to select for a
4970
+ // release call at each of them to survive. `clickSelect` drops the drill when a click lands on one of
4971
+ // our members, but that is the ONLY path that does; a marquee (`onSelectMany`), a legend locate, Ctrl+A,
4972
+ // an RFI jump and a switch back to 2D all leave it standing, and the panel would then describe somebody
4973
+ // else's IFC object while Delete and the arrow keys acted on your beam. Confidently wrong about what is
4974
+ // selected is the worst state this panel has. (Code review.)
4975
+ //
4976
+ // The view is told too, so the 3D highlight cannot outlive the panel that explained it. That call is
4977
+ // not re-entrant: it emits `onReferenceSelect(id, null)`, which finds the editor state already updated
4978
+ // on the line above and returns before repainting.
4979
+ {const _pre=refSelectedObjIdx!==null?refPanelPreempted():null,_v=window.Steel3DView;
4980
+ if(_pre){
4981
+ refSelectedObjIdx=null;
4982
+ if(_pre==='selection'){
4983
+ // OUR SELECTION DROPS THE REFERENCE ENTIRELY, exactly as `clickSelect` does for a direct member
4984
+ // click. Releasing to a whole-reference selection instead lit all nineteen of its objects at the
4985
+ // moment the user selected their own steel — a louder reference, from an action about our model.
4986
+ refSelectedId=null;
4987
+ if(_v&&_v.selectReference)_v.selectReference(null);
4988
+ if(legendTab==='refs')renderRefsTab();
4989
+ } else if(_v&&_v.selectReference&&_v.selectedReferenceObject&&_v.selectedReferenceObject()){
4990
+ _v.selectReference(refSelectedId); // an armed MODE only ends the drill; the reference you were reading stays selected
4991
+ }
4992
+ }}
4993
+ if(refSelectedId!==null&&refSelectedObjIdx!==null&&renderPanelReferenceObject(p))return;
4810
4994
  if(NO_PLAN_VIEW){p.innerHTML='<span class=badge>No editable plan view</span><div class=hint style="margin-top:8px">This model has no registered plan view to map into the 2D canvas. Elevation, section, detail, and unknown views stay available in 3D, but they are not edited as plans.</div>';return;}
4811
4995
  if(MODEL_RO){renderPanelV2(p);return;} // …after the grid panel, which is the one panel a v2 document does reach
4812
4996
  if(dimStyleMode&&(selIds.size||selDimIds.size))dimStyleMode=false; // anything that selects (Ctrl+A, Duplicates, Reversed beams, a legend/RFI locate…) takes the panel back from the style pane — one guard instead of a disarm call at every such command
@@ -7913,7 +8097,33 @@ const view3dApi={
7913
8097
  // one-way — the panel drives the 3D view but a pick in the 3D view leaves the panel showing the
7914
8098
  // previous row, which is worse than no highlight because it is confidently wrong. Found by clicking
7915
8099
  // the canvas for real; every panel-driven path had looked fine.
7916
- onReferenceSelect:(id)=>{if(refSelectedId===id)return;refSelectedId=id||null;if(legendTab==='refs')renderRefsTab();},
8100
+ // `obj` is the ONE object drilled into (Ctrl+click), or null for a whole-reference select. The panel is
8101
+ // rendered from it, so it is compared as well as the id: Ctrl+clicking a second object inside the SAME
8102
+ // reference leaves `id` unchanged, and an early return on the id alone would leave the Inspect panel
8103
+ // describing the first object while the 3D view highlights the second.
8104
+ onReferenceSelect:(id,obj)=>{
8105
+ const nextId=id||null,nextIdx=obj&&Number.isInteger(obj.index)?obj.index:null;
8106
+ if(refSelectedId===nextId&&refSelectedObjIdx===nextIdx)return;
8107
+ refSelectedId=nextId;refSelectedObjIdx=nextIdx;
8108
+ // DRILLING IN TAKES THE SELECTION, NOT JUST THE PANEL — the exact mirror of `clickSelect` dropping the
8109
+ // reference the moment a click lands on one of our own members. The two are one selection between
8110
+ // them, and the first cut let them coexist: with a beam selected, drilling into a reference object put
8111
+ // its facts in the panel while Delete and the arrow keys still acted on the beam. Panel and keystroke
8112
+ // target pointing at different things is the worst state this feature has.
8113
+ //
8114
+ // Only a DRILL steals. Selecting a whole reference (a row click) does not take the panel, so it has no
8115
+ // business taking the selection either.
8116
+ //
8117
+ // This is also what keeps `panel()`'s release guard from fighting an intentional drill: the guard fires
8118
+ // when something of ours is selected, and by the time it runs, nothing is. The browser pass caught
8119
+ // that — with a marquee selection live, drilling was silently impossible.
8120
+ const stole=nextIdx!==null&&(selIds.size||selDimIds.size||selGridIds.size||sel3dDimIds.size);
8121
+ if(stole){selIds.clear();selDimIds.clear();selGridIds.clear();sel3dDimIds.clear();}
8122
+ // The object tree, if the user has it open, comes to the object — see `revealRefTreeObject`. It
8123
+ // repaints the tab itself, so the ordinary repaint below is skipped when it did.
8124
+ if(!(nextId&&nextIdx!==null&&revealRefTreeObject(nextId,nextIdx))&&legendTab==='refs')renderRefsTab();
8125
+ if(stole)render();else panel(); // render() repaints the canvas too, so our own highlight goes with the selection
8126
+ },
7917
8127
  onBasePickModeChange:()=>{}, // Mode B armed state shows via the 3D crosshair + elevation readout; nothing else to reflect
7918
8128
  onBasePick:(p)=>{ // Mode B: retarget the armed column's base to the picked elevation (world mm → inches), ONE undo entry
7919
8129
  const m=byId(basePickColId); if(!m||m.role!=='column'||!m.col){toast('No column to trim');return;}
@@ -8799,8 +9009,58 @@ const refLoading=new Set(); // ids with a geometry fetch in flight — the
8799
9009
  const refFailed=new Map(); // id -> why its geometry could not be fetched (see loadReferenceGeometry)
8800
9010
  const refEmpty=new Set(); // ids the reader answered for, with nothing drawable in the answer
8801
9011
  let refSelectedId=null; // the reference the panel has expanded (and the 3D layer has selected)
9012
+ /**
9013
+ * The INDEX of the one object drilled into inside `refSelectedId`, or null.
9014
+ *
9015
+ * An index rather than an id, because that is what addresses a mesh — see `xrefSubSelected` in
9016
+ * web/steel-3d-view.js for why an IFC GlobalId cannot. It indexes `refGeom.get(refSelectedId).objects`,
9017
+ * the very array the 3D layer was handed, so the panel and the highlight cannot describe two different
9018
+ * objects.
9019
+ *
9020
+ * THE 3D LAYER IS THE OWNER OF THE INDEX. `onReferenceSelect` is the only thing that ever sets this to a
9021
+ * NUMBER; every other write — the row click, `refRemove`, the import, `panel()`'s takeover release —
9022
+ * only ever clears it to null. So the panel can never point at an object the 3D layer is not currently
9023
+ * drilled into, and a rebuild that drops the selection (a re-read after "Reload its geometry") clears
9024
+ * the panel with it. (An earlier draft of this comment claimed this was written from nowhere else at
9025
+ * all, which was simply false — review caught it; the invariant above is both true and stronger.)
9026
+ */
9027
+ let refSelectedObjIdx=null;
9028
+ /**
9029
+ * Which property-set groups the user has opened, PER OBJECT.
9030
+ *
9031
+ * `refId|objectIndex` → the set of open group indices. Group INDICES, because a set's name is neither
9032
+ * unique nor always present (`null` when the file omits it).
9033
+ *
9034
+ * PER OBJECT, NOT "THE LAST OBJECT". A single Set with a key beside it was the first cut, and the
9035
+ * independent QA pass failed it on exactly the sentence the QA script promises: close a group, look at
9036
+ * another object, come back — your choice is still yours. It was not; the key had moved on and the
9037
+ * default reopened it. Which is the right rule is not obvious in the abstract and is obvious in the
9038
+ * hand: an object you have already tidied should stay tidy, and what you opened on a DIFFERENT object
9039
+ * still says nothing about this one — this map gives both, where one Set could only give one.
9040
+ *
9041
+ * Unbounded by clicks and that is fine: an entry is two small integers' worth of state, and it lives
9042
+ * exactly as long as the page does.
9043
+ */
9044
+ const refPsetOpen=new Map(); // key -> Set of open group indices; the key's ABSENCE means "never touched"
8802
9045
  const refUnresolved=new Set(); // ids whose original file is missing from the project (relink case)
8803
9046
 
9047
+ /**
9048
+ * One geometry response, normalised for `refGeom` — the ONE place that shape is written.
9049
+ *
9050
+ * It used to be spelled out twice, at the two arrivals (the geometry route and the import), under a
9051
+ * comment asking that the two be kept identical. Review's point was that a comment is not a mechanism.
9052
+ *
9053
+ * BOTH `*Available` FLAGS DEFAULT TO `null`, NEVER `false`. An absent key means a server too old to
9054
+ * answer, which is exactly the "we cannot tell" state; `false` would claim the file records none, and
9055
+ * only the reader could know that. The server never sends `false` for `propertySetsAvailable` at all.
9056
+ */
9057
+ function refGeomFrom(d){
9058
+ return {
9059
+ objects:d.objects||[],dropped:d.dropped||0,spanMm:d.spanMm||0,
9060
+ colorsAvailable:d.colorsAvailable===undefined?null:d.colorsAvailable,
9061
+ propertySetsAvailable:d.propertySetsAvailable===undefined?null:d.propertySetsAvailable,
9062
+ };
9063
+ }
8804
9064
  function refList(){return Array.isArray(C.reference_models)?C.reference_models:[];}
8805
9065
  function refById(id){return refList().find(r=>r&&r.id===id)||null;}
8806
9066
  function refDisp(r){return (r&&r.display)||{};}
@@ -8813,7 +9073,13 @@ function pushReferences(){
8813
9073
  id:r.id,name:r.name,placement:r.placement||null,display:refDisp(r),
8814
9074
  objects:(refGeom.get(r.id)||{}).objects||[],
8815
9075
  })));
8816
- if(refSelectedId&&window.Steel3DView.selectReference)window.Steel3DView.selectReference(refSelectedId);
9076
+ // RE-ASSERT ONLY ON A REAL DIVERGENCE. The 3D layer preserves its own selection across the rebuild
9077
+ // above, and re-validates any object drilled into (`revalidateSubSelection`) — so an unconditional
9078
+ // `selectReference` here would UN-DRILL the user on every geometry arrival, and re-drilling by index
9079
+ // would re-select whatever landed in that slot after a re-read, which is the exact confusion the
9080
+ // re-validation exists to prevent. The one case worth fixing is the two genuinely disagreeing.
9081
+ const v=window.Steel3DView;
9082
+ if(refSelectedId&&v.selectReference&&(!v.selectedReference||v.selectedReference()!==refSelectedId))v.selectReference(refSelectedId);
8817
9083
  }
8818
9084
 
8819
9085
  /**
@@ -8844,7 +9110,7 @@ async function loadReferenceGeometry(id,opts){
8844
9110
  // a row ends up claiming both "file missing" and "nothing to draw", or keeps a stale reason after a
8845
9111
  // successful retry.
8846
9112
  const only=(set)=>{for(const s of [refUnresolved,refFailed,refEmpty])if(s!==set)s.delete(id);};
8847
- if(res.ok&&d.ok){refGeom.set(id,{objects:d.objects||[],dropped:d.dropped||0,spanMm:d.spanMm||0,colorsAvailable:d.colorsAvailable===undefined?null:d.colorsAvailable});only(null);}
9113
+ if(res.ok&&d.ok){refGeom.set(id,refGeomFrom(d));only(null);}
8848
9114
  else if(d.code==='reference-unresolved'){only(refUnresolved);refUnresolved.add(id);}
8849
9115
  else if(d.code==='reference-empty'){only(refEmpty);refEmpty.add(id);}
8850
9116
  // An `else` is mandatory here: a 500 whose body is not JSON parses to `{}`, so without one a failed
@@ -8863,7 +9129,20 @@ async function loadReferenceGeometry(id,opts){
8863
9129
  }
8864
9130
  console.error('[reference] geometry fetch failed',id,e);
8865
9131
  }
8866
- finally{refLoading.delete(id);pushReferences();if(legendTab==='refs')renderRefsTab();}
9132
+ // `panel()` IS PART OF THE ARRIVAL, not an extra — but ONLY when the panel is showing an object out of
9133
+ // a reference, which is the only thing on it this arrival can have changed.
9134
+ //
9135
+ // The reload case is why it is needed: the panel tells the user "your reader may be too old — reload its
9136
+ // geometry", they do exactly that, the new read carries the properties AND keeps the same object (so
9137
+ // neither the selection callback nor the re-assert fires), and the panel goes on repeating the sentence
9138
+ // that sent them there. Following your own instruction and seeing nothing happen is the worst version of
9139
+ // this bug.
9140
+ //
9141
+ // The condition is why it is SAFE. `panel()` rebuilds the whole inspector, so an unconditional repaint
9142
+ // here destroys an in-progress edit: a member selected, a value half-typed and not yet blurred, and any
9143
+ // reference finishing its fetch removes the focused input and restores the old value. `loadAllReferences`
9144
+ // fires one of these per uncached reference at boot, so it is not a rare race. (Both halves: Codex.)
9145
+ finally{refLoading.delete(id);pushReferences();if(legendTab==='refs')renderRefsTab();if(refSelectedObjIdx!==null)panel();}
8867
9146
  }
8868
9147
  /** Pull every reference's geometry once the 3D view is up. Sequential: one AWARE run at a time anyway. */
8869
9148
  async function loadAllReferences(){for(const r of refList())await loadReferenceGeometry(r.id);}
@@ -9010,7 +9289,7 @@ function buildRefRow(r){
9010
9289
  :failed?failed+' — use ⋯ ▸ Reload its geometry to try again'
9011
9290
  :empty?'The reader read this file but found nothing it could draw'
9012
9291
  :(geom&&geom.dropped)?geom.dropped+' object'+(geom.dropped===1?'':'s')+' in this file carried no usable mesh, so they are not shown'
9013
- :'Click to select the whole model';
9292
+ :'Click to select the whole model. Ctrl+click an object in 3D for just that one.';
9014
9293
  row.appendChild(name);
9015
9294
 
9016
9295
  // PERMANENT, not hover-revealed. A reference can arrive correctly sized and 74 m up, entirely
@@ -9035,8 +9314,9 @@ function buildRefRow(r){
9035
9314
 
9036
9315
  row.addEventListener('click',()=>{
9037
9316
  refSelectedId=refSelectedId===r.id?null:r.id;
9317
+ 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
9038
9318
  if(window.Steel3DView&&window.Steel3DView.selectReference)window.Steel3DView.selectReference(refSelectedId);
9039
- renderRefsTab();});
9319
+ renderRefsTab();panel();});
9040
9320
  return row;
9041
9321
  }
9042
9322
 
@@ -9157,6 +9437,19 @@ function buildRefDetail(r){
9157
9437
  :'Hiding this reference does not stop snapping to it — the cyan dot on the row does.';
9158
9438
  wrap.appendChild(note);
9159
9439
 
9440
+ // WHERE DRILLING IS TAUGHT. Nothing on the canvas says Ctrl+click exists, and a tooltip cannot teach it
9441
+ // — a keyboard or screen-reader user never sees one, which is the same reasoning the note above is
9442
+ // written for. This detail block is already where this feature explains itself in plain text (once the
9443
+ // row is open), so the one sentence goes here rather than becoming a banner or a first-run toast.
9444
+ //
9445
+ // Gated on there being geometry: offering a gesture against a reference that draws nothing is an
9446
+ // instruction the user can only follow into silence.
9447
+ if(refGeom.has(r.id)){
9448
+ const drill=Object.assign(document.createElement('div'),{className:'dnote'});
9449
+ drill.textContent='Ctrl+click one object in the 3D view to select just that part of the file and read what the file says about it.';
9450
+ wrap.appendChild(drill);
9451
+ }
9452
+
9160
9453
  // The TRUE size — measured off the geometry that is actually on screen, which is the only place this
9161
9454
  // number can be honest. The import modal deliberately shows none: before tessellation the sole
9162
9455
  // measurement available is the reader's own APPROXIMATE bbox, and that spans every point the file
@@ -9207,9 +9500,703 @@ function buildRefDetail(r){
9207
9500
  fix.addEventListener('click',()=>refMoveToOrigin(r.id));
9208
9501
  w.appendChild(document.createElement('br'));w.appendChild(fix);wrap.appendChild(w);
9209
9502
  }
9503
+ // LAST in the block, deliberately. Opening a tree of 17,460 objects must not push the "how does this
9504
+ // look" controls — the reason the row was expanded in the first place — off the top of the panel.
9505
+ buildRefTree(r,wrap);
9210
9506
  return wrap;
9211
9507
  }
9212
9508
 
9509
+ // ── The drilled-into reference object (S2 Stage A) ────────────────────────────────────────────────
9510
+ //
9511
+ // Ctrl+click one object inside a reference and this is what the Inspect panel shows: what the FILE says
9512
+ // about that object, read-only, in the file's own words. Nothing here is editable and nothing here is
9513
+ // ours — it never reaches the contract, the BOM, an export or the lock, exactly like the geometry it
9514
+ // describes.
9515
+
9516
+ /**
9517
+ * Plain English for an IFC type token, with the token itself kept beside it.
9518
+ *
9519
+ * TRANSLATED AND NOT REPLACED. "IFCWALLSTANDARDCASE" means nothing to the people this panel is written
9520
+ * for, and "Wall" alone quietly discards what the file actually said — which matters here more than
9521
+ * anywhere, because on a file like the Motebello sample the type is one of only two things that
9522
+ * distinguish one object from another. So both are shown, and an unmapped token degrades to a
9523
+ * title-cased version of itself rather than to a guess: a future entity reads as "Buildingelementproxy"
9524
+ * rather than as whatever this map last believed.
9525
+ */
9526
+ const IFC_TYPE_WORDS={IFCBEAM:'Beam',IFCCOLUMN:'Column',IFCMEMBER:'Member',IFCPLATE:'Plate',IFCSLAB:'Slab',
9527
+ IFCWALL:'Wall',IFCWALLSTANDARDCASE:'Wall',IFCWINDOW:'Window',IFCDOOR:'Door',IFCRAILING:'Railing',
9528
+ IFCSTAIR:'Stair',IFCSTAIRFLIGHT:'Stair flight',IFCRAMP:'Ramp',IFCROOF:'Roof',IFCCOVERING:'Covering',
9529
+ IFCFOOTING:'Footing',IFCPILE:'Pile',IFCCURTAINWALL:'Curtain wall',IFCFURNISHINGELEMENT:'Furnishing',
9530
+ IFCFLOWTERMINAL:'Terminal fitting',IFCFLOWSEGMENT:'Duct or pipe segment',IFCFLOWFITTING:'Duct or pipe fitting',
9531
+ IFCDISCRETEACCESSORY:'Accessory',IFCMECHANICALFASTENER:'Fastener',IFCREINFORCINGBAR:'Reinforcing bar',
9532
+ IFCBUILDINGELEMENTPART:'Building element part',IFCBUILDINGELEMENTPROXY:'Generic element'};
9533
+ function ifcTypeWords(t){
9534
+ const k=String(t||'').trim().toUpperCase();
9535
+ if(!k)return null;
9536
+ if(IFC_TYPE_WORDS[k])return IFC_TYPE_WORDS[k];
9537
+ const bare=k.replace(/^IFC/,'');
9538
+ return bare?bare.charAt(0)+bare.slice(1).toLowerCase():null;
9539
+ }
9540
+
9541
+ /**
9542
+ * Is this a name, or is it the file's way of writing "nothing"?
9543
+ *
9544
+ * Two of the Motebello sample's nineteen objects are named `-`. Printing that as a headline reads as a
9545
+ * broken template rather than as "the author did not name this", so a string with no letter and no digit
9546
+ * is treated as no name at all — and what the file DID write is then stated in words underneath, because
9547
+ * hiding it would be this panel telling a smaller truth than the file did.
9548
+ */
9549
+ function refObjNamed(n){return typeof n==='string'&&/[\p{L}\p{N}]/u.test(n);}
9550
+
9551
+ /**
9552
+ * The objects of one reference, grouped storey → IFC type, for the object tree (S2 Stage B).
9553
+ *
9554
+ * INDICES, NEVER OBJECTS. The result addresses each object by its position in the array it was built
9555
+ * from — the same handle the 3D layer and the Inspect panel already use, because an IFC GlobalId can be
9556
+ * absent or duplicated (see `xrefSubSelected` in web/steel-3d-view.js). It also means this structure
9557
+ * costs a few numbers per object, and nothing here has to be kept in step with the array it describes.
9558
+ *
9559
+ * ORDER IS FIRST APPEARANCE, not alphabetical. A building's storeys have an order — LG, L1, L2, ROOF —
9560
+ * that no sort of their names recovers ("L10" sorts before "L2", "BASEMENT" before everything), and we
9561
+ * are given no elevations to sort by. File order is the author's own sequence and it is the only
9562
+ * ordering here that is not invented. Types are ordered the same way within a storey, for the same
9563
+ * reason. (This preserves the order of the read it is given; it does not — and cannot — promise that two
9564
+ * reads of a changed file agree, which is why the tree's group state is dropped on a re-read.)
9565
+ *
9566
+ * THE STOREY-LESS GROUP GOES LAST, and is left as `null` for the renderer to name rather than labelled
9567
+ * here. A file that records no storeys at all — which is ordinary, though no sample file we hold does it;
9568
+ * Daldy contributes one such object among 17,460 — produces exactly one group, and the tree then
9569
+ * degrades to a flat list of types.
9570
+ */
9571
+ function groupReferenceObjects(objects){
9572
+ const list=Array.isArray(objects)?objects:[];
9573
+ const byStorey=new Map(); // storey label (or null) -> Map<type label, number[]>
9574
+ for(let i=0;i<list.length;i++){
9575
+ const o=list[i]||{};
9576
+ // Trimmed, and blank counts as absent — the same rule the Inspect panel's identity line follows, and
9577
+ // for the same measured reason: this file family pads fields to a fixed width (it is Motebello's
9578
+ // MATERIAL that arrives as eighty spaces), so a padded field would otherwise head a group with nothing.
9579
+ const s=(typeof o.storey==='string'&&o.storey.trim())?o.storey.trim():null;
9580
+ const t=(typeof o.ifcType==='string'&&o.ifcType.trim())?o.ifcType.trim():null;
9581
+ if(!byStorey.has(s))byStorey.set(s,new Map());
9582
+ const types=byStorey.get(s);
9583
+ if(!types.has(t))types.set(t,[]);
9584
+ types.get(t).push(i);
9585
+ }
9586
+ const out=[];
9587
+ for(const [storey,types] of byStorey){
9588
+ const groups=[...types].map(([type,indices])=>({type,words:ifcTypeWords(type),count:indices.length,indices}));
9589
+ out.push({storey,count:groups.reduce((n,g)=>n+g.count,0),types:groups});
9590
+ }
9591
+ // The unlabelled storey last, wherever it appeared. It is the one group whose position carries no
9592
+ // information from the file, so it is the one group we may place.
9593
+ out.sort((a,b)=>(a.storey===null?1:0)-(b.storey===null?1:0));
9594
+ return out;
9595
+ }
9596
+
9597
+ /** One `name: value` row. The FOUR value states are rendered differently ON PURPOSE — see the CSS. */
9598
+ function buildPropRow(prop){
9599
+ const row=document.createElement('div');row.className='psrow';
9600
+ row.appendChild(Object.assign(document.createElement('div'),{className:'psk',textContent:prop.name}));
9601
+ const v=document.createElement('div');
9602
+ // FOUR DIFFERENT FACTS, FOUR DIFFERENT SENTENCES. Each pair of them was, at some point on this branch,
9603
+ // rendered identically, and each collapse states something the file does not say:
9604
+ // a real value — printed verbatim, never parsed
9605
+ // `unreadable` — WE cannot render the shape the reader sent (a list, an enumerated value). A
9606
+ // statement about us. Was folded into null, which claimed the file left it blank.
9607
+ // `null` — the file records the property and gives it no value. A statement about the file.
9608
+ // `''` — the file records it as empty text. A different statement about the file.
9609
+ // `undefined` cannot reach here — `toPropertySets` normalises every value to `string|null` before it
9610
+ // leaves the server — so that arm is belt-and-braces, not a fifth state.
9611
+ if(prop.unreadable){v.className='psv psnone';v.textContent='— value in a form FloLess can’t show';}
9612
+ else if(prop.value===null||prop.value===undefined){v.className='psv psnone';v.textContent='— not recorded';}
9613
+ else if(prop.value===''){v.className='psv psempty';v.textContent='(empty text)';}
9614
+ else {v.className='psv';v.textContent=String(prop.value);}
9615
+ row.appendChild(v);
9616
+ return row;
9617
+ }
9618
+
9619
+ /**
9620
+ * One property set, as a collapsible group.
9621
+ *
9622
+ * COLLAPSED WHEN THERE IS MORE THAN ONE, expanded when there is exactly one: with a single group there
9623
+ * is nothing to choose between, and a click to reveal the only content would be a toll. The row count
9624
+ * sits in every header, so the shape of the object is legible without opening anything — which is what
9625
+ * makes collapsing-by-default a summary rather than a hiding place.
9626
+ */
9627
+ function buildPsetGroup(set,i,total,key){
9628
+ const wrap=document.createElement('div');wrap.className='psetgrp';
9629
+ const chosen=refPsetOpen.get(key); // absent = the user has never touched THIS object's groups
9630
+ const open=chosen?chosen.has(i):total===1;
9631
+ const bodyId='pset-'+i;
9632
+ const hd=document.createElement('button');hd.type='button';hd.className='psethd';
9633
+ hd.setAttribute('aria-expanded',String(open));
9634
+ hd.setAttribute('aria-controls',bodyId); // the other half of #moreMenu's recipe, which the first cut copied without
9635
+ // `aria-hidden` on the chevron: it is decoration, and without this a screen reader announces
9636
+ // "black right-pointing small triangle" ahead of the set name on every single header. (Codex review.)
9637
+ const chev=Object.assign(document.createElement('span'),{className:'chev',textContent:'▸'});
9638
+ chev.setAttribute('aria-hidden','true');
9639
+ hd.append(chev,
9640
+ Object.assign(document.createElement('span'),{className:'psn',textContent:set.name||'Unnamed property set'}),
9641
+ Object.assign(document.createElement('span'),{className:'psc',textContent:String(set.properties.length)}));
9642
+ hd.dataset.tip=(set.name||'This set has no name in the file')+' — '+set.properties.length+' propert'+(set.properties.length===1?'y':'ies')+' the file records for this object';
9643
+ const body=document.createElement('div');body.className='psetbody'+(open?' open':'');body.id=bodyId;
9644
+ for(const prop of set.properties)body.appendChild(buildPropRow(prop));
9645
+ hd.addEventListener('click',()=>{
9646
+ const now=!body.classList.contains('open');
9647
+ body.classList.toggle('open',now);hd.setAttribute('aria-expanded',String(now));
9648
+ // The first interaction on THIS object takes the default off the table, seeding the set with what the
9649
+ // default was showing — otherwise closing the only group of a one-group object would re-open it on the
9650
+ // very next repaint, and opening one of six would close again on the next repaint.
9651
+ let s=refPsetOpen.get(key);
9652
+ if(!s){s=new Set();if(total===1)s.add(0);refPsetOpen.set(key,s);}
9653
+ if(now)s.add(i);else s.delete(i);
9654
+ });
9655
+ wrap.append(hd,body);
9656
+ return wrap;
9657
+ }
9658
+
9659
+ /**
9660
+ * The Inspect panel for one object inside a reference model.
9661
+ *
9662
+ * RETURNS FALSE RATHER THAN RENDERING A HOLE when the selection cannot be resolved — a reference whose
9663
+ * geometry has been dropped, an index past the end after a re-read. `panel()` then falls through to
9664
+ * whatever it would otherwise have shown, which is the honest outcome: we no longer know what was
9665
+ * selected, so we say nothing about it rather than something empty under a confident heading.
9666
+ */
9667
+ function renderPanelReferenceObject(p){
9668
+ const r=refById(refSelectedId);if(!r)return false;
9669
+ const g=refGeom.get(refSelectedId);if(!g||!Array.isArray(g.objects))return false;
9670
+ const o=g.objects[refSelectedObjIdx];if(!o)return false;
9671
+
9672
+ const key=refSelectedId+'|'+refSelectedObjIdx; // `refPsetOpen` is keyed by this; nothing to reset
9673
+ p.replaceChildren();
9674
+
9675
+ p.appendChild(Object.assign(document.createElement('span'),{className:'badge',textContent:'Reference object'}));
9676
+ const chipRow=document.createElement('div');chipRow.className='row';chipRow.style.margin='0 0 6px';
9677
+ // The NEUTRAL chip, deliberately. The brand-bordered variant is this panel's "you can act on this"
9678
+ // signal (the parametric-connection chip wears it); borrowing it for borrowed geometry would say the
9679
+ // one thing about a reference that must never be said.
9680
+ const chip=Object.assign(document.createElement('span'),{className:'chip',textContent:'Somebody else’s IFC — read-only'});
9681
+ chip.style.borderColor='var(--line)';chip.style.color='var(--mut)';
9682
+ chipRow.appendChild(chip);p.appendChild(chipRow);
9683
+
9684
+ const named=refObjNamed(o.name);
9685
+ // Trimmed for the same reason the identity line below is: this file pads fields to a fixed width, and a
9686
+ // headline of eighty spaces followed by a word is a broken-looking panel, not a faithful one.
9687
+ p.appendChild(Object.assign(document.createElement('div'),{className:'robjname',textContent:named?String(o.name).trim():'Unnamed object'}));
9688
+
9689
+ const fact=(s)=>(typeof s==='string'&&s.trim()?s.trim():null);
9690
+ const words=ifcTypeWords(o.ifcType);
9691
+ const meta=[];
9692
+ // The TYPE token is trimmed too. It is the one identity field the first cut left raw, on the grounds
9693
+ // that a schema token cannot be padded — which is exactly the assumption the material field disproved
9694
+ // on this very file. Same rule everywhere is cheaper than a rule with one exception. (Code review.)
9695
+ const typeTok=fact(o.ifcType);
9696
+ if(words)meta.push(typeTok&&typeTok.toUpperCase()!==words.toUpperCase()?words+' ('+typeTok+')':words);
9697
+ // TRIMMED, AND A BLANK STRING IS ABSENT. Twelve of the Motebello sample's nineteen objects carry a
9698
+ // material of EIGHTY SPACES — a fixed-width field written out verbatim, which is a real thing IFC
9699
+ // authoring tools do. Truthiness alone accepted it, and the identity line rendered "… · BA-E05 · " with
9700
+ // a dangling separator and a paragraph of whitespace after it. Only a run against the real file could
9701
+ // have found that, which is the argument for the run.
9702
+ //
9703
+ // Trimming for DISPLAY is safe here in a way it would not be for a property value: this line is an
9704
+ // identity summary, and leading or trailing spaces on a storey name carry nothing a user can act on.
9705
+ // The property panel below still prints values exactly as the file wrote them.
9706
+ for(const f of [fact(o.storey),fact(o.profile),fact(o.material)])if(f)meta.push(f);
9707
+ // OMITTED, NOT BLANK. A "Storey —" row for a file that records no storey is a field the user could try
9708
+ // to fill; there is nothing here they can fill, so an absent fact is simply absent.
9709
+ // `robjmeta` / `robjnone` below are addressable on purpose: what this panel can get wrong is a
9710
+ // SENTENCE, and a test that reads the whole panel as one string cannot tell "the storey line is absent"
9711
+ // from "the storey line says something else that happens not to contain the storey". A mutation pass
9712
+ // found exactly that hole in both places.
9713
+ if(meta.length){const m=Object.assign(document.createElement('div'),{className:'hint robjmeta'});m.style.margin='0 0 4px';m.textContent=meta.join(' · ');p.appendChild(m);}
9714
+
9715
+ const inRef=Object.assign(document.createElement('div'),{className:'hint'});
9716
+ inRef.style.cssText='margin:0 0 2px;font-size:11px';
9717
+ inRef.textContent='In “'+r.name+'”';
9718
+ p.appendChild(inRef);
9719
+ // Say what the file wrote even where we refused to use it as a headline — this panel must never claim
9720
+ // to know less than the file does.
9721
+ if(!named&&typeof o.name==='string'&&o.name.trim()){
9722
+ const n=Object.assign(document.createElement('div'),{className:'hint'});
9723
+ n.style.cssText='margin:0 0 2px;font-size:11px';
9724
+ n.textContent='The file names it “'+o.name+'”.';
9725
+ p.appendChild(n);
9726
+ }
9727
+ const escNote=Object.assign(document.createElement('div'),{className:'hint'});
9728
+ escNote.style.cssText='margin:0 0 6px;font-size:11px';
9729
+ escNote.append(Object.assign(document.createElement('b'),{textContent:'Esc'}),document.createTextNode(' steps back to the whole reference.'));
9730
+ p.appendChild(escNote);
9731
+
9732
+ const div=document.createElement('div');div.className='divrow';div.appendChild(document.createElement('hr'));p.appendChild(div);
9733
+
9734
+ const sets=Array.isArray(o.propertySets)?o.propertySets:null;
9735
+ if(sets&&sets.length){
9736
+ if(!named){
9737
+ const why=Object.assign(document.createElement('div'),{className:'hint'});
9738
+ why.style.cssText='margin:0 0 6px;font-size:11px';
9739
+ why.textContent='This file didn’t give it a name — the property sets below are what tell it apart from the other objects in “'+r.name+'”.';
9740
+ p.appendChild(why);
9741
+ }
9742
+ sets.forEach((s,i)=>p.appendChild(buildPsetGroup(s,i,sets.length,key)));
9743
+ return true;
9744
+ }
9745
+
9746
+ const none=Object.assign(document.createElement('div'),{className:'hint robjnone'});
9747
+ none.style.fontSize='11px';
9748
+ // THE THREE-STATE ANSWER, and the two branches are the difference between a fact and a guess. `true`
9749
+ // means this read carried properties, so an object without any genuinely has none and saying so is a
9750
+ // fact. `null` means nobody could tell us — the file may record none, or the IFC reader may be too old
9751
+ // to send them — and "this model has no properties" would then be a false sentence about a fixable
9752
+ // state. So that branch names the fix, in the words the References tab already uses for its sibling
9753
+ // failure ("use ⋯ ▸ Reload its geometry to try again").
9754
+ //
9755
+ // AND THE FILE-WIDE FLAG IS NOT A PER-OBJECT FACT. `propertySetsAvailable` is `true` the moment ANY
9756
+ // object in the read carried usable sets; spending it on THIS object would state "the file attached
9757
+ // none" over an object whose sets we ourselves refused, because some other object's happened to be well
9758
+ // formed. `propertySetsRefused` is the per-object receipt that closes it. (Code review.)
9759
+ // "OFFERS PROPERTY INFORMATION", not "records properties". The receipt says the reader handed over
9760
+ // something set-shaped that we could not use — which includes a set with no usable properties in it,
9761
+ // and for that "the file records properties" would be a claim the evidence does not carry. (Codex.)
9762
+ if(o.propertySetsRefused)none.textContent='This file offers property information for this object that FloLess could not read — so none is shown rather than some of it guessed at.';
9763
+ else if(g.propertySetsAvailable===true)none.textContent='This object carries no properties. The file simply didn’t attach any to it.';
9764
+ // A LOCKED REFERENCE CANNOT BE RELOADED — the ⋯ item refuses it outright — so offering that as the
9765
+ // remedy would send the user to a dead end. Name the extra step instead of omitting the offer: unlike
9766
+ // the row menu's own hidden items, there IS something the user can do here.
9767
+ else none.textContent='This file’s properties couldn’t be read — that could mean the file records none, or that your IFC reader is too old to send them. In the References list (bottom left), open “'+r.name+'” ▸ ⋯ ▸ Reload its geometry to check with today’s reader.'
9768
+ +(refDisp(r).locked?' It is locked, so switch Locked off first.':'');
9769
+ p.appendChild(none);
9770
+ return true;
9771
+ }
9772
+
9773
+ // ── The object tree (S2 Stage B) ─────────────────────────────────────────────────────────────────
9774
+ //
9775
+ // What is INSIDE one reference, grouped storey → IFC type, in the row's own detail block. Selecting a
9776
+ // row drills into that object exactly as Ctrl+click does — it is the same call — and drilling in 3D
9777
+ // brings the tree to the object.
9778
+
9779
+ /**
9780
+ * Per-REFERENCE tree state, scoped per reference for the reason `refPsetOpen` is scoped per object.
9781
+ * (Its key is `refId|objIdx`; these are keyed by reference id alone, which is the level they belong to.)
9782
+ *
9783
+ * One global tree state would silently misapply reference A's open storeys to reference B's entirely
9784
+ * different ones — the same trap the property-set memory already avoids, one level up.
9785
+ *
9786
+ * `refTreeGroups` holds an EXPLICIT open/closed per group, not a set of "expanded" keys. A set cannot
9787
+ * express this: the default for a lone group is OPEN, so the set has to mean both "the user opened this"
9788
+ * and "the user has touched nothing", and those two cancel — clicking a lone group's header wrote the
9789
+ * key, which read back as still-open, and clicking again emptied the set, which re-armed the auto-open.
9790
+ * The header could never be closed, and worse, its click changed the OTHER level (whose default was
9791
+ * keyed on the same set being empty). A key that is simply absent means "no opinion — use the default".
9792
+ */
9793
+ const refTreeOpen=new Set(); // reference ids whose tree accordion is open
9794
+ const refTreeGroups=new Map(); // refId -> Map<group key ('storeyIdx' / 'storeyIdx:typeIdx'), boolean open>
9795
+ const refTreeQuery=new Map(); // refId -> the live filter text
9796
+ /** The id the filter input carries, so it can be found again across the repaint its own typing causes. */
9797
+ const REF_TREE_SEARCH_ID='refTreeSearch';
9798
+ /**
9799
+ * How many object rows one type group will build at once.
9800
+ *
9801
+ * The DOM is bounded: a group builds rows only once it is open, and the one path that opens groups
9802
+ * unasked (a filter at or below this cap) can by definition not exceed it. But ONE group can still be
9803
+ * enormous: Daldy's IFCMEMBER is 9,210 objects. This is the last bound, and it is stated in the UI
9804
+ * rather than applied silently: a list that stops at 300 with no explanation reads as a broken tree,
9805
+ * which is worse than a limit that says what it is.
9806
+ *
9807
+ * Deliberately NOT virtualisation. Nothing in this app windows a list — `#ciList` and `#vgList` are
9808
+ * both plain `overflow:auto` — and introducing it for one feature is more machinery than the problem
9809
+ * needs once rendering is lazy. What the user gives up past the cap is scroll-hunting; the filter is
9810
+ * the way through, and it is right there. The one row the cap may NOT drop is the selected one — see
9811
+ * the window in `buildRefTree`, without which "drilling in 3D shows you the row" was false for the
9812
+ * 8,910 members of that group that fall past row 300.
9813
+ */
9814
+ const REF_TREE_CAP=300;
9815
+
9816
+ /**
9817
+ * Does this object match the filter? Name, raw IFC type, storey, and the plain word the tree shows for
9818
+ * that type — the four things a row shows or sits under. `q` must arrive lowercased and trimmed; only
9819
+ * the haystack is lowercased here.
9820
+ */
9821
+ function refTreeMatches(o,q){
9822
+ if(!q)return true;
9823
+ const hay=[o&&o.name,o&&o.ifcType,o&&o.storey,ifcTypeWords(o&&o.ifcType)].filter((s)=>typeof s==='string').join(' ').toLowerCase();
9824
+ return hay.includes(q);
9825
+ }
9826
+
9827
+ /**
9828
+ * Make a `role=button` div actually behave like one.
9829
+ *
9830
+ * `role=button` without a tab stop and a key handler is a promise to a screen reader that the element
9831
+ * cannot keep — it announces "button, collapsed" and then Tab never reaches it. The legend's own
9832
+ * `.cat-hdr` elsewhere carries no role, so it at least does not lie; these do, so they earn the rest.
9833
+ * `stopPropagation` because the editor's global shortcut handler eats Space and Enter.
9834
+ *
9835
+ * `ownsTabStop:false` for anything inside a roving group — see `refTreeRoving`.
9836
+ */
9837
+ function refTreeKeyOperable(el,ownsTabStop){
9838
+ if(ownsTabStop!==false)el.tabIndex=0;
9839
+ el.addEventListener('keydown',(e)=>{
9840
+ if(e.key!=='Enter'&&e.key!==' ')return;
9841
+ e.preventDefault();e.stopPropagation();el.click();
9842
+ });
9843
+ }
9844
+
9845
+ /**
9846
+ * ONE tab stop for the whole list of object rows, with the arrows moving inside it.
9847
+ *
9848
+ * A capped type group is 300 rows, and several can be open at once. Giving each row a tab stop made the
9849
+ * tree keyboard-REACHABLE and the page keyboard-hostile: Tab had to be pressed hundreds of times to get
9850
+ * past the legend. This is the roving-tabindex pattern the editor already uses for its long selectable
9851
+ * lists — the active row is the selected one if it is on screen, else the first, and Arrow Up/Down move
9852
+ * both the focus and the stop. Tab then enters the list once and leaves it once.
9853
+ */
9854
+ function refTreeRoving(rows){
9855
+ const isSel=(n)=>String(n.className||'').split(/\s+/).includes('sel');
9856
+ const active=rows.find(isSel)||rows[0];
9857
+ rows.forEach((n)=>{n.tabIndex=n===active?0:-1;});
9858
+ rows.forEach((n,i)=>n.addEventListener('keydown',(e)=>{
9859
+ if(e.key!=='ArrowDown'&&e.key!=='ArrowUp')return;
9860
+ const next=rows[i+(e.key==='ArrowDown'?1:-1)];
9861
+ if(!next)return;
9862
+ e.preventDefault();e.stopPropagation();
9863
+ rows.forEach((m)=>{m.tabIndex=-1;});
9864
+ next.tabIndex=0;next.focus();
9865
+ }));
9866
+ }
9867
+
9868
+ /**
9869
+ * The tree for one reference, appended to its detail block.
9870
+ *
9871
+ * Renders NOTHING but a header until the user opens it, and nothing but group headers until they open a
9872
+ * group. That is what makes a 17,460-object file cost the same as a 19-object one on the way IN; opening
9873
+ * the tree itself is then one linear pass plus a header per storey×type (192 of them, on that file).
9874
+ */
9875
+ function buildRefTree(r,wrap){
9876
+ const geom=refGeom.get(r.id);
9877
+ const open=refTreeOpen.has(r.id);
9878
+ const hd=document.createElement('button');hd.type='button';hd.className='psethd';
9879
+ hd.setAttribute('aria-expanded',String(open));hd.setAttribute('aria-controls','reftree-'+r.id);
9880
+ const chev=Object.assign(document.createElement('span'),{className:'chev',textContent:'▸'});chev.setAttribute('aria-hidden','true');
9881
+ hd.append(chev,Object.assign(document.createElement('span'),{className:'psn',textContent:'What’s in this file'}),
9882
+ Object.assign(document.createElement('span'),{className:'psc',textContent:geom?String((geom.objects||[]).length):''}));
9883
+ hd.dataset.tip='List the objects inside this reference, grouped by storey and IFC type';
9884
+ wrap.appendChild(hd);
9885
+ const body=document.createElement('div');body.className='psetbody'+(open?' open':'');body.id='reftree-'+r.id;
9886
+ wrap.appendChild(body);
9887
+ hd.addEventListener('click',()=>{
9888
+ if(refTreeOpen.has(r.id))refTreeOpen.delete(r.id);else refTreeOpen.add(r.id);
9889
+ renderRefsTab();
9890
+ });
9891
+ if(!open)return;
9892
+
9893
+ // NOT AN EMPTY TREE — say which of the several reasons it is. A tree that renders nothing is
9894
+ // indistinguishable from a file with nothing in it, and only one of those is true at a time.
9895
+ if(!geom){
9896
+ const n=Object.assign(document.createElement('div'),{className:'dnote'});
9897
+ n.textContent=refLoading.has(r.id)?'Still reading this file…'
9898
+ :refUnresolved.has(r.id)?'Its file is missing from this project, so there is nothing to list.'
9899
+ :refFailed.has(r.id)?'Its geometry could not be loaded — use ⋯ ▸ Reload its geometry.'
9900
+ // The reader ANSWERED for this one and had nothing drawable to give. The row already says
9901
+ // "· nothing to draw"; saying "never read" three pixels below it would contradict it.
9902
+ :refEmpty.has(r.id)?'This file was read, but it holds nothing we can draw — so there is nothing to list.'
9903
+ :'This file hasn’t been read yet.';
9904
+ body.appendChild(n);return;
9905
+ }
9906
+ const objects=geom.objects||[];
9907
+ // Geometry present and empty is a FIFTH state, not a sixth branch of the one above: a cache entry that
9908
+ // predates the reader's own emptiness check returns ok with no objects. Without this the tree drew a
9909
+ // filter box over an empty bordered rectangle and said nothing at all — the exact outcome the comment
9910
+ // above promises to prevent.
9911
+ if(!objects.length){
9912
+ body.appendChild(Object.assign(document.createElement('div'),
9913
+ {className:'dnote',textContent:'Reading this file returned no objects — use ⋯ ▸ Reload its geometry to try again.'}));
9914
+ return;
9915
+ }
9916
+ const groups=groupReferenceObjects(objects);
9917
+ const q=(refTreeQuery.get(r.id)||'').trim().toLowerCase();
9918
+
9919
+ // The filter, inside the tree it filters — it is scoped to ONE reference's objects, so it is not a
9920
+ // peer of the tab's own controls. It reuses the property popover's SHAPE, not its CSS: every
9921
+ // `.ppsearch` rule is scoped to #propPop and cannot reach this panel, so the class is styled here.
9922
+ const sb=document.createElement('div');sb.className='reftreesearch';
9923
+ const inp=document.createElement('input');inp.type='text';inp.placeholder='Filter by name, type or storey…';
9924
+ inp.id=REF_TREE_SEARCH_ID;
9925
+ inp.autocomplete='off';inp.value=refTreeQuery.get(r.id)||'';
9926
+ inp.setAttribute('role','searchbox');inp.setAttribute('aria-label','Filter the objects in this reference');
9927
+ inp.addEventListener('keydown',(e)=>e.stopPropagation()); // the editor's global shortcuts must not see typing
9928
+ // TYPING REPAINTS THE TAB, WHICH DESTROYS THIS INPUT, so the focus has to be put back or the NEXT
9929
+ // character lands on the document — where `a` arms Add-member and Backspace deletes the selection.
9930
+ // (That is not hypothetical: the first version looked this up with a selector that could never match,
9931
+ // and typing "beam" into the filter armed a tool.) Found by id, because the id is the one thing that
9932
+ // survives the rebuild, and the whole selection is restored, so editing mid-word works.
9933
+ //
9934
+ // NOT WHILE COMPOSING. An IME builds one character out of several keystrokes and holds that state on
9935
+ // the INPUT ELEMENT; replacing the element mid-composition drops or mangles it. `isComposing` means
9936
+ // the user is mid-character, so the tree simply does not repaint until `compositionend` fires — the
9937
+ // filter is one keystroke stale for the duration, which nobody can see, and the character survives.
9938
+ //
9939
+ // Undo history is NOT preserved: it belongs to the element, and this rebuilds the element. Fixing that
9940
+ // means repainting the tree without rebuilding the whole tab, which is a larger change than this pass.
9941
+ const refilter=()=>{
9942
+ const from=inp.selectionStart,to=inp.selectionEnd,dir=inp.selectionDirection;
9943
+ refTreeQuery.set(r.id,inp.value);renderRefsTab();
9944
+ const again=document.getElementById(REF_TREE_SEARCH_ID);
9945
+ if(!again){console.error('[reference] the tree filter did not survive its repaint — typing would now reach the editor shortcuts');return;}
9946
+ again.focus();
9947
+ try{again.setSelectionRange(from,to,dir||'none');}catch(e){console.debug('[reference] could not restore the filter selection',e);}
9948
+ };
9949
+ inp.addEventListener('input',(e)=>{ if(e&&e.isComposing)return; refilter(); });
9950
+ inp.addEventListener('compositionend',refilter);
9951
+ sb.appendChild(inp);body.appendChild(sb);
9952
+
9953
+ const box=document.createElement('div');box.className='reftree';body.appendChild(box);
9954
+ const expanded=refTreeGroups.get(r.id)||new Map();
9955
+
9956
+ // MATCHED ONCE, NOT PER GROUP. Every count below is a lookup into this set. The old shape re-ran the
9957
+ // string work of `refTreeMatches` for each object once for its storey's count and again for its type's
9958
+ // count, and it measured 732 ms per keystroke — a filter you can outrun by typing.
9959
+ const hits=q?new Set():null;
9960
+ if(q)for(let i=0;i<objects.length;i++)if(refTreeMatches(objects[i],q))hits.add(i);
9961
+ const matched=q?hits.size:objects.length;
9962
+
9963
+ /**
9964
+ * A filter opens the groups it matched — UNLESS it matched more than one screenful.
9965
+ *
9966
+ * "Never hide a match behind a collapsed chevron" is the right instinct and it does not survive this
9967
+ * building: filtering Daldy for "mullion" matches 8,000-odd objects across ten storeys, and force-
9968
+ * expanding all of them built 2,795 rows and nine separate "showing 300 of …" lines — a wall, from a
9969
+ * rule meant to be helpful. Above the cap the groups keep whatever the user had open, and their headers
9970
+ * still read "N of M", so where the matches are is stated rather than dumped.
9971
+ */
9972
+ const wide=!!q&&matched>REF_TREE_CAP;
9973
+ // A SINGLE GROUP AT ITS LEVEL OPENS ITSELF — with nothing to choose between, a click to reach the only
9974
+ // content is a toll. It is also what makes the storey-less file and the single-storey file (Motebello)
9975
+ // land somewhere sensible with no special case.
9976
+ //
9977
+ // A CHOICE IS REMEMBERED AGAINST THE FILTER IT WAS MADE UNDER, which is what lets both of these be
9978
+ // true at once: a filter opens the groups it matched, AND a header still obeys a click while filtering.
9979
+ // Storing the choice alone could not do that — a storey closed with no filter went on suppressing its
9980
+ // own matches afterwards, so a user could type a precise query, read "(2 of 6)" on the header, and be
9981
+ // shown nothing. Keying the choice to the query means the collapse applies when that query returns
9982
+ // (including when it returns to empty) and stays out of the way under a different one.
9983
+ const isOpen=(key,only)=>{
9984
+ const chose=expanded.get(key);
9985
+ // `q:null` is the reveal's own mark: "this group holds the selection, keep it open under ANY query".
9986
+ // Without it, groups opened only to show a selected object collapsed the moment the filter changed —
9987
+ // including clearing it — so an object picked while filtering vanished from the tree the instant the
9988
+ // user emptied the box, while staying selected in 3D and in the panel.
9989
+ if(chose&&(chose.q===null||chose.q===q))return chose.open;
9990
+ if(q&&!wide)return true;
9991
+ return !!only;
9992
+ };
9993
+ const toggle=(key,wasOpen)=>{const s=new Map(refTreeGroups.get(r.id)||[]);
9994
+ s.set(key,{open:!wasOpen,q});refTreeGroups.set(r.id,s);renderRefsTab();};
9995
+ // THE STOREY TIER IS OMITTED ENTIRELY when the file records no storeys at all — chrome around a
9996
+ // grouping level that carries no information. One line says so instead, once.
9997
+ const flat=groups.length===1&&groups[0].storey===null;
9998
+ const built=[]; // every object row this paint produced, in order — see `refTreeRoving` at the end
9999
+ if(flat){
10000
+ const n=Object.assign(document.createElement('div'),{className:'dnote'});n.style.margin='0 0 4px';
10001
+ n.textContent='This file does not record storeys — its objects are grouped by type only.';
10002
+ box.appendChild(n);
10003
+ }
10004
+ groups.forEach((s,si)=>{
10005
+ const sKey=String(si);
10006
+ const sMatched=q?s.types.reduce((n,t)=>n+t.indices.reduce((m,i)=>m+(hits.has(i)?1:0),0),0):s.count;
10007
+ if(q&&!sMatched)return; // a storey with no match is gone, not greyed
10008
+ const sOpen=flat||isOpen(sKey,groups.length===1);
10009
+ if(!flat){
10010
+ const h=document.createElement('div');h.className='cat-hdr';h.setAttribute('role','button');
10011
+ h.setAttribute('aria-expanded',String(sOpen));
10012
+ h.append(Object.assign(document.createElement('span'),{className:'cat-chevron',textContent:sOpen?'▼':'▶'}),
10013
+ Object.assign(document.createElement('span'),{className:'cat-label',textContent:s.storey||'No storey recorded'}),
10014
+ // "N of M" WHILE FILTERING. A count that quietly means something different depending on a text box
10015
+ // above it is the same class of wrong as a stale one.
10016
+ Object.assign(document.createElement('span'),{className:'cat-count',textContent:q?'('+sMatched+' of '+s.count+')':'('+s.count+')'}));
10017
+ h.dataset.tip=(s.storey||'The file records no storey for these objects')+' — '+s.count+' object'+(s.count===1?'':'s');
10018
+ h.addEventListener('click',()=>toggle(sKey,sOpen));
10019
+ refTreeKeyOperable(h);
10020
+ box.appendChild(h);
10021
+ }
10022
+ if(!sOpen)return;
10023
+ // TWO TYPES CAN SHARE A PLAIN WORD, and Daldy proves it: `IFCWALL` and `IFCWALLSTANDARDCASE` both
10024
+ // read "Wall", so its LG storey listed "Wall (388)" directly above "Wall (52)" — two groups a user
10025
+ // cannot tell apart, differing only in a number. The raw token comes back for exactly those, and only
10026
+ // those: showing it on every header does not fit a 340px panel sixteen times over, and showing it
10027
+ // never leaves the list lying about what is in the file. (Found by running it on the real building.)
10028
+ const words=(t)=>t.words||'No type recorded';
10029
+ const dup=new Set(),once=new Set();
10030
+ s.types.forEach((t)=>{const w=words(t);if(once.has(w))dup.add(w);else once.add(w);});
10031
+ s.types.forEach((t,ti)=>{
10032
+ const tKey=si+':'+ti;
10033
+ const tHits=q?t.indices.filter((i)=>hits.has(i)):t.indices;
10034
+ if(q&&!tHits.length)return;
10035
+ const tOpen=isOpen(tKey,s.types.length===1);
10036
+ const h=document.createElement('div');h.className='cat-hdr'+(flat?'':' sub');h.setAttribute('role','button');
10037
+ h.setAttribute('aria-expanded',String(tOpen));
10038
+ h.append(Object.assign(document.createElement('span'),{className:'cat-chevron',textContent:tOpen?'▼':'▶'}),
10039
+ // The PLAIN WORD only. "Generic element (IFCBUILDINGELEMENTPROXY)" does not fit a 340px panel
10040
+ // repeated sixteen times, and the raw token is already shown on the object itself once selected —
10041
+ // except where two of this storey's types share that word, when it is the only thing separating them.
10042
+ Object.assign(document.createElement('span'),{className:'cat-label',textContent:words(t)+(dup.has(words(t))&&t.type?' · '+t.type:'')}),
10043
+ Object.assign(document.createElement('span'),{className:'cat-count',textContent:q?'('+tHits.length+' of '+t.count+')':'('+t.count+')'}));
10044
+ h.dataset.tip=(t.type||'The file records no IFC type for these objects')+' — '+t.count+' object'+(t.count===1?'':'s');
10045
+ h.addEventListener('click',()=>toggle(tKey,tOpen));
10046
+ refTreeKeyOperable(h);
10047
+ box.appendChild(h);
10048
+ if(!tOpen)return;
10049
+ const list=tHits;
10050
+ // THE SELECTED ROW IS NEVER THE ONE THE CAP DROPS. Taking a blind first-300 made "drill in 3D and the
10051
+ // tree shows you the row" false for 8,910 of this group's 9,210 members — the reveal opened the right
10052
+ // headers and then found nothing to scroll to. When the selection sits past the cap the window slides
10053
+ // to hold it, and the line below says so rather than still claiming the first 300.
10054
+ const want=(refSelectedId===r.id&&typeof refSelectedObjIdx==='number')?list.indexOf(refSelectedObjIdx):-1;
10055
+ let from=0;
10056
+ if(want>=REF_TREE_CAP)from=Math.min(want-(REF_TREE_CAP>>1),list.length-REF_TREE_CAP);
10057
+ const shown=list.slice(from,from+REF_TREE_CAP);
10058
+ // The ordinal of every row in one pass, rather than an indexOf per row: on a 9,210-index group a
10059
+ // filter whose matches sit late cost ~2.8M comparisons on EVERY keystroke.
10060
+ const ord=new Map();t.indices.forEach((i,n)=>ord.set(i,n+1));
10061
+ shown.forEach((idx)=>{ const row=buildRefObjRow(r,objects[idx],idx,t,flat,ord.get(idx)); built.push(row); box.appendChild(row); });
10062
+ if(list.length>REF_TREE_CAP){
10063
+ const more=Object.assign(document.createElement('div'),{className:'refcap'});
10064
+ more.textContent=from
10065
+ ?'Showing '+shown.length+' of '+list.length+', centred on the selected object — use the filter above to narrow this list.'
10066
+ :'Showing '+REF_TREE_CAP+' of '+list.length+' — use the filter above to narrow this list.';
10067
+ box.appendChild(more);
10068
+ }
10069
+ });
10070
+ });
10071
+ if(built.length)refTreeRoving(built);
10072
+ if(q&&!matched){
10073
+ const e=Object.assign(document.createElement('div'),{className:'lsempty'});
10074
+ e.textContent='No objects match “'+(refTreeQuery.get(r.id)||'').trim()+'”.';
10075
+ box.appendChild(e);
10076
+ }
10077
+ }
10078
+
10079
+ /**
10080
+ * Bring the tree to an object drilled into from the 3D view.
10081
+ *
10082
+ * ONLY IF THE TREE IS ALREADY OPEN. Ctrl+click in the canvas is not a request to rearrange the legend,
10083
+ * and opening a panel behind the user's back — expanding groups, scrolling a list they were not looking
10084
+ * at — is the kind of help that costs them their place. When the tree IS open the opposite is true: a
10085
+ * selection the tree cannot show is a tree disagreeing with the scene, so its groups open, the row
10086
+ * scrolls into view, and it flashes the way every other "you just navigated here" row in this panel does.
10087
+ *
10088
+ * TWO THINGS COULD HIDE THAT ROW and both are handled here rather than left to fail quietly: a filter the
10089
+ * object does not match (cleared, and the user is told, because a tree that silently drops the filter is
10090
+ * as confusing as one that silently ignores the selection), and a position past the row cap (handled by
10091
+ * the window in `buildRefTree`, which keys off the selection this function has already set).
10092
+ *
10093
+ * Returns false when it did nothing, so the caller can fall back to an ordinary repaint.
10094
+ */
10095
+ function revealRefTreeObject(refId,idx){
10096
+ if(!refTreeOpen.has(refId)||legendTab!=='refs')return false;
10097
+ const geom=refGeom.get(refId);
10098
+ const objects=geom&&geom.objects;
10099
+ if(!Array.isArray(objects)||!objects[idx])return false;
10100
+ const q=(refTreeQuery.get(refId)||'').trim().toLowerCase();
10101
+ const cleared=!!q&&!refTreeMatches(objects[idx],q);
10102
+ if(cleared)refTreeQuery.set(refId,'');
10103
+ const groups=groupReferenceObjects(objects);
10104
+ // `q:null` — open under ANY query, not just the one in the box right now. The path to the SELECTED
10105
+ // object is not a filter-scoped preference: filed against the current query, these opens evaporated as
10106
+ // soon as the user changed or cleared the filter, and the object they had just picked dropped out of
10107
+ // the tree while remaining lit in 3D. A later explicit click on the same header overwrites this.
10108
+ const s=new Map(refTreeGroups.get(refId)||[]);
10109
+ groups.forEach((st,si)=>st.types.forEach((t,ti)=>{
10110
+ if(t.indices.indexOf(idx)<0)return;
10111
+ s.set(String(si),{open:true,q:null});s.set(si+':'+ti,{open:true,q:null});
10112
+ }));
10113
+ refTreeGroups.set(refId,s);
10114
+ renderRefsTab();
10115
+ // SAID BEFORE ANYTHING ELSE CAN GO WRONG. Taking the filter away is a visible change to the user's own
10116
+ // state, so it is announced on every path that does it — including the one below that then fails to
10117
+ // find the row, which is exactly when an unexplained empty filter box would be most confusing.
10118
+ if(cleared)toast('Cleared the object filter to show the selected object');
10119
+ // Scoped to THIS reference's tree. Only the selected reference renders a detail block today, so an
10120
+ // unscoped lookup is right by accident; this makes it right on purpose.
10121
+ const row=document.querySelector('#reftree-'+refId+' .refobjrow[data-idx="'+idx+'"]');
10122
+ if(!row){console.error('[reference] object',idx,'of',refId,'is selected but has no row in the open tree');return true;}
10123
+ try{row.scrollIntoView({block:'nearest'});}catch(e){console.debug('[reference] scrollIntoView unavailable',e);}
10124
+ row.classList.add('flash');setTimeout(()=>row.classList.remove('flash'),900);
10125
+ return true;
10126
+ }
10127
+
10128
+ /** "1st", "2nd", "3rd", "4th" — including the 11th/12th/13th exceptions, which the naive rule gets wrong. */
10129
+ function ordinalSuffix(n){
10130
+ const t=n%100;
10131
+ if(t>=11&&t<=13)return 'th';
10132
+ return ['th','st','nd','rd'][n%10]||'th';
10133
+ }
10134
+
10135
+ /**
10136
+ * One object row.
10137
+ *
10138
+ * THE NAME IS NOT ENOUGH AND THIS FILE PROVES IT: twelve of Motebello's nineteen objects are called
10139
+ * "Betonfertigteil" and two are called "-". So the row carries its position within its own type group as
10140
+ * well — `#4/19` on that file, since all nineteen share one type — which always exists and is the one
10141
+ * thing that distinguishes two otherwise identical rows. The caller passes the ordinal in because it can
10142
+ * number a whole group in one pass; finding it per row was a linear scan of up to 9,210 indices.
10143
+ *
10144
+ * THE ORDINAL IS COUNTED AGAINST THE UNFILTERED GROUP. Numbering the filtered view would renumber every
10145
+ * object as the user types, which is a statement about the file that changes with a text box.
10146
+ */
10147
+ function buildRefObjRow(r,o,idx,group,flat,ordinal){
10148
+ const row=document.createElement('div');
10149
+ row.className='refobjrow'+(refSelectedId===r.id&&refSelectedObjIdx===idx?' sel':'');
10150
+ if(flat)row.style.paddingLeft='20px';
10151
+ row.dataset.idx=String(idx);
10152
+ // Enter/Space select, like `refTreeKeyOperable` — but selecting REPAINTS the tab, which destroys this
10153
+ // row, and the focus went to the document with it. A keyboard user who picks a row was then back at
10154
+ // the top of the panel and could not carry on arrowing. So the focus is put on the row that replaced
10155
+ // this one. (Rows do not own a tab stop of their own — `refTreeRoving` shares one between them.)
10156
+ row.setAttribute('role','button');
10157
+ row.addEventListener('keydown',(e)=>{
10158
+ if(e.key!=='Enter'&&e.key!==' ')return;
10159
+ e.preventDefault();e.stopPropagation();
10160
+ row.click();
10161
+ const again=document.querySelector('#reftree-'+r.id+' .refobjrow[data-idx="'+idx+'"]');
10162
+ if(again)again.focus();
10163
+ });
10164
+ const named=refObjNamed(o&&o.name);
10165
+ const label=named?String(o.name).trim():(group.words||'Object');
10166
+ row.appendChild(Object.assign(document.createElement('span'),{className:'ronm',textContent:label}));
10167
+ if(ordinal>0)row.appendChild(Object.assign(document.createElement('span'),{className:'rord',textContent:'#'+ordinal+'/'+group.count}));
10168
+ // The ordinal badge is the one thing on this row whose MEANING is not self-evident — `#4/19` could be
10169
+ // read as a date or an id — so the tooltip spells it out. It is the only place that can: the row is
10170
+ // already dense, and a second visible label per row on a 340px rail costs more than it explains.
10171
+ row.dataset.tip=(named?String(o.name).trim():'This file gives it no name')+' — '+(o&&o.ifcType||'no IFC type')
10172
+ +(o&&o.storey?' · '+String(o.storey).trim():'')
10173
+ +(ordinal>0?' — the '+ordinal+ordinalSuffix(ordinal)+' of '+group.count+' with this type in this storey':'');
10174
+ // THE SAME CALL Ctrl+click MAKES. Two routes into one selection, so they cannot drift into two.
10175
+ row.addEventListener('click',()=>{
10176
+ const v=window.Steel3DView;
10177
+ if(!v||!v.selectReferenceObject){
10178
+ console.error('[reference] the 3D view is not available, so a tree row cannot select',r.id,idx);
10179
+ toast('The 3D view isn’t ready yet — try again in a moment');return;
10180
+ }
10181
+ // Visibility is NOT what makes this fail — `setReferences` builds a mesh for every object whether the
10182
+ // reference is shown or not, so a hidden reference selects fine. What fails is the panel and the
10183
+ // renderer disagreeing about how many objects there are, and telling the user to toggle an eye icon
10184
+ // would send them after the wrong thing. A throw is caught for the same reason: it would otherwise
10185
+ // escape the listener and leave the tree half-drawn with no message at all.
10186
+ let ok=false;
10187
+ try{ok=v.selectReferenceObject(r.id,idx);}
10188
+ catch(e){
10189
+ console.error('[reference] selecting object',idx,'of',r.id,'threw',e);
10190
+ toast('Could not select that object — use ⋯ ▸ Reload its geometry');return;
10191
+ }
10192
+ if(!ok){
10193
+ console.error('[reference] object',idx,'of',r.id,'has no mesh — the panel and the 3D view disagree');
10194
+ toast('That object isn’t in the 3D scene — use ⋯ ▸ Reload its geometry');
10195
+ }
10196
+ });
10197
+ return row;
10198
+ }
10199
+
9213
10200
  /** A file size a human recognises from their file manager. KB under a megabyte, MB above it. */
9214
10201
  function fileSizeWords(bytes){
9215
10202
  const n=Number(bytes)||0;
@@ -9272,7 +10259,12 @@ function openRefRowMenu(r,anchorEl){closeRefRowMenu();
9272
10259
  if(nativeModelBounds())m.append(mk(REF_MOVE_LABEL,()=>refMoveToOrigin(r.id)));
9273
10260
  m.append(mk('Reload its geometry',()=>{
9274
10261
  if(refDisp(r).locked){toast('“'+r.name+'” is locked — unlock it to reload it');return;} // the lock freezes reload, as the schema says
9275
- refGeom.delete(r.id);refFailed.delete(r.id);refEmpty.delete(r.id);refUnresolved.delete(r.id);loadReferenceGeometry(r.id,{rebuild:true});}));
10262
+ refGeom.delete(r.id);refFailed.delete(r.id);refEmpty.delete(r.id);refUnresolved.delete(r.id);
10263
+ // The tree's group keys are POSITIONAL ('2:1' is the second storey's second type), so a
10264
+ // re-read that adds, drops or reorders anything makes them address different groups. Dropped
10265
+ // rather than migrated: there is no identity here to migrate them by.
10266
+ refTreeGroups.delete(r.id);refTreeQuery.delete(r.id);
10267
+ loadReferenceGeometry(r.id,{rebuild:true});}));
9276
10268
  m.appendChild(document.createElement('hr'));
9277
10269
  m.appendChild(mk('Remove',()=>refRemove(r),true));
9278
10270
  document.body.appendChild(m);
@@ -9302,8 +10294,9 @@ async function refRemove(r){
9302
10294
  adoptReferenceWrite(d.etag);
9303
10295
  const i=refList().findIndex(x=>x&&x.id===r.id);if(i>=0)C.reference_models.splice(i,1);
9304
10296
  refGeom.delete(r.id);refUnresolved.delete(r.id);refFailed.delete(r.id);refEmpty.delete(r.id);
9305
- if(refSelectedId===r.id)refSelectedId=null;
9306
- pushReferences();renderRefsTab();
10297
+ refTreeOpen.delete(r.id);refTreeGroups.delete(r.id);refTreeQuery.delete(r.id); // the tree goes with the reference
10298
+ 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
10299
+ pushReferences();renderRefsTab();panel();
9307
10300
  }catch(_){toast('Could not remove that reference');}
9308
10301
  }
9309
10302
 
@@ -9321,8 +10314,24 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9321
10314
  // `riProbeCentre` is reset alongside the rest on every open — it used to survive from the PREVIOUS
9322
10315
  // file, which only failed to matter because `riInsert` bails on a missing `riSha`.
9323
10316
  let riSha=null,riName='',riVerdict=null,riProbeCentre=null,riSoftT=null,riBusy=false;
10317
+ // ── ONE ATTEMPT'S IDENTITY (#580) ────────────────────────────────────────────────────────────────
10318
+ // `riRun` names the current attempt and `riAbort` is its escape hatch. Both exist because Cancel
10319
+ // used to only HIDE the modal: the upload kept going, and when the abandoned probe finally answered
10320
+ // it wrote its results into whatever the modal was showing by then. The independent QA pass caught
10321
+ // exactly that — cancel a 66 MB file, drop an 18 KB one, and be shown the big file's "5878 objects"
10322
+ // above the small file's name, one click away from adding the wrong thing.
10323
+ //
10324
+ // AND ABORTING IS NOT MERELY TIDY. The server cancels a reader run when its client disconnects, and
10325
+ // that guard could never fire from this UI, because the browser never disconnected — Cancel left the
10326
+ // request in flight, so a cancelled 66 MB read went on holding the single run lock for its full
10327
+ // duration and the next import queued behind the file the user had just given up on.
10328
+ let riRun=0,riAbort=null;
10329
+ /** End the current attempt: nothing it started may touch the modal, and its upload stops now. */
10330
+ const riStop=()=>{riRun++;if(riAbort){try{riAbort.abort();}catch(_){/* already settled */}riAbort=null;}};
9324
10331
  const riClearSoft=()=>{if(riSoftT){clearTimeout(riSoftT);riSoftT=null;}};
10332
+ let riStageNow='drop';
9325
10333
  const riStage=s=>{ // 'drop' | 'prog' | 'confirm'
10334
+ riStageNow=s;
9326
10335
  ri$('riDropStage').style.display=s==='drop'?'':'none';
9327
10336
  ri$('riProgStage').style.display=s==='prog'?'':'none';
9328
10337
  ri$('riConfirmStage').style.display=s==='confirm'?'':'none';
@@ -9336,10 +10345,11 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9336
10345
  function openRefImport(){
9337
10346
  if(!MODEL_V2){toast('Reference models need this project on the model-level contract');return;}
9338
10347
  if(!view3d){toast('Switch to the 3D view to add a reference model');return;}
10348
+ riStop(); // a previous attempt's in-flight probe must not answer into this one
9339
10349
  riSha=null;riName='';riVerdict=null;riProbeCentre=null;riErr('');ri$('riDrop').classList.remove('drag');
9340
10350
  riStage('drop');ri$('refImportModal').style.display='flex';}
9341
10351
  window.openRefImport=openRefImport;
9342
- function riClose(){riClearSoft();ri$('refImportModal').style.display='none';}
10352
+ function riClose(){riStop();riClearSoft();ri$('refImportModal').style.display='none';}
9343
10353
 
9344
10354
  const RI_MAX_BYTES=150*1024*1024; // mirrors MAX_BYTES in server/reference-import.ts (pinned by the parity test)
9345
10355
  function riReadFile(f){ if(!f||riBusy)return;riErr('');
@@ -9347,19 +10357,28 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9347
10357
  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;}
9348
10358
  riName=f.name;
9349
10359
  const fr=new FileReader();
9350
- fr.onerror=()=>{riStage('drop');riErr('Could not read that file.');};
9351
- fr.onload=()=>riProbe(String(fr.result||''),f);
10360
+ // The read itself is async, so it is part of the attempt: a 66 MB file still being turned into a
10361
+ // data URL when the user hits Cancel must not go on to probe.
10362
+ const mine=riRun;
10363
+ fr.onerror=()=>{if(mine!==riRun)return;riStage('drop');riErr('Could not read that file.');};
10364
+ fr.onload=()=>{if(mine!==riRun)return;riProbe(String(fr.result||''),f,mine);};
9352
10365
  riStage('prog');riProg('Reading “'+f.name+'”…');
9353
10366
  fr.readAsDataURL(f);}
9354
10367
 
9355
- async function riProbe(dataUrl,f){
10368
+ async function riProbe(dataUrl,f,mine){
9356
10369
  riProg('Checking what “'+f.name+'” says about itself…','Still checking — a large model takes a moment.');
10370
+ riAbort=new AbortController();
10371
+ const signal=riAbort.signal;
9357
10372
  try{
9358
- const res=await fetch(refApi('/probe'),{method:'POST',headers:{'content-type':'application/json'},
10373
+ const res=await fetch(refApi('/probe'),{method:'POST',signal,headers:{'content-type':'application/json'},
9359
10374
  // The model's CENTRE rides along with its span: "off-screen" is a question about the distance
9360
10375
  // between the reference and the steel, and the server has no other way to know where the steel is.
9361
10376
  body:JSON.stringify({dataUrl,name:f.name,nativeSpan:nativeModelSpan(),nativeCenter:nativeModelCentre()})});
9362
10377
  const d=await res.json().catch(()=>({}));
10378
+ // THE ANSWER IS ONLY OURS IF THE ATTEMPT IS STILL THE CURRENT ONE. Abort is best-effort — a
10379
+ // response already on the wire lands anyway — so the id is what actually stops a cancelled
10380
+ // file's facts being written under a different file's name.
10381
+ if(mine!==riRun)return;
9363
10382
  riClearSoft();
9364
10383
  if(!res.ok||!d.ok){riStage('drop');riErr(d.error||'Could not read that file.');return;}
9365
10384
  riSha=d.sha;riVerdict=d.verdict||null;
@@ -9376,7 +10395,11 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9376
10395
  ri$('riBytes').textContent=fileSizeWords(d.bytes||0);
9377
10396
  riShowVerdict(d.warn,d.bytes);
9378
10397
  riStage('confirm');
9379
- }catch(_){riClearSoft();riStage('drop');riErr('Could not reach the reader — check the app is running.');}}
10398
+ }catch(e){
10399
+ // An abort is the user's own Cancel, not a failure to report at them.
10400
+ if(mine!==riRun||(e&&e.name==='AbortError'))return;
10401
+ riClearSoft();riStage('drop');riErr('Could not reach the reader — check the app is running.');}
10402
+ finally{if(mine===riRun)riAbort=null;}}
9380
10403
 
9381
10404
  /** The advisory. AMBER, never red: a scale or position guess is an offer, not something being broken. */
9382
10405
  function riShowVerdict(warn,bytes){
@@ -9401,7 +10424,21 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9401
10424
 
9402
10425
  async function riInsert(){
9403
10426
  if(!riSha||riBusy)return;riBusy=true;
9404
- let inserted=null,d=null;
10427
+ // The insert is the SAME attempt as the probe that fed it, and Cancel stays visible for the whole
10428
+ // of it (the ✕ is hidden mid-run precisely so Cancel owns the exit). Without an identity, hitting
10429
+ // Cancel while "Reading the geometry…" was showing hid the modal and then committed the reference
10430
+ // anyway — the one outcome a Cancel must never produce.
10431
+ //
10432
+ // WHAT THE SERVER GUARANTEES, stated precisely rather than optimistically (an earlier version of
10433
+ // this comment claimed a cancelled insert "leaves nothing behind", which is not what the staged
10434
+ // order buys on its own): the route asks whether we have gone after the read and again inside the
10435
+ // project lock, and refuses to commit if we have — so an abort before that last check leaves the
10436
+ // copy rolled back and nothing written. It cannot refuse in the sliver between committing and its
10437
+ // response reaching us; that one is handled below, by releasing the claim so the broadcast lands.
10438
+ const mine=riRun;
10439
+ riAbort=new AbortController();
10440
+ const signal=riAbort.signal;
10441
+ let inserted=null,d=null,hadDrill=false; // `hadDrill` is read by the presentation half below, after the insert has already cleared the index
9405
10442
  const takeOrigin=!!ri$('riVerdict').querySelector('button.on')&&riVerdict&&riVerdict.offscreen;
9406
10443
  // Computed from the PROBE's own centre, which is what the offer was based on, and TOWARDS THE
9407
10444
  // MODEL'S CENTRE rather than the world origin — the same correction `refMoveToOrigin` carries, for
@@ -9414,23 +10451,39 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9414
10451
  riStage('prog');riProg('Reading the geometry…','Still reading — a whole building takes a moment.');
9415
10452
  try{
9416
10453
  const mid=newMutationId();claimMutation(mid);
9417
- const res=await fetch(refApi(''),{method:'POST',headers:{'content-type':'application/json','x-floless-mutation-id':mid},
10454
+ const res=await fetch(refApi(''),{method:'POST',signal,headers:{'content-type':'application/json','x-floless-mutation-id':mid},
9418
10455
  // The placement rides the INSERT, so the choice the user made in the modal is committed with
9419
10456
  // the reference rather than by a debounced PUT afterwards. Applying it in the presentation
9420
10457
  // block left it outside the point of no return: a closed tab or a save conflict would leave
9421
10458
  // the server holding the site coordinates the user had just asked to move away from.
9422
10459
  body:JSON.stringify({sha:riSha,name:riName,...(takeOrigin&&riOriginShift?{placement:{origin:riOriginShift}}:{})})});
9423
10460
  d=await res.json().catch(()=>({}));
10461
+ if(mine!==riRun){
10462
+ // Cancelled while this was in flight. The server refuses to commit for a client that has gone
10463
+ // — it asks twice, after the read and again inside the project lock — but it cannot refuse in
10464
+ // the sliver between committing and this response reaching us, so that sliver is handled here
10465
+ // rather than asserted away. RELEASING THE CLAIM is what handles it: the id was claimed so our
10466
+ // own echo would not be replayed at us, and if the write DID land, suppressing its broadcast
10467
+ // is precisely what would leave a reference committed on disk and invisible in the editor —
10468
+ // where the next full save could quietly drop it. Released, the broadcast reconciles instead.
10469
+ releaseMutation(mid);
10470
+ return;
10471
+ }
9424
10472
  riClearSoft();
9425
10473
  if(!res.ok||!d.ok){riStage('drop');riErr(d.error||'Could not add that reference.');return;}
9426
10474
  adoptReferenceWrite(d.etag);
9427
10475
  if(!Array.isArray(C.reference_models))C.reference_models=[];
9428
10476
  C.reference_models.push(d.reference);
9429
- refGeom.set(d.reference.id,{objects:d.objects||[],dropped:d.dropped||0,spanMm:d.spanMm||0,colorsAvailable:d.colorsAvailable===undefined?null:d.colorsAvailable});
9430
- refSelectedId=d.reference.id;
10477
+ refGeom.set(d.reference.id,refGeomFrom(d)); // the same normaliser the geometry route's arrival uses — one shape, one spelling
10478
+ hadDrill=refSelectedObjIdx!==null; // …before this line drops it; the presentation half below needs to know
10479
+ refSelectedId=d.reference.id;refSelectedObjIdx=null;
9431
10480
  inserted=d.reference;
9432
- }catch(e){riClearSoft();riStage('drop');riErr('Could not add that reference.');console.error('[reference] insert failed',e);return;}
9433
- finally{riBusy=false;}
10481
+ }catch(e){
10482
+ // Aborted: no response at all, so we cannot know whether the write landed. Same reasoning as
10483
+ // above — release the claim so a broadcast that does arrive is applied rather than swallowed.
10484
+ if(mine!==riRun||(e&&e.name==='AbortError')){releaseMutation(mid);return;}
10485
+ riClearSoft();riStage('drop');riErr('Could not add that reference.');console.error('[reference] insert failed',e);return;}
10486
+ finally{riBusy=false;if(mine===riRun)riAbort=null;}
9434
10487
  // ── PAST THE POINT OF NO RETURN. Everything above is the transaction; everything below is showing
9435
10488
  // it. They were one try, and a throw in the presentation half ran riErr() on a modal riClose() had
9436
10489
  // already hidden — so the user saw NOTHING while the reference was committed and on disk, and the
@@ -9445,13 +10498,26 @@ function adoptReferenceWrite(etag){if(!etag)return;const prev=serverEtag;serverE
9445
10498
  // WITH the insert — see the request body — so there is nothing to apply here.)
9446
10499
  if(window.Steel3DView&&window.Steel3DView.frameReference)window.Steel3DView.frameReference(inserted.id);
9447
10500
  renderRefsTab();
10501
+ // AND REPAINT THE INSPECT PANEL — but only if it was showing an object. The import wrote
10502
+ // `refSelectedId`/`refSelectedObjIdx` itself before `pushReferences`, so by the time the 3D layer
10503
+ // selects the new reference the editor state already matches and `onReferenceSelect` returns early
10504
+ // without repainting. Drill into an object, import a second reference, and the panel would go on
10505
+ // describing the object inside the FIRST one while everything else on screen had moved to the new
10506
+ // file. Gated for the same reason the geometry arrival is: an unconditional repaint here would
10507
+ // throw away whatever else the inspector was in the middle of. (Codex review, both halves.)
10508
+ if(hadDrill)panel();
9448
10509
  toast('Added “'+inserted.name+'” as a reference'+(d.dropped?' ('+d.dropped+' object'+(d.dropped===1?'':'s')+' had nothing to draw)':''));
9449
10510
  }catch(e){
9450
10511
  console.error('[reference] added, but the view could not be updated',e);
9451
10512
  toast('Added “'+inserted.name+'” — reload the view to see it');
9452
10513
  }}
9453
10514
 
9454
- ri$('riClose').onclick=riClose;ri$('riCancel').onclick=riClose;ri$('riBackdrop').onclick=riClose;
10515
+ ri$('riClose').onclick=riClose;ri$('riCancel').onclick=riClose;
10516
+ // THE BACKDROP IS NOT AN EXIT MID-RUN. `riStage` hides the ✕ during 'prog' so that Cancel owns the
10517
+ // exit — and the backdrop, a full-viewport overlay that looks like nothing at all, quietly offered
10518
+ // the same abort to a stray click just outside the panel. Hiding one of two identical exits and
10519
+ // leaving the invisible one is the version of that rule that does not hold. (UX review, #580.)
10520
+ ri$('riBackdrop').onclick=()=>{if(riStageNow!=='prog')riClose();};
9455
10521
  ri$('riInsert').onclick=riInsert;
9456
10522
  ri$('riDrop').onclick=()=>ri$('riFile').click();
9457
10523
  ri$('riDrop').onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();ri$('riFile').click();}};