@floless/app 0.134.2 → 0.134.4

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.
@@ -470,6 +470,7 @@
470
470
  .sw{width:12px;height:12px;border-radius:2px;display:inline-block}
471
471
  .swc{width:14px;height:14px;padding:0;border:1px solid var(--ctrl-border);border-radius:3px;cursor:pointer;background:none;flex:none;-webkit-appearance:none;appearance:none}
472
472
  .swc::-webkit-color-swatch-wrapper{padding:0} .swc::-webkit-color-swatch{border:none;border-radius:2px}
473
+ .swc::-moz-color-swatch{border:none;border-radius:2px}
473
474
  .hint{color:var(--mut);font-size:12px;line-height:1.5}
474
475
  .seg2{display:flex;border:1px solid var(--line);border-radius:6px;overflow:hidden;height:28px;margin-top:8px}
475
476
  .seg2 button{flex:1;border:0;border-radius:0;background:transparent;color:var(--mut)}
@@ -511,11 +512,13 @@
511
512
  input:disabled{opacity:.55;cursor:default}
512
513
  .badge{display:block;background:var(--brand);color:var(--brand-ink);text-align:center;font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:5px;border-radius:6px;margin-bottom:10px}
513
514
  .pick{color:var(--brand)!important}
514
- rect.lblhot{cursor:pointer;fill:rgba(251,191,36,.10);stroke:#fbbf24;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
515
- rect.lblhot:hover{fill:rgba(251,191,36,.28)}
515
+ rect.lblhot{cursor:pointer;fill:rgba(251,191,36,.10);stroke:#fbbf24;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
516
+ rect.lblhot:hover{fill:rgba(251,191,36,.28)}
517
+ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stroke-width:2;fill:rgba(251,191,36,.28);filter:drop-shadow(0 0 4px var(--brand))}
516
518
  rect.dethot{cursor:pointer;fill:rgba(168,85,247,.16);stroke:#a855f7;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
517
519
  rect.dethot:hover{fill:rgba(168,85,247,.34)}
518
520
  text.dettx{fill:#ddd6fe;font:bold 11px system-ui;text-anchor:middle;pointer-events:none}
521
+ text.lbltx{fill:#fde68a;font:bold 11px system-ui;text-anchor:middle;pointer-events:none}
519
522
  /* clickable callout bubbles (Workstream B): section/elevation/detail-ref + plain details — navigable cross-references drawn on the plan in select mode. Existing palette only: purple #a855f7 (details), cyan #22d3ee (sections/elevations); solid vs dashed separates the kinds. */
520
523
  g.cohot{cursor:pointer}
521
524
  circle.cobub{stroke-width:1.5;vector-effect:non-scaling-stroke;opacity:.55}
@@ -524,9 +527,10 @@
524
527
  circle.cobub.k-detailref,circle.cobub.k-elev{stroke-dasharray:3 3}
525
528
  g.cohot:hover circle.cobub{opacity:1;stroke-width:2;filter:drop-shadow(0 0 4px currentColor)}
526
529
  text.cotx{fill:#e2e8f0;font:bold 11px system-ui;text-anchor:middle;dominant-baseline:central;pointer-events:none;opacity:.6}
527
- /* Vectorized PDF overlay — crisp, snappable drawing linework rendered from the filter vectors, NOT a
528
- blurry raster (only vector PDFs; scanned sheets still fall back to the raster image). */
530
+ /* Reviewed source-PDF context under crisp, snappable Filter vectors. The raster is deliberately quiet
531
+ and inert: it restores native printed callouts without becoming a second geometry authority. */
529
532
  rect.pdfsheet{fill:#f8fafc}
533
+ image.pdfref{opacity:.42;pointer-events:none}
530
534
  g.pdfvec{pointer-events:none}
531
535
  g.pdfvec path{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.82;stroke-linecap:round;stroke-linejoin:round}
532
536
  g.pdfvec circle{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.55}
@@ -826,6 +830,15 @@
826
830
  input[type=number] rule near the top, which is what the three origin fields were missing. Leaving
827
831
  the per-id copy here would just be the template for the next field to be patched one at a time. */
828
832
  #confTarget{width:54px;text-align:right;padding:4px 6px;font:13px system-ui}
833
+ #confTargetState{font-size:11px;color:var(--mut);white-space:nowrap}
834
+ .read-diag{margin:12px 0 0;padding:8px 10px;border:1px solid var(--warn-edge);border-radius:6px;color:var(--warn);background:var(--warn-bg);font-size:12px}
835
+ .read-group{margin:8px 0;padding:8px 10px;border:1px solid var(--line);border-radius:6px;background:var(--bg)}
836
+ .read-group-head{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-bottom:6px;color:var(--text);font-size:12px}
837
+ .read-field{display:grid;grid-template-columns:minmax(120px,1fr) minmax(150px,2fr) auto;gap:10px;padding:4px 0;border-top:1px solid var(--line);font-size:12px;align-items:baseline}
838
+ .read-field:first-of-type{border-top:0}.read-field .read-value{overflow-wrap:anywhere}.read-field .read-pct{font-variant-numeric:tabular-nums;white-space:nowrap}
839
+ .read-notes{margin:12px 0 0;padding:10px 12px;border:1px solid var(--line);border-radius:6px;background:var(--sunken)}
840
+ .read-notes h3{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);margin:0 0 5px}.read-notes ul{margin:0 0 10px;padding-left:18px}.read-notes ul:last-child{margin-bottom:0}.read-notes li{font-size:12px;line-height:1.45;overflow-wrap:anywhere}
841
+ #svg:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
829
842
  .mgrid{padding:14px;overflow:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(168px,1fr));gap:12px}
830
843
  .dcard{border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--bg)}
831
844
  .dcard .dprev{height:120px;display:flex;align-items:center;justify-content:center;background:var(--sunken);color:var(--mut);font-size:11px;text-align:center;padding:8px;line-height:1.4}
@@ -1821,7 +1834,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1821
1834
  <span class=stat id=reviewUnavailStat data-tip="The server could not check connections for moved steel this time" hidden>Review check unavailable</span>
1822
1835
  <span class=stat id=csStat data-tip="Coordinate system — Global by default. Set a local frame from the ⋯ menu for skewed framing.">Axes <b>Global</b></span>
1823
1836
  <span class=stat id=snapStat style="display:none" data-tip="Snap restricted for this operation — right-click the canvas to change; click here or press Esc to clear">Snap <b>—</b></span>
1824
- <span class=stat id=confStat data-tip="Confidence report — AI-read score vs. target. Click to review element evidence." style="display:none">Confidence <b id=confPct>—</b><span id=confTgt></span></span>
1837
+ <button data-command-id="steel.confidence-report" class=stat id=confStat data-tip="Confidence report — review recorded drawing evidence." style="display:none" aria-haspopup=dialog aria-controls=confModal><span id=confLabel>Confidence</span> <b id=confPct>—</b><span id=confTgt></span></button>
1825
1838
  <span class=stat id=saveStat data-tip="Edits auto-save in this browser (localStorage)">Saved</span>
1826
1839
  <span class=stat id=srcStat style="display:none"></span><span style="flex:1"></span>
1827
1840
  <button data-command-id="steel.undo" id=undoB data-tip="Undo (Ctrl+Z)">↶</button>
@@ -1881,7 +1894,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1881
1894
  <button data-command-id="steel.show-member-length" id=lenToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show the length of each selected member in 2D and 3D"><span class=mck aria-hidden=true></span>Member length</button>
1882
1895
  <button data-command-id="steel.position-gizmo" id=posGizmoToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show a drag handle on the selected member for moving it and rolling its section right in the 3D view"><span class=mck aria-hidden=true></span>Position handle</button>
1883
1896
  <button data-command-id="steel.show-property-labels" id=plToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide property labels in the 2D plan (the property selection is shared with 3D — this hides them here only)"><span class=mck aria-hidden=true></span>Property labels</button>
1884
- <button data-command-id="steel.show-reference-sheet" id=refToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the traced reference sheet (the PDF/SVG drawing under the model). Hidden, it also stops contributing snap points."><span class=mck aria-hidden=true></span>Reference sheet</button>
1897
+ <button data-command-id="steel.show-reference-sheet" id=refToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the source drawing under the model. The source image is visual context; traced lines—not the raster—provide snap points."><span class=mck aria-hidden=true></span>Reference sheet</button>
1885
1898
  <button data-command-id="steel.grid" id=gridEditB data-tip="Grid lines — a plan reference with structural bay spacings (n*d repeats a bay). Shows in 2D and 3D; drawing and drags snap to its lines and intersections.">Grid lines…</button>
1886
1899
  <button data-command-id="steel.dimension-style" id=dimStyleB data-tip="Dimension style — end marks, label position and label background. Sets the defaults every dimension follows unless you give it its own style.">Dimension style…</button>
1887
1900
  </div>
@@ -1940,7 +1953,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1940
1953
  ResizeObserver(canvas.parentElement) keep working untouched — they now measure #pane3d. -->
1941
1954
  <div id=stagewrap>
1942
1955
  <div id=pane2d>
1943
- <div id=stage><svg id=svg></svg></div>
1956
+ <div id=stage><svg id=svg tabindex=-1 aria-label="2D model plan"></svg></div>
1944
1957
  <div id=zoombar>
1945
1958
  <button data-command-id="steel.zoom" id=zOut data-tip="Zoom out">−</button>
1946
1959
  <input data-command-id="steel.zoom" aria-label="Zoom level" id=zRange type=range min=10 max=400 step=1 value=100>
@@ -2291,8 +2304,8 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2291
2304
  </div>
2292
2305
  </div>
2293
2306
  </div></div>
2294
- <div id=confModal><div class=mbackdrop id=confBackdrop></div>
2295
- <div class=mpanel><div class=mhead><b>Confidence report</b><label class=conf-tgt data-tip="Confidence target for this read (%). Overrides the workflow default; saved with the contract.">Target <input data-command-id="steel.confidence-target" id=confTarget type=number min=0 max=100 step=1> %</label><button data-command-id="steel.dialog-close#the confidence report" id=confClose>✕</button></div>
2307
+ <div id=confModal role=dialog aria-modal=true aria-labelledby=confTitle><div class=mbackdrop id=confBackdrop></div>
2308
+ <div class=mpanel><div class=mhead><b id=confTitle>Confidence report</b><label class=conf-tgt data-tip="Confidence target for this read (%). Overrides the workflow default; saved with the contract.">Target <input data-command-id="steel.confidence-target" id=confTarget type=number min=0 max=100 step=1 placeholder="—"> % <span id=confTargetState></span></label><button data-command-id="steel.dialog-close#the confidence report" id=confClose aria-label="Close confidence report">✕</button></div>
2296
2309
  <div id=confCats class=conf-cats></div>
2297
2310
  <div id=confFilter class=conf-filter></div>
2298
2311
  <div id=confBody class=conf-body></div></div></div>
@@ -2480,7 +2493,7 @@ let CatalogPicker = null; // steel-catalog-picker.js — provider-neutral Profil
2480
2493
  let SteelCore = null; // steel-3d-core.js module namespace — boot() awaits its dynamic import before main() so the classic script can call its pure helpers (sanitizeDims3d) at load
2481
2494
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
2482
2495
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
2483
- let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null;
2496
+ let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null, ProfileColours = null, ReferenceSheet = null, ReadConfidence = null;
2484
2497
  let PlanXf = null; // steel-plan-transform.js — the px↔world registration boundary. Already in the module graph (V2Projection imports it); named here so the classic script can read a sheet's registration angle and fit scale when it draws a rolled section footprint.
2485
2498
  let ReviewClient = null; // connection-review-client.js — how one observation of the connection review state is ordered against the one on screen, and when a refresh cycle may stop. A module because its totality has to be unit-testable; see its header.
2486
2499
  let V2_SCHEMA = null, V2_SESSION = null, V2_PROJECTION = null;
@@ -3007,12 +3020,13 @@ async function boot() {
3007
3020
  if (!APP_ID) { showEmpty('⊞', 'No workflow selected', 'Open a workflow in the FloLess canvas, then open the contract editor from that workflow’s node.'); return; }
3008
3021
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
3009
3022
  startContractEvents(); // subscribe first; contract events buffer until the atomic snapshot is installed
3010
- [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ReviewClient] = await Promise.all([
3023
+ [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence] = await Promise.all([
3011
3024
  import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'),
3012
3025
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
3013
3026
  import('./steel-model-v2-commands.js'), import('./steel-model-v2-client-validation.js'),
3014
3027
  import('./steel-split-view.js'), import('./steel-filter-core.js'), import('./steel-plan-transform.js'),
3015
- import('./steel-catalog-picker.js'), import('./connection-review-client.js'),
3028
+ import('./steel-catalog-picker.js'), import('./connection-review-client.js'), import('./steel-profile-colours.js'),
3029
+ import('./steel-reference-sheet.js'), import('./steel-read-confidence.js'),
3016
3030
  ]);
3017
3031
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + '/snapshot' + CONTRACT_QS);
3018
3032
  // 204 = the project-scoped "nothing stored yet", the quiet twin of the generic 404 below. It carries
@@ -3173,7 +3187,7 @@ async function boot() {
3173
3187
  if(!Array.isArray(C.detail_placements))C.detail_placements=[]; // model-global draft-only placed detail images (Slice 4)
3174
3188
  if(!C.dim_overlays||typeof C.dim_overlays!=='object'||Array.isArray(C.dim_overlays))C.dim_overlays={bolt_pitch:true,edge_clearance:true,cope_size:true,base_plate:true,anchor_depth:true}; // model-global legend DIMENSIONS toggles — all on by default
3175
3189
  if(!C.dim_style||typeof C.dim_style!=='object'||Array.isArray(C.dim_style))C.dim_style={}; // model-global dimension-style defaults. This object-guard is the ONLY normalisation on the load path: `sanitizeDimStyle()` has no production call site (#851). Harmless as it stands — `dimStyle()` re-checks every key against DIM_DEF on each read, and the schema types dim_style `additionalProperties:true` with no enums, so junk here can neither reach the canvas nor refuse a save.
3176
- if(!Array.isArray(C.views))C.views=[]; // model-global saved views (Views Organizer): ensure an array in boot()'s OUTER scope (like dims3d/detail_placements above). `sanitizeViews()` likewise has no production call site, and CANNOT simply be given one: it always writes `projection`, which `$defs.view` (additionalProperties:false) forbids, so calling it would refuse the next save. See the note in applyDraftFields (#851).
3190
+ if(!Array.isArray(C.views))C.views=[]; // model-global saved views (Views Organizer): ensure an array in boot()'s OUTER scope (like dims3d/detail_placements above). The array-guard is all this path needs — `C` here is the server-validated contract, so its views have already passed `$defs.view`. `sanitizeViews()` is for the path that has NOT been validated: the localStorage draft, via DRAFT_SANITIZERS in applyDraftFields (#854).
3177
3191
  // Reference models (#278) are always a model-level array in the native contract.
3178
3192
  if(!Array.isArray(C.reference_models))C.reference_models=[];
3179
3193
  main(); // (C.prop_labels is normalised inside main(), right after the PROP_DEFS/sanitizePropLabels registry is defined — see ~"normalise the contract's incoming value" — since that helper isn't in scope out here in boot())
@@ -3408,8 +3422,8 @@ function memberEndGroup(f){if(f.basis&&f.basis.kind==='drawing'){for(const p of
3408
3422
  function memberEndRole(f){return f.role==='horizontal-brace'?'Horizontal brace':f.role==='vertical-brace'?'Vertical brace':f.role==='brace-unknown'?'Brace':'Beam';}
3409
3423
  function memberEndClassification(f){return ({'aligned-auto':'Aligned automatically','aligned-manual':'Aligned after review','kept-short':'Kept intentionally short','needs-review':'Needs review','stale':'Decision needs review','not-checkable':'Not checkable'})[f.classification]||f.classification;}
3410
3424
  function memberEndReason(f){const words={
3411
- 'cross-view-conflict':'Source views disagree','brace-type-unknown':'Brace type is not recorded','multiple-targets':'Two possible work points','near-coincident-supports':'Nearby supports do not share one exact work point','candidate-overflow':'Too many nearby supports to prove one target','gap-too-large':'Gap larger than expected','crossing-angle-too-small':'Crossing angle is too small','target-out-of-reach':'Support does not span the work point','unresolved-profile':'Support footprint could not be proved','unsupported-placement':'Support placement could not be proved','existing-endpoint':'Existing endpoint requires review','unobserved-endpoint':'No drawing endpoint evidence','view-unregistered':'This view is not registered for geometry','stale-context':'The model changed since this decision'};
3412
- return (f.reasonCodes||[]).map(r=>words[r]||r).join(' · ');
3425
+ 'cross-view-conflict':'Source views disagree','brace-type-unknown':'Brace type is not recorded','multiple-targets':'Two possible work points','near-coincident-supports':'Nearby supports do not share one exact work point','candidate-overflow':'Too many nearby supports to prove one target','gap-too-large':'Gap larger than expected','crossing-angle-too-small':'Crossing angle is too small','target-out-of-reach':'Support does not span the work point','unresolved-profile':'Support footprint could not be proved','unsupported-placement':'Support placement could not be proved','existing-endpoint':'Existing endpoint requires review','unobserved-endpoint':'No drawing endpoint evidence','endpoint-elevation-missing':'Drawing endpoint elevation is missing.','view-scale-invalid':'This view has no usable drawing scale.','observation-scale-mismatch':'Drawing evidence uses a different scale than this view.','view-unregistered':'This view is not registered for geometry','view-policy-forbidden':'This endpoint cannot be checked in this view','subject-geometry-invalid':'Member geometry is incomplete','stale-context':'The model changed since this decision'};
3426
+ return (f.reasonCodes||[]).map(r=>words[r]||'Additional endpoint diagnostic').join(' · ');
3413
3427
  }
3414
3428
  function memberEndTargetName(t){return (t.memberIds||[]).join(' + ')+' centerline';}
3415
3429
  function memberEndTargetEqual(a,b){
@@ -3439,6 +3453,7 @@ function installMemberEndContract(doc,etag,revision){
3439
3453
  const activePlan=C.plans&&C.plans[C.active];
3440
3454
  if(activePlan&&activePlan.viewKind==='plan'){NO_PLAN_VIEW=false;V2_PROJECTION=v2ProjectionForSheet(activePlan.sheet);P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;}
3441
3455
  else{V2_PROJECTION=null;NO_PLAN_VIEW=true;if(!activePlan)C.active=0;P=activePlan?{...structuredClone(activePlan),members:[],segments:[],dims:[],details:[],callouts:[],tos_callouts:[],grid:null,default_tos:Number.isFinite(activePlan.elevation_in)?activePlan.elevation_in:0}:{sheet:'',members:[],segments:[],dims:[],details:[],callouts:[],tos_callouts:[],grid:null,default_tos:0};resetPlanViewState(C.active);}
3456
+ syncElevationContext();
3442
3457
  // A server command replaces the model underneath the editor's local history. Retaining those snapshots
3443
3458
  // would let Ctrl+Z resurrect pre-command geometry without the server-owned decision/audit metadata.
3444
3459
  undo.length=0;redo.length=0;updUR();
@@ -4104,9 +4119,11 @@ function parseVec(s){s=String(s==null?'':s).trim();if(!s)return null;
4104
4119
  const d=parseLen(s);return d==null?null:{dist:d};}
4105
4120
  // To-level TOS mapping (spec §4.5): default-follow ends land on the target level automatically;
4106
4121
  // explicit overrides shift by Δ so relative offsets survive. Columns keep their height (bos shifts by Δ).
4107
- // best-effort: framing plans carry TOS at the level UNO — assume the L2 datum +16'-6" (198"); each end's
4108
- // 'default' checkbox links it to this value (auto-updates when changed); uncheck to override.
4109
- let defaultTOS=198, addProfile='', addMaterial='', addType='beam'; // addProfile/addMaterial/addType are independent defaults for newly drawn members
4122
+ // Legacy plans can still carry default-follow ends. Native v2 plans do not: this number is only their
4123
+ // read-only active-plan elevation context and is synchronized whenever the active projection changes.
4124
+ let defaultTOS=0, addProfile='', addMaterial='', addType='beam'; // addProfile/addMaterial/addType are independent defaults for newly drawn members
4125
+ function nativeElevationModel(){return C&&C.type===MODEL_V2_TYPE;}
4126
+ function syncElevationContext(){const value=Number(P&&P.default_tos);defaultTOS=Number.isFinite(value)?value:0;return defaultTOS;}
4110
4127
  const profileCatalog=window.__STEEL_PROFILE_CATALOG||{environment:'US',standard:'Profile catalog',families:[],rows:[]};
4111
4128
  const profileCatalogRows=CatalogPicker.buildProfileRows(profileCatalog,window.__AISC_SECTIONS||{},window.__AISC_WEIGHTS||{});
4112
4129
  const materialCatalog=CatalogPicker.materialCatalogDescriptorFor(profileCatalog.environment||'US',window.__STEEL_MATERIAL_CATALOG);
@@ -4192,6 +4209,7 @@ function apply(json){
4192
4209
  V2_SESSION.restoreSnapshot(d);
4193
4210
  V2_PROJECTION=v2ProjectionForSheet(C.plans[C.active].sheet);
4194
4211
  P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;
4212
+ syncElevationContext();
4195
4213
  updCS();
4196
4214
  selIds=new Set([...selIds].filter(id=>byId(id)||/^det:/.test(id))); // keep a selected placed-detail id (det:…) — it isn't a member
4197
4215
  selDimIds.forEach(id=>{if(!(P.dims||[]).some(x=>x.id===id))selDimIds.delete(id);}); // drop any dim selection the undo removed
@@ -4723,10 +4741,11 @@ function applyDraftFields(d){
4723
4741
  // (bogus weight/dash token) and `dims3d` (degenerate `axisDir`, whose own doc says "run at every point
4724
4742
  // a dims3d array is assigned") are the same story with the same cost.
4725
4743
  //
4726
- // `views` is DELIBERATELY ABSENT and must stay absent until `sanitizeViews` is fixed: it always writes
4727
- // `projection`, and `$defs.view` is `additionalProperties:false` with no such key, so wiring it here
4728
- // would CAUSE the refused save this block exists to prevent (it also writes `camera`/`clips`/`objects`
4729
- // as `null`, which the schema types as objects). Filed separately — do not "finish the set" here.
4744
+ // `views` was held out of this registry until #854 for a reason worth keeping written down: its
4745
+ // sanitiser was itself unsaveable. `sanitizeViews` minted a root `projection` against a
4746
+ // `$defs.view` that is `additionalProperties:false`, and wrote `camera`/`clips`/`objects` as `null`
4747
+ // where the schema types each as an object — so wiring it would have CAUSED the refused save this
4748
+ // block exists to prevent. The sanitiser was corrected first, in the same change that wired it.
4730
4749
  // EACH ENTRY ENFORCES THE SCHEMA AND NOTHING ELSE. A guard here may reject what the schema cannot
4731
4750
  // hold — that is the whole job, since anything else refuses the restore or the next save — and may
4732
4751
  // never impose an opinion of its own, because the draft is the user's data and the loss is silent.
@@ -4771,6 +4790,13 @@ function applyDraftFields(d){
4771
4790
  // minLength 1, axis is an enum and the row is additionalProperties:false, NONE of which
4772
4791
  // sanitizeDims3d checks — so any of them used to cost the entire draft.
4773
4792
  dims3d:v=>arr(v)&&rowsOk(SteelCore.sanitizeDims3d(v),'dim3'),
4793
+ // Canonicalise what the view module owns (id, name, display mode, provenance), then let `$defs.view`
4794
+ // itself refuse the rows it cannot hold — the same two-step as `dims3d`, and for the same reason:
4795
+ // `sanitizeViews` knows nothing of the schema, so an opaque `camera`/`clips`/`objects` snapshot from
4796
+ // an older editor carrying a key this schema closed off is caught HERE rather than being restated
4797
+ // there. A refused row costs that one saved view and is warned about below; passing it through would
4798
+ // cost the entire draft, since `views` is a root the schema types.
4799
+ views:v=>arr(v)&&rowsOk(sanitizeViews(v),'view'),
4774
4800
  };
4775
4801
  for(const key of rootKeys)if(key in d){
4776
4802
  const raw=structuredClone(d[key]),clean=DRAFT_SANITIZERS[key];
@@ -4945,14 +4971,10 @@ function updUR(){document.getElementById('undoB').disabled=!undo.length;document
4945
4971
  // index moved off it — a blank/RFI/other-plan profile must not shift a real profile's slot.) Rebuilt at
4946
4972
  // render() top so it tracks edits without touching every profs.push site.
4947
4973
  let colorRank=[];
4948
- // Canonical designation (MIRRORS server contract-to-scene canonProfile): upper, x/X/× → X, whitespace
4949
- // around X / after the prefix removed, mixed-fraction spaces kept. One identity for 2D / 3D / IFC / Tekla.
4950
- function canonProfile(s){return String(s||'').trim().toUpperCase().replace(/×/g,'X').replace(/\s*X\s*/g,'X').replace(/^([A-Z]+)\s+/,'$1');}
4951
- function buildColorRank(){colorRank=[...new Set([...(C.plans||[]).flatMap(pl=>(pl.members||[]).map(m=>canonProfile(m.profile))).filter(Boolean), ...Object.keys(WT||{}).map(canonProfile)])].sort();}
4952
- function colorFor(p){const k=canonProfile(p);
4953
- const ov=C.profile_colors[p]??(Object.entries(C.profile_colors).find(([kk])=>canonProfile(kk)===k)||[])[1]; // override: exact key, then canonical (case + x/X/× + separator whitespace) — mirrors contract-to-scene pickColor so an override resolves identically in 2D + 3D
4954
- if(ov)return ov;
4955
- const i=colorRank.indexOf(k);return PAL[((i%PAL.length)+PAL.length)%PAL.length];} // i<0 (blank/CUSTOM/unresolved) wraps to PAL[last], matching pickColor so those members agree in 2D + 3D too
4974
+ const canonProfile=s=>ProfileColours.canonicalProfile(s);
4975
+ function buildColorRank(){colorRank=ProfileColours.profileColourRank(C,WT);}
4976
+ function colorFor(p){return ProfileColours.profileColour(p,C.profile_colors,colorRank,PAL,message=>console.warn('steel-editor: '+message));}
4977
+ function setProfileColour(profile,colour){ProfileColours.setCanonicalProfileColour(C.profile_colors,profile,colour);}
4956
4978
  // F5: per member-type 2D line style. Tokens → px; dashes chosen to avoid the reserved semantic patterns
4957
4979
  // (RFI 10 6, brace 30 8 6 8, grid 12 4 2 4). med+solid (or absent) = today's default (line.member stroke-width:6).
4958
4980
  const MS_W={thin:3,med:6,thick:9},MS_D={solid:'',dashed:'14 8',dotted:'2 8',dashdot:'18 7 3 7'};
@@ -5369,11 +5391,14 @@ function columnSectionPoly(m){
5369
5391
  return Object.assign([[cx-r,cy-r],[cx+r,cy-r],[cx+r,cy+r],[cx-r,cy+r]],{placeholder:true});
5370
5392
  }
5371
5393
  const _polyStr=pts=>pts.map(p=>p[0].toFixed(1)+','+p[1].toFixed(1)).join(' ');
5372
- // Vector overlay: render THIS sheet's filter linework crisply (sharp, snappable, measurable) instead of
5373
- // the blurry raster JPEG. Vector PDFs expose filterElsForPlan(); a genuinely scanned sheet (no vectors)
5374
- // falls back to the RB64 raster. ponytail: all line d's are merged into ONE <path> so the browser parses
5375
- // one node, not thousands — fast to re-render on pan/zoom.
5376
- function hasOverlay(){const d=drawablePlan();return d?d.renders:!!RB64;} // F13: the active plan carries a reference sheet — vector linework or a scanned raster. Keyed on whether anything DRAWABLE actually paints, so a vector sheet whose every layer is hidden (or whose survivors are all text) greys the toggle out instead of offering to show a blank page; only a sheet with NO vectors falls through to the raster (#507)
5394
+ // Reference-sheet overlay: reuse THIS plan's reviewed Drawing Filter raster as inert source context,
5395
+ // then render the Filter linework crisply above it as the only snappable/measurable authority. The
5396
+ // resolver requires one unique sheet match and the same registered extent Drawing Filter uses; it never
5397
+ // copies the confidential bytes into plans[].raster_b64. A genuinely scanned legacy plan with no saved
5398
+ // Filter raster still falls back to RB64. ponytail: all line d's are merged into ONE <path> so the
5399
+ // browser parses one node, not thousands — fast to re-render on pan/zoom.
5400
+ function reviewedRaster(){return ReferenceSheet?ReferenceSheet.resolvePlanReferenceRaster(P,C&&C.filter):{ok:false,reason:'resolver-unavailable'};}
5401
+ function hasOverlay(){const r=reviewedRaster(),d=drawablePlan();return r.ok||(d?d.renders:!!RB64);} // F13: a reviewed raster is useful even when its vectors are absent/all non-drawable: the raster restores the source PDF's native printed context while remaining inert
5377
5402
  // #507: `filter.layers[].drawable === false` means "listed but not drawn (e.g. a text/title-block
5378
5403
  // layer)" — the schema's own words. Only the Steel Filter's row styling ever honoured it; the plan drew
5379
5404
  // every element regardless, so a reader that marked its noise non-drawable exactly as instructed still
@@ -5385,13 +5410,13 @@ function hasOverlay(){const d=drawablePlan();return d?d.renders:!!RB64;} // F1
5385
5410
  function nonDrawableLayers(){const f=C&&C.filter,out=new Set();
5386
5411
  for(const l of (f&&f.layers)||[]) if(l&&l.drawable===false&&typeof l.name==='string') out.add(l.name);
5387
5412
  return out;}
5388
- // The sheet's linework MINUS every non-drawable layer — the one set all three overlay consumers share
5389
- // (draw, snap, has-a-sheet), so what you can see, what you can snap to, and whether the toggle is even
5390
- // enabled can never disagree. null and [] mean DIFFERENT things and callers must keep them apart:
5391
- // null = this plan carries no vector overlay at all (a scanned sheet, so the raster IS the reference
5392
- // sheet); [] = it carries one but every layer of it is hidden, and the raster must NOT stand in for it
5393
- // — that bitmap is a picture of the whole sheet, so it would put the very text and title block the user
5394
- // suppressed straight back on screen.
5413
+ // The sheet's INTERACTIVE linework MINUS every non-drawable layer — the one set the vector draw and snap
5414
+ // consumers share, so a traced line that is excluded can never remain an invisible snap target. The
5415
+ // reviewed raster is a separate, inert source-image context and may still show that printed ink faintly.
5416
+ // null and [] mean DIFFERENT things and callers must keep them apart:
5417
+ // null = this plan carries no vector overlay at all; [] = it carries one but every vector layer is
5418
+ // excluded. Neither state authorizes a vector or a snap candidate. The reviewed source image, when
5419
+ // present, is resolved independently and never changes this set.
5395
5420
  // NOT folded into filterElsForPlan(): gridReadFromDrawing() reads the RAW set to detect the printed
5396
5421
  // grid, and the bubbles it hunts routinely sit on an annotation layer a reader would mark non-drawable.
5397
5422
  // Hiding them from the canvas must not blind the detector.
@@ -5420,17 +5445,20 @@ function drawablePlan(){
5420
5445
  return _draw;}
5421
5446
  function drawableElsForPlan(){const d=drawablePlan();return d?d.els:null;}
5422
5447
  function hiddenLayerCount(){const d=drawablePlan();return d?d.hidden:0;}
5448
+ function rasterImageSvg(r){const b=r.rect;return `<image class=pdfref aria-hidden=true href="data:image/jpeg;base64,${r.rasterB64}" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" preserveAspectRatio="none"/>`;}
5423
5449
  function overlaySvg(){
5424
5450
  if(!refSheetOn)return ''; // F13: reference sheet hidden → draw neither the raster/vector linework NOR the white pdfsheet backdrop
5425
- const d0=drawablePlan();
5426
- if(!d0)return RB64?`<image href="data:image/jpeg;base64,${RB64}" x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`:''; // no vectors at all: the scanned raster IS the reference sheet
5427
- if(!d0.renders)return ''; // vectors exist but nothing left will paint: draw NOTHING. Not the white backdrop (that reads as a failed read), and emphatically not RB64 — the raster pictures the WHOLE sheet, so it would put the suppressed text and title block straight back on screen
5451
+ const rr=reviewedRaster(),d0=drawablePlan();
5452
+ let out=rr.ok?`<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>${rasterImageSvg(rr)}`:'';
5453
+ if(!d0)return out||(RB64?`<image href="data:image/jpeg;base64,${RB64}" x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`:''); // legacy scanned plan: only when no reviewed Filter raster resolves
5454
+ if(!d0.renders)return out; // no drawable vectors means no path and no snap geometry; a reviewed raster may still provide inert printed context
5428
5455
  const els=d0.els;
5429
5456
  let d='',circ='';
5430
5457
  for(const e of els){if(!e)continue;
5431
5458
  if(e.kind==='line'){if(typeof e.d==='string'&&e.d)d+=e.d+' ';else if(e.x1!=null&&e.x2!=null)d+=`M${e.x1} ${e.y1}L${e.x2} ${e.y2}`;}
5432
5459
  else if(e.kind==='circle'&&e.r>0)circ+=`<circle cx="${e.cx}" cy="${e.cy}" r="${e.r}"/>`;}
5433
- return `<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/><g class=pdfvec>${d?`<path d="${d}"/>`:''}${circ}</g>`;
5460
+ if(!out)out=`<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`;
5461
+ return `${out}<g class=pdfvec>${d?`<path d="${d}"/>`:''}${circ}</g>`;
5434
5462
  }
5435
5463
  // --- geometric edit: extend/trim (snap nearest end to a target line) + split at a point ---
5436
5464
  function lineX(p1,p2,p3,p4){const x1=p1[0],y1=p1[1],x2=p2[0],y2=p2[1],x3=p3[0],y3=p3[1],x4=p4[0],y4=p4[1];
@@ -5977,7 +6005,7 @@ function gridCancelLinePick(){if(gridLinePick&&gridLinePick.line)gridLinePick.li
5977
6005
  function planColumnCount(){let n=0;for(const m of ((P&&P.members)||[]))if(m.role==='column')n++;return n;}
5978
6006
  // The active plan's steel-filter elements (per-sheet linework the reader captured).
5979
6007
  function filterElsForPlan(){const f=C&&C.filter;if(!f)return null;
5980
- const sh=(f.sheets||[]).find(s=>s&&s.sheet&&P&&P.sheet&&s.sheet.toUpperCase()===P.sheet.toUpperCase());
6008
+ const match=ReferenceSheet&&ReferenceSheet.resolvePlanFilterSheet(P,f),sh=match&&match.ok?match.sheet:null;
5981
6009
  const els=sh&&sh.elements;
5982
6010
  return (Array.isArray(els)&&els.length)?els:null;}
5983
6011
  // Detect the printed grid in the sheet's linework (grid-core gridFromDrawing) and apply it. keep = an
@@ -6434,8 +6462,14 @@ function stepSlotText(commandId){
6434
6462
  var typing=t&&(t.isContentEditable||t.tagName==='INPUT'||t.tagName==='TEXTAREA'||t.tagName==='SELECT');
6435
6463
  if(e.key==='?'&&typing)return; // F1 stays reachable while typing, by design
6436
6464
  try{
6437
- if(window.parent&&window.parent!==window&&typeof window.parent.__instructorKey==='function'){
6438
- if(window.parent.__instructorKey(e.key))e.preventDefault();
6465
+ if(window.parent&&window.parent!==window){
6466
+ /* The key came from THIS frame, so make it authoritative before the
6467
+ shell opens help. This repairs a missed startup-ready hand-off (or a
6468
+ hidden sibling frame becoming ready later) and gives the sheet the
6469
+ live carrier it needs to return focus to the exact control. */
6470
+ if(typeof window.parent.__instructorReady==='function')window.parent.__instructorReady(window);
6471
+ if(typeof window.parent.__instructorReport==='function')window.parent.__instructorReport(snapshot(),window);
6472
+ if(typeof window.parent.__instructorKey==='function'&&window.parent.__instructorKey(e.key))e.preventDefault();
6439
6473
  }
6440
6474
  }catch(err){/* cross-origin or torn-down parent */}
6441
6475
  },true);
@@ -6578,7 +6612,7 @@ function applyZoom(z,ax,ay){z=Math.max(ZMIN,Math.min(ZMAX,z));
6578
6612
  zoom=z;svg.setAttribute('width',EXTX*zoom);svg.setAttribute('height',EXTY*zoom);
6579
6613
  if(pt){const m=svg.getScreenCTM();stage.scrollLeft+=(m.a*pt.x+m.e)-ax;stage.scrollTop+=(m.d*pt.y+m.f)-ay;}
6580
6614
  document.getElementById('zRange').value=Math.round(zoom*100);
6581
- document.getElementById('zPct').textContent=Math.round(zoom*100)+'%';updateBadges();}
6615
+ document.getElementById('zPct').textContent=Math.round(zoom*100)+'%';updateBadges();refreshProfileLabelOverlay();}
6582
6616
  function zoomCentered(z){const r=stage.getBoundingClientRect();applyZoom(z,r.left+stage.clientWidth/2,r.top+stage.clientHeight/2);}
6583
6617
  function fitToWindow(){applyZoom(Math.min(stage.clientWidth/EXTX,stage.clientHeight/EXTY)*0.98);}
6584
6618
  // --- duplicate the selected member(s) in place (Ctrl+D) ---
@@ -6741,7 +6775,9 @@ async function selectReviewedJoint(jointId,kind){
6741
6775
  hidden until something else happens to move the review state — which on a quiet model is never. */
6742
6776
  window.renderReviewSurface=renderReviewSurface;
6743
6777
  renderReviewSurface();
6744
- function esc(s){return String(s).replace(/[<>&"]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));}
6778
+ // Keep this tiny helper regex-free: source-slice.mjs deliberately refuses to guess whether `/` begins
6779
+ // a regex, and security tests lift this exact production function to prove hostile connection names stay inert.
6780
+ function esc(s){const entities={'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'};return String(s).split('').map(c=>entities[c]||c).join('');}
6745
6781
  function memberEndReviewSvg(){
6746
6782
  if(!memberEndReview||NO_PLAN_VIEW||!P||!P.members)return '';
6747
6783
  const f=memberEndReview.report.findings[memberEndReview.focus];if(!f)return '';
@@ -6755,7 +6791,57 @@ function memberEndReviewSvg(){
6755
6791
  const pt=projected[Math.max(0,chosenIndex)];if(pt)out+=`<text class=mer-label x="${(start[0]+pt[0])/2}" y="${(start[1]+pt[1])/2-8/zoom}" style="font-size:${11/zoom}px">${esc(fmtFtIn(memberEndDistance(f,targets[Math.max(0,chosenIndex)])/25.4))}</text>`;
6756
6792
  return out+'</g>';
6757
6793
  }
6794
+ let profileLabelState={labels:[],source:'none',hidden:0,message:null,diagnostic:null};
6795
+ function profilePickViewport(){
6796
+ try{
6797
+ const m=svg.getScreenCTM().inverse(),r=stage.getBoundingClientRect(),p=svg.createSVGPoint();
6798
+ p.x=r.left;p.y=r.top;const a=p.matrixTransform(m);p.x=r.right;p.y=r.bottom;const b=p.matrixTransform(m);
6799
+ return [Math.min(a.x,b.x),Math.min(a.y,b.y),Math.max(a.x,b.x),Math.max(a.y,b.y)];
6800
+ }catch(_){return [X0,Y0,X1,Y1];}
6801
+ }
6802
+ function profilePickProfiles(){return [...profileCatalogValues(),...Object.keys(WT||{}),...(C.members||[]).map(m=>m&&m.profile).filter(Boolean)];}
6803
+ function profileLabelQuery(allowFallback){
6804
+ return DetailRefs.planProfileLabelOverlay(P,allowFallback?C.filter:null,{profiles:profilePickProfiles(),viewport:profilePickViewport(),max:500});
6805
+ }
6806
+ function profilePickGuidance(){const armed=picking&&pickKind==='profile';return (armed&&profileLabelState.diagnostic)||profileLabelState.message||'Choose a highlighted profile label by click, Enter, or Space.';}
6807
+ function profileLabelFocusKey(lb){return lb.text+'@'+lb.disp[0]+','+lb.disp[1];}
6808
+ function profileLabelMarkup(labels){let out='';for(const lb of labels){const w=Math.max(40,lb.text.length*11);
6809
+ out+=`<rect class=lblhot data-command-id="steel.apply-profile-label#${esc(lb.text)}" data-command-instance-label="${esc(lb.text)}" data-prof="${esc(lb.text)}" data-pick-key="${esc(profileLabelFocusKey(lb))}" role="button" tabindex="0" x="${lb.disp[0]-w/2}" y="${lb.disp[1]-10}" width="${w}" height="20" rx="3" aria-label="Apply profile ${esc(lb.text)}"></rect><text class=lbltx x="${lb.disp[0]}" y="${lb.disp[1]+4}">${esc(lb.text)}</text>`;}return out;}
6810
+ function profilePickerFocusToken(){const active=document.activeElement;if(!active)return null;
6811
+ if(active.id==='addPick'||active.id==='pickProf')return {kind:'control',id:active.id};
6812
+ if(active.classList&&active.classList.contains('lblhot'))return {kind:'label',key:active.dataset.pickKey,ownerId:mode==='add'?'addPick':'pickProf'};
6813
+ return null;}
6814
+ function restoreProfilePickerFocus(token){if(!token)return false;let target=null;
6815
+ if(token.kind==='control')target=document.getElementById(token.id);
6816
+ else{const group=document.getElementById('profileLabelOverlay');if(group)for(const el of group.querySelectorAll('.lblhot'))if(el.dataset.pickKey===token.key){target=el;break;}if(!target&&token.ownerId)target=document.getElementById(token.ownerId);}
6817
+ if(!target||typeof target.focus!=='function')return false;target.focus({preventScroll:true});return true;}
6818
+ // Applying a keyboard-focused SVG hotspot rebuilds the SVG inside that same keydown dispatch. Chromium
6819
+ // finalises focus for the removed SVG node only after the handler returns, which can overwrite render()'s
6820
+ // synchronous focus restoration and leave focus on <body>. Re-home it on the next task, but only while
6821
+ // focus is still nowhere useful so an intervening user/script focus move is never stolen.
6822
+ function restoreProfilePickerOwnerAfterApply(id){const rehome=()=>{const active=document.activeElement;
6823
+ if(active&&active!==document.body&&active!==svg)return;const target=document.getElementById(id);
6824
+ if(target&&typeof target.focus==='function')target.focus({preventScroll:true});};
6825
+ // The immediate task covers removal of the SVG event target. sync3D can repaint the inspector after its
6826
+ // first async scene refresh, so repeat across that boundary; every attempt refuses to steal meaningful focus.
6827
+ setTimeout(rehome,0);setTimeout(rehome,100);setTimeout(rehome,250);}
6828
+ function reflectProfilePickGuidance(){
6829
+ for(const el of document.querySelectorAll('[data-profile-pick-status]'))el.textContent=profilePickGuidance();
6830
+ }
6831
+ function refreshProfileLabelOverlay(){
6832
+ const group=document.getElementById('profileLabelOverlay');if(!group)return;
6833
+ const focusToken=profilePickerFocusToken();
6834
+ const armed=picking&&pickKind==='profile';profileLabelState=profileLabelQuery(armed);
6835
+ group.replaceChildren();
6836
+ for(const lb of profileLabelState.labels){const w=Math.max(40,lb.text.length*11),rect=document.createElementNS('http://www.w3.org/2000/svg','rect'),label=document.createElementNS('http://www.w3.org/2000/svg','text');
6837
+ rect.setAttribute('class','lblhot');rect.dataset.commandId='steel.apply-profile-label#'+lb.text;rect.dataset.commandInstanceLabel=lb.text;rect.dataset.prof=lb.text;rect.dataset.pickKey=profileLabelFocusKey(lb);rect.setAttribute('role','button');rect.setAttribute('tabindex','0');rect.setAttribute('aria-label','Apply profile '+lb.text);rect.setAttribute('x',lb.disp[0]-w/2);rect.setAttribute('y',lb.disp[1]-10);rect.setAttribute('width',w);rect.setAttribute('height',20);rect.setAttribute('rx',3);
6838
+ label.setAttribute('class','lbltx');label.setAttribute('x',lb.disp[0]);label.setAttribute('y',lb.disp[1]+4);label.textContent=lb.text;group.append(rect,label);
6839
+ }
6840
+ reflectProfilePickGuidance();
6841
+ restoreProfilePickerFocus(focusToken);
6842
+ }
6758
6843
  function render(){
6844
+ const profileFocusToken=profilePickerFocusToken();
6759
6845
  /* The Instructor's second publish trigger, and the one that catches what input
6760
6846
  events cannot: an arm or disarm inside a PROMISE callback (an async contract
6761
6847
  load, an awaited edit) resolves long after the macrotask the originating
@@ -6773,7 +6859,7 @@ function render(){
6773
6859
  buildColorRank(); // refresh the model-global colour rank before any colorFor() call below (B2 — keeps 2D hues stable across plans + matched to 3D)
6774
6860
  reanchorAllPlans(); // F9: glue magnetic dims to their members BEFORE anything reads P.dims — covers every mutation path that ends in a render()
6775
6861
  if(geoMode&&(selIds.size<1||(geoMode==='split'&&selIds.size!==1))){geoMode=null;setGeo();} // Split needs exactly one member; Extend/Trim works on any selection. setGeo() clears BOTH geo + geoel (not a bare remove('geo')) so the grid affordance can't outlive the tool
6776
- let s=overlaySvg(); // crisp vector linework (snappable) when the sheet has vectors; raster only for scanned PDFs
6862
+ let s=overlaySvg(); // reviewed source image (inert) beneath crisp Filter vectors (the only snap authority)
6777
6863
  s+=gridSvg(); // structural grid under the linework (members/dims stay on top)
6778
6864
  for(const sg of P.segments) s+=`<line class=seg data-seg="${sg.id}" x1="${sg.a[0]}" y1="${sg.a[1]}" x2="${sg.b[0]}" y2="${sg.b[1]}"/>`;
6779
6865
  for(const m of P.members){const c=colorFor(m.profile);const sel=selIds.has(m.id);const fh=findHits.has(m.id);const on=sel||fh;const g=on?` style="filter:drop-shadow(0 0 3px ${c}) drop-shadow(0 0 8px ${c})"`:'';
@@ -6795,8 +6881,10 @@ function render(){
6795
6881
  const _sty=(_fx||_sw||_sd)?` style="${_fx}${_sw}${_sd}"`:'';
6796
6882
  s+=`<line class="member${rfi?' rfi':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" x1="${m.wp[0][0]}" y1="${m.wp[0][1]}" x2="${m.wp[1][0]}" y2="${m.wp[1][1]}" stroke="${c}"${_sty}/>`;}
6797
6883
  {const hsel=sel2d();if(hsel.length>=1){const HR=epR();for(const sm of hsel)for(let i=0;i<2;i++) s+=`<circle class="handle ${i===0?'ep-start':'ep-end'}" data-mid="${sm.id}" data-h="${i}" cx="${sm.wp[i][0]}" cy="${sm.wp[i][1]}" r="${HR}"/>`;}} // end 1 (start) yellow, end 2 (end) magenta · shown for every selected member · radius grows with zoom (epR) so it stays visible against the thick line
6798
- if((mode==='add'||(picking&&pickKind==='profile'))&&P.labels) for(const lb of P.labels){const w=Math.max(40,lb.text.length*11);
6799
- s+=`<rect class=lblhot data-prof="${esc(lb.text)}" x="${lb.disp[0]-w/2}" y="${lb.disp[1]-10}" width="${w}" height="20" rx="3"><title>${esc(lb.text)}</title></rect>`;}
6884
+ if(mode==='add'||(picking&&pickKind==='profile')){
6885
+ const armed=picking&&pickKind==='profile';profileLabelState=profileLabelQuery(armed);
6886
+ s+=`<g id=profileLabelOverlay>${profileLabelMarkup(profileLabelState.labels)}</g>`;
6887
+ }
6800
6888
  // One hot-zone per PHYSICAL callout bubble — details[] AND callouts[], undeduplicated, because you pick
6801
6889
  // the bubble beside the end you are detailing. Reading details[] alone left nothing to click on a set
6802
6890
  // whose reader landed everything in callouts[] (#397), which made binding a detail — and so everything
@@ -6837,7 +6925,7 @@ function render(){
6837
6925
  // `profs` and `detTexts()` live — so the combobox offers the same list with no mirror to keep filled.
6838
6926
  // Deleting the elements while these two writes stayed made render() throw on null here, which also
6839
6927
  // killed every call after it on this line (stats/panel/upd*/syncDisplayRows). Measured in Chromium.
6840
- svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
6928
+ svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();restoreProfilePickerFocus(profileFocusToken);
6841
6929
  if(selFilterReady)reflectSelFilter(); // keep the Select-bar Members/Connections buttons in sync with the model — a new/removed connection kind (e.g. the first auto-detailed base plate) flips their on/off without a manual toggle. Gated on selFilterReady so it doesn't run until the deferred first reflect has armed it (that reflect needs BASE_MEMBER_TYPES, initialised later in main()).
6842
6930
  if(view3dShown&&window.Steel3DView){window.Steel3DView.setSelection(selIds);if(window.Steel3DView.setGridSelection)window.Steel3DView.setGridSelection(selGridIds);updateIsolateBtn();if((selIds.size||selGridIds.size)&&window.Steel3DView.selectedClips&&window.Steel3DView.selectedClips().length)window.Steel3DView.setSelectedClips([]);refreshLegendSel();} // keep the 3D member + grid highlight in sync; selecting geometry clears any clip selection (exclusive)
6843
6931
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -7074,12 +7162,12 @@ function refPanelPreempted(){
7074
7162
  }
7075
7163
  function renderMemberEndPanel(p){
7076
7164
  const state=memberEndReview,rows=state.report.findings,groups=new Map();rows.forEach((f,i)=>{const g=memberEndGroup(f);if(!groups.has(g))groups.set(g,[]);groups.get(g).push([f,i]);});
7077
- const actionable=rows.filter(f=>f.classification==='needs-review'&&state.chosen.has(memberEndKey(f))),selected=actionable.filter(f=>state.selected.has(memberEndKey(f))).length;
7165
+ const canChoose=rows.filter(f=>f.classification==='needs-review'&&(f.targets||[]).length>0),readyToSelect=canChoose.filter(f=>state.chosen.has(memberEndKey(f))),selected=readyToSelect.filter(f=>state.selected.has(memberEndKey(f))).length;
7078
7166
  const historyAction=memberEndHistoryAction(state.undoDirection);
7079
7167
  p.setAttribute('aria-busy',String(!!state.busy));p.setAttribute('aria-labelledby','memberEndReviewTitle');
7080
7168
  const disabled=state.busy?' disabled':'';
7081
7169
  let html=`<div class=mer-head><div><div class=mer-title id=memberEndReviewTitle>Member ends short of support centerlines</div><div class=hint>${memberEndUnresolved(state.report)} unresolved end${memberEndUnresolved(state.report)===1?'':'s'} on ${new Set(rows.map(f=>f.memberId)).size} member${new Set(rows.map(f=>f.memberId)).size===1?'':'s'}</div></div><button id=merDone data-command-id="steel.member-end-review-close" class=ghost data-tip="Close member-end review"${disabled}>Done</button></div>`;
7082
- const toolbar=[];if(actionable.length>selected)toolbar.push(`<button id=merAll data-command-id="steel.member-end-select-all" class=ghost${disabled}>Select all</button>`);if(selected)toolbar.push(`<button id=merClear data-command-id="steel.member-end-select-clear" class=ghost${disabled}>Clear</button>`);html+=`<div class=mer-toolbar>${toolbar.join('')}<span class=hint>${selected} selected</span></div>`;
7170
+ const toolbar=[];if(readyToSelect.length>selected)toolbar.push(`<button id=merAll data-command-id="steel.member-end-select-all" class=ghost${disabled}>Select all</button>`);if(selected)toolbar.push(`<button id=merClear data-command-id="steel.member-end-select-clear" class=ghost${disabled}>Clear</button>`);html+=`<div class=mer-toolbar>${toolbar.join('')}<span class=hint>${selected} selected</span></div>`;
7083
7171
  for(const [group,items] of groups){html+=`<section class=mer-group><div class=mer-group-title>${esc(group)}</div>`;for(const [f,i] of items){const key=memberEndKey(f),target=state.chosen.get(key),checked=state.selected.has(key),canCheck=f.classification==='needs-review'&&!!target;
7084
7172
  const evidence=target?memberEndTargetName(target)+' · Extend '+fmtFtIn(memberEndDistance(f,target)/25.4):memberEndReason(f)||memberEndClassification(f);
7085
7173
  html+=`<div class="mer-row${i===state.focus?' focused':''}" data-mer-row="${i}">${canCheck?`<input type=checkbox data-mer-check="${i}" data-command-id="steel.member-end-select#${esc(f.memberId+' end '+(f.end+1))}" aria-label="Include ${esc(f.memberId)} end ${f.end+1}" ${checked?'checked':''}${disabled}>`:'<span aria-hidden=true></span>'}<div><label${canCheck?` for="merCheck${i}"`:''}>${esc(memberEndRole(f)+' '+f.memberId+' · End '+(f.end+1))}</label><div class=mer-evidence>${esc(evidence)}</div><div class=mer-actions>`;
@@ -7091,10 +7179,10 @@ function renderMemberEndPanel(p){
7091
7179
  html+='</div></div></div>';}
7092
7180
  html+='</section>';}
7093
7181
  html+=`<div class=mer-nav><button id=merPrev data-command-id="steel.member-end-review-nav#previous" class=ghost${disabled}>Previous</button><button id=merNext data-command-id="steel.member-end-review-nav#next" class=ghost${disabled}>Next</button>${state.undoToken?`<button id=merUndo data-command-id="steel.member-end-history#${esc(historyAction.label)}" class=ghost data-tip="${historyAction.tip}"${disabled}>${historyAction.label}</button>`:''}</div><div class=mer-live role=status aria-live=polite aria-atomic=true>${esc(state.live||'')}</div>`;
7094
- if(selected)html+=`<button id=merApply data-command-id="steel.member-end-apply" class=mer-primary${disabled}>${state.busy?'Working…':'Extend '+selected+' end'+(selected===1?'':'s')+' to centerlines'}</button>`;else html+='<div class=hint style="margin-top:9px">No ends selected</div>';
7182
+ if(selected)html+=`<button id=merApply data-command-id="steel.member-end-apply" class=mer-primary${disabled}>${state.busy?'Working…':'Extend '+selected+' end'+(selected===1?'':'s')+' to centerlines'}</button>`;else html+=`<div class=hint style="margin-top:9px">${canChoose.length?'No ends selected':'No endpoints are available to extend'}</div>`;
7095
7183
  p.innerHTML=html;
7096
7184
  const done=document.getElementById('merDone');if(done)done.onclick=closeMemberEndReview;
7097
- const all=document.getElementById('merAll');if(all)all.onclick=()=>{for(const f of actionable)state.selected.add(memberEndKey(f));panel();};
7185
+ const all=document.getElementById('merAll');if(all)all.onclick=()=>{for(const f of readyToSelect)state.selected.add(memberEndKey(f));panel();};
7098
7186
  const clear=document.getElementById('merClear');if(clear)clear.onclick=()=>{state.selected.clear();panel();};
7099
7187
  p.querySelectorAll('[data-mer-row]').forEach(row=>row.addEventListener('click',e=>{if(e.target.closest('button,input'))return;focusMemberEnd(+row.dataset.merRow);}));
7100
7188
  p.querySelectorAll('[data-mer-check]').forEach(input=>{input.id='merCheck'+input.dataset.merCheck;input.onchange=()=>{const f=rows[+input.dataset.merCheck],key=memberEndKey(f);input.checked?state.selected.add(key):state.selected.delete(key);state.focus=+input.dataset.merCheck;panel();render();};input.onfocus=()=>{state.focus=+input.dataset.merCheck;selIds=new Set([rows[state.focus].memberId]);if(view3dShown&&window.Steel3DView)window.Steel3DView.setSelection(selIds);};});
@@ -7108,6 +7196,17 @@ function renderMemberEndScanPanel(p){
7108
7196
  p.innerHTML=`<div class=mer-head><div><div class=mer-title id=memberEndScanTitle>${state.error?'Member-end check needs attention':'Checking member ends'}</div><div class=hint>Drawing and model evidence</div></div></div><div class=mer-live role=status aria-live=polite aria-atomic=true>${esc(state.live)}</div>${state.error?'<button id=merRetry data-command-id="steel.member-end-retry" class=mer-primary>Check again</button>':''}`;
7109
7197
  const retry=document.getElementById('merRetry');if(retry)retry.onclick=()=>scanMemberEnds();
7110
7198
  }
7199
+ function nativeElevationContextHtml(){
7200
+ const plan=(C.plans||[])[C.active]||{},values=[];let unknown=0;
7201
+ for(const member of P.members||[])for(const end of member.ends||[]){const raw=end&&end.tos,value=raw==null?NaN:Number(raw);if(Number.isFinite(value))values.push(value);else unknown++;}
7202
+ const range=!values.length?'No finite visible endpoints':(Math.min(...values)===Math.max(...values)
7203
+ ?fmtFtIn(values[0]):fmtFtIn(Math.min(...values))+' to '+fmtFtIn(Math.max(...values)));
7204
+ const planElevation=Number.isFinite(plan.elevation_in)?fmtFtIn(plan.elevation_in):'Not recorded';
7205
+ return '<div style="border-top:1px solid var(--line);margin-top:12px;padding-top:12px"><div class=sect>Elevation context</div>'+
7206
+ '<div class=hint style="margin:0 0 5px;font-size:11px">Plan elevation <b>'+esc(planElevation)+'</b> ('+esc(P.sheet)+')</div>'+
7207
+ '<div class=hint style="margin:0 0 5px;font-size:11px">Visible member endpoints <b>'+esc(range)+'</b>'+ (unknown?' · '+unknown+' unknown':'') +'</div>'+
7208
+ '<div class=hint style="margin:0;font-size:11px">Member elevations are explicit in this model. Select a member to inspect or edit its endpoints.</div></div>';
7209
+ }
7111
7210
  function panel(){
7112
7211
  const p=document.getElementById('panel');
7113
7212
  p.removeAttribute('aria-busy');p.removeAttribute('aria-labelledby');
@@ -7216,8 +7315,8 @@ function panel(){
7216
7315
  p.innerHTML=`<span class=badge>Add member</span>
7217
7316
  ${memberTypeField('mTypeA',[{memberType:addType}])}
7218
7317
  <div class=sect style="margin-top:8px">Current profile</div>
7219
- <div style="display:flex;gap:6px"><input data-command-id="steel.add-profile" aria-label="Current profile" id=addProf class=combo data-src=profiles placeholder="type or pick (e.g. W16X26)" value="${esc(addProfile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseA class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=addPick class="ghost${pk?' on':''}" data-tip="Pick profile by clicking a label in the drawing">⌖ pick</button></div>
7220
- <div class=hint id=pickHint style="margin-top:4px;font-style:italic${pk?';color:var(--brand)':''}">${pk?'Click a profile label in the drawing…':'or click a label in the drawing'}</div>
7318
+ <div style="display:flex;gap:6px"><input data-command-id="steel.add-profile" aria-label="Current profile" id=addProf class=combo data-src=profiles placeholder="type or pick (e.g. W16X26)" value="${esc(addProfile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseA class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=addPick class="ghost${pk?' on':''}" aria-pressed="${pk?'true':'false'}" data-tip="Pick profile from drawing labels by click, Enter, or Space">⌖ pick</button></div>
7319
+ <div class=hint id=pickHint data-profile-pick-status role=status aria-live=polite style="margin-top:4px;font-style:italic${pk?';color:var(--brand)':''}">${esc(profilePickGuidance())}</div>
7221
7320
  <div class=elab style="margin-top:9px">Material grade</div>
7222
7321
  <div style="display:flex;gap:6px"><input data-command-id="steel.add-material" aria-label="Material grade" id=addMat class=combo data-src=materials placeholder="Profile default · ${esc(profileDefaultMaterial(addProfile))}" value="${esc(addMaterial)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-material-catalog" id=materialBrowseA class=ghost data-tip="Browse structural member grades">Browse</button></div>
7223
7322
  <div class=divrow><hr></div>
@@ -7431,14 +7530,16 @@ function panel(){
7431
7530
  {const qb=document.getElementById('qdPlaceG');if(qb)qb.onclick=()=>quickDimSpacing(qdAnchorPt);}
7432
7531
  return;}
7433
7532
  const arr=selArr();
7434
- if(arr.length===0){p.innerHTML='<h3 style="display:flex;justify-content:space-between;align-items:center">Legend'+(Object.keys(C.profile_colors).length?'<button data-command-id="steel.profile-colours-reset" class=ghost id=resetCols style="font-size:10px;padding:1px 6px">reset colours</button>':'')+'</h3><div class=legend>'+profs.filter(pr=>P.members.some(mm=>mm.profile===pr)).map(pr=>`<span><input data-command-id="steel.profile-colour#${esc(pr)}" aria-label="Colour for ${esc(pr)}" type=color class=swc data-prof="${esc(pr)}" value="${colorFor(pr)}" data-tip="Click to recolour ${esc(pr)}">${esc(pr)}</span>`).join('')+'</div><div class=hint style="margin-top:12px">Click a member to edit; <b>Ctrl</b>/<b>Shift+click</b> to add/remove; drag an empty area to <b>box-select</b> — <b>left→right</b> grabs fully-enclosed, <b>right→left</b> grabs touched (Ctrl/Shift adds). Drag a selected line to move it (all selected move together) — it snaps onto nearby grid/endpoints; drag an end dot to adjust — also snaps (<b>Alt</b> off). Hold <b>Shift</b> to keep it straight (H/V). <b>Ctrl+D</b> duplicate, <b>Ctrl+Z/Y</b> undo/redo, <b>Del</b> delete, <b>Esc</b> deselect. <b>Scroll</b> zoom, <b>middle-drag</b> pan, <b>Home</b> fit. Short even dashes = RFI (size unresolved, e.g. MF). A line with <b>arrowheads</b> is a <b>brace</b> — solid = above the floor, long–short dashes = below; the double arrowhead marks its lower end.</div>'+
7533
+ if(arr.length===0){const elevationContext=nativeElevationModel()?nativeElevationContextHtml():
7435
7534
  '<div style="border-top:1px solid var(--line);margin-top:12px;padding-top:12px"><div class=sect>Project defaults</div>'+
7436
7535
  '<div class=hint style="margin:0 0 6px;font-size:11px">Level <b>'+esc(fmtFtIn(defaultTOS))+'</b> ('+esc(P.sheet)+'). '+((P.tos_callouts&&P.tos_callouts.length)?'Per-zone T.O. STEEL callouts from the drawing applied to each member; ':'')+'ends ticked <b>default</b> follow the level.</div>'+
7437
7536
  '<div class=elab>Default TOS</div><input data-command-id="steel.default-tos" aria-label="Default TOS" id=defTos inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="'+esc(fmtFtIn(defaultTOS))+'"><span class=edec>'+esc(fmtDecIn(defaultTOS))+'</span>'+
7438
7537
  '<button data-command-id="steel.ends-reset-default" class="ghostw f" id=applyTos>Reset all ends to default</button></div>';
7439
- document.getElementById('defTos').onchange=e=>{defaultTOS=parseLen(e.target.value);ModelCmd.setPlanDefaultTos(P,defaultTOS);syncDefaults();scheduleSave();render();sync3D();}; // sync3D: this moves every unset-elevation member on THIS sheet, so the 3D meshes and the per-sheet scale cache both have to follow — without it the 3D kept drawing them at the old datum
7440
- document.getElementById('applyTos').onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTOS);}); // overwrites EVERY member, overrides included - unlike syncDefaults, which skips them
7441
- document.querySelectorAll('.swc').forEach(c=>c.onchange=e=>{C.profile_colors[c.dataset.prof]=e.target.value;scheduleSave();render();sync3D();}); // recolour a profile (applies everywhere it's drawn; sync3D repaints a live 3D scene, no-op in 2D)
7538
+ p.innerHTML='<h3 style="display:flex;justify-content:space-between;align-items:center">Legend'+(Object.keys(C.profile_colors).length?'<button data-command-id="steel.profile-colours-reset" class=ghost id=resetCols style="font-size:10px;padding:1px 6px">reset colours</button>':'')+'</h3><div class=legend>'+profs.filter(pr=>P.members.some(mm=>mm.profile===pr)).map(pr=>`<span><input data-command-id="steel.profile-colour#${esc(pr)}" aria-label="Colour for ${esc(pr)}" type=color class=swc data-prof="${esc(pr)}" value="${colorFor(pr)}" data-tip="Click to recolour ${esc(pr)}">${esc(pr)}</span>`).join('')+'</div><div class=hint style="margin-top:12px">Click a member to edit; <b>Ctrl</b>/<b>Shift+click</b> to add/remove; drag an empty area to <b>box-select</b> — <b>left→right</b> grabs fully-enclosed, <b>right→left</b> grabs touched (Ctrl/Shift adds). Drag a selected line to move it (all selected move together) — it snaps onto nearby grid/endpoints; drag an end dot to adjust — also snaps (<b>Alt</b> off). Hold <b>Shift</b> to keep it straight (H/V). <b>Ctrl+D</b> duplicate, <b>Ctrl+Z/Y</b> undo/redo, <b>Del</b> delete, <b>Esc</b> deselect. <b>Scroll</b> zoom, <b>middle-drag</b> pan, <b>Home</b> fit. Short even dashes = RFI (size unresolved, e.g. MF). A line with <b>arrowheads</b> is a <b>brace</b> — solid = above the floor, long–short dashes = below; the double arrowhead marks its lower end.</div>'+elevationContext;
7539
+ const defTos=document.getElementById('defTos'),applyTos=document.getElementById('applyTos');
7540
+ if(defTos)defTos.onchange=e=>{defaultTOS=parseLen(e.target.value);ModelCmd.setPlanDefaultTos(P,defaultTOS);syncDefaults();scheduleSave();render();sync3D();};
7541
+ if(applyTos)applyTos.onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTOS);});
7542
+ document.querySelectorAll('.swc').forEach(c=>c.onchange=e=>{setProfileColour(c.dataset.prof,e.target.value);scheduleSave();render();sync3D();}); // recolour a profile (applies everywhere it's drawn; sync3D repaints a live 3D scene, no-op in 2D)
7442
7543
  const _rc=document.getElementById('resetCols');if(_rc)_rc.onclick=()=>{C.profile_colors={};scheduleSave();render();};
7443
7544
  return;}
7444
7545
  if(arr.length>1){
@@ -7455,9 +7556,9 @@ function panel(){
7455
7556
  const exPH='5 3/4&quot; · 1&#39;-0 1/4&quot;';
7456
7557
  const endName=id=>({bos:'column bottom',tosC:'column top',ntC:'column top',dtC:'column top',cnC:'column top',tosA:'start end',ntA:'start end',dtA:'start end',cnA:'start end',tosB:'end end',ntB:'end end',dtB:'end end',cnB:'end end'})[id]||id;
7457
7558
  // multi-aware field renderers: show the shared value when all agree, else a "Varies" placeholder (typing applies to all).
7458
- const mTos=(id,label,os)=>{const defA=agg(os,o=>o.tosDef!==false),def=defA===true,vEff=def?defaultTOS:agg(os,o=>o.tosDef!==false?defaultTOS:o.tos);
7459
- return `<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName(id))}" aria-label="Use default TOS for ${esc(endName(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`+
7460
- `<input data-command-id="steel.end-tos#${esc(endName(id))}" aria-label="TOS for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${(!def&&VV(vEff))?'Varies':exPH}" value="${def?esc(fmtFtIn(defaultTOS)):valOf(vEff)}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${def?esc(fmtDecIn(defaultTOS)):decOf(vEff)}</span>`;};
7559
+ const mTos=(id,label,os)=>{const native=nativeElevationModel(),defA=agg(os,o=>o.tosDef!==false),def=!native&&defA===true,vEff=native?agg(os,o=>o.tos):(def?defaultTOS:agg(os,o=>o.tosDef!==false?defaultTOS:o.tos));
7560
+ return (native?`<div class=elab>${label}</div>`:`<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName(id))}" aria-label="Use default TOS for ${esc(endName(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`)+
7561
+ `<input data-command-id="steel.end-tos#${esc(endName(id))}" aria-label="${native?'Elevation':'TOS'} for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${(!def&&VV(vEff))?'Varies':exPH}" value="${def?esc(fmtFtIn(defaultTOS)):valOf(vEff)}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${def?esc(fmtDecIn(defaultTOS)):decOf(vEff)}</span>`;};
7461
7562
  const mFt=(id,label,os,get)=>{const a=agg(os,get);return `<div class=elab>${label}</div><input data-command-id="steel.end-elevation#${esc(endName(id))}" aria-label="Elevation for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${VV(a)?'Varies':exPH}" value="${valOf(a)}"><span class=edec>${decOf(a)}</span>`;};
7462
7563
  const mNote=(id,os)=>{const a=agg(os,o=>o.note||'');return `<input data-command-id="steel.end-note#${esc(endName(id))}" aria-label="Connection or note for ${esc(endName(id))}" id=${id} class="f combo" data-src=conntypes placeholder="${VV(a)?'Varies':'connection / note'}" value="${VV(a)?'':esc(a||'')}" autocomplete=off>`;};
7463
7564
  const mDet=(id,os)=>{const a=agg(os,o=>o.detail||'');return `<div class=elab>Connection detail</div><input data-command-id="steel.end-detail#${esc(endName(id))}" aria-label="Connection detail for ${esc(endName(id))}" id=${id} class=combo data-src=details placeholder="${VV(a)?'Varies':'e.g. 5-S504'}" value="${VV(a)?'':esc(a||'')}" autocomplete=off>`;};
@@ -7465,11 +7566,11 @@ function panel(){
7465
7566
  let elev='';
7466
7567
  if(!allBeam&&!allCol) elev=`<div class="hint f" style="border:1px solid var(--line);border-radius:6px;padding:8px 10px">Mixed beam + column — select one type only to edit levels.</div>`;
7467
7568
  else if(allCol){const cs=cols.map(m=>m.col);
7468
- elev=`<div class="sect f">Elevation</div>${mFt('bos',dotS+'Bottom (BOS)',cs,o=>o.bos)}${mTos('tosC',dotE+'Top (TOS)',cs)}${mNote('ntC',cs)}${mDet('dtC',cs)}`;}
7569
+ elev=`<div class="sect f">Elevation</div>${mFt('bos',dotS+(nativeElevationModel()?'Bottom elevation':'Bottom (BOS)'),cs,o=>o.bos)}${mTos('tosC',dotE+(nativeElevationModel()?'Top elevation':'Top (TOS)'),cs)}${mNote('ntC',cs)}${mDet('dtC',cs)}`;}
7469
7570
  else{const s0=beams.map(m=>m.ends[0]),s1=beams.map(m=>m.ends[1]);
7470
- elev=`<div class="sect f">${dotS}Start</div>${mTos('tosA','TOS',s0)}${mNote('ntA',s0)}${mDet('dtA',s0)}`+
7571
+ elev=`<div class="sect f">${dotS}Start</div>${mTos('tosA',nativeElevationModel()?'Start elevation':'TOS',s0)}${mNote('ntA',s0)}${mDet('dtA',s0)}`+
7471
7572
  `<div class=divrow><hr><button data-command-id="steel.ends-match" class=ghost id=matchEnds>Match → both ends (each)</button><hr></div>`+
7472
- `<div class=sect>${dotE}End</div>${mTos('tosB','TOS',s1)}${mNote('ntB',s1)}${mDet('dtB',s1)}`;}
7573
+ `<div class=sect>${dotE}End</div>${mTos('tosB',nativeElevationModel()?'End elevation':'TOS',s1)}${mNote('ntB',s1)}${mDet('dtB',s1)}`;}
7473
7574
  // The placement aggregates over the ELIGIBLE subset only — a member whose profile resolves to no section
7474
7575
  // is skipped by the bake entirely, so folding it in would report a Varies (or a value) for a member
7475
7576
  // nothing applies to. ONE subset for both axes and both offsets, because the bake has one answer for all
@@ -7596,8 +7697,8 @@ function panel(){
7596
7697
  const mfSug=((m.mf||/^MF/i.test(m.profile))&&_lvl&&C.moment_frames)?[...new Set(C.moment_frames.flatMap(f=>f[_lvl]||[]))].filter(Boolean):[];
7597
7698
  const endName2=id=>({bos:'column bottom',tosC:'column top',ntC:'column top',dtC:'column top',cnC:'column top',tosA:'start end',ntA:'start end',dtA:'start end',cnA:'start end',tosB:'end end',ntB:'end end',dtB:'end end',cnB:'end end'})[id]||id;
7598
7699
  const ftFld=(id,label,v)=>`<div class=elab>${label}</div><input data-command-id="steel.end-elevation#${esc(endName2(id))}" aria-label="Elevation for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"><span class=edec>${esc(fmtDecIn(v))}</span>`;
7599
- const tosFld=(id,label,o)=>{const def=o.tosDef!==false,v=def?defaultTOS:o.tos;
7600
- return `<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName2(id))}" aria-label="Use default TOS for ${esc(endName2(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div><input data-command-id="steel.end-tos#${esc(endName2(id))}" aria-label="TOS for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${esc(fmtDecIn(v))}</span>`;};
7700
+ const tosFld=(id,label,o)=>{const native=nativeElevationModel(),def=!native&&o.tosDef!==false,v=def?defaultTOS:o.tos;
7701
+ return (native?`<div class=elab>${label}</div>`:`<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName2(id))}" aria-label="Use default TOS for ${esc(endName2(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`)+`<input data-command-id="steel.end-tos#${esc(endName2(id))}" aria-label="${native?'Elevation':'TOS'} for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${esc(fmtDecIn(v))}</span>`;};
7601
7702
  const nin=(id,v)=>`<input data-command-id="steel.end-note#${esc(endName2(id))}" aria-label="Connection or note for ${esc(endName2(id))}" id=${id} class="f combo" data-src=conntypes placeholder="connection / note" value="${esc(v||'')}" autocomplete=off>`;
7602
7703
  const dFld=(id,o)=>{const hasPrev=o.detail&&previewFor(o.detail);return `<div class=elab>Connection detail</div><div style="display:flex;gap:6px"><input data-command-id="steel.end-detail#${esc(endName2(id))}" aria-label="Connection detail for ${esc(endName2(id))}" id=${id} class=combo data-src=details placeholder="e.g. 5-S504" value="${esc(o.detail||'')}" style="flex:1" autocomplete=off>${hasPrev?`<button data-command-id="steel.detail-preview#${esc(endName2(id))}" aria-label="Open connection detail for ${esc(endName2(id))}" id=${id}_open class=ghost data-tip="Open detail ${esc(o.detail)}">⤢</button>`:''}<button data-command-id="steel.pick-detail" aria-label="Pick connection detail for ${esc(endName2(id))}" id=${id}_pk class="ghost${(picking&&pickKind==='detail'&&pickEnd===o)?' on':''}" data-tip="Pick a detail callout from the drawing">⌖</button></div>`;};
7603
7704
  // Per-end connection-library picker (sets o.conn = a connections[] row id). When set, the row's
@@ -7658,10 +7759,10 @@ function panel(){
7658
7759
  };
7659
7760
  const dotS='<span class=epdot style="background:#facc15"></span>',dotE='<span class=epdot style="background:#f472b6"></span>'; // start=yellow, end=magenta — matches the canvas end markers
7660
7761
  const elev = col
7661
- ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+'Bottom (BOS)',m.col.bos)}${tosFld('tosC',dotE+'Top (TOS)',m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}${dStat('dtC',m.col,'col')}`
7662
- : `<div class="sect f">${dotS}Start</div>${tosFld('tosA','TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}${dStat('dtA',m.ends[0],0)}
7762
+ ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+(nativeElevationModel()?'Bottom elevation':'Bottom (BOS)'),m.col.bos)}${tosFld('tosC',dotE+(nativeElevationModel()?'Top elevation':'Top (TOS)'),m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}${dStat('dtC',m.col,'col')}`
7763
+ : `<div class="sect f">${dotS}Start</div>${tosFld('tosA',nativeElevationModel()?'Start elevation':'TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}${dStat('dtA',m.ends[0],0)}
7663
7764
  ${isBrace(m)?'':`<div class=divrow><hr><button data-command-id="steel.ends-match" class=ghost id=matchEnds>Match → both ends</button><hr></div>`}
7664
- <div class=sect>${dotE}End</div>${tosFld('tosB','TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}${dStat('dtB',m.ends[1],1)}`;
7765
+ <div class=sect>${dotE}End</div>${tosFld('tosB',nativeElevationModel()?'End elevation':'TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}${dStat('dtB',m.ends[1],1)}`;
7665
7766
  const bpj=col?(C.joints||[]).find(j=>j&&j.kind==='base-plate'&&j.main===m.id):null; // this column's base-plate joint, if detailed
7666
7767
  const pFld=(key,label,ph,unit)=>{const raw=bpj&&bpj.params&&bpj.params[key]!=null?bpj.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtFtIn(Number(raw)/25.4)):esc(String(raw)));return `<div class=elab>${label}</div><input data-command-id="steel.connection-parameter#${esc('base plate '+label.toLowerCase())}" aria-label="${esc(label)}" id=bp_${key} inputmode=decimal placeholder="${esc(ph)}" value="${val}" autocomplete=off>${unit&&unit!=='mm'?`<span class=edec>${unit}</span>`:''}`;}; // mm params shown/entered in ft-in
7667
7768
  const bpSect=bpj?`<div class=divrow><hr><span class=sect style="margin:0">Base plate</span><hr></div>
@@ -7782,7 +7883,7 @@ function panel(){
7782
7883
  p.innerHTML=`<h3>Member ${esc(m.id)}</h3>
7783
7884
  ${typeFilterHTML()}
7784
7885
  ${memberTypeField('mTypeS',[m])}
7785
- <div class="f"><div class=elab>Profile</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-profile" aria-label="Profile" id=pf class=combo data-src=profiles value="${esc(m.profile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseS class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=pickProf class="ghost${(picking&&pickKind==='profile')?' on':''}" data-tip="Pick profile by clicking a label in the drawing">⌖ pick</button></div>${(picking&&pickKind==='profile')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--brand)">Click a profile label in the drawing…</div>':(picking&&pickKind==='detail')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--purple)">Click a detail callout in the drawing…</div>':''}</div>
7886
+ <div class="f"><div class=elab>Profile</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-profile" aria-label="Profile" id=pf class=combo data-src=profiles value="${esc(m.profile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseS class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=pickProf class="ghost${(picking&&pickKind==='profile')?' on':''}" aria-pressed="${(picking&&pickKind==='profile')?'true':'false'}" data-tip="Pick profile from drawing labels by click, Enter, or Space">⌖ pick</button></div>${(picking&&pickKind==='profile')?'<div class="hint" data-profile-pick-status role=status aria-live=polite style="margin-top:4px;font-style:italic;color:var(--brand)">'+esc(profilePickGuidance())+'</div>':(picking&&pickKind==='detail')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--purple)">Click a detail callout in the drawing…</div>':''}</div>
7786
7887
  <div class="f"><div class=elab>Material grade</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-material" aria-label="Material grade" id=mat class=combo data-src=materials value="${esc(m.material||'')}" placeholder="Profile default · ${esc(profileDefaultMaterial(m.profile))}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-material-catalog" id=materialBrowseS class=ghost data-tip="Browse structural member grades">Browse</button></div><div class=hint>${m.material?esc(m.material)+' · explicit':'Follows the selected profile automatically'}</div></div>
7787
7888
  ${appearanceSect}
7788
7889
  ${braceSect}
@@ -7819,7 +7920,7 @@ function panel(){
7819
7920
  {const rp=document.getElementById('rfiPill');if(rp){const go=()=>openRFI(m.id);rp.onclick=go;rp.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();go();}};}} // F12: the RFI pill opens the list focused on THIS member (role=button span → keydown for Enter/Space). stopPropagation so idle Space/Enter doesn't ALSO hit the global repeat-last handler (:3804) — matches the editor's local-keydown convention (:1738,:4212)
7820
7921
  document.getElementById('pickProf').onclick=()=>{if(picking&&pickKind==='profile'){picking=false;}else{picking=true;pickKind='profile';pickEnd=null;}render();};
7821
7922
  document.getElementById('mTypeS').onchange=e=>{const v=e.target.value;if(!normMemberTypeKey(v)){e.target.value=memberTypeLabel(memberTypeOf(m));return;}edit(()=>{const k=memberTypeFromInput(v);if(k&&memberTypeOf(m)!==k)applyMemberType([m],k);});}; // retype → role + legend recategorize (edit() → sync3D → build3DLegend); undoable
7822
- {const _cc=document.getElementById('msColor');if(_cc)_cc.onchange=e=>{C.profile_colors[m.profile]=e.target.value;scheduleSave();render();sync3D();};} // F1: recolour this member's profile (same write as the legend swatch) — sync3D() repaints a live 3D scene (no-op in 2D) so colour is truly 2D+3D
7923
+ {const _cc=document.getElementById('msColor');if(_cc)_cc.onchange=e=>{setProfileColour(m.profile,e.target.value);scheduleSave();render();sync3D();};} // F1: recolour this member's profile (same write as the legend swatch) — sync3D() repaints a live 3D scene (no-op in 2D) so colour is truly 2D+3D
7823
7924
  document.querySelectorAll('.msW').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'weight',b.dataset.w)); // F5: per member-type line weight
7824
7925
  document.querySelectorAll('.msD').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'dash',b.dataset.d)); // F5: per member-type line dash
7825
7926
  document.querySelectorAll('.mfsug').forEach(b=>b.onclick=()=>edit(()=>{const profile=b.dataset.s;ModelCmd.patchMember(m,{profile,mf:true,rfi:_wt(profile)==null});if(!profs.includes(profile)){profs.push(profile);profs.sort();}})); // record the moment-frame provenance (drives the confidence "schedule-resolved" factor)
@@ -8318,8 +8419,8 @@ const PROP_KEYS=new Set(PROP_DEFS.map(d=>d.key));
8318
8419
  //
8319
8420
  // `placement` (an enum) and the three booleans ARE schema-constrained, so clamping those is this
8320
8421
  // function's job rather than an opinion.
8321
- function sanitizePropLabels(x){const o=(x&&typeof x==='object'&&!Array.isArray(x))?x:{};
8322
- return {props:Array.isArray(o.props)?o.props.filter(k=>typeof k==='string'):[],
8422
+ function sanitizePropLabels(x){const hasState=!!(x&&typeof x==='object'&&!Array.isArray(x)),o=hasState?x:{};
8423
+ return {props:Array.isArray(o.props)?o.props.filter(k=>typeof k==='string'):(hasState?[]:['profile']),
8323
8424
  placement:['start','mid','end'].includes(o.placement)?o.placement:'mid',
8324
8425
  selected_only:o.selected_only===true,
8325
8426
  vis2d:o.vis2d!==false,vis3d:o.vis3d!==false, // per-view label VISIBILITY (B1): default ON; the property SELECTION (props) stays shared across 2D+3D — only show/hide is independent
@@ -8419,12 +8520,9 @@ function renderPropLabels(){const pl=C.prop_labels;propLabelsHidden=0;if(!pl||!p
8419
8520
  //
8420
8521
  // A SECOND MESSAGE WAS ADDED HERE AND REMOVED, and the reason is worth keeping. The UX review noted that
8421
8522
  // "visibility on, no properties ticked" leaves a toggle reading on over a canvas with no chips — true, and
8422
- // "Clear all" reaches it in one click. But `props: []` with visibility on is not an anomaly, it is the
8423
- // RESTING STATE OF EVERY DOCUMENT: `sanitizePropLabels` writes `props: []` and defaults both flags on, and
8424
- // the reader emits the same empty skeleton. So the predicate that was supposed to explain a rare state
8425
- // matched every project that had never used the feature, and parked a permanent pill telling the user to
8426
- // right-click a member. Measured by review, not reasoned about. The honest place for that explanation is
8427
- // the popup where "Clear all" lives, not the canvas.
8523
+ // "Clear all" reaches it in one click. A MISSING preference now starts with Profile, while an explicit
8524
+ // `props: []` remains the user's legitimate cleared state. Parking a permanent pill over that deliberate
8525
+ // state would still be noise; the Properties popup is where the selection and "Clear all" live.
8428
8526
  function updatePropHint(){let el=document.getElementById('plHint');
8429
8527
  const show=view2dShown&&propLabelsHidden>0; // a 2D-CANVAS hint: it belongs on screen whenever the plan is, not only when the plan holds the tools
8430
8528
  if(!show){if(el)el.style.display='none';return;}
@@ -9217,7 +9315,8 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
9217
9315
  const go=document.createElement('button');go.className='primary';go.disabled=true;go.textContent=tool==='move'?'Move here':'Copy here';
9218
9316
  C.plans.forEach((pl,i)=>{const row=document.createElement('div');row.className='lvrow'+(pl===P?' cur':'');
9219
9317
  const nm=document.createElement('span');nm.textContent=planLabel(pl,i)+(pl===P?' (current)':''); // the page's ONE plan-label rule — this modal and the header switcher must not disagree about what a plan is called
9220
- const ts=document.createElement('span');ts.className='lvtos';const nM=(pl.members||[]).length;ts.textContent=nM+' member'+(nM===1?'':'s')+' · TOS '+fmtFtIn(pl.default_tos!=null?pl.default_tos:198);
9318
+ const ts=document.createElement('span');ts.className='lvtos';const nM=(pl.members||[]).length;
9319
+ const elevation=nativeElevationModel()?Number(pl.elevation_in):Number(pl.default_tos);ts.textContent=nM+' member'+(nM===1?'':'s')+' · '+(nativeElevationModel()?'Elevation ':'TOS ')+fmtFtIn(Number.isFinite(elevation)?elevation:0);
9221
9320
  row.append(nm,ts);
9222
9321
  if(pl!==P){row.onclick=()=>{pick=i;rows.forEach(r=>r.classList.remove('pick'));row.classList.add('pick');go.disabled=false;};
9223
9322
  row.ondblclick=()=>{pick=i;toLevelCommit(tool,i);closeLevelModal();};}
@@ -9307,6 +9406,14 @@ function toast(msg,sticky,ms){let t=document.getElementById('toast');
9307
9406
  t.setAttribute('role','status');t.setAttribute('aria-live','polite');t.setAttribute('aria-atomic','true');
9308
9407
  t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},ms>0?ms:TOAST_MS);}
9309
9408
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
9409
+ function applyProfileLabel(prof){
9410
+ if(mode!=='add'&&picking&&pickKind==='profile'&&selIds.size===1){const id=[...selIds][0];picking=false;edit(()=>{const m=byId(id);ModelCmd.patchMember(m,{profile:prof,rfi:_wt(prof)==null});if(!profs.includes(prof)){profs.push(prof);profs.sort();}});restoreProfilePickerOwnerAfterApply('pickProf');return true;}
9411
+ if(mode==='add'&&!drawDraft){addProfile=prof;if(picking&&pickKind==='profile'){picking=false;render();restoreProfilePickerOwnerAfterApply('addPick');return true;}
9412
+ const hi=document.getElementById('addProf');if(hi)hi.value=addProfile;const ph=document.getElementById('pickHint');if(ph){ph.classList.add('pick');setTimeout(()=>ph&&ph.classList.remove('pick'),450);}return true;}
9413
+ return false;
9414
+ }
9415
+ svg.addEventListener('keydown',e=>{const t=e.target;if(!t||!t.classList||!t.classList.contains('lblhot'))return;
9416
+ if(e.key!=='Enter'&&e.key!==' ')return;e.preventDefault();e.stopPropagation();applyProfileLabel(t.dataset.prof);});
9310
9417
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
9311
9418
  if(memberEndReview){const pick=t.closest&&t.closest('[data-mer-canvas-target]');if(pick&&!memberEndReview.busy){const f=memberEndReview.report.findings[memberEndReview.focus];chooseMemberEndTarget(memberEndKey(f),+pick.dataset.merCanvasTarget);}e.preventDefault();e.stopPropagation();return;}
9312
9419
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
@@ -9369,11 +9476,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
9369
9476
  return;}
9370
9477
  if(t.classList.contains('handle')){const id=t.dataset.mid||[...selIds][0],m=byId(id),h=+t.dataset.h;if(!m)return;buildSnap(id);
9371
9478
  drag={type:'end',h,id,anchor:m.wp[1-h].slice(),orig:m.wp[h].slice(),pre:snapshot()};svg.setPointerCapture(e.pointerId);e.preventDefault();return;} // anchor = the fixed end (length ref); orig = where this end started (moved ref)
9372
- if(t.classList.contains('lblhot')){const prof=t.dataset.prof;
9373
- if(mode!=='add'&&picking&&pickKind==='profile'&&selIds.size===1){const id=[...selIds][0];picking=false;edit(()=>{const m=byId(id);ModelCmd.patchMember(m,{profile:prof,rfi:_wt(prof)==null});if(!profs.includes(prof)){profs.push(prof);profs.sort();}});return;} // in Add mode a profile pick ALWAYS means "adopt as the current add profile" (a 3D draw can leave a member selected)
9374
- if(mode==='add'&&!drawDraft){addProfile=prof;if(picking&&pickKind==='profile'){picking=false;render();return;} // adopt a label's profile ONLY before the first click; mid-draw a label click falls through to drawClick → places the END on that label's point (mirrors the seg guard)
9375
- const hi=document.getElementById('addProf');if(hi)hi.value=addProfile;const ph=document.getElementById('pickHint');if(ph){ph.classList.add('pick');setTimeout(()=>ph&&ph.classList.remove('pick'),450);}return;}
9376
- return;}
9479
+ if(t.classList.contains('lblhot')){applyProfileLabel(t.dataset.prof);return;} // Add mode adopts it; an armed inspector applies it. Enter/Space call the same path above.
9377
9480
  if(t.classList.contains('dethot')){const det=t.dataset.det;
9378
9481
  if(picking&&pickKind==='detail'&&pickEnd){const o=pickEnd;picking=false;pickEnd=null;edit(()=>{ModelCmd.patchEnd(o,{detail:det});});}return;}
9379
9482
  {const cg=t.closest('g.cohot');if(cg){const sheet=cg.dataset.coSheet,prev=cg.dataset.coPrev; // Workstream B smart jump
@@ -9638,13 +9741,13 @@ function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if
9638
9741
  document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
9639
9742
  function updPlToggle(){const b=document.getElementById('plToggleB');if(b){const on=!!(C.prop_labels&&plVis(false));b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}} // B1: 2D property-label visibility (independent of 3D)
9640
9743
  document.getElementById('plToggleB').onclick=e=>{e.stopPropagation();C.prop_labels.vis2d=!C.prop_labels.vis2d;updPlToggle();refreshPropLabels();};
9641
- const REF_TIP='Show or hide the traced reference sheet (the PDF/SVG drawing under the model). Hidden, it also stops contributing snap points.';
9744
+ const REF_TIP='Show or hide the source drawing under the model. The source image is visual context; traced lines—not the raster—provide snap points.';
9642
9745
  function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;const on=refSheetOn;b.disabled=!hasOverlay();b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));
9643
- // #507: a non-drawable layer is excluded whatever this toggle says, and NOTHING in the editor sets
9644
- // that flag — the reader writes it and Steel Filter only dims the row. So say it here, on the one
9645
- // control a user consults to reason about the backdrop, instead of leaving the omission silent.
9746
+ // #507 + #875: a non-drawable layer remains absent from traced vectors and snaps, while the reviewed
9747
+ // source image may still show its printed ink faintly as context. Say both halves where the user
9748
+ // reasons about the backdrop instead of making "visible" sound equivalent to "snappable".
9646
9749
  const n=hiddenLayerCount();
9647
- b.setAttribute('data-tip',REF_TIP+(n?(' '+n+' layer'+(n===1?'':'s')+' marked “listed but not drawn” '+(n===1?'is':'are')+' always excluded — review them in Drawing Filter.'):''));}
9750
+ b.setAttribute('data-tip',REF_TIP+(n?(' '+n+' layer'+(n===1?'':'s')+' marked “listed but not drawn” '+(n===1?'is':'are')+' excluded from traced linework and snap points, though its printed ink may remain faintly visible in the source image.'):''));}
9648
9751
  document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v2',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();};
9649
9752
  document.getElementById('gridEditB').onclick=()=>{setGridMode(!gridMode);render();};
9650
9753
  document.getElementById('dimStyleB').onclick=()=>{setDimStyleMode(!dimStyleMode);render();};
@@ -11626,7 +11729,7 @@ function viewGenKey(s){return s.kind+':'+s.index;}
11626
11729
  function closeViewGenerator(){const modal=document.getElementById('viewGenModal');if(modal)modal.style.display='none';viewGenState=null;
11627
11730
  const target=viewGenLauncher&&viewGenLauncher.isConnected?viewGenLauncher:document.getElementById('vwSaveMore');viewGenLauncher=null;if(target)target.focus();}
11628
11731
  function openViewGenerator(launcher){const geo=gridGeo(),gc=GC();if(!geo||!gc){toast('This plan has no usable structural grid');return;}
11629
- const sources=ViewGen.sourcesFromGrid(geo,gc.mmPerPx(P.pt_per_ft),P.sheet);
11732
+ const sources=ViewGen.sourcesFromGrid(geo,gc.mmPerPx(P.pt_per_ft),P.sheet,P.modelGrid);
11630
11733
  const selected=ViewGen.preselectedSourceKeys(selGridIds,sources),ignoredFree=ViewGen.unsupportedFreeGridCount(selGridIds);
11631
11734
  viewGenLauncher=launcher||document.activeElement;viewGenState={tab:'grid',look:'positive',selected,lastAnchor:null,sources,ignoredFree,
11632
11735
  depths:{grid:{ahead:'2\'-0"',behind:'2\'-0"'},levels:{above:'2\'-0"',below:'2\'-0"'}},committedDepths:{grid:{ahead:'2\'-0"',behind:'2\'-0"'},levels:{above:'2\'-0"',below:'2\'-0"'}}};
@@ -17067,6 +17170,8 @@ stage.addEventListener('pointerdown',e=>{if(e.button!==1)return;e.preventDefault
17067
17170
  pan={x:e.clientX,y:e.clientY,sl:stage.scrollLeft,st:stage.scrollTop};stage.setPointerCapture(e.pointerId);stage.style.cursor='grabbing';});
17068
17171
  stage.addEventListener('pointermove',e=>{if(!pan)return;stage.scrollLeft=pan.sl-(e.clientX-pan.x);stage.scrollTop=pan.st-(e.clientY-pan.y);});
17069
17172
  stage.addEventListener('pointerup',()=>{if(pan){pan=null;stage.style.cursor='';}});
17173
+ let profileScrollFrame=0;
17174
+ stage.addEventListener('scroll',()=>{if(profileScrollFrame)return;const later=window.requestAnimationFrame||((fn)=>setTimeout(fn,16));profileScrollFrame=later(()=>{profileScrollFrame=0;refreshProfileLabelOverlay();});},{passive:true});
17070
17175
  document.getElementById('exp').onclick=()=>{const out={pt_per_ft:FT,elev_units:'inch',members:P.members.map(m=>{ensureMeta(m);return {profile:m.profile,workpoint:m.wp,role:m.role,rfi:_wt(m.profile)==null,
17071
17176
  length_ft:+_lenFt(m).toFixed(1),weight_plf:_wt(m.profile), // columns measure vertical height (TOS−BOS), not their ~0 plan-point distance
17072
17177
  ends:m.role==='column'?undefined:m.ends, column:m.role==='column'?m.col:undefined};})};
@@ -17536,8 +17641,66 @@ function bandColorForPct(p){return p==null?'var(--mut)':p>=95?BANDC.verified:p>=
17536
17641
  // target_confidence input default (read in boot()); else none. Editing the override never touches
17537
17642
  // the .flo, so it can't disarm the Run gate.
17538
17643
  function effectiveTarget(){const t=C&&C.target_confidence;return typeof t==='number'?t:(TARGET_CONF!=null?TARGET_CONF:null);}
17539
- function updConf(){const el=document.getElementById('confStat');if(!el)return;const s=scoreContractJS();
17644
+ function readConfidenceProjection(){return ReadConfidence?ReadConfidence.projectReadConfidence(C):{rows:[],diagnostics:[{code:'projector-unavailable'}]};}
17645
+ function readTargetControl(){const ct=document.getElementById('confTarget'),state=document.getElementById('confTargetState'),tgt=effectiveTarget();
17646
+ if(ct&&document.activeElement!==ct){ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder='—';}
17647
+ if(state)state.textContent=tgt==null?'No target set':(typeof C.target_confidence==='number'?'Saved target':('Workflow default '+tgt+'%'));}
17648
+ function readPlanIndex(row){const member=(C.members||[]).find(m=>m&&m.id===row.memberId);if(!member)return -1;
17649
+ for(const observation of row.observations||[]){const i=(C.plans||[]).findIndex(p=>p&&p.viewKind==='plan'&&p.sheet===observation.sheet);if(i>=0)return i;}
17650
+ const sheets=V2Projection&&V2Projection.memberSheets?V2Projection.memberSheets(C,row.memberId):[];
17651
+ return (C.plans||[]).findIndex(p=>p&&p.viewKind==='plan'&&sheets.includes(p.sheet));}
17652
+ function readValueText(field){if(field.kind!=='elevation')return String(field.value);
17653
+ const value=field.value||{};if(typeof value.known==='number'&&isFinite(value.known))return fmtFtIn(value.known/25.4)+' ('+String(value.known)+' mm)';
17654
+ return 'Unknown'+(typeof value.rfiRef==='string'&&value.rfiRef.trim()?(' · '+value.rfiRef.trim()):'');}
17655
+ function readNotesHtml(){const groups=[];const add=(label,notes)=>{const unique=[...new Set((Array.isArray(notes)?notes:[]).filter(n=>typeof n==='string'&&n.trim()).map(n=>n.trim()))];if(unique.length)groups.push({label,notes:unique});};
17656
+ add('Model notes',C.read_notes);for(const p of C.plans||[])add('Sheet '+String(p.sheet||'—'),p.read_notes);
17657
+ if(!groups.length)return '';return '<section class=read-notes aria-label="Sheet read notes">'+groups.map(g=>'<h3>'+esc(g.label)+'</h3><ul>'+g.notes.map(n=>'<li>'+esc(n)+'</li>').join('')+'</ul>').join('')+'</section>';}
17658
+ function readFieldsHtml(row,target){return (row.observations||[]).map(observation=>{
17659
+ const flags=[observation.provenanceLabel];if(observation.inherited)flags.push('Shared evidence — inherited after split');if(observation.verified)flags.push('✓ Human-confirmed observation');
17660
+ return '<div class=read-group><div class=read-group-head><b>'+esc(observation.sheet||'Unknown sheet')+'</b><span>'+flags.map(esc).join(' · ')+'</span></div>'+observation.fields.map(field=>{
17661
+ const below=target!=null&&field.confidence<target;return '<div class=read-field><b>'+esc(field.label)+'</b><span class=read-value>'+esc(readValueText(field))+'</span><span class=read-pct'+(below?' style="color:var(--warn)"':'')+'>'+field.confidence+'%'+(below?' · below target':'')+'</span></div>';}).join('')+'</div>';}).join('');}
17662
+ let confReadBand='all',confRestoreMember=null,confRestoreControl=null;
17663
+ function rememberConfControl(control,kind){confRestoreControl={kind,value:control.dataset[kind]};}
17664
+ function restoreConfControl(){if(!confRestoreControl)return false;const pending=confRestoreControl;confRestoreControl=null;
17665
+ const selectors={readBand:'#confFilter [data-read-band]',readCat:'#confFilter [data-read-cat]',band:'#confFilter [data-band]',fcat:'#confFilter [data-fcat]'};
17666
+ const selector=selectors[pending.kind];if(!selector)return false;const next=[...document.querySelectorAll(selector)].find(control=>control.dataset[pending.kind]===pending.value);if(!next)return false;next.focus();return true;}
17667
+ function renderReadConf(){const projection=readConfidenceProjection(),target=effectiveTarget(),summary=ReadConfidence.summarizeReadConfidence(projection,target);
17668
+ if(!['all','beams','columns'].includes(confCat))confCat='all';if(target==null)confReadBand='all';readTargetControl();
17669
+ const metric=(label,value,note)=>'<div class=ccard><div class=cc-label>'+label+'</div><div class=cc-score>'+value+'</div><div class=cc-counts><span>'+note+'</span></div></div>';
17670
+ document.getElementById('confCats').innerHTML=metric('Recorded fields',summary.totalFields,'immutable drawing values')+metric('Below target',target==null?'—':summary.belowFields,target==null?'No target set':('strictly below '+target+'%'))+metric('Members affected',target==null?'—':summary.affectedMembers,'review destinations')+metric('Not recorded',summary.notRecordedMembers,'members without field confidence');
17671
+ const disabled=target==null,blocked='Set a target above to filter uncertain reads.';
17672
+ document.getElementById('confFilter').innerHTML='<span class=glab>Read confidence</span><span class=grp><button data-command-id="steel.confidence-filter#all recorded reads" data-read-band=all class="'+(confReadBand==='all'?'on':'')+'" aria-pressed="'+(confReadBand==='all')+'">All</button><button data-command-id="steel.confidence-filter#reads below target" data-read-band=below class="'+(confReadBand==='below'?'on':'')+'" aria-pressed="'+(confReadBand==='below')+'"'+(disabled?' disabled aria-disabled=true data-blocked-reason="'+esc(blocked)+'"':'')+'>Below target</button></span><span class=glab>Category</span><span class=grp>'+[['all','All'],['beams','Beams'],['columns','Columns']].map(([key,label])=>'<button data-command-id="steel.confidence-filter#category '+key+'" data-read-cat="'+key+'" class="'+(confCat===key?'on':'')+'" aria-pressed="'+(confCat===key)+'">'+label+'</button>').join('')+'</span><span class=glab style="margin-left:auto">'+(target==null?'No target set':(summary.belowFields+' fields below '+target+'% · '+summary.affectedMembers+' members'))+'</span>';
17673
+ let rows=projection.rows.map((row,i)=>({row,i,member:(C.members||[]).find(m=>m&&m.id===row.memberId)}));
17674
+ if(confCat==='beams')rows=rows.filter(x=>(x.member&&x.member.role)!=='column');else if(confCat==='columns')rows=rows.filter(x=>x.member&&x.member.role==='column');
17675
+ if(confReadBand==='below')rows=rows.filter(x=>ReadConfidence.rowIsBelowTarget(x.row,target));
17676
+ let h=projection.diagnostics.length?'<div class=read-diag role=alert>'+projection.diagnostics.length+' drawing-confidence record'+(projection.diagnostics.length===1?' could':'s could')+' not be read. Review the source contract before treating this report as complete.</div>':'';
17677
+ if(!rows.length){const unread=projection.diagnostics.length>0,category=confCat==='beams'?'beam':confCat==='columns'?'column':null;
17678
+ const empty=unread?'No readable members match this filter. Unread drawing-confidence records remain and may affect the result.':
17679
+ confReadBand==='below'&&target!=null?(category?'No recorded '+category+' fields are below the '+target+'% target.':'No recorded fields are below the '+target+'% target.'):
17680
+ category?'No '+category+' members match this filter.':'No members in the model yet.';
17681
+ h+='<div class=hint style="padding:14px 0">'+empty+'</div>';}
17682
+ else{h+='<table class=ftab><thead><tr><th>Read</th><th>Member</th><th>Type</th><th>Source</th><th>Evidence</th><th></th></tr></thead><tbody>';
17683
+ rows.forEach(({row,i,member})=>{const below=ReadConfidence.rowIsBelowTarget(row,target),sources=[...new Set(row.observations.map(o=>o.sheet).filter(Boolean))];let evidence;
17684
+ if(row.state==='unobserved')evidence='No active drawing observation is linked to this member.';else if(row.state==='unrecorded')evidence='No per-field read confidence was recorded for this member.';else evidence='Lowest recorded field '+row.minimum+'%'+(below?' · below '+target+'% target':'');
17685
+ const exp=confExpand===row.memberId,region='confReadFields'+i;
17686
+ h+='<tr class=confrow data-mid="'+esc(row.memberId)+'"><td>'+(row.minimum==null?'—':(row.minimum+'%'))+'</td><td>'+esc((member&&member.profile)||row.memberId)+'</td><td>'+esc(member&&member.role==='column'?'Column':member&&member.memberType==='brace'?'Brace':'Beam')+'</td><td>'+esc(sources.join(', ')||'—')+'</td><td><span class="chip '+(below?'assumed':'')+'">'+esc(evidence)+'</span></td><td>'+(row.fieldCount?'<button data-command-id="steel.confidence-fields#'+esc(row.memberId)+'" class=ghost data-review="'+esc(row.memberId)+'" aria-expanded="'+exp+'" aria-controls="'+region+'">Review fields</button> ':'')+'<button data-command-id="steel.locate-member#'+esc(row.memberId)+'" class=ghost data-read-loc="'+esc(row.memberId)+'">Locate</button></td></tr>';
17687
+ if(exp)h+='<tr id="'+region+'"><td></td><td colspan=5 class=conf-expand>'+readFieldsHtml(row,target)+'</td></tr>';});h+='</tbody></table>';}
17688
+ h+=readNotesHtml();document.getElementById('confBody').innerHTML=h;wireReadConf(projection);
17689
+ if(!restoreConfControl()&&confRestoreMember){const id=confRestoreMember;confRestoreMember=null;const next=[...document.querySelectorAll('#confBody [data-review]')].find(b=>b.dataset.review===id);if(next)next.focus();}}
17690
+ function wireReadConf(projection){document.querySelectorAll('#confFilter [data-read-band]').forEach(b=>b.onclick=()=>{if(b.disabled)return;rememberConfControl(b,'readBand');confReadBand=b.dataset.readBand;renderConf();});
17691
+ document.querySelectorAll('#confFilter [data-read-cat]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'readCat');confCat=b.dataset.readCat;renderConf();});
17692
+ document.querySelectorAll('#confBody [data-review]').forEach(b=>b.onclick=()=>{const id=b.dataset.review;confExpand=confExpand===id?null:id;confRestoreMember=id;renderConf();});
17693
+ document.querySelectorAll('#confBody [data-read-loc]').forEach(b=>b.onclick=()=>locateReadMember(b.dataset.readLoc,projection));}
17694
+ async function locateReadMember(id,projection){const row=projection.rows.find(r=>r.memberId===id),canonical=(C.members||[]).find(member=>member&&member.id===id);if(!row||!canonical)return;const pi=readPlanIndex(row);
17695
+ selDimIds.clear();selIds=new Set([id]);geoMode=null;setGeo();closeConf(false);
17696
+ if(pi>=0){if(pi!==C.active)setPlan(pi);const projected=byId(id);if(projected){render();zoomToMember(projected);if(view3d)document.getElementById('stage3d').focus();else svg.focus();toast('Selected '+id+' on '+String(C.plans[pi].sheet)+'.');return;}}
17697
+ render();await setView('3d');if(!view3d){svg.focus();toast('Selected '+id+', but it has no editable 2D plan view and 3D is unavailable.');return;}
17698
+ if(window.Steel3DView)window.Steel3DView.setSelection(selIds);document.getElementById('stage3d').focus();toast('Selected '+id+' in 3D — no editable 2D plan view is available.');}
17699
+ function updConf(){const el=document.getElementById('confStat');if(!el)return;
17700
+ if(nativeElevationModel()){const projection=readConfidenceProjection();if(!projection.rows.length){el.style.display='none';return;}el.style.display='';const target=effectiveTarget(),summary=ReadConfidence.summarizeReadConfidence(projection,target),unread=summary.diagnosticCount;document.getElementById('confLabel').textContent='Read confidence';document.getElementById('confPct').textContent=summary.totalFields+' field'+(summary.totalFields===1?'':'s');const tg=document.getElementById('confTgt');tg.textContent=(target==null?(summary.lowest==null?' · not recorded':(' · lowest '+summary.lowest+'%')):(' · '+summary.belowFields+' below '+target+'%'+(summary.notRecordedMembers?' · '+summary.notRecordedMembers+' members not recorded':'')))+(unread?' · '+unread+' unread':'');tg.style.color=(target!=null&&summary.belowFields)||unread?'var(--warn)':'';el.dataset.tip=(unread?unread+' drawing-confidence record'+(unread===1?' could':'s could')+' not be read; the result is incomplete. ':'')+(target==null?'No confidence target is set. Click to review recorded drawing fields.':summary.belowFields+' recorded drawing field'+(summary.belowFields===1?' is':'s are')+' below the '+target+'% target. Click to review them.');return;}
17701
+ const s=scoreContractJS();
17540
17702
  if(!s.byMember.length){el.style.display='none';return;}el.style.display='';
17703
+ document.getElementById('confLabel').textContent='Confidence';
17541
17704
  const sc=s.overall.score,col=bandColorForPct(sc),tgt=effectiveTarget();
17542
17705
  const b=document.getElementById('confPct');b.textContent=sc==null?'—':sc+'%';b.style.color=col;
17543
17706
  // Goal suffix: "· target N%" (muted, static) + "(−G%)" gap in the band color, shown only while below target.
@@ -17550,14 +17713,14 @@ function updConf(){const el=document.getElementById('confStat');if(!el)return;co
17550
17713
  el.dataset.tip='Confidence '+(sc==null?'—':sc+'%')+(tgt!=null?' vs target '+tgt+'%':'')+' — '+s.overall.tons.toFixed(1)+' t scored · '+s.overall.rfiCount+' RFI. Click for the report.';}
17551
17714
  // --- the report modal ---
17552
17715
  let confBand='all',confCat='all',confExpand=null;
17553
- function openConf(){confExpand=null;renderConf();document.getElementById('confModal').style.display='flex';}
17554
- function closeConf(){document.getElementById('confModal').style.display='none';}
17716
+ function openConf(){confExpand=null;renderConf();document.getElementById('confModal').style.display='flex';document.getElementById('confClose').focus();}
17717
+ function closeConf(restore=true){document.getElementById('confModal').style.display='none';if(restore)document.getElementById('confStat').focus();}
17555
17718
  function confOpen(){return document.getElementById('confModal').style.display==='flex';}
17556
17719
  function _bar(pct){return '<div class=cc-bar><div class=cc-fill style="width:'+(pct||0)+'%;background:'+bandColorForPct(pct)+';'+(pct==null?'opacity:0':'')+'"></div></div>';}
17557
17720
  function _countsHtml(c){const out=['verified','high','med','low','rfi'].filter(k=>c[k]>0).map(k=>'<span style="color:'+BANDC[k]+'">'+BANDLAB[k][0]+' <b>'+c[k]+'</b></span>').join('');return out||'<span>—</span>';}
17558
- function renderConf(){const s=scoreContractJS();const cat=s.byCategory;
17721
+ function renderConf(){if(nativeElevationModel()){renderReadConf();return;}const s=scoreContractJS();const cat=s.byCategory;
17559
17722
  const ct=document.getElementById('confTarget');if(ct&&document.activeElement!==ct){ // value = the per-read OVERRIDE only; the app default shows as a placeholder (empty = using default)
17560
- ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder=TARGET_CONF!=null?String(TARGET_CONF):'70';}
17723
+ ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder='—';}readTargetControl();
17561
17724
  const card=(key,label,cs,stub)=>'<div class="ccard'+(stub?' stub':' click')+(confCat===key?' on':'')+'" data-cat="'+key+'"'+(stub?' data-tip="not scored yet"':'')+'>'+
17562
17725
  '<div class=cc-label>'+label+'</div>'+
17563
17726
  '<div class=cc-score style="color:'+(stub?'var(--mut)':bandColorForPct(cs.score))+'">'+(stub||cs.score==null?'—':cs.score+'%')+'</div>'+
@@ -17570,7 +17733,7 @@ function renderConf(){const s=scoreContractJS();const cat=s.byCategory;
17570
17733
  '<span class=glab>Category</span><span class=grp>'+cats.map(c=>'<button data-command-id="steel.confidence-filter#category '+c+'" data-fcat="'+c+'" class="'+(confCat===c?'on':'')+'" aria-pressed="'+(confCat===c?'true':'false')+'">'+(c==='all'?'All':c[0].toUpperCase()+c.slice(1))+'</button>').join('')+'</span>'+
17571
17734
  '<span class=glab style="margin-left:auto">Coverage: '+s.coverage.members+' members · '+s.coverage.segments+' segments (approx.)</span>';
17572
17735
  document.getElementById('confBody').innerHTML=confBodyHtml(s);
17573
- wireConf();}
17736
+ wireConf();restoreConfControl();}
17574
17737
  function confBodyHtml(s){
17575
17738
  if(!s.byMember.length&&!s.byDetail.length)return '<div class=hint style="padding:14px 0">No members in the model yet.</div>';
17576
17739
  if(confCat==='connections'){
@@ -17605,18 +17768,22 @@ function confBodyHtml(s){
17605
17768
  h+='</tbody></table>';return h;}
17606
17769
  function wireConf(){
17607
17770
  document.querySelectorAll('#confCats .ccard.click').forEach(c=>c.onclick=()=>{confCat=(confCat===c.dataset.cat?'all':c.dataset.cat);renderConf();});
17608
- document.querySelectorAll('#confFilter [data-band]').forEach(b=>b.onclick=()=>{confBand=b.dataset.band;renderConf();});
17609
- document.querySelectorAll('#confFilter [data-fcat]').forEach(b=>b.onclick=()=>{confCat=b.dataset.fcat;renderConf();});
17771
+ document.querySelectorAll('#confFilter [data-band]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'band');confBand=b.dataset.band;renderConf();});
17772
+ document.querySelectorAll('#confFilter [data-fcat]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'fcat');confCat=b.dataset.fcat;renderConf();});
17610
17773
  document.querySelectorAll('#confBody tr.confrow').forEach(r=>r.onclick=e=>{if(e.target.closest('button'))return;const id=r.dataset.mid;confExpand=confExpand===id?null:id;renderConf();});
17611
17774
  document.querySelectorAll('#confBody button[data-loc]').forEach(b=>b.onclick=e=>{e.stopPropagation();const pi=+b.dataset.pi;if(pi!==C.active)setPlan(pi);const m=byId(b.dataset.loc);if(!m)return;selDimIds.clear();selIds=new Set([m.id]);geoMode=null;setGeo();closeConf();render();zoomToMember(m);});}
17612
17775
  document.getElementById('confStat').onclick=openConf;
17613
- document.getElementById('confTarget').onchange=e=>{ // per-read target override → contract.target_confidence (never the .flo)
17614
- const raw=String(e.target.value).trim();
17615
- if(raw===''){delete C.target_confidence;} // cleared → fall back to the app default
17616
- else{let v=Math.round(+raw);if(!isFinite(v))return;v=Math.max(0,Math.min(100,v));C.target_confidence=v;e.target.value=v;}
17617
- scheduleSave();updConf();};
17776
+ function commitConfTarget(el){ // per-read target override → contract.target_confidence (never the .flo)
17777
+ const raw=String(el.value).trim(),had=typeof C.target_confidence==='number',before=had?C.target_confidence:null;let after=null;
17778
+ if(raw===''){if(had)delete C.target_confidence;} // cleared → fall back to the app default
17779
+ else{let v=Math.round(+raw);if(!isFinite(v))return;v=Math.max(0,Math.min(100,v));after=v;C.target_confidence=v;el.value=v;}
17780
+ if(before!==after)scheduleSave(); // Enter then blur/change is one mutation, not two
17781
+ updConf();if(confOpen())renderConf();}
17782
+ document.getElementById('confTarget').onchange=e=>commitConfTarget(e.target);
17783
+ document.getElementById('confTarget').onkeydown=e=>{if(e.key!=='Enter')return;e.preventDefault();commitConfTarget(e.target);e.target.blur();};
17618
17784
  document.getElementById('confClose').onclick=closeConf;
17619
17785
  document.getElementById('confBackdrop').onclick=closeConf;
17786
+ document.getElementById('confModal').addEventListener('keydown',e=>{e.stopPropagation();if(e.key==='Escape'){e.preventDefault();closeConf();return;}if(e.key!=='Tab')return;const f=[...document.querySelectorAll('#confModal button,#confModal input,#confModal [tabindex]')].filter(n=>!n.disabled&&n.offsetParent!==null);if(!f.length)return;const first=f[0],last=f[f.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}});
17620
17787
  // --- detail preview lightbox (click a card / an end's ⤢ to enlarge) ---
17621
17788
  const SHEET_PREV=C.sheet_previews||{}, DBUB=C.detail_bubbles||{};
17622
17789
  // Both halves of a detail reference are parsed in steel-detail-refs.js, where they are covered by tests;
@@ -18118,7 +18285,7 @@ document.addEventListener('keydown',e=>{if(!comboInput||comboPop.style.display==
18118
18285
  function resetPlanViewState(i){
18119
18286
  // The 2D viewport still needs FINITE numbers even though nothing is drawn into it: fitToWindow() divides by
18120
18287
  // EXTX/EXTY, and a NaN zoom propagates into the viewBox and into every snap tolerance derived from it.
18121
- X0=0;Y0=0;X1=1000;Y1=1000;FT=(P&&P.pt_per_ft>0)?P.pt_per_ft:12;RB64='';EXTX=1000;EXTY=1000;
18288
+ X0=0;Y0=0;X1=1000;Y1=1000;FT=(P&&P.pt_per_ft>0)?P.pt_per_ft:12;RB64='';EXTX=1000;EXTY=1000;syncElevationContext();
18122
18289
  svg.setAttribute('viewBox',`${X0} ${Y0} ${X1-X0} ${Y1-Y0}`);
18123
18290
  // The profile list, read from the native document root. Deriving it from
18124
18291
  // `P.members` would be the silent-empty this design refuses; deriving it from `weights` alone would be a
@@ -18156,6 +18323,7 @@ function setPlan(i){
18156
18323
  NO_PLAN_VIEW=false;
18157
18324
  V2_PROJECTION=v2ProjectionForSheet(canonical.sheet);
18158
18325
  P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;
18326
+ syncElevationContext();
18159
18327
  // clip = the drawing's display-space crop. A contract may ship WITHOUT a raster/clip (a shared or
18160
18328
  // committed contract strips raster_b64 for confidentiality), so fall back to the members' bounding
18161
18329
  // box (padded) → the editor renders members on a blank canvas instead of crashing on P.clip[0].
@@ -18178,7 +18346,6 @@ function setPlan(i){
18178
18346
  csaxisMode=false;setCsMode(); // set-axes tool resets per plan; P.frame itself is per-plan data (persisted), so it stays
18179
18347
  snapOnlyClear2d();closeSnapMenu(); // a snap override never outlives its plan (different geometry)
18180
18348
  disarmCm(); // Move/Copy resets per plan too (its counts persist — they're session prefs, not plan data)
18181
- defaultTOS=198;
18182
18349
  document.getElementById('detailsBtn').textContent='Details ('+detTexts().length+')'; // counts what the modal LISTS — openDetails() sets the same label from the same list, and the two disagreed on a callouts-only sheet (#397)
18183
18350
  setMode();render();fitToWindow();
18184
18351
  refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan switcher is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
@@ -18778,17 +18945,17 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
18778
18945
  refSheetOn=_srs2;C.filter=sf;P.sheet=ssh;_ovSnapEls=null;P.members=sm;P.segments=ss;P.dims=sd;dimsVisible=sdv;zoom=sz;}
18779
18946
  // 11) member length — true 3D distance between the two end nodes: level beam = plan run, plumb column = TOS−BOS
18780
18947
  // height (its plan points coincide → 0 plan distance), and a SLOPED member picks up its elevation rise.
18781
- {const sf=FT,st=defaultTOS;FT=12;defaultTOS=198;
18948
+ {const sf=FT,st=defaultTOS;FT=12;defaultTOS=204;
18782
18949
  ok(near(_lenFt({role:'beam',wp:[[0,0],[120,0]]}),10),'_lenFt level beam = plan run (no TOS delta)');
18783
18950
  ok(near(_lenFt({role:'column',wp:[[0,0],[0,0]],col:{bos:0,tos:120,tosDef:false}}),10),'_lenFt plumb column = |TOS−BOS| height (not ~0 plan distance)');
18784
- ok(near(_lenFt({role:'column',wp:[[5,5],[5,5]],col:{bos:12,tos:null,tosDef:true}}),(198-12)/12),'_lenFt column default TOS follows the level');
18951
+ ok(near(_lenFt({role:'column',wp:[[5,5],[5,5]],col:{bos:12,tos:null,tosDef:true}}),(204-12)/12),'_lenFt column default TOS follows the level');
18785
18952
  // sloped brace: 3 ft plan run + 3 ft TOS rise → true length √(3²+3²), NOT the 3 ft plan projection
18786
18953
  ok(near(_lenFt({role:'beam',wp:[[0,0],[36,0]],ends:[{tos:0,tosDef:false},{tos:36,tosDef:false}]}),Math.hypot(3,0,3)),'_lenFt sloped beam = true 3D length (plan run + TOS rise)');
18787
18954
  // battered column: 4 ft plan lean + 12 ft rise → √(4²+12²), not the bare height
18788
18955
  ok(near(_lenFt({role:'column',wp:[[0,0],[48,0]],col:{bos:0,tos:144,tosDef:false}}),Math.hypot(4,0,12)),'_lenFt battered column includes the plan lean');
18789
18956
  // _mTons (BOM) shares the SAME 3D helper → agrees with the inspector (no BOM-vs-display divergence), incl. default-follow
18790
18957
  const dc={role:'column',profile:'W10X49',col:{bos:0,tos:null,tosDef:true}};
18791
- ok(near(_mTons(dc,10,198), _lenFt(dc)*49/2000),'_mTons shares _len3dFt with the display (agree even for a default-follow column)');
18958
+ ok(near(_mTons(dc,10,204), _lenFt(dc)*49/2000),'_mTons shares _len3dFt with the display (agree even for a default-follow column)');
18792
18959
  FT=sf;defaultTOS=st;}
18793
18960
  // 12) Tekla area-select — window (L→R drag) = fully enclosed; crossing (R→L drag) = touched
18794
18961
  {const r=[0,0,10,10],win=(a,b)=>inRect(a,r)&&inRect(b,r),crs=(a,b)=>rectHit(a,b,r);
@@ -18909,14 +19076,14 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
18909
19076
 
18910
19077
  // onElevateMember materialises an unset T.O.S from the OWNING sheet's datum (and from 0, like the
18911
19078
  // bake, when that sheet has none) — never from the active sheet's defaultTOS
18912
- {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=198;
19079
+ {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=204;
18913
19080
  const off={sheet:'S-OFF2',pt_per_ft:36,default_tos:348,members:[],dims:[]};
18914
19081
  const bm={id:'el1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
18915
19082
  const noDef={sheet:'S-NODEF',pt_per_ft:12,members:[],dims:[]};
18916
19083
  const bm2={id:'el2',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
18917
19084
  off.members=[bm];noDef.members=[bm2];C.plans=[savedP,off,noDef];
18918
19085
  view3dApi.onElevateMember('el1',12);
18919
- ok(Math.abs(bm.ends[0].tos-360)<1e-6,'onElevateMember materialises from the OWNING sheet datum (348+12), not the active one (198+12)');
19086
+ ok(Math.abs(bm.ends[0].tos-360)<1e-6,'onElevateMember materialises from the OWNING sheet datum (348+12), not the active one (204+12)');
18920
19087
  view3dApi.onElevateMember('el2',12);
18921
19088
  ok(Math.abs(bm2.ends[0].tos-12)<1e-6,'a sheet with no default_tos resolves to 0 like the bake, not to the active sheet');
18922
19089
  C.plans=savedPlans;P=savedP;defaultTOS=savedTos;}
@@ -19002,7 +19169,7 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
19002
19169
  const leg=(id,wp,ends,off)=>({id,role:'beam',memberType:'brace',profile:'HSS6X6X5/8',wp,
19003
19170
  brace:{type:'vertical',floor:'above',offset:off},ends});
19004
19171
  const AB=[[0,0],[240,0]],BA=[[240,0],[0,0]];
19005
- const lo={tos:0,tosDef:false},hi={tos:198,tosDef:false};
19172
+ const lo={tos:0,tosDef:false},hi={tos:204,tosDef:false};
19006
19173
  // RIGHT: same canonical wp order, transposed elevations → two distinct signatures → both kept.
19007
19174
  P.members=[leg('lA',AB,[lo,hi],12),leg('lB',AB,[hi,lo],-12)];
19008
19175
  ok(redundantDups().length===0,'redundantDups keeps BOTH legs of a correctly-emitted X');