@floless/app 0.132.1 → 0.133.0

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.
@@ -707,6 +707,30 @@
707
707
  body.v3d #snapSect [data-snap3d]{display:flex}
708
708
  #moreMenu .mhint{color:var(--mut);font-size:11px;line-height:1.4;padding:4px 12px 6px;max-width:230px;white-space:normal}
709
709
  #rfiStat{cursor:pointer;text-decoration:underline dotted} #rfiStat:hover b{color:var(--ink-max)}
710
+ #endsStat{color:var(--mut)} #endsStat.has{color:var(--warn)} #endsStat.has b{color:var(--warn)}
711
+ body.member-end-review #stage{cursor:default}
712
+ #panel .mer-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px}
713
+ #panel .mer-title{font-size:10px;font-weight:700;line-height:1.35;letter-spacing:.08em;text-transform:uppercase;color:var(--text)}
714
+ #panel .mer-toolbar,#panel .mer-nav{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:10px}
715
+ #panel .mer-group{margin-top:12px;padding-top:9px;border-top:1px solid var(--line)}
716
+ #panel .mer-group-title{font-size:10px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--mut);margin-bottom:5px}
717
+ #panel .mer-row{display:grid;grid-template-columns:18px minmax(0,1fr);gap:7px;padding:8px 5px;border-left:3px solid transparent;border-radius:4px}
718
+ #panel .mer-row.focused{background:var(--brand-wash);border-left-color:var(--brand)}
719
+ #panel .mer-row:focus-within{outline:2px solid var(--brand);outline-offset:-2px}
720
+ #panel .mer-row label{display:flex;align-items:flex-start;gap:7px;min-width:0;color:var(--text);font-size:12px;font-weight:600;line-height:1.35;cursor:pointer}
721
+ #panel .mer-row input[type=checkbox]{margin-top:1px;cursor:pointer}
722
+ #panel .mer-evidence{font-size:11px;line-height:1.4;color:var(--mut);margin-top:3px;overflow-wrap:anywhere}
723
+ #panel .mer-actions{display:flex;gap:6px;flex-wrap:wrap;margin-top:6px}
724
+ #panel .mer-actions button,#panel .mer-toolbar button,#panel .mer-nav button{font-size:11px;padding:4px 7px}
725
+ #panel .mer-actions button.selected{border-color:var(--brand);background:var(--brand-wash);color:var(--text)}
726
+ #panel .mer-primary{width:100%;margin-top:10px;background:var(--brand);border-color:var(--brand);color:var(--brand-ink);font-weight:700}
727
+ #panel .mer-live{min-height:18px;margin-top:7px;font-size:11px;line-height:1.4;color:var(--mut)}
728
+ .mer-extension{stroke:var(--warn);stroke-width:2;stroke-dasharray:8 5;vector-effect:non-scaling-stroke;pointer-events:none}
729
+ .mer-target-line{stroke:var(--cyan);stroke-width:3;stroke-dasharray:3 4;vector-effect:non-scaling-stroke;fill:none;pointer-events:none}
730
+ .mer-end-marker,.mer-target-marker{fill:var(--panel);stroke-width:2;vector-effect:non-scaling-stroke}
731
+ .mer-end-marker{stroke:var(--warn);pointer-events:none} .mer-target-marker{stroke:var(--cyan);pointer-events:all;cursor:pointer}
732
+ .mer-target-marker.selected{stroke:var(--brand);stroke-width:4}
733
+ .mer-label{fill:var(--text);font:700 11px system-ui;paint-order:stroke;stroke:var(--bg);stroke-width:3px;stroke-linejoin:round;pointer-events:none}
710
734
  #confStat{cursor:pointer;text-decoration:underline dotted} #confStat:hover b{filter:brightness(1.25)}
711
735
  .conf-cats{display:grid;grid-template-columns:repeat(2,1fr);gap:10px;padding:14px;border-bottom:1px solid var(--line)}
712
736
  .ccard{background:var(--bg);border:1px solid var(--line);border-radius:8px;padding:10px 12px}
@@ -1757,6 +1781,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1757
1781
  <span class=stat id=mcStat>Members <b id=mc>0</b></span><span class=stat id=wtStat>Weight <b id=wt>0</b> tons · <b id=wtlb>0</b> lb</span>
1758
1782
  <span class=stat id=rfiStat data-tip="Click to list members with an unresolved size (RFI — Request for Information)">RFI <b id=rc>0</b></span>
1759
1783
  <span class=stat id=dupStat data-tip="Overlapping/duplicate members (same geometry)">Dup <b id=dpc>0</b></span>
1784
+ <span class=stat id=endsStat data-tip="Member ends that may stop at a support face instead of its centerline.">Ends <b id=endsCount>—</b></span>
1760
1785
  <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>
1761
1786
  <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>
1762
1787
  <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>
@@ -1840,6 +1865,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1840
1865
  <div class=msec-body>
1841
1866
  <button data-command-id="steel.check-duplicates" id=dupB data-tip="Selects overlapping members drawn twice by mistake — review, then press Delete to remove the extra one.">Duplicates</button>
1842
1867
  <button data-command-id="steel.check-reversed" id=revB data-tip="Select beams drawn the wrong way — a mostly-horizontal beam should run left→right, a steep/skew beam bottom→up. Review, then press P to swap their direction.">Reversed beams</button>
1868
+ <button data-command-id="steel.check-member-ends" id=memberEndsB data-tip="Find beam and brace ends that may stop at support faces instead of support centerlines. Drawing reads automatically align only unambiguous cases; review the rest here.">Check member ends short of supports</button>
1843
1869
  <button data-command-id="steel.merge-collinear" id=mrgB data-tip="Joins straight, end-to-end runs of the same profile into one beam. Undoable.">Merge collinear beams</button>
1844
1870
  </div>
1845
1871
  <button data-command-id="steel.menu-section#Coordinate system" class=msec-hdr data-sec=coords aria-expanded=false data-tip="Local vs global drawing axes (for skewed framing)">Coordinate system<span class=chev aria-hidden=true>▸</span></button>
@@ -2406,6 +2432,7 @@ function claimMutation(id) { ownWrites.push(id); while (ownWrites.length > OWN_W
2406
2432
  * forever, where the only thing it can do is wrongly suppress somebody else's event. */
2407
2433
  function releaseMutation(id) { const i = ownWrites.indexOf(id); if (i >= 0) ownWrites.splice(i, 1); }
2408
2434
  let C, PAL, WT;
2435
+ let CatalogPicker = null; // steel-catalog-picker.js — provider-neutral Profile and Material catalogue dialogs
2409
2436
  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
2410
2437
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
2411
2438
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
@@ -2465,6 +2492,82 @@ const DEFAULT_PAL=['#60a5fa','#94a3b8','#f59e0b','#34d399','#f472b6','#a78bfa','
2465
2492
  // `conflicted` LATCHES: once a save is refused, firing the identical PUT every 500 ms debounce tick is
2466
2493
  // wasted traffic and makes the pill flicker in a way that reads as broken rather than informative.
2467
2494
  let serverEtag = null;
2495
+ let serverRevision = -1;
2496
+ let contractEventEpoch = 0;
2497
+ let contractEventReady = false;
2498
+ let contractEventWatermark = null;
2499
+ let contractEventSource = null;
2500
+ let contractBootSnapshotInstalled = false;
2501
+ const CONTRACT_EVENT_BOOTSTRAP_ATTEMPTS = 3;
2502
+ const CONTRACT_EVENT_BOOTSTRAP_RETRY_MS = 250;
2503
+
2504
+ function contractEventMatches(m){return m&&typeof m==='object'&&m.type==='contract-changed'&&m.appId===APP_ID&&((m.project||'')===PROJECT);}
2505
+ function editorHasUnsavedWork(){const sv=document.getElementById('saveStat');return !!sv&&(sv.classList.contains('dirty')||sv.classList.contains('err')||sv.classList.contains('conflict'));}
2506
+ function parkDraftForExternalChange(){const parked=flushLocalDraft?flushLocalDraft():false;if(!parked)console.warn('steel-editor: pending edits could not be parked before an external model update');return parked;}
2507
+ function handleContractChanged(m){
2508
+ if(!contractEventMatches(m))return;
2509
+ if(!Number.isSafeInteger(m.storeRevision)||m.storeRevision<0||typeof m.etag!=='string'){console.warn('steel-editor: ignored an unorderable contract event');return;}
2510
+ const own=m.mutationId?ownWrites.indexOf(m.mutationId):-1;
2511
+ if(own>=0){const newest=own===ownWrites.length-1;ownWrites.splice(0,own+1);if(newest&&m.storeRevision>serverRevision){const prev=serverEtag;serverEtag=m.etag;serverRevision=m.storeRevision;restampDraftBase(prev,m.etag);}return;}
2512
+ if(m.storeRevision<=serverRevision)return;
2513
+ if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
2514
+ if(editorHasUnsavedWork()){
2515
+ const parked=parkDraftForExternalChange();
2516
+ const lead=(typeof m.reason==='string'&&CHANGE_LEAD[m.reason])||'The AI updated this model';
2517
+ showAiUpdateBanner(parked?lead+' — reload to see it (you have unsaved edits).':lead+' — but this browser could not save your unsaved edits, so reloading would lose them. Copy them out first.',parked?undefined:{noReload:true});
2518
+ }else location.reload();
2519
+ }
2520
+ function bufferContractEvent(m){
2521
+ if(!Number.isSafeInteger(m.storeRevision)||m.storeRevision<0||typeof m.etag!=='string'){console.warn('steel-editor: ignored an unorderable contract event');return;}
2522
+ if(!contractEventWatermark||m.storeRevision>=contractEventWatermark.storeRevision)contractEventWatermark=m;
2523
+ }
2524
+ function drainContractEvents(epoch){if(epoch!==contractEventEpoch||!contractEventReady)return;const row=contractEventWatermark;contractEventWatermark=null;if(row)handleContractChanged(row);}
2525
+ async function rebootstrapContractEvents(epoch,attempt=0){
2526
+ if(epoch!==contractEventEpoch)return;contractEventReady=false;
2527
+ try{
2528
+ const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/snapshot'+CONTRACT_QS);
2529
+ if(epoch!==contractEventEpoch)return;
2530
+ if(!res.ok)throw new Error('snapshot HTTP '+res.status);
2531
+ const snap=await res.json();
2532
+ if(epoch!==contractEventEpoch)return;
2533
+ if(!snap||!Number.isSafeInteger(snap.storeRevision)||typeof snap.etag!=='string')throw new Error('snapshot payload was not an atomic contract triple');
2534
+ if(snap.storeRevision>serverRevision){
2535
+ if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
2536
+ if(editorHasUnsavedWork()){
2537
+ const parked=parkDraftForExternalChange();
2538
+ showAiUpdateBanner(parked?'A newer model is available. Your edits are still here. Resolve the model update, then check member ends again.':'Live updates reconnected, but this browser could not save your edits. Copy them out before reloading.',parked?undefined:{noReload:true});
2539
+ }else{location.reload();return;}
2540
+ }
2541
+ if(epoch!==contractEventEpoch)return;contractEventReady=true;drainContractEvents(epoch);
2542
+ }catch(e){
2543
+ if(epoch!==contractEventEpoch)return;
2544
+ contractEventReady=false;
2545
+ console.warn('steel-editor: reconnect snapshot failed',e&&e.message?e.message:e);
2546
+ const nextAttempt=attempt+1;
2547
+ if(nextAttempt<CONTRACT_EVENT_BOOTSTRAP_ATTEMPTS){
2548
+ const delay=CONTRACT_EVENT_BOOTSTRAP_RETRY_MS*Math.pow(2,attempt);
2549
+ setTimeout(()=>epoch===contractEventEpoch&&!contractEventReady?rebootstrapContractEvents(epoch,nextAttempt):undefined,delay);
2550
+ }else{
2551
+ showAiUpdateBanner('Live updates disconnected — reconnecting could not verify the latest model. Retrying on a fresh connection.');
2552
+ const failedSource=contractEventSource;
2553
+ if(failedSource){failedSource.onopen=null;failedSource.onmessage=null;failedSource.onerror=null;failedSource.close();}
2554
+ contractEventSource=null;startContractEvents();
2555
+ }
2556
+ }
2557
+ }
2558
+ function startContractEvents(){
2559
+ if(typeof EventSource==='undefined')return;
2560
+ try{
2561
+ const source=new EventSource('/api/events');contractEventSource=source;
2562
+ source.onopen=()=>{
2563
+ if(source!==contractEventSource)return;
2564
+ if(!contractBootSnapshotInstalled)return;
2565
+ contractEventEpoch++;contractEventReady=false;contractEventWatermark=null;rebootstrapContractEvents(contractEventEpoch);
2566
+ };
2567
+ source.onmessage=e=>{if(source!==contractEventSource)return;let m;try{m=JSON.parse(e.data);}catch{return;}if(!contractEventMatches(m))return;if(!contractEventReady)bufferContractEvent(m);else handleContractChanged(m);};
2568
+ source.onerror=()=>{if(source!==contractEventSource)return;contractEventReady=false;if(source.readyState===EventSource.CLOSED){ownWrites.length=0;console.warn('steel-editor: SSE channel closed — live updates paused');showAiUpdateBanner('Live updates disconnected — reload to resume change detection.');}};
2569
+ }catch(e){console.warn('steel-editor: could not open live updates',e&&e.message?e.message:e);}
2570
+ }
2468
2571
  let conflicted = false;
2469
2572
  // Serialize THIS tab's writes. Without it the editor conflicts with ITSELF: a slow autosave still in
2470
2573
  // flight when the next one (or flushContract, which Approve awaits) fires means two requests carrying
@@ -2625,13 +2728,15 @@ function contractFailureState(status, code, serverError, projectScoped) {
2625
2728
  async function boot() {
2626
2729
  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; }
2627
2730
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
2628
- [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf] = await Promise.all([
2731
+ startContractEvents(); // subscribe first; contract events buffer until the atomic snapshot is installed
2732
+ [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker] = await Promise.all([
2629
2733
  import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'),
2630
2734
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
2631
2735
  import('./steel-model-v2-commands.js'), import('./steel-model-v2-client-validation.js'),
2632
2736
  import('./steel-split-view.js'), import('./steel-filter-core.js'), import('./steel-plan-transform.js'),
2737
+ import('./steel-catalog-picker.js'),
2633
2738
  ]);
2634
- const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + CONTRACT_QS);
2739
+ const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + '/snapshot' + CONTRACT_QS);
2635
2740
  // 204 = the project-scoped "nothing stored yet", the quiet twin of the generic 404 below. It carries
2636
2741
  // no body and no code, so it routes straight to the same empty state rather than through the
2637
2742
  // publication-code branches, which only an app-keyed read can produce.
@@ -2695,7 +2800,8 @@ async function boot() {
2695
2800
  // Parse into a LOCAL first (unit 5, P1c-3). `C` is the global everything else in this page reads, so
2696
2801
  // assigning before the type is validated would publish a document this editor cannot render — briefly
2697
2802
  // live, and observable to anything that runs in between. Validate, then publish.
2698
- const loaded = await res.json();
2803
+ const snapshotPayload = await res.json();
2804
+ const loaded = snapshotPayload && snapshotPayload.contract;
2699
2805
  // Shape first, then type. A body that is null, an array or a scalar has no `type` to test, so a
2700
2806
  // type-only gate waved it through and the failure surfaced as a raw red `boot().catch` — "Cannot read
2701
2807
  // properties of null (reading 'palette')" — instead of the styled state this item introduces. `plans`
@@ -2740,7 +2846,8 @@ async function boot() {
2740
2846
  C = loaded;
2741
2847
  // The server's tag for the contract we just read. Every write echoes it back, so a write that would
2742
2848
  // land on top of someone else's is refused instead of silently winning.
2743
- serverEtag = res.headers.get('ETag');
2849
+ serverEtag = snapshotPayload.etag || res.headers.get('ETag');
2850
+ serverRevision = Number.isSafeInteger(snapshotPayload.storeRevision) ? snapshotPayload.storeRevision : -1;
2744
2851
  // The confidence target is a workflow INPUT (target_confidence), not contract data. Read its declared
2745
2852
  // default only for an app-scoped editor: a project owns its contract independently of the installed
2746
2853
  // workflow, so asking /api/app/<id> there can only add a normal 404 to the console. A project-specific
@@ -2767,6 +2874,8 @@ async function boot() {
2767
2874
  if (!_sj.weights || typeof _sj.weights !== 'object' || !_sj.sections || typeof _sj.sections !== 'object') throw new Error('payload missing weights/sections');
2768
2875
  window.__AISC_WEIGHTS = _sj.weights;
2769
2876
  window.__AISC_SECTIONS = _sj.sections;
2877
+ window.__STEEL_PROFILE_CATALOG = _sj.catalog;
2878
+ window.__STEEL_MATERIAL_CATALOG = _sj.materials;
2770
2879
  } catch (e) {
2771
2880
  window.__AISC_LOAD_FAILED = true;
2772
2881
  console.warn('AISC shape table failed to load — sizes and weights are unavailable:', e && e.message ? e.message : e);
@@ -2785,109 +2894,9 @@ async function boot() {
2785
2894
  // Reference models (#278) are always a model-level array in the native contract.
2786
2895
  if(!Array.isArray(C.reference_models))C.reference_models=[];
2787
2896
  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())
2788
- // SSE: listen for external contract writebacks (e.g. the terminal AI PUT a revision).
2789
- // We open our own EventSource to the same /api/events endpoint as the main app.
2790
- // Uses the same parse format: es.onmessage → JSON.parse(e.data) → {type, ...}.
2791
- if (typeof EventSource !== 'undefined') {
2792
- try {
2793
- const es = new EventSource('/api/events');
2794
- es.onmessage = (e) => {
2795
- let m;
2796
- try { m = JSON.parse(e.data); } catch { return; }
2797
- if (!m || typeof m !== 'object') return;
2798
- if (m.type !== 'contract-changed') return;
2799
- if (m.appId !== APP_ID) return;
2800
- // …and the same PROJECT. Two projects of one app share an appId, so without this a write to one
2801
- // reloads the other's tab and (before the removal below was dropped) destroyed its draft — item
2802
- // A's own bug class, left half-fixed: the key became project-scoped while the invalidation did
2803
- // not. `|| ''` on both sides because an app-scoped write carries no `project` at all.
2804
- if ((m.project || '') !== PROJECT) return;
2805
- // OUR OWN echo, recognised by NAME rather than by clock (unit 5, P1c-3).
2806
- const own = m.mutationId ? ownWrites.indexOf(m.mutationId) : -1;
2807
- if (own >= 0) {
2808
- // Everything OLDER than the match is superseded: SSE preserves order on a connection, so an
2809
- // echo we have not seen by the time a later one arrives is never coming.
2810
- const newest = own === ownWrites.length - 1;
2811
- ownWrites.splice(0, own + 1);
2812
- // Adopt the tag the server produced for our write — but ONLY from the newest echo. This is the
2813
- // case the old clock could never cover (a PUT that succeeds while its response is lost leaves
2814
- // `serverEtag` stale, so the tab's own next save is refused against its own change) — and
2815
- // review found the mirror image: a LATE echo carries an OLDER tag, and adopting that rolls
2816
- // `serverEtag` backwards, guaranteeing a 412 on the user's next write.
2817
- if (newest && typeof m.etag === 'string' && m.etag) { const prev = serverEtag; serverEtag = m.etag; restampDraftBase(prev, m.etag); }
2818
- return;
2819
- }
2820
- // An external write. The draft is deliberately NOT dropped here any more: with a server-issued
2821
- // base recorded, a reload now compares bases and OFFERS a stale draft back instead of masking
2822
- // the newer version with it — which is the only thing the removal was ever protecting against.
2823
- // Removing it first was actively harmful, because it ran BEFORE the `hasUnsaved` check below:
2824
- // in exactly the case where work was at risk, the durable copy was destroyed and only in-memory
2825
- // `C` survived, so the banner's own Reload button lost it.
2826
- // Auto-reload straight into the AI's version so the user never has to hit refresh — EXCEPT
2827
- // when they have unsaved in-browser edits (saveStat 'dirty'/'err'), where a silent reload
2828
- // would discard their work; there we fall back to the choose-to-reload banner.
2829
- const sv = document.getElementById('saveStat');
2830
- // 'conflict' counts as unsaved, and omitting it lost data: after a refused save the edits are
2831
- // unsaved BY DEFINITION, so a silent reload here would drop the localStorage draft (above) and
2832
- // discard exactly the work the conflict banner had just promised was "still here".
2833
- // (Historically this also had to compensate for the 2.5 s echo suppressor, which stopped working
2834
- // the moment the conflict latch tripped — persistServer returned before stamping its timestamp,
2835
- // so the window expired and stayed expired. Identity has no such state, but this check is load
2836
- // bearing on its own merits and stays.)
2837
- const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err')
2838
- || sv.classList.contains('conflict'));
2839
- if (hasUnsaved) {
2840
- // GET THE EDIT ONTO DISK FIRST. 'dirty' also covers the 500 ms debounce window, where
2841
- // `persist()` has not run yet and the edit lives only in `C` — so the Reload this banner is
2842
- // about to offer would discard it, with no draft to park and nothing to offer back. That is
2843
- // the same loss the stale-draft flow exists to prevent, arriving 500 ms earlier.
2844
- //
2845
- // The LOCAL half only. The server write stays on its debounce: the store has just moved, so a
2846
- // PUT fired from here would be refused anyway, and racing one against the write we are
2847
- // reacting to buys nothing. `persist()` is idempotent and does not disarm the timer, so the
2848
- // pending tick rewriting the same row a moment later changes nothing.
2849
- // The RESULT matters: quota exceeded, private mode, storage disabled by policy — persist()
2850
- // swallows each into a red pill, and offering "↻ Reload" over an edit that reached no storage
2851
- // is offering the very loss this flush exists to prevent, with a button on it.
2852
- const parked = flushLocalDraft ? flushLocalDraft() : false;
2853
- if (!parked) console.warn('steel-editor: the pending edit could not be written to this browser — a reload would lose it');
2854
- // WHAT happened, not a guess at who. Absent or unrecognised → today's wording byte for byte.
2855
- // The contract PUT — the one writer that usually IS the terminal AI — deliberately sends no
2856
- // reason, so the generic sentence stays correct for it; and a tab left open across an
2857
- // auto-update can outlive its server, so a token from a NEWER build has to degrade quietly
2858
- // rather than reach the bar.
2859
- //
2860
- // Read INSIDE this branch on purpose. Computed above the `if`, a `CHANGE_LEAD` that ever
2861
- // became unreachable (P3 is actively refactoring `main()`'s closure) would throw here — and
2862
- // an exception at this point means the tab neither banners NOR reloads, silently going deaf
2863
- // to external writes with the error swallowed by the event loop. The reload path must not be
2864
- // able to fail for a reason that only the banner path cares about.
2865
- const lead = (typeof m.reason === 'string' && CHANGE_LEAD[m.reason]) || 'The AI updated this model';
2866
- showAiUpdateBanner(parked
2867
- ? lead + ' — reload to see it (you have unsaved edits).'
2868
- // No Reload offered here, deliberately: with nothing in storage it is a button that destroys
2869
- // their work, and there is no second copy to offer back afterwards.
2870
- : lead + ' — but this browser could not save your unsaved edits, so reloading would lose them. Copy them out first.',
2871
- parked ? undefined : { noReload: true });
2872
- } else location.reload();
2873
- };
2874
- es.onerror = () => {
2875
- // Transient drops (readyState CONNECTING) auto-reconnect — ignore. A CLOSED channel is
2876
- // terminal: live writeback detection is dead, so surface it (the banner's Reload re-opens
2877
- // the editor and its EventSource) instead of leaving the user on a silently-stale view.
2878
- if (es.readyState === EventSource.CLOSED) {
2879
- // Every id we are still holding is now DEAD: the channel that would have carried its echo is
2880
- // gone, so none can ever be matched. Holding them serves nothing and is the only way the list
2881
- // grows without bound — the one case review raised against retaining an id past its response.
2882
- ownWrites.length = 0;
2883
- console.warn('steel-editor: SSE channel closed — live updates paused');
2884
- showAiUpdateBanner('Live updates disconnected — reload to resume change detection.');
2885
- }
2886
- };
2887
- } catch (_) {
2888
- // If EventSource construction itself throws (unusual), the Reload button still works
2889
- }
2890
- }
2897
+ contractBootSnapshotInstalled=true;
2898
+ contractEventReady=true;
2899
+ drainContractEvents(contractEventEpoch);
2891
2900
  }
2892
2901
 
2893
2902
  /**
@@ -3058,6 +3067,7 @@ const newModelId=()=>`m-v2-${Date.now().toString(36)}-${(v2IdSeq++).toString(36)
3058
3067
  V2_SESSION=V2Commands.createV2CommandSession(C,{
3059
3068
  validate:doc=>V2Validation.validateClientSteelModelV2(doc,V2_SCHEMA),
3060
3069
  mintId:newModelId,
3070
+ resolveSection:m=>{const d=profileDimsIn(m&&m.profile);return d?{...d,units:'in'}:null;},
3061
3071
  afterCommit:()=>{v2InvalidateMemberIndex();if(DEV_MODE&&V2_PROJECTION)P=ModelCmd.deepFreezeProjection(V2_PROJECTION.plan);}
3062
3072
  });
3063
3073
  let mode='sel', drag=null, picking=false, pickKind='profile', pickEnd=null, geoMode=null;
@@ -3065,7 +3075,7 @@ let dimMode=false, dimDraft=null, dimAxis='free', selDimIds=new Set(), dimsVisib
3065
3075
  let qdAnchorPt=(()=>{try{const v=localStorage.getItem('steel:qdAnchor:v2');return (v==='a'||v==='b'||v==='mid')?v:'a';}catch(_){return 'a';}})(); // F7 quick-dim: which point on each beam to space between (start/mid/end), persisted
3066
3076
  let dimEdit=null; // F8: the open double-click value editor {id,l,r,pin} or null (a modal popup)
3067
3077
  let _lastDimDown=null; // F8: {id,t} of the last dim pointerdown, for manual double-click detection
3068
- let drawDraft=null; // Add-member tool: the first CLICKED start point (or null) — click-to-start / click-to-finish, mirroring the Dimension tool (no more press-drag)
3078
+ let drawDraft=null,drawBasisTok=null; // Add-member tool: the first CLICKED start point + immutable authoring-basis snapshot (or null) — both picks must stay in one frame
3069
3079
  let calloutsVisible=true; // Workstream B: show/hide the clickable callout bubbles (details + section/elevation/detail-ref) on the plan in select mode
3070
3080
  let showSelLen=(()=>{try{return localStorage.getItem('steel:selLen:v2')==='1';}catch(_){return false;}})(); // ⋯ Display → Show member length: paint each selected member's length on the canvas (opt-in, default off)
3071
3081
  let refSheetOn=(()=>{try{return localStorage.getItem('steel:refSheet:v2')!=='0';}catch(_){return true;}})(); // ⋯ Display → Reference sheet (F13): show/hide the traced PDF/SVG overlay under the model (default ON; only an explicit '0' hides it)
@@ -3091,6 +3101,85 @@ let selGridIds=new Set(); // selected grid-line ids — synthetic keys 'gv:i'/
3091
3101
  let selIds=new Set();
3092
3102
  let findHits=new Set(); // Find-in-model highlight (Workspaces Ctrl+F) — kept SEPARATE from selIds so a search never clobbers/drops the user's real selection
3093
3103
  let undo=[], redo=[];
3104
+ let memberEndReview=null;
3105
+ let memberEndScan=null;
3106
+ let memberEndStatus={known:false,count:null,etag:null,revision:null,scopeSig:null};
3107
+ const memberEndKey=f=>f.memberId+'\0'+f.end;
3108
+ function memberEndHistoryAction(direction){return direction==='redo'?{label:'Redo',tip:'Redo the newest member-end resolution'}:{label:'Undo',tip:'Undo the newest member-end resolution'};}
3109
+ function memberEndScope(){const plan=C.plans&&C.plans[C.active];return view3d?{kind:'model-3d'}:{kind:'active-view',viewId:plan&&plan.sheet||''};}
3110
+ function memberEndScopeSig(scope){return JSON.stringify(scope||memberEndScope());}
3111
+ function memberEndUnresolved(report){const c=report&&report.counts||{};return (c.needsReview||0)+(c.stale||0)+(c.notCheckable||0);}
3112
+ function updateMemberEndStatus(){
3113
+ const stale=!memberEndStatus.known||memberEndStatus.etag!==serverEtag||memberEndStatus.revision!==serverRevision||memberEndStatus.scopeSig!==memberEndScopeSig();
3114
+ const n=stale?null:memberEndStatus.count,el=document.getElementById('endsStat'),v=document.getElementById('endsCount'),b=document.getElementById('memberEndsB');
3115
+ if(v)v.textContent=n==null?'—':String(n);if(el)el.classList.toggle('has',n>0);if(b)b.textContent=n==null?'Check member ends short of supports':'Member ends short of supports ('+n+')';
3116
+ }
3117
+ function invalidateMemberEndReview(message){memberEndStatus={known:false,count:null,etag:null,revision:null,scopeSig:null};if(memberEndReview||memberEndScan){memberEndReview=null;memberEndScan=null;document.body.classList.remove('member-end-review');selIds.clear();render();}updateMemberEndStatus();if(message)toast(message);}
3118
+ window.invalidateMemberEndReview=invalidateMemberEndReview;
3119
+ function memberEndGroup(f){if(f.basis&&f.basis.kind==='drawing'){for(const p of C.plans||[])for(const o of p.memberObservations||[])if(f.basis.origins.some(x=>x.observationId===o.id))return p.sheet+(p.viewKind==='elevation'?' · elevation':'');}return f.basis&&f.basis.kind==='geometry-review'?'3D geometry review':'Model';}
3120
+ function memberEndRole(f){return f.role==='horizontal-brace'?'Horizontal brace':f.role==='vertical-brace'?'Vertical brace':f.role==='brace-unknown'?'Brace':'Beam';}
3121
+ 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;}
3122
+ function memberEndReason(f){const words={
3123
+ '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'};
3124
+ return (f.reasonCodes||[]).map(r=>words[r]||r).join(' · ');
3125
+ }
3126
+ function memberEndTargetName(t){return (t.memberIds||[]).join(' + ')+' centerline';}
3127
+ function memberEndTargetEqual(a,b){
3128
+ if(!a||!b||a.kind!==b.kind)return false;
3129
+ const ai=a.memberIds||[],bi=b.memberIds||[],ap=a.point||{},bp=b.point||{},az=ap.z||{},bz=bp.z||{};
3130
+ return ai.length===bi.length&&ai.every((id,i)=>id===bi[i])&&ap.x===bp.x&&ap.y===bp.y&&az.known===bz.known;
3131
+ }
3132
+ function memberEndCanKeepShort(f){
3133
+ if(!f||f.classification!=='needs-review'||!f.basis||f.basis.kind!=='drawing')return !!f&&f.classification==='needs-review';
3134
+ const origins=f.basis.origins||[],first=origins[0]&&origins[0].observedPoint;
3135
+ return !!first&&origins.every(o=>{const p=o&&o.observedPoint;return !!p&&p.x===first.x&&p.y===first.y&&p.z&&first.z&&p.z.known===first.z.known;});
3136
+ }
3137
+ function memberEndChoicesForReport(report,previous){
3138
+ const chosen=new Map();
3139
+ for(const f of report&&report.findings||[]){
3140
+ if(f.classification!=='needs-review')continue;
3141
+ const key=memberEndKey(f),targets=f.targets||[],prior=previous&&previous.get(key);
3142
+ const retained=prior&&targets.find(t=>memberEndTargetEqual(t,prior));
3143
+ if(retained)chosen.set(key,retained);else if(targets.length===1)chosen.set(key,targets[0]);
3144
+ }
3145
+ return chosen;
3146
+ }
3147
+ function memberEndDistance(f,t){const a=f.currentPoint,z=a&&a.z&&Number.isFinite(a.z.known)?a.z.known:t.point.z.known;return Math.hypot(t.point.x-a.x,t.point.y-a.y,t.point.z.known-z);}
3148
+ function memberEndSnapshot(doc){return {v2:true,members:doc.members,grid:doc.grid||null,plans:(doc.plans||[]).map(p=>({sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],frame:p.frame||null,datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:doc.joints||[],connections:doc.connections||[],details:doc.detail_placements||[],views:doc.views||[],member_types:doc.member_types||[],dim_style:doc.dim_style||null,member_styles:doc.member_styles||{},...(Array.isArray(doc.reference_models)?{reference_models:doc.reference_models}:{})};}
3149
+ function installMemberEndContract(doc,etag,revision){
3150
+ V2_SESSION.restoreSnapshot(memberEndSnapshot(doc));V2_PROJECTIONS.clear();
3151
+ const activePlan=C.plans&&C.plans[C.active];
3152
+ 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;}
3153
+ 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);}
3154
+ // A server command replaces the model underneath the editor's local history. Retaining those snapshots
3155
+ // would let Ctrl+Z resurrect pre-command geometry without the server-owned decision/audit metadata.
3156
+ undo.length=0;redo.length=0;updUR();
3157
+ const prev=serverEtag;serverEtag=etag;serverRevision=revision;restampDraftBase(prev,etag);conflicted=false;render();sync3D();
3158
+ }
3159
+ async function memberEndRequest(path,body){
3160
+ if(!PROJECT)throw new Error('Member-end review is available inside a project.');
3161
+ const mutating=path!=='scan',mid=mutating?newMutationId():null,headers={'content-type':'application/json'};if(mutating){headers['x-floless-mutation-id']=mid;if(serverEtag)headers['if-match']=serverEtag;claimMutation(mid);}
3162
+ let res;try{res=await fetch('/api/projects/'+encodeURIComponent(PROJECT)+'/member-ends/'+path,{method:'POST',headers,body:JSON.stringify(body)});}catch(e){if(mid)releaseMutation(mid);throw e;}
3163
+ const d=await res.json().catch(()=>({}));if(!res.ok){if(mid)releaseMutation(mid);const error=new Error(d.error||('Member-end request failed ('+res.status+')'));error.code=d.code;error.status=res.status;throw error;}return d;
3164
+ }
3165
+ async function scanMemberEnds(liveMessage){
3166
+ closeMore();if((memberEndScan&&memberEndScan.busy)||(memberEndReview&&memberEndReview.busy))return;if(!PROJECT){toast('Open this model from a project to check member ends.');return;}
3167
+ memberEndScan={busy:true,error:false,live:'Checking member ends against drawing and model evidence…'};panel();
3168
+ const b=document.getElementById('memberEndsB');if(b)b.textContent='Checking member ends…';
3169
+ try{await window.flushContract();const scope=memberEndScope();const d=await memberEndRequest('scan',{scope});serverEtag=d.etag;serverRevision=d.storeRevision;memberEndStatus={known:true,count:memberEndUnresolved(d.report),etag:d.etag,revision:d.storeRevision,scopeSig:memberEndScopeSig(scope)};
3170
+ if(!d.report.findings.length){memberEndReview=null;memberEndScan={busy:false,error:false,live:'No member ends are short of support centerlines.'};document.body.classList.remove('member-end-review');updateMemberEndStatus();panel();const settled=memberEndScan;if(b){b.classList.add('ok');b.textContent='No short member ends ✓';}setTimeout(()=>{if(memberEndScan===settled){memberEndScan=null;panel();}if(b)b.classList.remove('ok');updateMemberEndStatus();},1500);return;}
3171
+ const chosen=memberEndChoicesForReport(d.report),selected=new Set();for(const f of d.report.findings)if(f.classification==='needs-review'&&f.targets&&f.targets.length===1&&!f.geometryOnly)selected.add(memberEndKey(f));
3172
+ memberEndScan=null;memberEndReview={report:d.report,scope,chosen,selected,focus:0,busy:false,undoToken:d.undo&&d.undo.token||null,undoDirection:d.undo&&d.undo.direction||null,live:typeof liveMessage==='string'?liveMessage:'Check each endpoint against its drawing or model evidence.'};document.body.classList.add('member-end-review');selIds.clear();focusMemberEnd(0);updateMemberEndStatus();
3173
+ }catch(e){memberEndReview=null;memberEndStatus={known:false,count:null,etag:null,revision:null,scopeSig:null};document.body.classList.remove('member-end-review');selIds.clear();memberEndScan={busy:false,error:true,live:e&&e.message?e.message:'Could not check member ends.'};updateMemberEndStatus();panel();toast(memberEndScan.live);}
3174
+ }
3175
+ function closeMemberEndReview(){if(memberEndReview&&memberEndReview.busy){memberEndReview.live='Finish the current member-end action before closing.';panel();return;}memberEndReview=null;document.body.classList.remove('member-end-review');selIds.clear();render();moreBtn.focus();}
3176
+ function focusMemberEnd(index){if(!memberEndReview||memberEndReview.busy)return;const rows=memberEndReview.report.findings;if(!rows.length)return;memberEndReview.focus=(index+rows.length)%rows.length;const f=rows[memberEndReview.focus];selIds=new Set([f.memberId]);render();queueMicrotask(()=>document.querySelector('.mer-row.focused input,.mer-row.focused button')?.focus({preventScroll:true}));}
3177
+ function chooseMemberEndTarget(key,index){if(!memberEndReview||memberEndReview.busy)return;const f=memberEndReview.report.findings.find(x=>memberEndKey(x)===key);const t=f&&f.targets&&f.targets[index];if(!f||!t)return;memberEndReview.chosen.set(key,t);memberEndReview.selected.add(key);memberEndReview.live='Selected '+memberEndTargetName(t)+' for '+f.memberId+' end '+(f.end+1)+'.';panel();render();}
3178
+ async function applyMemberEndSelection(){if(!memberEndReview||memberEndReview.busy)return;const selections=[];for(const f of memberEndReview.report.findings){const key=memberEndKey(f),target=memberEndReview.chosen.get(key);if(f.classification==='needs-review'&&memberEndReview.selected.has(key)&&target)selections.push({findingId:f.findingId,contextHash:f.contextHash,memberId:f.memberId,end:f.end,target});}if(!selections.length)return;
3179
+ const review=memberEndReview;review.busy=true;review.live='Extending selected member ends…';panel();try{const d=await memberEndRequest('apply',{scope:review.scope,selections});installMemberEndContract(d.contract,d.etag,d.storeRevision);if(memberEndReview!==review)return scanMemberEnds();const previousChosen=review.chosen;review.report=d.report;review.undoToken=d.undoToken;review.undoDirection='undo';review.selected.clear();review.chosen=memberEndChoicesForReport(d.report,previousChosen);review.busy=false;review.live='Extended '+selections.length+' member end'+(selections.length===1?'':'s')+' to support centerlines.';memberEndStatus={known:true,count:memberEndUnresolved(d.report),etag:d.etag,revision:d.storeRevision,scopeSig:memberEndScopeSig(review.scope)};updateMemberEndStatus();panel();undoToast(review.live,()=>undoMemberEndResolution());}catch(e){if(memberEndReview===review){review.busy=false;review.live=e.message||'The model changed — check member ends again.';panel();}toast(e.message||'Could not extend member ends.');}}
3180
+ async function keepMemberEnd(f){if(!memberEndReview||memberEndReview.busy)return;const review=memberEndReview;review.busy=true;panel();try{const d=await memberEndRequest('keep-short',{scope:review.scope,findingId:f.findingId,contextHash:f.contextHash,memberId:f.memberId,end:f.end,reason:'other-reviewed'});installMemberEndContract(d.contract,d.etag,d.storeRevision);if(memberEndReview!==review)return scanMemberEnds();review.report=d.report;review.undoToken=d.undoToken;review.undoDirection='undo';review.selected.delete(memberEndKey(f));review.busy=false;review.live='Kept '+f.memberId+' end '+(f.end+1)+' short.';memberEndStatus={known:true,count:memberEndUnresolved(d.report),etag:d.etag,revision:d.storeRevision,scopeSig:memberEndScopeSig(review.scope)};updateMemberEndStatus();panel();}catch(e){if(memberEndReview===review){review.busy=false;review.live=e.message||'Could not keep this member end short.';panel();}}}
3181
+ async function restoreMemberEnd(f){if(!memberEndReview||memberEndReview.busy)return;const review=memberEndReview;review.busy=true;panel();try{const d=await memberEndRequest('restore',{scope:review.scope,findingId:f.findingId,contextHash:f.contextHash,memberId:f.memberId,end:f.end});installMemberEndContract(d.contract,d.etag,d.storeRevision);if(memberEndReview!==review)return scanMemberEnds();review.report=d.report;review.undoToken=d.undoToken;review.undoDirection='undo';review.busy=false;review.live='Restored the traced endpoint for '+f.memberId+'.';memberEndStatus={known:true,count:memberEndUnresolved(d.report),etag:d.etag,revision:d.storeRevision,scopeSig:memberEndScopeSig(review.scope)};updateMemberEndStatus();panel();}catch(e){if(memberEndReview===review){review.busy=false;review.live=e.message||'Could not restore the traced endpoint.';panel();}}}
3182
+ async function undoMemberEndResolution(){if(!memberEndReview||memberEndReview.busy||!memberEndReview.undoToken)return;const review=memberEndReview,token=review.undoToken;review.busy=true;review.live='Updating member-end history…';panel();try{const d=await memberEndRequest('undo',{token});installMemberEndContract(d.contract,d.etag,d.storeRevision);const next=memberEndHistoryAction(d.direction),completed=d.direction==='redo'?'Undid member-end changes':'Redid member-end changes';review.busy=false;await scanMemberEnds(completed+' · '+next.label+' is available');}catch(e){if(memberEndReview===review){review.busy=false;if(e.code==='member-end-undo-unavailable'){review.undoToken=null;review.undoDirection=null;review.live='This history action is no longer available. Check member ends again.';}else review.live='Could not confirm the history action. Check member ends again before retrying.';panel();}toast(e.message||'Could not update member-end history.');}}
3094
3183
  // Selection is MODEL-WIDE, not per-sheet: the 3D shows every plan, so a pick / box-select / Ctrl-click can
3095
3184
  // span sheets. byId + selArr therefore search ALL plans (not just the active P) so the inspector + edits see
3096
3185
  // the whole selection — else selecting a roof (S-203) member while S-202 is active shows nothing, and a
@@ -3144,18 +3233,15 @@ function ensureMeta(m){return ModelCmd.ensureMeta(m);} // unit 5 P3a: the mode
3144
3233
  // MIRROR of server/contract-to-scene.ts depthPosition (same 0.5774 ≈ 30° threshold, mm units) — the
3145
3234
  // inspector must highlight the SAME default the bake uses, or the 3D differs from what the panel says.
3146
3235
  function posDefault(m){
3147
- if(m.position==='top'||m.position==='middle'||m.position==='bottom')return m.position;
3148
- if(m.role==='column')return 'middle';
3149
- if(isBrace(m)&&m.brace&&m.brace.type==='vertical')return 'middle';
3150
3236
  const k=304.8/((P&&P.pt_per_ft>0)?P.pt_per_ft:1);
3151
3237
  const z0=(m.ends&&m.ends[0]&&m.ends[0].tos!=null)?m.ends[0].tos:defaultTOS;
3152
3238
  const z1=(m.ends&&m.ends[1]&&m.ends[1].tos!=null)?m.ends[1].tos:defaultTOS;
3153
3239
  const dz=Math.abs((z0||0)-(z1||0))*25.4, horiz=Math.hypot(m.wp[1][0]-m.wp[0][0],m.wp[1][1]-m.wp[0][1])*k;
3154
- return dz>horiz*0.5774?'middle':'top';}
3240
+ return SteelCore.effectiveDepthPosition(m.position,m.role==='column'?'column':'beam',dz,horiz,isBrace(m)&&m.brace&&m.brace.type==='vertical');}
3155
3241
  // Effective HORIZONTAL profile position — where the work-line sits ACROSS the section. No heuristic:
3156
3242
  // absent = centred, which is what every member did before the field existed. MIRROR of
3157
3243
  // server/contract-to-scene.ts planePosition().
3158
- function posHDefault(m){return (m.positionH==='left'||m.positionH==='right')?m.positionH:'middle';}
3244
+ function posHDefault(m){return SteelCore.effectiveWidthPosition(m.positionH);}
3159
3245
  // Can this member take a Profile Position at all? It needs ONE thing: a section with faces to name. A
3160
3246
  // resolved designation supplies that through profileDimsIn; a CUSTOM/imported section supplies w+d.
3161
3247
  //
@@ -3237,12 +3323,13 @@ function posSectionSvg(m){
3237
3323
  const sec=dims?{w:dims.w,d:dims.d}:((m&&m.section&&m.section.w>0&&m.section.d>0)?{w:m.section.w/25.4,d:m.section.d/25.4}:null);
3238
3324
  if(!sec)return '';
3239
3325
  const round=!!(dims&&dims.round);
3240
- const ex=SteelCore.sectionExtents(SteelCore.outlineFor(m.profile,sec.w,sec.d,null,round));
3326
+ const local=sectionShapeComponents(m.profile,sec.w,sec.d,12,round),localAll=local.flat();
3327
+ const ex={lo:[Math.min(...localAll.map(p=>p[0])),Math.min(...localAll.map(p=>p[1]))],hi:[Math.max(...localAll.map(p=>p[0])),Math.max(...localAll.map(p=>p[1]))]};
3241
3328
  const oy=SteelCore.faceOffset(posHDefault(m),ex.lo[0],ex.hi[0])+(+m.positionHOffset||0)/25.4;
3242
3329
  const oz=SteelCore.faceOffset(posDefault(m),ex.lo[1],ex.hi[1])+(+m.positionOffset||0)/25.4;
3243
3330
  const th=(+m.rot||0)*Math.PI/180,c=Math.cos(th),s=Math.sin(th);
3244
3331
  const map=(u,v)=>[-(u*c-v*s),-(u*s+v*c)];
3245
- const out=sectionShapePts(m.profile,sec.w,sec.d,12,round).map(([x,y])=>map(x+oy,y+oz));
3332
+ const outs=local.map(points=>points.map(([x,y])=>map(x+oy,y+oz))),out=outs.flat();
3246
3333
  const stub=Math.max(sec.w,sec.d)*0.45,pad=Math.max(sec.w,sec.d)*0.16;
3247
3334
  const all=out.concat([[-stub,0],[0,-stub],[0,0]]);
3248
3335
  const xs=all.map(p=>p[0]),ys=all.map(p=>p[1]);
@@ -3255,7 +3342,7 @@ function posSectionSvg(m){
3255
3342
  <line x1="0" y1="${f(-stub)}" x2="0" y2="0" stroke="var(--brand)" stroke-width="${f(sw)}"/>
3256
3343
  <text x="${f(-stub)}" y="${f(-sw*2.5)}" fill="var(--cyan)" font-size="${f(sw*8)}" text-anchor="middle">+W</text>
3257
3344
  <text x="${f(sw*3)}" y="${f(-stub)}" fill="var(--brand)" font-size="${f(sw*8)}">+D</text>
3258
- <polygon points="${out.map(p=>f(p[0])+','+f(p[1])).join(' ')}" fill="var(--brand-wash)" stroke="var(--text)" stroke-width="${f(sw)}" stroke-linejoin="round"/>
3345
+ ${outs.map(points=>`<polygon points="${points.map(p=>f(p[0])+','+f(p[1])).join(' ')}" fill="var(--brand-wash)" stroke="var(--text)" stroke-width="${f(sw)}" stroke-linejoin="round"/>`).join('')}
3259
3346
  <circle cx="0" cy="0" r="${f(sw*2.6)}" fill="var(--warn)"/>
3260
3347
  </svg>`;}
3261
3348
  // The two numeric offsets: stored in MILLIMETRES (contracts are canonical metric), shown and typed in the
@@ -3264,6 +3351,52 @@ function posSectionSvg(m){
3264
3351
  // on every untouched member would be noise on twelve sections' worth of rail.
3265
3352
  const posOffDisp=v=>(typeof v==='number'&&isFinite(v)&&v!==0)?fmtFtIn(v/25.4):'';
3266
3353
  const posOffSet=v=>typeof v==='number'&&isFinite(v)&&v!==0;
3354
+ let positionBasisGeneration=0,positionBasisFingerprint='',positionBasisListeners=new Set();
3355
+ let positionBasisViewUnsub=null;
3356
+ function positionAuthoringBasis(){
3357
+ let raw;
3358
+ if(view3d&&window.Steel3DView&&window.Steel3DView.positionAuthoringBasis){raw=window.Steel3DView.positionAuthoringBasis();}
3359
+ else if(!(P&&P.frame))raw={ok:true,kind:'global',x:[1,0,0],y:[0,1,0]};
3360
+ else{
3361
+ try{
3362
+ const plan={...P,modelGrid:C&&C.grid,grid:C&&C.grid},o=P.frame.o,u=P.frame.u,v=[u[1],-u[0]];
3363
+ const a=PlanXf.sheetPxToWorld(o,plan,{known:0}),bx=PlanXf.sheetPxToWorld([o[0]+u[0],o[1]+u[1]],plan,{known:0}),by=PlanXf.sheetPxToWorld([o[0]+v[0],o[1]+v[1]],plan,{known:0});
3364
+ const c=SteelCore.canonicalPositionBasis([bx.x-a.x,bx.y-a.y,0],[by.x-a.x,by.y-a.y,0]);
3365
+ raw=c?{ok:true,kind:'local',x:[...c.x],y:[...c.y]}:{ok:false,code:'position-authoring-basis-unavailable',message:'Profile Position unavailable: this plan’s local axes are not fully registered.'};
3366
+ }catch(_){raw={ok:false,code:'position-authoring-basis-unavailable',message:'Profile Position unavailable: this plan’s local axes are not fully registered.'};}
3367
+ }
3368
+ const fingerprint=JSON.stringify([view3d?'3d':'2d',P&&P.sheet,raw.ok,raw.kind,raw.x,raw.y,raw.code]);
3369
+ if(fingerprint!==positionBasisFingerprint){positionBasisFingerprint=fingerprint;positionBasisGeneration++;for(const fn of positionBasisListeners)try{fn();}catch(_){}}
3370
+ return Object.freeze({...raw,generation:positionBasisGeneration,capabilityVersion:SteelCore.POSITION_BASIS_CAPABILITY_VERSION,x:raw.x?Object.freeze([...raw.x]):undefined,y:raw.y?Object.freeze([...raw.y]):undefined});
3371
+ }
3372
+ function onPositionAuthoringBasisChange(listener){positionBasisListeners.add(listener);return()=>positionBasisListeners.delete(listener);}
3373
+ function positionFrameLabel(s){return !s.ok?'Unavailable':s.kind==='global'?'Global':(s.kind==='plane'?'Work plane X/Y':(view3d?'3D local X′/Y′':'2D local X′/Y′'));}
3374
+ function positionFrameHTML(){const s=positionAuthoringBasis();return `<div id=posFrame data-position-basis-capability="${SteelCore.POSITION_BASIS_CAPABILITY_VERSION}" class=hint style="margin:0 0 6px;color:${s.ok&&s.kind!=='global'?'var(--cyan)':'var(--mut)'}">Edit frame · <b>${esc(positionFrameLabel(s))}</b></div><div id=posPositionStatus class=hint role=status aria-live=polite aria-atomic=true style="margin:0 0 6px${s.ok?';display:none':';border:1px solid var(--line);border-radius:6px;padding:7px 8px'}">${s.ok?'':esc(s.message)}</div>`;}
3375
+ const POSITION_CONTROL_IDS=['posOff','posHOff','detRotZ','posTop','posMid','posBot','posHLeft','posHMid','posHRight','rot0','rot90','rot180','rot270'];
3376
+ function wirePositionAvailability(){const s=positionAuthoringBasis();for(const id of POSITION_CONTROL_IDS){const el=document.getElementById(id);if(!el)continue;el.setAttribute('aria-describedby','posFrame posPositionStatus');el.disabled=!s.ok;if(!s.ok)el.dataset.blockedReason=s.message;else delete el.dataset.blockedReason;}return s;}
3377
+ function refreshPositionFrameUI(){const s=positionAuthoringBasis(),frame=document.getElementById('posFrame'),status=document.getElementById('posPositionStatus');if(frame){frame.style.color=s.ok&&s.kind!=='global'?'var(--cyan)':'var(--mut)';const b=frame.querySelector&&frame.querySelector('b');if(b)b.textContent=positionFrameLabel(s);}if(status){status.textContent=s.ok?'':s.message;status.style.display=s.ok?'none':'block';}wirePositionAvailability();}
3378
+ onPositionAuthoringBasisChange(refreshPositionFrameUI);
3379
+ function positionRefuse(message,source){const el=document.getElementById('posPositionStatus');if(el){el.style.display='block';el.style.border='1px solid var(--line)';el.style.borderRadius='6px';el.style.padding='7px 8px';el.textContent=message;}toast(message,false,5200);if(source&&source.focus)source.focus();return false;}
3380
+ function positionRebaseInput(m){const c=v2CanonicalMember(m.id),z0=c&&SteelCore.knownZ(c.from&&c.from.z),z1=c&&SteelCore.knownZ(c.to&&c.to.z);if(!c||z0==null||z1==null)return null;
3381
+ const dims=profileDimsIn(c.profile),sec=dims?{w:dims.w*25.4,d:dims.d*25.4,round:!!dims.round}:((c.section&&c.section.w>0&&c.section.d>0)?{w:c.section.w,d:c.section.d,round:false}:null);
3382
+ const extents=sec?SteelCore.sectionExtents(SteelCore.outlineFor(c.profile,sec.w,sec.d,null,sec.round)):null;
3383
+ return {canonical:c,from:[c.from.x,c.from.y,z0],to:[c.to.x,c.to.y,z1],extents};}
3384
+ function positionBasisMatches(member,target){if(target.kind==='global')return !member.positionBasis;if(!member.positionBasis)return false;const c=SteelCore.canonicalPositionBasis(target.x,target.y);return !!c&&JSON.stringify(member.positionBasis)===JSON.stringify({x:[...c.x],y:[...c.y]});}
3385
+ function applyPositionAuthoringBasis(member,target){
3386
+ if(!target||!target.ok)return false;
3387
+ if(target.kind==='global'){delete member.positionBasis;return true;}
3388
+ const c=SteelCore.canonicalPositionBasis(target.x,target.y);if(!c)return false;
3389
+ member.positionBasis={x:[...c.x],y:[...c.y]};return true;
3390
+ }
3391
+ function commitPositionEdit(members,userPatch,source){const captured=positionAuthoringBasis();if(!captured.ok)return positionRefuse(captured.message,source);const prepared=[],blockers=[];
3392
+ for(const m of members){const input=positionRebaseInput(m);if(!input){blockers.push(m.id+' has incomplete work points');continue;}
3393
+ let patch={};if(!positionBasisMatches(input.canonical,captured)){const r=SteelCore.reexpressMemberPlacement(input.canonical,input.from,input.to,captured,input.extents);if(!r.ok){const msg=r.code==='position-rebase-section-unresolved'
3394
+ ?m.id+' cannot be re-expressed because '+(m.profile||'its profile')+' has no resolved section'
3395
+ :m.id+' could not be re-expressed safely';blockers.push(msg);continue;}patch=r.patch;}
3396
+ prepared.push({m,patch:Object.assign({},patch,userPatch)});}
3397
+ if(blockers.length)return positionRefuse('No changes made — '+blockers.join('; ')+'. Resolve every blocker, or set Depth and Width to Middle in each stored frame first.',source);
3398
+ const current=positionAuthoringBasis();if(current.generation!==captured.generation)return positionRefuse('Frame changed — review the refreshed Profile Position and try again.',source);
3399
+ edit(()=>{for(const row of prepared)ModelCmd.patchMember(row.m,row.patch);});return true;}
3267
3400
  /*
3268
3401
  * ONE row of the Profile Position section: heading + offset box on the first line, named faces on the
3269
3402
  * second. The mockup drew all three on one line; at 280 px — ~246 px of content once the rail's padding and
@@ -3278,7 +3411,7 @@ const posOffSet=v=>typeof v==='number'&&isFinite(v)&&v!==0;
3278
3411
  const posRow=(label,offId,offLabel,offVal,offTip,buttons,ph)=>
3279
3412
  `<div class=elabrow><span class=elab>${label}</span><label class="detf posoff"><span>${offLabel}</span>`
3280
3413
  +`<input data-command-id="steel.position-offset#${esc(label.toLowerCase()+' axis')}" aria-label="${esc(label+' '+offLabel)}" id=${offId} class="${posOffSet(offVal)?'set':''}" inputmode=decimal value="${esc(posOffDisp(offVal))}" placeholder="${ph||'0&quot;'}" data-tip="${offTip}" autocomplete=off></label></div>`
3281
- +`<div class=seg2 style="margin-top:2px">${buttons}</div>`;
3414
+ +`<div class=seg2 role=group aria-label="${esc(label+' position')}" style="margin-top:2px">${buttons}</div>`;
3282
3415
  /*
3283
3416
  * A THIRD blank-commit behaviour, and it is not either of the two this file already has.
3284
3417
  *
@@ -3291,16 +3424,16 @@ const posRow=(label,offId,offLabel,offVal,offTip,buttons,ph)=>
3291
3424
  * than the neighbouring `defTos`/`mTos` handlers, which pass a possibly-null `parseLen` straight through —
3292
3425
  * deliberately, and noted here so it is not "fixed" back down to match them. (ui-ux review.)
3293
3426
  */
3294
- function posSetOff(m,key,raw){
3427
+ function posSetOff(m,key,raw,source){
3295
3428
  const t=String(raw==null?'':raw).trim();
3296
- if(t===''){edit(()=>ModelCmd.patchMember(m,{[key]:undefined}));return;}
3429
+ if(t===''){commitPositionEdit([m],{[key]:undefined},source);return;}
3297
3430
  const inch=parseLen(t);
3298
3431
  // Reverting is right — a length we cannot read must never become 0, which would MOVE the steel. But the
3299
3432
  // revert has to be announced: this panel toasts for everything else, so a field that silently blanks
3300
3433
  // reads as "accepted, displayed oddly". `3-1/2"` is standard detailer shorthand AND the shape fmtFtIn
3301
3434
  // itself emits, so it is typed often and rejected every time.
3302
3435
  if(inch==null||!isFinite(inch)){toast(`Couldn’t read “${t}” as a length — try 3 1/2" or 1'-3 1/2".`);render();return;}
3303
- edit(()=>ModelCmd.patchMember(m,{[key]:inch*25.4}));}
3436
+ commitPositionEdit([m],{[key]:inch*25.4},source);}
3304
3437
  // A member's UNIT direction in world mm, off the canonical model — or null when it has none (an unknown
3305
3438
  // elevation, a zero-length line, or no canonical member at all). The one thing §1.10 needs in order to ask
3306
3439
  // "did this member's axis actually reverse?", which is a question about the STORED geometry rather than
@@ -3358,11 +3491,12 @@ function swapMemberEnds(m){
3358
3491
  // the plan points through sheet pixels and comes back a few nanometres out.
3359
3492
  const reversed=!!(preAxis&&post&&Math.hypot(preAxis[0]+post[0],preAxis[1]+post[1],preAxis[2]+post[2])<1e-6);
3360
3493
  const g=reversed?SteelCore.memberGeometryV2(v2CanonicalMember(m.id)):null;
3361
- const fr=g&&SteelCore.partFrame(g.line[0],g.line[1]);
3494
+ const pb=m.positionBasis&&SteelCore.basisFromAxes(m.positionBasis.x,m.positionBasis.y);
3495
+ const fr=g&&SteelCore.partFrame(g.line[0],g.line[1],pb?pb.z:undefined,pb?pb.x:undefined);
3362
3496
  // No canonical geometry (an unknown elevation) or no frame (zero length) ⇒ no placement change. Inventing
3363
3497
  // a branch here would write a transform the bake will not honour, which is worse than leaving it alone.
3364
3498
  if(fr){
3365
- const cur={position:m.position,positionOffset:m.positionOffset,positionH:m.positionH,positionHOffset:m.positionHOffset,rot:m.rot};
3499
+ const cur={position:m.position,positionOffset:m.positionOffset,positionH:m.positionH,positionHOffset:m.positionHOffset,positionBasis:m.positionBasis,rot:m.rot};
3366
3500
  const next=SteelCore.reversePlacement(cur,fr.degenerate);
3367
3501
  const patch={};for(const k of Object.keys(next))if(!Object.is(next[k],cur[k]))patch[k]=next[k];
3368
3502
  if(Object.keys(patch).length)ModelCmd.patchMember(m,patch);
@@ -3526,7 +3660,38 @@ function parseVec(s){s=String(s==null?'':s).trim();if(!s)return null;
3526
3660
  // explicit overrides shift by Δ so relative offsets survive. Columns keep their height (bos shifts by Δ).
3527
3661
  // best-effort: framing plans carry TOS at the level UNO — assume the L2 datum +16'-6" (198"); each end's
3528
3662
  // 'default' checkbox links it to this value (auto-updates when changed); uncheck to override.
3529
- let defaultTOS=198, addProfile='', addType='beam'; // addType = the member type new members are drawn with (Add-member panel)
3663
+ let defaultTOS=198, addProfile='', addMaterial='', addType='beam'; // addProfile/addMaterial/addType are independent defaults for newly drawn members
3664
+ const profileCatalog=window.__STEEL_PROFILE_CATALOG||{environment:'US',standard:'Profile catalog',families:[],rows:[]};
3665
+ const profileCatalogRows=CatalogPicker.buildProfileRows(profileCatalog,window.__AISC_SECTIONS||{},window.__AISC_WEIGHTS||{});
3666
+ const materialCatalog=CatalogPicker.materialCatalogDescriptorFor(profileCatalog.environment||'US',window.__STEEL_MATERIAL_CATALOG);
3667
+ const materialCatalogRows=materialCatalog?.rows||[];
3668
+ const profilePicker=CatalogPicker.createCatalogPicker({
3669
+ kind:'profile',catalog:profileCatalog,rows:profileCatalogRows,onRetry:()=>location.reload(),document
3670
+ });
3671
+ const materialPicker=CatalogPicker.createCatalogPicker({
3672
+ kind:'material',catalog:materialCatalog||{environment:profileCatalog.environment||'US',standard:'Material catalog',navigation:[]},rows:materialCatalogRows,document
3673
+ });
3674
+ function profileCatalogValues(){return profileCatalogRows.flatMap(r=>[r.designation,...(r.aliases||[])]);}
3675
+ function profileDefaultMaterial(profile){const p=_canonDes(profile);return /^W\d/.test(p)?'A992':p.startsWith('HSS')?'A500-GR.B':'A36';}
3676
+ function applyProfileChoice(ids,value){
3677
+ const v=_canonDes(value);if(!v)return;
3678
+ edit(()=>{for(const id of ids){const m=byId(id);if(m)ModelCmd.patchMember(m,{profile:v,rfi:_wt(v)==null});}if(!profs.includes(v)){profs.push(v);profs.sort(CatalogPicker.naturalProfileCompare);}});
3679
+ }
3680
+ function applyMaterialChoice(ids,value){
3681
+ const v=value===CatalogPicker.MATERIAL_DEFAULT?undefined:String(value||'').trim();if(value!==CatalogPicker.MATERIAL_DEFAULT&&!v)return;
3682
+ edit(()=>{for(const id of ids){const m=byId(id);if(m)ModelCmd.patchMember(m,{material:v});}});
3683
+ }
3684
+ function openProfilePicker({ids=[],current=null,scope='',invoker,onApply}={}){
3685
+ const targets=[...ids];
3686
+ profilePicker.open({current,scope,count:targets.length||1,invoker,error:window.__AISC_LOAD_FAILED?'The active environment catalog could not be loaded.':null,
3687
+ source:`${profileCatalog.standard||'Profile catalog'} · ${profileCatalogRows.length.toLocaleString()} profiles · ${profileCatalog.environment||'US'}`,
3688
+ onApply:onApply||((value)=>applyProfileChoice(targets,value))});
3689
+ }
3690
+ function openMaterialPicker({ids=[],current=null,scope='',invoker,onApply}={}){
3691
+ const targets=[...ids],env=profileCatalog.environment||'US';
3692
+ materialPicker.open({current,scope,count:targets.length||1,invoker,error:materialCatalogRows.length?null:`No material catalog is installed for the ${env} environment.`,
3693
+ source:`${materialCatalog?.provider?.label||'Material catalog'} · ${env}`,onApply:onApply||((value)=>applyMaterialChoice(targets,value))});
3694
+ }
3530
3695
  let basePickColId=null; // Mode B: the column whose base an armed 3D level-pick retargets
3531
3696
  const MIN_COL_STUB_IN=12; // never trim a column below a 1' stub (keeps bos < tos)
3532
3697
  // Mode B: arm the 3D column-base pick on `colId` (a level-snapped elevation → col.bos). 3D-view only.
@@ -3587,7 +3752,7 @@ function apply(json){
3587
3752
  if(sel3dDimIds.size){const ok=new Set((C.dims3d||[]).map(x=>x.id));sel3dDimIds=new Set([...sel3dDimIds].filter(id=>ok.has(id)));} // drop stale 3D-dim selections
3588
3753
  if(selGridIds.size)selGridIds.clear(); // grid ids are index-based synthetics — an undo can reshuffle the grid, so just drop the transient grid selection
3589
3754
  dimDraft=null;dimChainPrev=null;dimPrevClear(); // undo/redo changed geometry under the tool → abandon any in-progress dim placement / chain (else the chain head points at a removed segment)
3590
- drawDraft=null;drawPrevClear(); // …likewise abandon an in-progress Add-member start point
3755
+ drawDraft=null;drawBasisTok=null;drawPrevClear(); // …likewise abandon an in-progress Add-member start point + its frame snapshot
3591
3756
  cmDraft=null;cmPrevClear();cmHudClose(); // same for an in-progress Move/Copy pick — the base may reference removed geometry
3592
3757
  if(window.Steel3DView&&window.Steel3DView.cmClear3d)window.Steel3DView.cmClear3d(); // and the 3D-side draft/ghosts
3593
3758
  if(window.Steel3DView&&window.Steel3DView.setClipState&&'clips' in d)window.Steel3DView.setClipState(d.clips); // restore clips + work area alongside the contract
@@ -3628,7 +3793,7 @@ function edit(fn){
3628
3793
  try{fn();}
3629
3794
  catch(err){
3630
3795
  if(err&&err.name==='V2CommandError'){
3631
- drawDraft=null;dimDraft=null;cmDraft=null;drawPrevClear();dimPrevClear();cmPrevClear();
3796
+ drawDraft=null;drawBasisTok=null;dimDraft=null;cmDraft=null;drawPrevClear();dimPrevClear();cmPrevClear();
3632
3797
  const text=err.code==='elevation-unknown'
3633
3798
  ?`Couldn’t complete that edit: the elevation is unknown. Enter the TOS first.`
3634
3799
  :(err.message||'That edit could not be applied safely.');
@@ -3838,13 +4003,13 @@ async function persistServer(force){const seq=saveSeq;
3838
4003
  // write is usually still in flight — the server broadcasts before it replies — so releasing here would
3839
4004
  // make the tab read its OWN echo as external and reload itself mid-edit. The id is released when the
3840
4005
  // echo consumes it, when the write fails, or when the SSE channel closes (nothing can echo after that).
3841
- if(res.ok){const t=res.headers.get('ETag');if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}conflicted=false;} // chain the next edit off the new tag, and re-point the stored draft at the version it is now a delta from (see restampDraftBase)
4006
+ if(res.ok){const d=await res.json().catch(()=>({})),t=d.etag||res.headers.get('ETag');if(d.contract&&t&&Number.isSafeInteger(d.storeRevision))installMemberEndContract(d.contract,t,d.storeRevision);else{if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}if(Number.isSafeInteger(d.storeRevision))serverRevision=Math.max(serverRevision,d.storeRevision);}conflicted=false;} // chain the next edit off the new tag, and install any server-staled endpoint authority instead of leaving the browser on bytes the server deliberately transformed
3842
4007
  else releaseMutation(mid); // 400/500: nothing was written, so nothing will echo
3843
4008
  if(seq===saveSeq)setSaved(res.ok?'ok':'err'); // only the latest save owns the pill (a stale late response must not clobber a newer verdict)
3844
4009
  if(!res.ok)console.error('server save rejected ('+res.status+')',await res.text().catch(()=>'')); // 400 = schema reject: edits won't be what Approve bakes
3845
4010
  }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}
3846
4011
  });}
3847
- function scheduleSave(){setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{saveT=null;persist();persistServer();},500);} // clear the handle as it fires: `saveT !== null` is read as "a write is still pending" (the project send refuses on it), and a spent timer id would read as pending forever // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
4012
+ function scheduleSave(){if(memberEndStatus.known||memberEndReview)invalidateMemberEndReview();setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{saveT=null;persist();persistServer();},500);} // clear the handle as it fires: `saveT !== null` is read as "a write is still pending" (the project send refuses on it), and a spent timer id would read as pending forever // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
3848
4013
  // The boot-scope SSE handler's seam into that debounce — see `flushLocalDraft` for why the handler
3849
4014
  // cannot reach `persist()` itself.
3850
4015
  //
@@ -3901,7 +4066,7 @@ window.flushContract = async () => {
3901
4066
  showConflictBanner();
3902
4067
  throw new Error('save conflict');
3903
4068
  }
3904
- if (res.ok) { const t = res.headers.get('ETag'); if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } conflicted = false; }
4069
+ if (res.ok) { const d = await res.json().catch(() => ({})); const t = d.etag || res.headers.get('ETag'); if (d.contract && t && Number.isSafeInteger(d.storeRevision)) installMemberEndContract(d.contract, t, d.storeRevision); else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); } conflicted = false; }
3905
4070
  else releaseMutation(mid);
3906
4071
  if (seq === saveSeq) setSaved(res.ok ? 'ok' : 'err'); // only the latest save owns the pill
3907
4072
  if (!res.ok) throw new Error('save failed (' + res.status + ')');
@@ -4198,8 +4363,36 @@ function _canonDes(s){return String(s==null?'':s).trim().toUpperCase()
4198
4363
  .replace(/[×✕✖]/g,'X').replace(/[‐-―−]/g,'-').replace(/[‘’ʹ′]/g,"'").replace(/[“”ʺ″]/g,'"')
4199
4364
  .replace(/ /g,' ').replace(/(\d)\s+(\d+\/\d+)/g,'$1-$2').replace(/\s+/g,'');}
4200
4365
  function _aiscSec(key){return (window.__AISC_SECTIONS||{})[key];}
4366
+ function _parseDoubleAngleIn(profile){
4367
+ const p=_canonDes(profile);if(!p.startsWith('2L'))return null;
4368
+ const orientation=p.endsWith('SLBB')?'slbb':p.endsWith('LLBB')?'llbb':null;
4369
+ const body=p.slice(2).replace(/(LLBB|SLBB)$/,'');
4370
+ const pd=t=>{const s=String(t).trim();if(!/^(?:\d+(?:\.\d+)?|\d+(?:\s+|-)\d+\/\d+|\d+\/\d+)$/.test(s))return null;let mm=s.match(/^(\d+)(?:\s+|-)(\d+)\/(\d+)$/);if(mm)return +mm[1]+ +mm[2]/+mm[3];mm=s.match(/^(\d+)\/(\d+)$/);if(mm)return +mm[1]/+mm[2];const d=Number(s);return isFinite(d)?d:null;};
4371
+ const toks=body.split('X');if(toks.length!==3&&toks.length!==4)return null;
4372
+ const v=toks.map(pd);if(v.some(n=>n==null||n<=0)||(!orientation&&Math.abs(v[0]-v[1])>1e-9))return null;
4373
+ return{d:v[0],b:v[1],t:v[2],gap:toks.length===4?v[3]:0,orientation:orientation||'llbb'};
4374
+ }
4375
+ function _profileCatalogRow(profile){return CatalogPicker.resolveProfileCatalogRow(profileCatalogRows,profile);}
4376
+ function _profileDisplaySectionIn(profile){
4377
+ const row=_profileCatalogRow(profile);if(!row)return _parseDoubleAngleIn(profile)?{shape:'double-angle',..._parseDoubleAngleIn(profile)}:null;
4378
+ const sec=_aiscSec(_canonDes(row.designation)),shape=row.sectionShape;
4379
+ if(shape==='double-angle'){const pair=_parseDoubleAngleIn(row.designation);return pair?{shape,...pair}:null;}
4380
+ if(shape==='solid-circle')return sec&&sec[0]>0?{shape,diameter:sec[0]}:null;
4381
+ if(shape==='tee')return sec&&sec[2]>0&&sec[3]>0?{shape,tw:sec[2],tf:sec[3]}:null;
4382
+ if(shape==='chs')return sec&&sec[0]>0&&sec[2]>0?{shape,od:sec[0],t:sec[2]}:null;
4383
+ if(shape==='rhs'||shape==='angle')return sec&&sec[2]>0?{shape,t:sec[2]}:null;
4384
+ if(shape==='i'||shape==='channel')return sec&&sec[2]>0&&sec[3]>0?{shape,tw:sec[2],tf:sec[3]}:null;
4385
+ return null;
4386
+ }
4201
4387
  function profileDimsIn(profile){
4202
4388
  if(!profile)return null;
4389
+ const display=_profileDisplaySectionIn(profile);
4390
+ if(display&&display.shape==='double-angle'){
4391
+ return display.orientation==='slbb'
4392
+ ?{d:2*display.d+display.gap,w:display.b,round:false}
4393
+ :{d:display.d,w:2*display.b+display.gap,round:false};
4394
+ }
4395
+ if(display&&display.shape==='solid-circle')return{d:display.diameter,w:display.diameter,round:true};
4203
4396
  const p=String(profile).trim().toUpperCase().replace(/[×✕✖]/g,'X'); // separator may be x / X / × / ✕ / ✖ — the SAME fold as server contract-to-scene profileDimsIn, or the two disagree about which designations resolve
4204
4397
  if(p===''||/(^|[^A-Z])MF($|[^A-Z])/.test(p))return null;
4205
4398
  const m=p.match(/^([A-Z]+)\s*(.+)$/);if(!m)return null;
@@ -4253,7 +4446,7 @@ function sectionKindOf(profile){return SteelCore.sectionKindOf(profile);}
4253
4446
  // 3D solid and the IFC/Tekla export carry:
4254
4447
  // • the DESIGNATION states it outright for an angle and a rectangular/round HSS — L4X4X3/8 is a 3/8" leg,
4255
4448
  // HSS8X4X3/8 a 3/8" wall — and no table is needed to read it;
4256
- // • the AISC table carries web+flange for the open rolled shapes (W/S/M/HP, C/MC), served in the
4449
+ // • the AISC table carries web+flange for the open rolled shapes (W/S/M/HP, C/MC, WT/ST/MT), served in the
4257
4450
  // /api/aisc-shapes mirror as elements 2 and 3.
4258
4451
  // Returns nulls freely: an untabulated or imported section has no real thickness anywhere, and
4259
4452
  // sectionOutlinePts falls back to its estimate rather than inventing one here.
@@ -4273,29 +4466,42 @@ function profileThkIn(profile){
4273
4466
  // character would not change a single answer today. It is here so the two folds are the same fold, which
4274
4467
  // is the property that stops them drifting — not because anything currently depends on it.
4275
4468
  const p=String(profile).trim().toUpperCase().replace(/[×✕✖]/g,'X').replace(/[‐-―−]/g,'-').replace(/ /g,' ');
4469
+ // A double angle starts with a digit, so it deliberately does not enter the rolled-family prefix parser
4470
+ // below. Its third dimension is the shared leg thickness; the optional fourth token is the gap and the
4471
+ // LLBB/SLBB suffix is orientation. This is the same designation source used by server parseDoubleAngle.
4472
+ if(p.startsWith('2L')){
4473
+ const body=p.slice(2).replace(/(LLBB|SLBB)$/,'');
4474
+ const _pd=t=>{const s=String(t).trim();let mm=s.match(/^(\d+)(?:\s+|-)(\d+)\/(\d+)$/);if(mm)return +mm[1]+ +mm[2]/+mm[3];mm=s.match(/^(\d+)\/(\d+)$/);if(mm)return +mm[1]/+mm[2];const d=parseFloat(s);return isFinite(d)?d:null;};
4475
+ const toks=body.split('X').map(_pd);
4476
+ return toks.length>=3&&toks[2]>0?{t:toks[2]}:null;
4477
+ }
4276
4478
  const m=p.match(/^([A-Z]+)\s*(.+)$/);if(!m)return null;
4277
4479
  const prefix=m[1],sec=_aiscSec(_canonDes(profile));
4278
4480
  // parseDim, not parseFloat: a fractional thickness token is the WHOLE point here, and parseFloat('3/8')
4279
4481
  // is 3 — a 3" leg on a 4" angle. Same fold and same parse as profileDimsIn above.
4280
4482
  const _pd=t=>{const s=String(t).trim();let mm=s.match(/^(\d+)(?:\s+|-)(\d+)\/(\d+)$/);if(mm)return +mm[1]+ +mm[2]/+mm[3];mm=s.match(/^(\d+)\/(\d+)$/);if(mm)return +mm[1]/+mm[2];const d=parseFloat(s);return isFinite(d)?d:null;};
4281
4483
  const toks=m[2].split('X').map(_pd);
4282
- if(prefix==='L'||prefix==='HSS'||prefix==='TUBE'){
4283
- if(toks.length>=3&&toks[2]>0)return {t:toks[2]}; // A×B×t
4284
- if(prefix==='HSS'&&toks.length===2&&toks[1]>0)return {t:toks[1]}; // round HSS OD×wall
4285
- return null; // a PIPE names its NPS, not its wall
4484
+ if(prefix==='L'){
4485
+ return toks.length>=3&&toks[2]>0?{t:toks[2]}:null; // A×B×t
4486
+ }
4487
+ if(prefix==='HSS'||prefix==='TUBE'||prefix==='PIPE'){
4488
+ // HSS and PIPE table rows carry the provider's design wall. That is the physical thickness used by
4489
+ // the 3D annulus/RHS and canonical CHS; reading the nominal label token here would make the plan the
4490
+ // only view drawing a different wall. PIPE cannot be parsed from its NPS/schedule name at all.
4491
+ if(sec&&sec[2]!=null&&sec[2]>0)return {t:sec[2]};
4492
+ if(toks.length>=3&&toks[2]>0)return {t:toks[2]};
4493
+ if(prefix==='HSS'&&toks.length===2&&toks[1]>0)return {t:toks[1]};
4494
+ return null;
4286
4495
  }
4287
- // EXACTLY the families the server's `xsectionFor` types — ^(W|S|M|HP)$ and ^(C|MC)$ — and deliberately
4288
- // NOT the tees (WT/ST/MT), even though the catalogue does carry their web and flange. `xsectionFor`
4289
- // answers `rect` for a tee, so the 3D solid and the IFC/Tekla export draw it from the ESTIMATE; a plan
4290
- // that read the real value here would be the only truthful view, which is just the old disagreement
4291
- // pointing the other way. The plan's job is to show the member that gets fabricated. Widening this means
4292
- // widening `xsectionFor` first, and that changes exported geometry — its own change, with its own review.
4496
+ // EXACTLY the table-backed open families the server's `xsectionFor` types. Tees are included now that
4497
+ // AWARE v0.125 carries their canonical descriptor; leaving them out would make the plan the sole view
4498
+ // still estimating a member whose 3D solid and export both use the provider web and flange.
4293
4499
  // BOTH or neither, because `xsectionFor` gates on both (`twtf = tw != null && tf != null`) and drops the
4294
4500
  // whole section to `rect` otherwise. Returning a lone `tw` would hand the plan a real web against a 3D
4295
4501
  // estimating both — the same disagreement in miniature. No row in today's catalogue has exactly one of
4296
4502
  // the pair, so no designation can currently reach it; this is a guard on the table GENERATOR, which is
4297
4503
  // why the agreement matrix cannot see it and this line has to say it instead. (Found by code review.)
4298
- if(/^(W|S|M|HP|C|MC)$/.test(prefix)&&sec)return (sec[2]!=null&&sec[3]!=null)?{tw:sec[2],tf:sec[3]}:null;
4504
+ if(/^(W|S|M|HP|C|MC|WT|ST|MT)$/.test(prefix)&&sec)return (sec[2]!=null&&sec[3]!=null)?{tw:sec[2],tf:sec[3]}:null;
4299
4505
  return null;
4300
4506
  }
4301
4507
  // Local section outline (centred at origin), w/d in PX. The POINTS come from SteelCore.sectionOutlinePts —
@@ -4316,6 +4522,24 @@ function sectionShapePts(profile,w,d,ppf,round){
4316
4522
  return SteelCore.sectionOutlinePts(round===true?'ROUND':sectionKindOf(profile),w,d,
4317
4523
  thk?{tw:px(thk.tw),tf:px(thk.tf),t:px(thk.t)}:null).outer;
4318
4524
  }
4525
+ // The plan needs every physical component, not only the legacy single outline above: tees are not I-shapes,
4526
+ // solid rounds are not boxes, and a 2L is two separate angles with air between them. Values returned by
4527
+ // _profileDisplaySectionIn are inches, so scale the descriptor into the same sheet-pixel unit as w/d before
4528
+ // handing it to the topology builder shared with the 3D renderer.
4529
+ function sectionShapeComponents(profile,w,d,ppf,round){
4530
+ const k=ppf>0?ppf/12:0,xs=_profileDisplaySectionIn(profile);
4531
+ const scaled=xs?Object.fromEntries(Object.entries(xs).map(([key,value])=>[
4532
+ key,typeof value==='number'&&['d','b','t','gap','diameter','od','tw','tf'].includes(key)?value*k:value,
4533
+ ])):null;
4534
+ const topology=SteelCore.sectionTopology(scaled,w,d,round===true?'ROUND':sectionKindOf(profile));
4535
+ const pathPoints=path=>{
4536
+ if(path&&path.kind==='polygon')return path.points;
4537
+ if(path&&path.kind==='circle')return Array.from({length:SteelCore.ROUND_SEGMENTS||48},(_,i)=>{const a=i/(SteelCore.ROUND_SEGMENTS||48)*Math.PI*2;return[path.cx+path.radius*Math.cos(a),path.cy+path.radius*Math.sin(a)];});
4538
+ return[];
4539
+ };
4540
+ const components=topology.map(component=>pathPoints(component.outer)).filter(points=>points.length>=3);
4541
+ return components.length?components:[sectionShapePts(profile,w,d,ppf,round)];
4542
+ }
4319
4543
  // Column plan polygon (absolute px). Primary: derive from profile + pt_per_ft + rot. Fallback: a small
4320
4544
  // square footprint so an unresolved (RFI) column still reads as a section, never a bare point.
4321
4545
  // ponytail: filter-traced fallback (the saved section linework) deferred — the marker covers the rare
@@ -4359,6 +4583,14 @@ function planRegistration(){
4359
4583
  }
4360
4584
  _planXfCache={key,xf};return xf;
4361
4585
  }
4586
+ function positionEffectiveWorldRot(m){
4587
+ if(!m||!m.positionBasis)return +m.rot||0;
4588
+ const basis=SteelCore.basisFromAxes(m.positionBasis.x,m.positionBasis.y),g=SteelCore.memberGeometryV2(v2CanonicalMember(m.id));
4589
+ if(!basis||!g)return null;
4590
+ const a=SteelCore.partFrame(g.line[0],g.line[1],basis.z,basis.x),global=SteelCore.partFrame(g.line[0],g.line[1]);if(!a||!global)return null;
4591
+ const th=(+m.rot||0)*Math.PI/180,c=Math.cos(th),s=Math.sin(th),w=[c*a.y[0]+s*a.z[0],c*a.y[1]+s*a.z[1],c*a.y[2]+s*a.z[2]];
4592
+ return Math.atan2(w[0]*global.z[0]+w[1]*global.z[1]+w[2]*global.z[2],w[0]*global.y[0]+w[1]*global.y[1]+w[2]*global.y[2])*180/Math.PI;
4593
+ }
4362
4594
  function columnSectionPoly(m){
4363
4595
  const wp=m&&m.wp;if(!wp||!wp.length)return null;
4364
4596
  const a=wp[0],b=wp[wp.length-1],cx=(a[0]+b[0])/2,cy=(a[1]+b[1])/2;
@@ -4385,8 +4617,8 @@ function columnSectionPoly(m){
4385
4617
  // The roll goes through SteelCore, which owns the world→sheet-px placement (the Y flip and the sheet's
4386
4618
  // registration angle). Applied raw here, as it was, the plan drew every section as the MIRROR of the
4387
4619
  // 3D solid and the export — see sectionOutlinePx for the measurement and the algebra.
4388
- const xf=planRegistration(),rotN=+m.rot||0,wPx=sec.w/12*ppf,dPx=sec.d/12*ppf;
4389
- const pts=SteelCore.sectionOutlinePx(sectionShapePts(m.profile,wPx,dPx,ppf,dims&&dims.round),rotN,xf.rad,xf.fitScale);
4620
+ const xf=planRegistration(),rotN=positionEffectiveWorldRot(m),wPx=sec.w/12*ppf,dPx=sec.d/12*ppf;if(rotN==null)return null;
4621
+ const localComponents=sectionShapeComponents(m.profile,wPx,dPx,ppf,dims&&dims.round);
4390
4622
  // A column now takes a Profile Position like every other member, so the FOOTPRINT has to move with it —
4391
4623
  // otherwise the plan draws the section centred on a work point the 3D and the export put it off.
4392
4624
  // The offset is built in the SAME local frame and the SAME px units as the outline and pushed through
@@ -4395,12 +4627,14 @@ function columnSectionPoly(m){
4395
4627
  // true 3D location while the outline stayed in this function's own (battered-column-approximate) frame,
4396
4628
  // which is a NEW contradiction in the one place this is meant to remove one. And the swing is left to
4397
4629
  // sectionOutlinePx, which applies the identical roll — applying it here as well would double the angle.
4398
- const exPx=SteelCore.sectionExtents(SteelCore.outlineFor(m.profile,wPx,dPx,null,!!(dims&&dims.round)));
4630
+ const allLocal=localComponents.flat(),xs=allLocal.map(p=>p[0]),ys=allLocal.map(p=>p[1]);
4631
+ const exPx={lo:[Math.min(...xs),Math.min(...ys)],hi:[Math.max(...xs),Math.max(...ys)]};
4399
4632
  const mmToPx=ppf/(12*25.4); // px per foot ÷ mm per foot: the two offsets are stored in MILLIMETRES
4400
4633
  const oy=SteelCore.faceOffset(posHDefault(m),exPx.lo[0],exPx.hi[0])+(+m.positionHOffset||0)*mmToPx;
4401
4634
  const oz=SteelCore.faceOffset(posDefault(m),exPx.lo[1],exPx.hi[1])+(+m.positionOffset||0)*mmToPx;
4402
4635
  const [dx,dy]=SteelCore.sectionOutlinePx([[oy,oz]],rotN,xf.rad,xf.fitScale)[0];
4403
- return pts.map(([x,y])=>[cx+dx+x,cy+dy+y]);
4636
+ const components=localComponents.map(points=>SteelCore.sectionOutlinePx(points,rotN,xf.rad,xf.fitScale).map(([x,y])=>[cx+dx+x,cy+dy+y]));
4637
+ const pts=components[0];if(components.length>1)pts.components=components;return pts;
4404
4638
  }
4405
4639
  const r=ppf?Math.max(6,(6/12)*ppf):8; // ~6" or a floor, so it stays visible even unscaled
4406
4640
  // Tagged, because this square claims no size and the caller cannot tell that by looking at it. It used
@@ -5496,6 +5730,7 @@ function stepSlotText(commandId){
5496
5730
  }
5497
5731
  }catch(e){/* cross-origin or torn-down parent */}
5498
5732
  try{window.__instructor.dispose();}catch(e){}
5733
+ try{if(positionBasisViewUnsub)positionBasisViewUnsub();positionBasisViewUnsub=null;positionBasisListeners.clear();}catch(e){}
5499
5734
  });
5500
5735
  publishSoon(); // first report, so the shell is not blank until the first click
5501
5736
 
@@ -5629,6 +5864,19 @@ function doDup(){const arr=sel2d();if(!arr.length)return;const o=12,pv=snapshot(
5629
5864
  mc.addMembers(P,[c]);ns.add(c.id);}
5630
5865
  selIds=ns;selDimIds.clear();mode='sel';setMode();pushUndo(pv);render();}
5631
5866
  function esc(s){return String(s).replace(/[<>&"]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));}
5867
+ function memberEndReviewSvg(){
5868
+ if(!memberEndReview||NO_PLAN_VIEW||!P||!P.members)return '';
5869
+ const f=memberEndReview.report.findings[memberEndReview.focus];if(!f)return '';
5870
+ const subject=P.members.find(m=>m.id===f.memberId);if(!subject)return '';
5871
+ const start=subject.wp&&subject.wp[f.end];if(!start)return '';
5872
+ const targets=f.classification==='needs-review'?(f.targets||[]):((f.classification==='aligned-auto'||f.classification==='aligned-manual')?[f.target]:[]);if(!targets.length)return '';
5873
+ const plan=C.plans&&C.plans[C.active],projected=[];for(const t of targets){try{projected.push(PlanXf.worldToSheetPx(t.point,{...plan,modelGrid:C.grid}));}catch(_){return '';}}
5874
+ let out='<g class=mer-overlay aria-hidden=true>';for(const id of new Set(targets.flatMap(t=>t.memberIds||[]))){const m=P.members.find(x=>x.id===id);if(m&&m.wp)out+=`<line class=mer-target-line x1="${m.wp[0][0]}" y1="${m.wp[0][1]}" x2="${m.wp[1][0]}" y2="${m.wp[1][1]}"/>`;}
5875
+ const r=7/zoom,chosen=memberEndReview.chosen.get(memberEndKey(f)),chosenIndex=chosen?targets.findIndex(t=>memberEndTargetEqual(t,chosen)):0;out+=`<polygon class=mer-end-marker points="${start[0]},${start[1]-r} ${start[0]+r},${start[1]} ${start[0]},${start[1]+r} ${start[0]-r},${start[1]}"/>`;
5876
+ projected.forEach((pt,i)=>{out+=`<line class=mer-extension x1="${start[0]}" y1="${start[1]}" x2="${pt[0]}" y2="${pt[1]}"/><rect class="mer-target-marker${i===chosenIndex?' selected':''}" data-mer-canvas-target="${i}" x="${pt[0]-r}" y="${pt[1]-r}" width="${2*r}" height="${2*r}"/><text class=mer-label x="${pt[0]+10/zoom}" y="${pt[1]-8/zoom}" style="font-size:${11/zoom}px">${String.fromCharCode(65+i)}</text>`;});
5877
+ 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>`;
5878
+ return out+'</g>';
5879
+ }
5632
5880
  function render(){
5633
5881
  /* The Instructor's second publish trigger, and the one that catches what input
5634
5882
  events cannot: an arm or disarm inside a PROMISE callback (an async contract
@@ -5663,7 +5911,7 @@ function render(){
5663
5911
  // A placeholder footprint on a member that is NOT an RFI reads as a real, small section — the size is
5664
5912
  // the one thing on this canvas it cannot be trusted for, so it says so rather than looking resolved.
5665
5913
  const _ph=(pts&&pts.placeholder&&!rfi)?` data-tip="Footprint shown as a placeholder — the AISC table gives no footprint for this shape. Its weight and length are still exact."`:'';
5666
- if(pts){s+=`<polygon class="member${rfi?' rfi':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" points="${_polyStr(pts)}" fill="${c}" stroke="${c}"${g}${_ph}/>`;continue;}}
5914
+ if(pts){const components=pts.components||[pts];s+=components.map((part,index)=>`<polygon class="member${rfi?' rfi':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" data-part="${index}" points="${_polyStr(part)}" fill="${c}" stroke="${c}"${g}${_ph}/>`).join('');continue;}}
5667
5915
  const ls=memberLineStyle(m); // F5: category line weight/dash. Inline style (NOT a presentation attr) so it beats line.member/.sel CSS width; the glow still cues selection.
5668
5916
  const _fx=on?`filter:drop-shadow(0 0 3px ${c}) drop-shadow(0 0 8px ${c});`:'', _sw=(ls&&ls.w)?`stroke-width:${ls.w}px;`:'', _sd=(ls&&ls.d&&!rfi)?`stroke-dasharray:${ls.d};`:''; // RFI keeps its semantic 10 6 dash
5669
5917
  const _sty=(_fx||_sw||_sd)?` style="${_fx}${_sw}${_sd}"`:'';
@@ -5704,13 +5952,14 @@ function render(){
5704
5952
  s+=renderDims();
5705
5953
  s+=renderPropLabels(); // right-click property-label chips (2D); 3D labels ride the div-overlay pool
5706
5954
  s+=renderSelLenLabels(); // on-select member-length chips (2D), gated by the ⋯ Display "Show member length" toggle
5955
+ s+=memberEndReviewSvg();
5707
5956
  if(P.frame)s+=axisGlyphSvg(P.frame.o,P.frame.u,false); // local-axes glyph at the origin (only when a frame is set; removed on reset)
5708
5957
  // No datalist population here any more. The #profiles and #details <datalist>s went with the rest of
5709
5958
  // them (an OS-drawn white popup has no themed mode), and COMBO_SRC.profiles/.details already read
5710
5959
  // `profs` and `detTexts()` live — so the combobox offers the same list with no mirror to keep filled.
5711
5960
  // Deleting the elements while these two writes stayed made render() throw on null here, which also
5712
5961
  // killed every call after it on this line (stats/panel/upd*/syncDisplayRows). Measured in Chromium.
5713
- svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
5962
+ svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
5714
5963
  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()).
5715
5964
  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)
5716
5965
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -5747,8 +5996,8 @@ function updateHandles(m){svg.querySelectorAll(`circle.handle[data-mid="${m.id}"
5747
5996
  function updateLine(m){
5748
5997
  if(isBrace(m)){const g=svg.querySelector(`g.bracesym[data-id="${m.id}"]`); // a brace is a symbol group — re-serialize the whole glyph so it follows the drag live (moves off true WPs, redraws offset)
5749
5998
  if(g){const glow=selIds.has(m.id)||findHits.has(m.id);const c=colorFor(m.profile);g.outerHTML=braceSymbol(m,c,glow?` style="filter:drop-shadow(0 0 3px ${c}) drop-shadow(0 0 8px ${c})"`:'');}return;}
5750
- if(m.role==='column'){const pg=svg.querySelector(`polygon.member[data-id="${m.id}"]`); // columns are polygons — re-derive their footprint from the moved centroid so they follow the drag live
5751
- if(pg){const pts=columnSectionPoly(m);if(pts)pg.setAttribute('points',_polyStr(pts));}return;}
5999
+ if(m.role==='column'){const pgs=svg.querySelectorAll(`polygon.member[data-id="${m.id}"]`); // columns may be multi-component polygons (2L) — re-derive every footprint part from the moved centroid
6000
+ if(pgs.length){const pts=columnSectionPoly(m),components=pts&&(pts.components||[pts]);if(components)pgs.forEach((pg,index)=>{if(components[index])pg.setAttribute('points',_polyStr(components[index]));});}return;}
5752
6001
  const ln=svg.querySelector(`line.member[data-id="${m.id}"]`);
5753
6002
  if(ln){ln.setAttribute('x1',m.wp[0][0]);ln.setAttribute('y1',m.wp[0][1]);ln.setAttribute('x2',m.wp[1][0]);ln.setAttribute('y2',m.wp[1][1]);}}
5754
6003
  /** The four header readouts computed from the ACTIVE PLAN's member list. Named once — see stats(). */
@@ -5945,10 +6194,49 @@ function refPanelPreempted(){
5945
6194
  if(view3d&&v&&v.frameArmed&&v.frameArmed())return 'mode';
5946
6195
  return null;
5947
6196
  }
6197
+ function renderMemberEndPanel(p){
6198
+ 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]);});
6199
+ const actionable=rows.filter(f=>f.classification==='needs-review'&&state.chosen.has(memberEndKey(f))),selected=actionable.filter(f=>state.selected.has(memberEndKey(f))).length;
6200
+ const historyAction=memberEndHistoryAction(state.undoDirection);
6201
+ p.setAttribute('aria-busy',String(!!state.busy));p.setAttribute('aria-labelledby','memberEndReviewTitle');
6202
+ const disabled=state.busy?' disabled':'';
6203
+ 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>`;
6204
+ 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>`;
6205
+ 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;
6206
+ const evidence=target?memberEndTargetName(target)+' · Extend '+fmtFtIn(memberEndDistance(f,target)/25.4):memberEndReason(f)||memberEndClassification(f);
6207
+ 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>`;
6208
+ if(f.classification==='needs-review'){
6209
+ if((f.targets||[]).length>1)html+=(f.targets||[]).map((t,ti)=>`<button data-command-id="steel.member-end-target#${esc(memberEndTargetName(t))}" class="ghost${memberEndTargetEqual(target,t)?' selected':''}" data-mer-target="${i}:${ti}" aria-pressed="${memberEndTargetEqual(target,t)}" data-tip="Choose ${esc(memberEndTargetName(t))}"${disabled}>${String.fromCharCode(65+ti)} · ${esc(memberEndTargetName(t))}</button>`).join('');
6210
+ if(memberEndCanKeepShort(f))html+=`<button data-command-id="steel.member-end-keep-short#${esc(f.memberId+' end '+(f.end+1))}" class=ghost data-mer-keep="${i}" data-tip="Record this endpoint as intentionally short for the current model context"${disabled}>Keep short</button>`;
6211
+ }
6212
+ if((f.classification==='aligned-auto'||f.classification==='aligned-manual')&&f.basis&&f.basis.kind==='drawing')html+=`<button data-command-id="steel.member-end-restore#${esc(f.memberId+' end '+(f.end+1))}" class=ghost data-mer-restore="${i}" data-tip="Restore the immutable endpoint traced from the drawing"${disabled}>Restore traced end</button>`;
6213
+ html+='</div></div></div>';}
6214
+ html+='</section>';}
6215
+ 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>`;
6216
+ 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>';
6217
+ p.innerHTML=html;
6218
+ const done=document.getElementById('merDone');if(done)done.onclick=closeMemberEndReview;
6219
+ const all=document.getElementById('merAll');if(all)all.onclick=()=>{for(const f of actionable)state.selected.add(memberEndKey(f));panel();};
6220
+ const clear=document.getElementById('merClear');if(clear)clear.onclick=()=>{state.selected.clear();panel();};
6221
+ p.querySelectorAll('[data-mer-row]').forEach(row=>row.addEventListener('click',e=>{if(e.target.closest('button,input'))return;focusMemberEnd(+row.dataset.merRow);}));
6222
+ 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);};});
6223
+ p.querySelectorAll('[data-mer-target]').forEach(b=>b.onclick=()=>{const [i,t]=b.dataset.merTarget.split(':').map(Number);state.focus=i;chooseMemberEndTarget(memberEndKey(rows[i]),t);});
6224
+ p.querySelectorAll('[data-mer-keep]').forEach(b=>b.onclick=()=>keepMemberEnd(rows[+b.dataset.merKeep]));
6225
+ p.querySelectorAll('[data-mer-restore]').forEach(b=>b.onclick=()=>restoreMemberEnd(rows[+b.dataset.merRestore]));
6226
+ const prev=document.getElementById('merPrev'),next=document.getElementById('merNext'),applyB=document.getElementById('merApply'),undoB=document.getElementById('merUndo');if(prev)prev.onclick=()=>focusMemberEnd(state.focus-1);if(next)next.onclick=()=>focusMemberEnd(state.focus+1);if(applyB)applyB.onclick=applyMemberEndSelection;if(undoB)undoB.onclick=undoMemberEndResolution;
6227
+ }
6228
+ function renderMemberEndScanPanel(p){
6229
+ const state=memberEndScan;p.setAttribute('aria-busy',String(!!state.busy));p.setAttribute('aria-labelledby','memberEndScanTitle');
6230
+ 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>':''}`;
6231
+ const retry=document.getElementById('merRetry');if(retry)retry.onclick=()=>scanMemberEnds();
6232
+ }
5948
6233
  function panel(){
5949
6234
  const p=document.getElementById('panel');
6235
+ p.removeAttribute('aria-busy');p.removeAttribute('aria-labelledby');
5950
6236
  queueMicrotask(()=>syncV2SelectionNotice(p));
5951
6237
  if(!selDimIds.size||!dimsVisible)dimSplitMode=false;document.body.classList.toggle('dimsplit',dimSplitMode); // split mode is meaningless without a (visible) dim selected — also disarms when dims are hidden
6238
+ if(memberEndScan){renderMemberEndScanPanel(p);return;}
6239
+ if(memberEndReview){renderMemberEndPanel(p);return;}
5952
6240
  if(gridMode){renderGridPanel(p);return;}
5953
6241
  // FIRST after the grid takeover, and ABOVE the two "there is nothing to say" panels below — because for
5954
6242
  // a drilled-into reference object there IS something to say, and it is true. A reference model is
@@ -6050,13 +6338,18 @@ function panel(){
6050
6338
  p.innerHTML=`<span class=badge>Add member</span>
6051
6339
  ${memberTypeField('mTypeA',[{memberType:addType}])}
6052
6340
  <div class=sect style="margin-top:8px">Current profile</div>
6053
- <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.pick-profile" id=addPick class="ghost${pk?' on':''}" data-tip="Pick profile by clicking a label in the drawing">⌖ pick</button></div>
6341
+ <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>
6054
6342
  <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>
6343
+ <div class=elab style="margin-top:9px">Material grade</div>
6344
+ <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>
6055
6345
  <div class=divrow><hr></div>
6056
6346
  <div class=sect>Draw a member</div>
6057
6347
  <div class=hint id=drawHint>${view3d?'✏️ Click the start then the end — both land on the <b>working plane</b>. A near-vertical pick pair becomes a column. <b>Shift</b> = straight, <b>Esc</b> = exit.':drawHintText()}</div>`;
6058
6348
  const ap=document.getElementById('addProf');
6059
6349
  ap.oninput=ap.onchange=e=>{addProfile=_canonDes(e.target.value);};
6350
+ const am=document.getElementById('addMat');am.oninput=am.onchange=e=>{addMaterial=String(e.target.value||'').trim().toUpperCase();};
6351
+ document.getElementById('profileBrowseA').onclick=e=>openProfilePicker({current:addProfile||null,scope:'New members',invoker:e.currentTarget,onApply:v=>{addProfile=_canonDes(v);render();}});
6352
+ document.getElementById('materialBrowseA').onclick=e=>openMaterialPicker({current:addMaterial||'',scope:'New members',invoker:e.currentTarget,onApply:v=>{addMaterial=v===CatalogPicker.MATERIAL_DEFAULT?'':String(v);render();}});
6060
6353
  document.getElementById('addPick').onclick=()=>{picking=!pk;pickKind='profile';pickEnd=null;render();}; // labels are already hot in Add mode — this arms the same highlighted "pick a label" state as the member inspector
6061
6354
  document.getElementById('mTypeA').onchange=e=>{const v=e.target.value;
6062
6355
  if(!normMemberTypeKey(v)){e.target.value=memberTypeLabel(addType);return;} // blank or punctuation-only ("!!!") normalises to no key → mints nothing, so don't burn an undo step on it
@@ -6258,7 +6551,7 @@ function panel(){
6258
6551
  const allKnown=arr.every(m=>_wt(m.profile)!=null);
6259
6552
  const totalW=allKnown?Math.round(arr.reduce((t,m)=>t+_lenFt(m)*_wt(m.profile),0)):null;
6260
6553
  const dupSet=new Set(redundantDups()), dupSel=arr.filter(m=>dupSet.has(m.id)).length;
6261
- const profAgg=agg(arr,m=>m.profile), allVerified=arr.every(m=>m.verified===true);
6554
+ const profAgg=agg(arr,m=>m.profile), matAgg=agg(arr,m=>m.material||''), allVerified=arr.every(m=>m.verified===true);
6262
6555
  const VV=v=>v===VARIES, valOf=v=>VV(v)||v==null?'':esc(fmtFtIn(v)), decOf=v=>VV(v)||v==null?'':esc(fmtDecIn(v));
6263
6556
  const exPH='5 3/4&quot; · 1&#39;-0 1/4&quot;';
6264
6557
  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;
@@ -6282,7 +6575,7 @@ function panel(){
6282
6575
  // is skipped by the bake entirely, so folding it in would report a Varies (or a value) for a member
6283
6576
  // nothing applies to. ONE subset for both axes and both offsets, because the bake has one answer for all
6284
6577
  // four. Columns are IN it now: they take a Profile Position like every other member (design §4).
6285
- const hOk=arr.filter(posEligible),hSkip=arr.length-hOk.length;
6578
+ const hOk=arr,hSkip=arr.filter(m=>!posEligible(m)).length;
6286
6579
  const posA=hOk.length?agg(hOk,m=>posDefault(m)):null;
6287
6580
  const posHA=hOk.length?agg(hOk,m=>posHDefault(m)):null;
6288
6581
  // A mixed selection must read BLANK, not the first member's value — an offset silently inherited across a
@@ -6304,11 +6597,13 @@ function panel(){
6304
6597
  ${typeFilterHTML()}
6305
6598
  <div class="row hint" style="margin-top:0">Edits apply to <b>all ${arr.length}</b> selected · a blank <b>Varies</b> field is left unchanged.</div>
6306
6599
  ${memberTypeField('mTypeM',arr)}
6307
- <div class="f"><div class=elab>Profile</div><input data-command-id="steel.selection-profile" aria-label="Profile" id=pf class=combo data-src=profiles placeholder="${VV(profAgg)?'Varies':''}" value="${VV(profAgg)?'':esc(profAgg||'')}" autocomplete=off></div>
6600
+ <div class="f"><div class=elab>Profile</div><div style="display:flex;gap:6px"><input data-command-id="steel.selection-profile" aria-label="Profile" id=pf class=combo data-src=profiles placeholder="${VV(profAgg)?'Varies':''}" value="${VV(profAgg)?'':esc(profAgg||'')}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseM class=ghost data-tip="Browse the active environment profile catalog">Browse</button></div></div>
6601
+ <div class="f"><div class=elab>Material grade</div><div style="display:flex;gap:6px"><input data-command-id="steel.selection-material" aria-label="Material grade" id=mat class=combo data-src=materials placeholder="${VV(matAgg)?'Varies':VV(profAgg)?'Profile default · per member':'Profile default · '+esc(profileDefaultMaterial(profAgg))}" value="${VV(matAgg)?'':esc(matAgg||'')}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-material-catalog" id=materialBrowseM class=ghost data-tip="Browse structural member grades">Browse</button></div></div>
6308
6602
  <div class="row hint">Total length <b>${totalL} ft</b>${totalW!=null?` · <b>${totalW.toLocaleString()} lb</b>`:''}${dupSel?` · <span style="color:var(--err)">${dupSel} duplicate${dupSel>1?'s':''}</span> (overlap a kept member — deleting these dedupes)`:''}</div>
6309
6603
  <div class=row><button data-command-id="steel.selection-verified" class=ghostw id=verifyBtn${allVerified?' style="border-color:var(--ok-edge);color:var(--ok)"':''}>${allVerified?'✓ All verified — click to unverify':'Mark all verified'}</button></div>
6310
6604
  ${elev}
6311
6605
  <div class=divrow><hr><span class=sect style="margin:0" data-tip="${POSTIP.head}">Profile Position <span style="opacity:.45;font-weight:400">ⓘ</span></span><hr></div>
6606
+ ${positionFrameHTML()}
6312
6607
  ${hOk.length?posRow('Depth','posOff','Offset',VV(offA)?null:offA,POSTIP.offD,
6313
6608
  `<button data-command-id="steel.position-face#with its top face on the line" id=posTop class="${posA==='top'?'on':''}" aria-pressed="${posA==='top'?'true':'false'}" data-tip="${POSTIP.top}">Top</button><button data-command-id="steel.position-face#centred in depth" id=posMid class="${posA==='middle'?'on':''}" aria-pressed="${posA==='middle'?'true':'false'}" data-tip="${POSTIP.mid}">Middle</button><button data-command-id="steel.position-face#with its underside on the line" id=posBot class="${posA==='bottom'?'on':''}" aria-pressed="${posA==='bottom'?'true':'false'}" data-tip="${POSTIP.bot}">Bottom</button>`,
6314
6609
  VV(offA)?'Varies':'0&quot;')
@@ -6316,10 +6611,10 @@ function panel(){
6316
6611
  `<button data-command-id="steel.position-face#with its left face on the line" id=posHLeft class="${posHA==='left'?'on':''}" aria-pressed="${posHA==='left'?'true':'false'}" data-tip="${POSTIP.left}">Left</button><button data-command-id="steel.position-face#centred across the line" id=posHMid class="${posHA==='middle'?'on':''}" aria-pressed="${posHA==='middle'?'true':'false'}" data-tip="${POSTIP.midH}">Middle</button><button data-command-id="steel.position-face#with its right face on the line" id=posHRight class="${posHA==='right'?'on':''}" aria-pressed="${posHA==='right'?'true':'false'}" data-tip="${POSTIP.right}">Right</button>`,
6317
6612
  VV(offHA)?'Varies':'0&quot;')
6318
6613
  +((VV(posA)||VV(posHA))?`<div class=hint style="margin-top:4px">${VV(posA)&&VV(posHA)?'Depth and width vary across the selection, so neither row has a face lit':VV(posA)?'Depth varies across the selection, so no depth face is lit':'Width varies across the selection, so no width face is lit'}. Pick one to set every selected member.</div>`:'')
6319
- +(hSkip?`<div class=hint style="margin-top:4px">${hSkip} of the ${arr.length} selected members ${hSkip>1?'have':'has'} no section to place, and ${hSkip>1?'are':'is'} left unchanged.</div>`:'')
6614
+ +(hSkip?`<div class=hint style="margin-top:4px">${hSkip} of the ${arr.length} selected members ${hSkip>1?'have':'has'} no resolved section. Same-frame edits stay available; changing edit frame will refuse atomically if a named face cannot be decoded.</div>`:'')
6320
6615
  :`<div class=hint style="margin-top:8px">None of the selected members has a section to place — their profiles do not resolve, so they are left unchanged. Any placement they already carry is kept, and applies again once the profile resolves.</div>`}
6321
6616
  <div class=elabrow><span class=elab>Rotation</span><label class="detf posoff"><span>Angle °</span><input data-command-id="steel.position-rotation#a typed angle" aria-label="Rotation angle" id=detRotZ inputmode=decimal placeholder="${rotAgg===VARIES?'Varies':'0'}" value="${rotAgg===VARIES?'':esc(String(Number(rotAgg)||0))}" data-tip="${POSTIP.rot}" autocomplete=off></label></div>
6322
- <div class=seg2 style="margin-top:2px"><button data-command-id="steel.position-rotation#0" id=rot0 class="${rotAgg===0?'on':''}" aria-pressed="${rotAgg===0?'true':'false'}" data-tip="${POSTIP.rot}">0°</button><button data-command-id="steel.position-rotation#90" id=rot90 class="${rotAgg===90?'on':''}" aria-pressed="${rotAgg===90?'true':'false'}" data-tip="${POSTIP.rot}">90°</button><button data-command-id="steel.position-rotation#180" id=rot180 class="${rotAgg===180?'on':''}" aria-pressed="${rotAgg===180?'true':'false'}" data-tip="${POSTIP.rot}">180°</button><button data-command-id="steel.position-rotation#270" id=rot270 class="${rotAgg===270?'on':''}" aria-pressed="${rotAgg===270?'true':'false'}" data-tip="${POSTIP.rot}">270°</button></div>
6617
+ <div class=seg2 role=group aria-label="Section rotation" style="margin-top:2px"><button data-command-id="steel.position-rotation#0" id=rot0 class="${rotAgg===0?'on':''}" aria-pressed="${rotAgg===0?'true':'false'}" data-tip="${POSTIP.rot}">0°</button><button data-command-id="steel.position-rotation#90" id=rot90 class="${rotAgg===90?'on':''}" aria-pressed="${rotAgg===90?'true':'false'}" data-tip="${POSTIP.rot}">90°</button><button data-command-id="steel.position-rotation#180" id=rot180 class="${rotAgg===180?'on':''}" aria-pressed="${rotAgg===180?'true':'false'}" data-tip="${POSTIP.rot}">180°</button><button data-command-id="steel.position-rotation#270" id=rot270 class="${rotAgg===270?'on':''}" aria-pressed="${rotAgg===270?'true':'false'}" data-tip="${POSTIP.rot}">270°</button></div>
6323
6618
  <div class=divrow><hr><span class=sect style="margin:0">Modify geometry</span><hr></div>
6324
6619
  <div class=seg2 style="margin-top:0"><button data-command-id="steel.extend-trim" id=geoEL class="${geoMode==='el'?'on':''}" aria-pressed="${geoMode==='el'?'true':'false'}">Extend / Trim all</button></div>
6325
6620
  <div class=hint style="margin-top:6px">${geoMode==='el'?'Click a <b>target line</b> (member, segment, or grid line) — the nearest end of <b>every</b> selected member snaps to where it meets that line.':'<b>Extend/Trim</b> (E) every selected member\'s nearest end to one line. <b>Esc</b> cancels.'}</div>
@@ -6328,9 +6623,12 @@ function panel(){
6328
6623
  ${qdHasBeam?`<div class=seg2 style="margin-top:0"><button data-command-id="steel.quick-dimension-anchor#start" id=qdPtA class="${qdAnchorPt==='a'?'on':''}" aria-pressed="${qdAnchorPt==='a'?'true':'false'}" data-tip="Measure between each beam's START point">Start</button><button data-command-id="steel.quick-dimension-anchor#middle" id=qdPtMid class="${qdAnchorPt==='mid'?'on':''}" aria-pressed="${qdAnchorPt==='mid'?'true':'false'}" data-tip="Measure between each beam's MIDPOINT">Middle</button><button data-command-id="steel.quick-dimension-anchor#end" id=qdPtB class="${qdAnchorPt==='b'?'on':''}" aria-pressed="${qdAnchorPt==='b'?'true':'false'}" data-tip="Measure between each beam's END point">End</button></div>`:''}
6329
6624
  <div class=row style="margin-top:6px"><button data-command-id="steel.quick-dimension-place" class=ghostw id=qdPlace data-tip="Place spacing dimensions between the ${qdN} selected members · Shortcut: Q">📏 Place spacing dims (${qdN}) <span style="opacity:.55">(Q)</span></button></div>`:''}
6330
6625
  <div class="row f"><button data-command-id="steel.members-delete" class=danger id=del>Delete selected (${arr.length})</button></div>`;
6331
- wireTypeFilter(p);
6626
+ wireTypeFilter(p);wirePositionAvailability();
6332
6627
  // wiring — every commit applies to the whole selection; a blank field is a no-op (leaves each member's own value).
6333
6628
  document.getElementById('pf').onchange=e=>{const v=_canonDes(e.target.value);if(!v)return;edit(()=>{for(const m of selArr())ModelCmd.patchMember(m,{profile:v,rfi:_wt(v)==null});if(!profs.includes(v)){profs.push(v);profs.sort();}});};
6629
+ document.getElementById('profileBrowseM').onclick=e=>openProfilePicker({ids:arr.map(m=>m.id),current:VV(profAgg)?null:profAgg,scope:`${arr.length} selected members`,invoker:e.currentTarget});
6630
+ document.getElementById('mat').onchange=e=>{const v=String(e.target.value||'').trim();if(VV(matAgg)&&!v)return;applyMaterialChoice(arr.map(m=>m.id),v||CatalogPicker.MATERIAL_DEFAULT);};
6631
+ document.getElementById('materialBrowseM').onclick=e=>openMaterialPicker({ids:arr.map(m=>m.id),current:VV(matAgg)?null:(matAgg||''),scope:`${arr.length} selected members`,invoker:e.currentTarget});
6334
6632
  document.getElementById('mTypeM').onchange=e=>{const v=e.target.value;if(!normMemberTypeKey(v)){e.target.value=memberTypeValueFor(selArr());return;}edit(()=>{const k=memberTypeFromInput(v);if(!k)return;applyMemberType(selArr(),k);});}; // type owns Column-vs-beam-style role and legend category
6335
6633
  document.getElementById('verifyBtn').onclick=()=>edit(()=>{const v=!allVerified;for(const m of selArr())ModelCmd.patchMember(m,{verified:v});});
6336
6634
  {const _gel=document.getElementById('geoEL');if(_gel)_gel.onclick=()=>{geoMode=(geoMode==='el'?null:'el');setGeo();render();};}
@@ -6348,10 +6646,8 @@ function panel(){
6348
6646
  // so an all-ineligible selection must not enter it and leave an empty entry on the stack.
6349
6647
  // COLUMNS ARE NO LONGER EXCLUDED — the old `if(m.role!=='column')` skipped every column silently, and a
6350
6648
  // column now takes the same placement as anything else (design §4).
6351
- {const setAll=patch=>{const targets=selArr().filter(posEligible),sk=selArr().length-targets.length;
6352
- if(targets.length)edit(()=>{for(const m of targets)ModelCmd.patchMember(m,patch);});
6353
- if(sk)toast(sk+' member'+(sk>1?'s':'')+' skipped — a profile that does not resolve to a section has no face to place');};
6354
- const btn=(id,patch)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setAll(patch);};
6649
+ {const setAll=(patch,source)=>commitPositionEdit(selArr(),patch,source);
6650
+ const btn=(id,patch)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setAll(patch,b);};
6355
6651
  btn('posTop',{position:'top'});btn('posMid',{position:'middle'});btn('posBot',{position:'bottom'});
6356
6652
  btn('posHLeft',{positionH:'left'});btn('posHMid',{positionH:'middle'});btn('posHRight',{positionH:'right'});
6357
6653
  // The offsets: a BLANK commit is a no-op here, not a clear — blank means "Varies, leave each alone" on
@@ -6360,12 +6656,12 @@ function panel(){
6360
6656
  const off=(id,key)=>{const i=document.getElementById(id);if(i)i.onchange=e=>{const t=e.target.value.trim();if(t==='')return;
6361
6657
  const inch=parseLen(t);
6362
6658
  if(inch==null||!isFinite(inch)){toast(`Couldn’t read “${t}” as a length — try 3 1/2" or 1'-3 1/2".`);render();return;}
6363
- setAll({[key]:inch*25.4});};};
6659
+ setAll({[key]:inch*25.4},i);};};
6364
6660
  off('posOff','positionOffset');off('posHOff','positionHOffset');}
6365
6661
  // Rotation — apply one angle to every selected member's section (blank input = no-op). Normalised (-360,360).
6366
6662
  {const setRot=v=>{const raw=String(v).trim();let r=Number(raw.replace(',','.'));
6367
6663
  if(!isFinite(r)){toast('Couldn’t read “'+raw+'” as an angle — enter degrees, e.g. 45 or -90.');render();return;}
6368
- r=r%360;edit(()=>{for(const m of selArr())ModelCmd.patchMember(m,{rot:r});});};
6664
+ r=r%360;commitPositionEdit(selArr(),{rot:r},document.activeElement);};
6369
6665
  const _ri=document.getElementById('detRotZ');if(_ri)_ri.onchange=e=>{if(e.target.value.trim()==='')return;setRot(e.target.value);};
6370
6666
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
6371
6667
  chip('rot0',0);chip('rot90',90);chip('rot180',180);chip('rot270',270);}
@@ -6586,7 +6882,8 @@ function panel(){
6586
6882
  p.innerHTML=`<h3>Member ${esc(m.id)}</h3>
6587
6883
  ${typeFilterHTML()}
6588
6884
  ${memberTypeField('mTypeS',[m])}
6589
- <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.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>
6885
+ <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>
6886
+ <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>
6590
6887
  ${appearanceSect}
6591
6888
  ${braceSect}
6592
6889
  <div class="row hint">Length <b>${L} ft</b> · ${wpf==null?'<span id=rfiPill class="pill pill-clickable" role=button tabindex=0 data-tip="Open the RFI list, focused on this member" style="background:var(--err-bg)">RFI — size unresolved</span>':'Weight <b>'+(_lenFt(m)*wpf).toFixed(0)+' lb</b> · '+wpf+' lb/ft'}</div>
@@ -6596,14 +6893,15 @@ function panel(){
6596
6893
  ${defPts}
6597
6894
  ${bpSect}${spSect}${copeSect}
6598
6895
  <div class=divrow><hr><span class=sect style="margin:0" data-tip="${POSTIP.head}">Profile Position <span style="opacity:.45;font-weight:400">ⓘ</span></span><hr></div>
6599
- ${hEl?posRow('Depth','posOff','Offset',m.positionOffset,POSTIP.offD,
6896
+ ${positionFrameHTML()}
6897
+ ${posRow('Depth','posOff','Offset',m.positionOffset,POSTIP.offD,
6600
6898
  `<button data-command-id="steel.position-face#with its top face on the line" id=posTop class="${pos==='top'?'on':''}" aria-pressed="${pos==='top'?'true':'false'}" data-tip="${POSTIP.top}">Top</button><button data-command-id="steel.position-face#centred in depth" id=posMid class="${pos==='middle'?'on':''}" aria-pressed="${pos==='middle'?'true':'false'}" data-tip="${POSTIP.mid}">Middle</button><button data-command-id="steel.position-face#with its underside on the line" id=posBot class="${pos==='bottom'?'on':''}" aria-pressed="${pos==='bottom'?'true':'false'}" data-tip="${POSTIP.bot}">Bottom</button>`)
6601
6899
  +posRow('Width','posHOff','Offset',m.positionHOffset,POSTIP.offW,
6602
6900
  `<button data-command-id="steel.position-face#with its left face on the line" id=posHLeft class="${posH==='left'?'on':''}" aria-pressed="${posH==='left'?'true':'false'}" data-tip="${POSTIP.left}">Left</button><button data-command-id="steel.position-face#centred across the line" id=posHMid class="${posH==='middle'?'on':''}" aria-pressed="${posH==='middle'?'true':'false'}" data-tip="${POSTIP.midH}">Middle</button><button data-command-id="steel.position-face#with its right face on the line" id=posHRight class="${posH==='right'?'on':''}" aria-pressed="${posH==='right'?'true':'false'}" data-tip="${POSTIP.right}">Right</button>`)
6603
6901
  +(hApprox?`<div class=hint style="margin-top:4px">${hApprox}</div>`:'')
6604
- :`<div class=hint style="margin-top:8px">${hWhy}</div>`}
6902
+ +(!hEl?`<div class=hint style="margin-top:4px">${hWhy} Same-frame edits remain available; changing edit frame will refuse if a named face cannot be decoded.</div>`:'')}
6605
6903
  <div class=elabrow><span class=elab>Rotation</span><label class="detf posoff"><span>Angle °</span><input data-command-id="steel.position-rotation#a typed angle" aria-label="Rotation angle" id=detRotZ inputmode=decimal value="${rotDisp}" data-tip="${POSTIP.rot}" autocomplete=off></label></div>
6606
- <div class=seg2 style="margin-top:2px"><button data-command-id="steel.position-rotation#0" id=rot0 class="${rotN===0?'on':''}" aria-pressed="${rotN===0?'true':'false'}" data-tip="${POSTIP.rot}">0°</button><button data-command-id="steel.position-rotation#90" id=rot90 class="${rotN===90?'on':''}" aria-pressed="${rotN===90?'true':'false'}" data-tip="${POSTIP.rot}">90°</button><button data-command-id="steel.position-rotation#180" id=rot180 class="${rotN===180?'on':''}" aria-pressed="${rotN===180?'true':'false'}" data-tip="${POSTIP.rot}">180°</button><button data-command-id="steel.position-rotation#270" id=rot270 class="${rotN===270?'on':''}" aria-pressed="${rotN===270?'true':'false'}" data-tip="${POSTIP.rot}">270°</button></div>
6904
+ <div class=seg2 role=group aria-label="Section rotation" style="margin-top:2px"><button data-command-id="steel.position-rotation#0" id=rot0 class="${rotN===0?'on':''}" aria-pressed="${rotN===0?'true':'false'}" data-tip="${POSTIP.rot}">0°</button><button data-command-id="steel.position-rotation#90" id=rot90 class="${rotN===90?'on':''}" aria-pressed="${rotN===90?'true':'false'}" data-tip="${POSTIP.rot}">90°</button><button data-command-id="steel.position-rotation#180" id=rot180 class="${rotN===180?'on':''}" aria-pressed="${rotN===180?'true':'false'}" data-tip="${POSTIP.rot}">180°</button><button data-command-id="steel.position-rotation#270" id=rot270 class="${rotN===270?'on':''}" aria-pressed="${rotN===270?'true':'false'}" data-tip="${POSTIP.rot}">270°</button></div>
6607
6905
  ${hEl?`<button class=psethd id=posSecHd data-command-id="steel.position-section-view" type=button aria-expanded="${posSecOpen?'true':'false'}" aria-controls=posSecBody data-tip="A drawing of this section looking along the member from its start point — the outline where the placement actually puts it, with the work-line marked">
6608
6906
  <span class=chev>▶</span><span class=psn>Section view</span></button>
6609
6907
  <div class="psetbody${posSecOpen?' open':''}" id=posSecBody style="padding-left:0">${posSectionSvg(m)}</div>`:''}
@@ -6612,8 +6910,11 @@ function panel(){
6612
6910
  <div class=hint style="margin-top:6px">${geoMode==='el'?'Click a <b>target line</b> — another member, a grey segment, or a grid line. The nearest end of this member snaps to where the two lines meet (extends if short, trims if it overshoots).':geoMode==='split'?'Click a <b>point on this member</b> to cut it into two members.':'<b>Extend/Trim</b> (E) an end to meet another line · <b>Split</b> (S) at a point. <b>Esc</b> cancels.'}</div>
6613
6911
  ${col?'':`<div class=row><button data-command-id="steel.ends-swap" class=ghostw id=swapEnds aria-keyshortcuts=P data-tip="Reverse the beam: swap its yellow start and magenta end handles · Shortcut: P">⇄ Swap start ↔ end <span style="opacity:.55">(P)</span></button></div>`}`}
6614
6912
  <div class="row f"><button data-command-id="steel.member-delete" class=danger id=del>Delete member</button></div>`;
6615
- wireTypeFilter(p);
6913
+ wireTypeFilter(p);wirePositionAvailability();
6616
6914
  document.getElementById('pf').onchange=e=>edit(()=>{const v=_canonDes(e.target.value);ModelCmd.patchMember(m,{profile:v,rfi:_wt(v)==null});if(v&&!profs.includes(v)){profs.push(v);profs.sort();}});
6915
+ document.getElementById('profileBrowseS').onclick=e=>openProfilePicker({ids:[m.id],current:m.profile,scope:`Member ${m.id}`,invoker:e.currentTarget});
6916
+ document.getElementById('mat').onchange=e=>applyMaterialChoice([m.id],String(e.target.value||'').trim()||CatalogPicker.MATERIAL_DEFAULT);
6917
+ document.getElementById('materialBrowseS').onclick=e=>openMaterialPicker({ids:[m.id],current:m.material||'',scope:`Member ${m.id}`,invoker:e.currentTarget});
6617
6918
  {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)
6618
6919
  document.getElementById('pickProf').onclick=()=>{if(picking&&pickKind==='profile'){picking=false;}else{picking=true;pickKind='profile';pickEnd=null;}render();};
6619
6920
  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
@@ -6634,16 +6935,16 @@ function panel(){
6634
6935
  const _bo=document.getElementById('brOff');if(_bo)_bo.onchange=e=>{const v=e.target.value.trim();const n=v===''?0:parseLen(v);setBr(b=>b.offset=Number.isFinite(n)?n:0);};
6635
6936
  const _bf=document.getElementById('brFlip');if(_bf)_bf.onclick=()=>setBr(b=>b.offset=-(b.offset||0)); // draw the symbol on the other side (no typing a minus)
6636
6937
  const _bsw=document.getElementById('brSwap');if(_bsw)_bsw.onclick=()=>edit(()=>{normBrace(m);ModelCmd.patchMemberBrace(m,{lowerEnd:1-braceLowerEnd(m)});});}
6637
- {const setPos=v=>edit(()=>{ModelCmd.patchMember(m,{position:v});}); // profile placement on the reference line; persists + re-extrudes the 3D
6938
+ {const setPos=(v,source)=>commitPositionEdit([m],{position:v},source); // profile placement on the reference line; persists + re-extrudes the 3D
6638
6939
  const _pt=document.getElementById('posTop'),_pm=document.getElementById('posMid'),_pb=document.getElementById('posBot');
6639
- if(_pt)_pt.onclick=()=>setPos('top');if(_pm)_pm.onclick=()=>setPos('middle');if(_pb)_pb.onclick=()=>setPos('bottom');}
6640
- {const setPosH=v=>edit(()=>{ModelCmd.patchMember(m,{positionH:v});}); // the width half of the same placement — shifts the section ACROSS the line (3D + exports)
6940
+ if(_pt)_pt.onclick=()=>setPos('top',_pt);if(_pm)_pm.onclick=()=>setPos('middle',_pm);if(_pb)_pb.onclick=()=>setPos('bottom',_pb);}
6941
+ {const setPosH=(v,source)=>commitPositionEdit([m],{positionH:v},source); // the width half of the same placement — shifts the section ACROSS the line (3D + exports)
6641
6942
  const _hl=document.getElementById('posHLeft'),_hm=document.getElementById('posHMid'),_hr=document.getElementById('posHRight');
6642
- if(_hl)_hl.onclick=()=>setPosH('left');if(_hm)_hm.onclick=()=>setPosH('middle');if(_hr)_hr.onclick=()=>setPosH('right');}
6943
+ if(_hl)_hl.onclick=()=>setPosH('left',_hl);if(_hm)_hm.onclick=()=>setPosH('middle',_hm);if(_hr)_hr.onclick=()=>setPosH('right',_hr);}
6643
6944
  // The two numeric offsets — past the named face, on the section's OWN axis. See posSetOff for why a blank
6644
6945
  // commit CLEARS rather than storing 0, and why an unparseable one leaves the model alone.
6645
- {const _od=document.getElementById('posOff');if(_od)_od.onchange=e=>posSetOff(m,'positionOffset',e.target.value);
6646
- const _ow=document.getElementById('posHOff');if(_ow)_ow.onchange=e=>posSetOff(m,'positionHOffset',e.target.value);}
6946
+ {const _od=document.getElementById('posOff');if(_od)_od.onchange=e=>posSetOff(m,'positionOffset',e.target.value,_od);
6947
+ const _ow=document.getElementById('posHOff');if(_ow)_ow.onchange=e=>posSetOff(m,'positionHOffset',e.target.value,_ow);}
6647
6948
  // Section view: the panel's own themed disclosure (the property-set accordion), never <details> — whose
6648
6949
  // native marker triangle is exactly the browser default this theme must not leak. `posSecOpen` is
6649
6950
  // module-scoped so it survives p.innerHTML, and toggles in place rather than re-rendering the panel.
@@ -6656,7 +6957,7 @@ function panel(){
6656
6957
  // the one thing a placement field may never do.
6657
6958
  {const setRot=v=>{const raw=String(v).trim();let r=Number(raw.replace(',','.'));
6658
6959
  if(!isFinite(r)){toast('Couldn’t read “'+raw+'” as an angle — enter degrees, e.g. 45 or -90.');render();return;}
6659
- r=r%360;edit(()=>{ModelCmd.patchMember(m,{rot:r});});};
6960
+ r=r%360;commitPositionEdit([m],{rot:r},document.activeElement);};
6660
6961
  const _ri=document.getElementById('detRotZ');if(_ri)_ri.onchange=e=>setRot(e.target.value);
6661
6962
  const chip=(id,val)=>{const b=document.getElementById(id);if(b)b.onclick=()=>setRot(val);};
6662
6963
  chip('rot0',0);chip('rot90',90);chip('rot180',180);chip('rot270',270);}
@@ -6758,8 +7059,9 @@ function panel(){
6758
7059
  document.getElementById('del').onclick=()=>edit(()=>{deleteV2Selection({memberIds:[m.id],dimIds:selDimIds});selIds.clear();selDimIds.clear();});
6759
7060
  {const vb=document.getElementById('verifyBtn');if(vb)vb.onclick=()=>edit(()=>{ModelCmd.patchMember(m,{verified:!m.verified});});}
6760
7061
  }
6761
- function addFromSeg(sid){const sg=P.segments.find(s=>s.id===sid);if(!sg)return;const prof=addProfile;const id='m'+Date.now();const pv=snapshot();
6762
- const nm=ensureMeta({id,profile:prof,wp:[sg.a.slice(),sg.b.slice()],angle:sg.o,rfi:(_wt(prof)==null)});
7062
+ function addFromSeg(sid){const sg=P.segments.find(s=>s.id===sid);if(!sg)return;const basis=positionAuthoringBasis();if(!basis.ok){positionRefuse(basis.message);return;}const prof=addProfile;const id='m'+Date.now();const pv=snapshot();
7063
+ const nm=ensureMeta({id,profile:prof,material:addMaterial||undefined,wp:[sg.a.slice(),sg.b.slice()],angle:sg.o,rfi:(_wt(prof)==null)});
7064
+ if(!applyPositionAuthoringBasis(nm,basis)){positionRefuse('Profile Position unavailable: the current authoring axes are invalid.');return;}
6763
7065
  applyMemberType([nm],addType);MC().addMembers(P,[nm]); // applyMemberType writes role/memberType, not geometry — it stays here
6764
7066
  if(prof&&!profs.includes(prof)){profs.push(prof);profs.sort();}pushUndo(pv);render();sync3D();}
6765
7067
  // --- marquee hit-test (crossing selection): does segment ab touch rect [x0,y0,x1,y1]? ---
@@ -7049,7 +7351,7 @@ const PROP_DEFS=[
7049
7351
  {key:'type', label:'Type', get:m=>memberTypeLabel(memberTypeOf(m)), fmt:v=>v==null?'':String(v)},
7050
7352
  {key:'role', label:'Role', get:m=>m.role==='column'?'Column':'Beam', fmt:v=>v||''},
7051
7353
  {key:'length', label:'Length', get:m=>_lenFt(m), labelGet:m=>_lenFtLabel(m), fmt:v=>v==null?'':v.toFixed(1)+' ft'},
7052
- {key:'weight', label:'Weight', get:m=>{const w=_wt(m.profile);return w==null?undefined:_lenFt(m)*w;}, labelGet:m=>{const w=_wt(m.profile),l=_lenFtLabel(m);return (w==null||l==null)?undefined:l*w;}, fmt:v=>v==null?'':Math.round(v).toLocaleString()+' lb'},
7354
+ {key:'weight', label:'Weight', get:m=>{const w=_wt(m.profile);return w==null?undefined:_lenFt(m)*w;}, labelGet:m=>{const w=_wt(m.profile),l=_lenFtLabel(m);return (w==null||l==null)?undefined:l*w;}, fmt:v=>v==null?'':Math.round(v).toLocaleString('en-US')+' lb'},
7053
7355
  // The column suppression is GONE: a column takes the same Profile Position as every other member now
7054
7356
  // (design §4), so hiding its depth face would be the label lying about geometry the bake applies.
7055
7357
  {key:'position', label:'Position', get:m=>posEligible(m)?posDefault(m):((m.position==='top'||m.position==='middle'||m.position==='bottom')?m.position+' (not applied)':undefined), fmt:v=>v?v[0].toUpperCase()+v.slice(1):''},
@@ -7443,14 +7745,16 @@ function dimHintText(){if(dimChainPrev)return 'Chaining — click the next point
7443
7745
  return stepSlotText('steel.dimension')+' · '+a+(dimChain?' · Chain ON':'')+(loc?' · local axes':'');}
7444
7746
  // ---- Add-member draw: click-to-start / click-to-finish (mirrors the Dimension tool; snaps on both clicks) ----
7445
7747
  function drawClick(e){const s=dimSnapAt(e,drawDraft);const p=[s.x,s.y]; // dimSnapAt = buildSnap()+snap(); anchor=drawDraft → once a start exists, ⟂/∥ can square/align the end point
7446
- if(!drawDraft){drawDraft=p;if(picking&&pickKind==='profile'){picking=false;render();}drawPrev(e);return;} // click 1 → the start point (starting a draw disarms an armed ⌖ pick)
7748
+ if(!drawDraft){const basis=positionAuthoringBasis();if(!basis.ok){positionRefuse(basis.message,e.currentTarget);return;}drawDraft=p;drawBasisTok=basis;if(picking&&pickKind==='profile'){picking=false;render();}drawPrev(e);return;} // click 1 captures the frame with the start point
7749
+ const currentBasis=positionAuthoringBasis();if(!drawBasisTok||currentBasis.generation!==drawBasisTok.generation){drawDraft=null;drawBasisTok=null;drawPrevClear();positionRefuse('Frame changed — pick both member points again.',e.currentTarget);render();return;}
7447
7750
  const a=drawDraft,b=e.shiftKey?orthoLock(a[0],a[1],p[0],p[1]):p; // Shift = straight (ortho, local-frame aware)
7448
7751
  if(len(a,b)<=6){drawPrev(e);return;} // sub-6px 2nd pick (double-click / near-miss) → KEEP the start, don't commit (mirrors dimClick's zero-length guard)
7449
7752
  const dx=Math.abs(b[0]-a[0]),dy=Math.abs(b[1]-a[1]),o=dx>3*dy?'H':(dy>3*dx?'V':'D'); // classify H/V/diagonal like the old drag-commit
7450
- const id='m'+Date.now(),pv=snapshot();const nm=ensureMeta({id,profile:addProfile,wp:[a,b],angle:o,rfi:(_wt(addProfile)==null)});
7753
+ const id='m'+Date.now(),pv=snapshot();const nm=ensureMeta({id,profile:addProfile,material:addMaterial||undefined,wp:[a,b],angle:o,rfi:(_wt(addProfile)==null)});
7754
+ if(!applyPositionAuthoringBasis(nm,drawBasisTok)){drawDraft=null;drawBasisTok=null;drawPrevClear();positionRefuse('Profile Position unavailable: the captured authoring axes are invalid.',e.currentTarget);return;}
7451
7755
  applyMemberType([nm],addType);MC().addMembers(P,[nm]); // the Add-member panel's type owns role + legend category
7452
7756
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}pushUndo(pv);
7453
- drawDraft=null;render();drawPrev(e);} // commit → clear the draft, keep the tool armed for the next member
7757
+ drawDraft=null;drawBasisTok=null;render();drawPrev(e);} // commit → clear the draft + basis, keep the tool armed for the next member
7454
7758
  function drawPrevClear(){const g=document.getElementById('drawPrevLine');if(g)g.remove();snapClear();}
7455
7759
  function drawPrev(e){if(mode!=='add'||view3d){drawPrevClear();return;}
7456
7760
  {const h=document.getElementById('drawHint');if(h)h.innerHTML=drawHintText();} // keep the side-panel hint live (stage-aware)
@@ -7971,6 +8275,7 @@ function toast(msg,sticky,ms){let t=document.getElementById('toast');
7971
8275
  t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},ms>0?ms:TOAST_MS);}
7972
8276
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
7973
8277
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
8278
+ 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;}
7974
8279
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
7975
8280
  if(dimMode){dimClick(e);e.preventDefault();return;} // tool armed → all clicks place dimension points
7976
8281
  if(cmTool){cmClick(e);e.preventDefault();return;} // Move/Copy armed → clicks pick base/destination
@@ -8225,7 +8530,7 @@ svg.addEventListener('dblclick',e=>{ // dbl-click a grid bubble → rename tha
8225
8530
  gridRenameBubble(gb.dataset.gl!=null?'l':(gb.dataset.gv!=null?'v':'h'),+(gb.dataset.gl!=null?gb.dataset.gl:(gb.dataset.gv!=null?gb.dataset.gv:gb.dataset.gh)),gb.querySelector('circle'));}});
8226
8531
  function setMode(){document.body.classList.toggle('add',mode==='add');document.getElementById('mAdd').classList.toggle('on',mode==='add');
8227
8532
  picking=false;pickKind='profile';pickEnd=null; // a pick armed in one mode must never bleed into the other (an inspector ⌖ pick would otherwise show the Add panel's button pre-armed)
8228
- if(mode!=='add'){drawDraft=null;drawPrevClear();cmHudClose();if(view3d&&window.Steel3DView&&window.Steel3DView.drClear3d)window.Steel3DView.drClear3d();}} // leaving Add-member drops the in-progress start + preview, closes any open typed-entry HUD, and clears the 3D draw start (else a stale Add token could revalidate on re-arm — Codex)
8533
+ if(mode!=='add'){drawDraft=null;drawBasisTok=null;drawPrevClear();cmHudClose();if(view3d&&window.Steel3DView&&window.Steel3DView.drClear3d)window.Steel3DView.drClear3d();}} // leaving Add-member drops the in-progress start + basis + preview, closes any open typed-entry HUD, and clears the 3D draw start
8229
8534
  document.getElementById('mAdd').onclick=()=>{if(dimMode){dimMode=false;setDimMode();}if(csaxisMode){csaxisMode=false;setCsMode();}if(cmTool)disarmCm();if(qdPick){qdPick=null;setQdPickCls();}
8230
8535
  if(gridMode||gridPick||gridLinePick){if(gridLinePick&&gridLinePick.line)gridLinePick.line.remove();gridMode=false;gridPick=false;gridLinePick=null;gridSetPickClass();} // arming Add leaves the grid panel — same mutual exclusion Move/Copy already enforces. In 3D addActive() consumes the click AHEAD of the grid pick, so without this the Add gesture would run while the grid button + hint still claimed an armed pick (the A shortcut routes through this same handler)
8231
8536
  if(view3d&&window.Steel3DView){const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))window.Steel3DView.toggleDimTool();if(window.Steel3DView.disarmFrame3d)window.Steel3DView.disarmFrame3d();if(window.Steel3DView.armRefMeasure3d){window.Steel3DView.armRefMeasure3d(null);refMeasureClear();}} // the 3D dim tool + the local frame share the left-click — disarm both when entering add mode
@@ -8318,6 +8623,7 @@ document.getElementById('revB').onclick=()=>{const ids=reversedBeams(); // bea
8318
8623
  setTimeout(()=>{delete b.dataset.flash;b.classList.remove('ok');b.textContent='Reversed beams';},1500);return;}
8319
8624
  if(mode==='add'){mode='sel';setMode();}geoMode=null;setGeo();selDimIds.clear();selIds=new Set(ids);fitToWindow();render();
8320
8625
  toast(ids.length+' reversed beam'+(ids.length>1?'s':'')+' selected — press P to swap direction');}; // select reversed → review → P swaps them
8626
+ document.getElementById('memberEndsB').onclick=scanMemberEnds;
8321
8627
  document.getElementById('mrgB').onclick=()=>{const r=mergeCollinearJS(P.members); // conservative; result is undoable (Ctrl+Z)
8322
8628
  if(!r.mergedAway){toast('Nothing to merge');return;}
8323
8629
  // edit() returns FALSE on a refusal (and has already toasted the reason). The success toast must be
@@ -8339,6 +8645,7 @@ addEventListener('keydown',e=>{
8339
8645
  // its own keydown stops them.
8340
8646
  const _ae=document.activeElement||{};
8341
8647
  const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test(_ae.tagName)||_ae.id==='planTrigger';
8648
+ if(memberEndReview){if(e.key==='Escape'){e.preventDefault();closeMemberEndReview();}return;}
8342
8649
  if(dimEdit){if(e.key==='Escape'){e.preventDefault();closeDimEdit();}return;} // F8 popup is modal — suppress every editor/tool shortcut (incl. Ctrl+Z under the popup). Its own input/buttons handle their keys and stopPropagation, so they never reach here (Codex R2 #8).
8343
8650
  // A live drag-out to Tekla owns Escape: the 3D view cancels the gesture on its own handler (this one
8344
8651
  // runs first). Without this, Escape would fall through to the deselect below and clear the very
@@ -8386,7 +8693,7 @@ addEventListener('keydown',e=>{
8386
8693
  if(e.key==='Escape'&&dimMode){if(dimChainPrev){dimChainPrev=null;dimPrevClear();}else if(dimDraft){dimDraft=null;dimPrevClear();}else{dimMode=false;setDimMode();}render();return;} // Esc: end the chain → drop the in-progress dim → exit the tool
8387
8694
  if(e.key==='Escape'&&selDimIds.size){if(dimSplitMode){dimSplitMode=false;snapClear();render();}else{selDimIds.clear();render();}return;} // Esc on a selected dim: end split mode → else deselect
8388
8695
  if(e.key==='Escape'&&view3d&&mode==='add'){if(cmHudIsOpen()){cmHudClose();return;}if(window.Steel3DView&&window.Steel3DView.drEscape&&window.Steel3DView.drEscape())return;} // 3D draw: Esc closes an open typed-entry HUD first, then drops the in-progress start pick, then exits add mode (falls through below)
8389
- if(e.key==='Escape'&&!view3d&&mode==='add'&&drawDraft){drawDraft=null;drawPrevClear();render();return;} // 2D Add-member: 1st Esc drops the in-progress start point (2nd falls through below → exits the tool), like the Dimension tool
8696
+ if(e.key==='Escape'&&!view3d&&mode==='add'&&drawDraft){drawDraft=null;drawBasisTok=null;drawPrevClear();render();return;} // 2D Add-member: 1st Esc drops the in-progress start point + frame snapshot
8390
8697
  // Esc while typing the true distance leaves the BOX, and stops there. Without this the press falls all
8391
8698
  // the way to the catch-all below — which is not guarded by `inForm` — and clears the user's member
8392
8699
  // selection as the answer to "I have finished typing", which is not a thing they asked for.
@@ -9134,18 +9441,19 @@ const view3dApi={
9134
9441
  closeCmHud:()=>{if(cmHudIsOpen())cmHudClose();}, // the view closes an open typed-entry HUD on frame drift / rebuild (invalidatePointEntry)
9135
9442
 
9136
9443
  disarmAdd:()=>{if(mode==='add'){mode='sel';setMode();render();}},
9137
- onAddMember3d:(aMm,bMm)=>{const k=304.8/((P&&P.pt_per_ft>0)?P.pt_per_ft:1),r6=n=>Math.round(n*1e6)/1e6; // mm → wp px (Y FLIPPED) + elevation inches
9444
+ onAddMember3d:(aMm,bMm,basis)=>{if(!basis||!basis.ok){positionRefuse('Profile Position unavailable: the captured 3D authoring axes are invalid.');return;}const k=304.8/((P&&P.pt_per_ft>0)?P.pt_per_ft:1),r6=n=>Math.round(n*1e6)/1e6; // mm → wp px (Y FLIPPED) + elevation inches
9138
9445
  const wpA=[r6(aMm[0]/k),r6(-aMm[1]/k)],wpB=[r6(bMm[0]/k),r6(-bMm[1]/k)];
9139
9446
  const zA=r6(aMm[2]/25.4),zB=r6(bMm[2]/25.4);
9140
9447
  const hpx=Math.hypot(wpB[0]-wpA[0],wpB[1]-wpA[1]),hIn=hpx/FT*12,dzIn=Math.abs(zB-zA);
9141
9448
  const id='m'+Date.now();
9142
9449
  edit(()=>{let m;
9143
- if(hIn<6&&dzIn>6){m=ensureMeta({id,profile:addProfile,wp:[wpA.slice(),wpA.slice()],role:'column'}); // near-vertical run → a column at the plan point
9450
+ if(hIn<6&&dzIn>6){m=ensureMeta({id,profile:addProfile,material:addMaterial||undefined,wp:[wpA.slice(),wpA.slice()],role:'column'}); // near-vertical run → a column at the plan point
9144
9451
  m.col={bos:Math.min(zA,zB),tos:Math.max(zA,zB),note:'',tosDef:false,detail:''};}
9145
- else{const near=z=>Math.abs(z-defaultTOS)<0.5; // a pick ON the level stays default-linked
9146
- m=ensureMeta({id,profile:addProfile,wp:[wpA,wpB],role:'beam',angle:_mAngle([wpA,wpB])}); // classify H/V/D from the PLAN delta — same rule as _mAngle + the 2D add path (all three agree)
9452
+ else{const near=z=>Math.abs(z-defaultTOS)<0.5; // a pick ON the level stays default-linked
9453
+ m=ensureMeta({id,profile:addProfile,material:addMaterial||undefined,wp:[wpA,wpB],role:'beam',angle:_mAngle([wpA,wpB])}); // classify H/V/D from the PLAN delta — same rule as _mAngle + the 2D add path (all three agree)
9147
9454
  const mfNote=/(^|[^A-Z])MF/i.test(addProfile||'')?'moment':''; // a moment-frame profile keeps the auto note ensureMeta gives 2D-drawn members
9148
- m.ends=[{tos:near(zA)?null:zA,note:mfNote,tosDef:near(zA),detail:''},{tos:near(zB)?null:zB,note:mfNote,tosDef:near(zB),detail:''}];}
9455
+ m.ends=[{tos:near(zA)?null:zA,note:mfNote,tosDef:near(zA),detail:''},{tos:near(zB)?null:zB,note:mfNote,tosDef:near(zB),detail:''}];}
9456
+ if(!applyPositionAuthoringBasis(m,basis))throw new Error('Captured 3D authoring basis is invalid');
9149
9457
  if((addType==='column')===(m.role==='column'))ModelCmd.setMemberType(m,addType); // 3D geometry decides column-vs-beam; only stamp the panel's type when it agrees with that role
9150
9458
  m.rfi=(_wt(addProfile)==null);MC().addMembers(P,[m]);
9151
9459
  if(addProfile&&!profs.includes(addProfile)){profs.push(addProfile);profs.sort();}
@@ -14840,7 +15148,7 @@ function reflectActivePane(){
14840
15148
  // and Extend/Trim/Split (geoMode — the 3D view arms it via E/S and drives it through
14841
15149
  // view3dApi.onTrimExtend/onSplit, so cancelling it would kill an active 3D trim).
14842
15150
  function onActivePaneChange(){
14843
- drawDraft=null;drawPrevClear();
15151
+ drawDraft=null;drawBasisTok=null;drawPrevClear();
14844
15152
  let disarmed2d=gridMode||csaxisMode||picking;
14845
15153
  if(gridMode)setGridMode(false);
14846
15154
  if(csaxisMode){csaxisMode=false;setCsMode();}
@@ -15038,6 +15346,7 @@ let viewSeq=0; // monotonic per view switch — see the staleness check after
15038
15346
  // show/hide/rebuild/fit: inferring those again from the DOM would be a second implementation of the rule
15039
15347
  // the pure module exists to own.
15040
15348
  async function setView(on,{remember=true}={}){
15349
+ if(memberEndReview&&memberEndReview.busy){memberEndReview.live='Finish the current member-end action before changing views.';panel();return;}
15041
15350
  const seq=++viewSeq;
15042
15351
  const mode=SplitView.sanitizeMode(on); // REQUESTED
15043
15352
  const stageEl=document.getElementById('stagewrap');
@@ -15049,7 +15358,7 @@ async function setView(on,{remember=true}={}){
15049
15358
  const want=resolved.mode; // EFFECTIVE
15050
15359
  const effects=SplitView.nextMode(viewMode,want);
15051
15360
  let failed=false; // a 3D open that threw: keep the shared tail, skip the persist
15052
- drawDraft=null;drawPrevClear(); // any view switch drops an in-progress 2D Add-member start — it's a plan-pixel point, meaningless after the switch (else a stale point finishes a member on return)
15361
+ drawDraft=null;drawBasisTok=null;drawPrevClear(); // any view switch drops an in-progress 2D Add-member start + frame snapshot
15053
15362
  // B6: cancel the 2D-only panel-takeover / armed-pick tools on any view switch. They have no 3D counterpart, so if
15054
15363
  // left armed they take over the panel while you're in 3D or silently resume on return to 2D (the "active command
15055
15364
  // survives a 2D↔3D switch" bug). Cross-view tools stay armed by design and setView only drops their in-progress
@@ -15074,7 +15383,8 @@ async function setView(on,{remember=true}={}){
15074
15383
  // reverts for the same reason once the renderer exists; this branch is the path where it never did.
15075
15384
  if(!window.Steel3DView){applyViewState('2d');toast('3D view unavailable (renderer failed to load)');return;} // stay in 2D
15076
15385
  try{
15077
- if(!view3dReady){window.Steel3DView.init(document.getElementById('stage3d'),view3dApi);view3dReady=true;}
15386
+ if(!view3dReady){window.Steel3DView.init(document.getElementById('stage3d'),view3dApi);view3dReady=true;
15387
+ if(window.Steel3DView.onPositionAuthoringBasisChange)positionBasisViewUnsub=window.Steel3DView.onPositionAuthoringBasisChange(()=>{positionBasisFingerprint='';positionAuthoringBasis();});}
15078
15388
  applyViewState(want);
15079
15389
  window.Steel3DView.show();
15080
15390
  updCS();if(typeof csSyncF3d==='function')csSyncF3d(); // reflect the (persisted) 3D local frame in the Axes chip IMMEDIATELY — before the awaited rebuild, else the chip shows a stale "Global" for the rebuild's duration (QA F14)
@@ -15121,6 +15431,7 @@ async function setView(on,{remember=true}={}){
15121
15431
  // that survives that round trip today. The 2D pane keeps its viewBox; a narrower pane just shows less.
15122
15432
  if(effects.show2d)render();
15123
15433
  if(propPopOpen()){if(propPopPinned){dockPropPop();renderPropPop();}else closePropPop(true);} // the popup is anchored to one canvas — re-dock if pinned (renderPropPop re-syncs its "Show in this view" checkbox to the now-live view), else dismiss on the view switch
15434
+ if(memberEndReview&&memberEndScopeSig(memberEndReview.scope)!==memberEndScopeSig())invalidateMemberEndReview('The view changed — check member ends again.');
15124
15435
  panel(); // repaint the inspector for the NOW-current view (view3d is final here): a cross-view tool stays armed but its in-progress draft was dropped above — Add-member's drawHint (:2288) and Move/Copy's cmHint are view-specific, so without this the panel keeps the stale 2D "Click 2: end" (drawDraft already null) instead of the 3D working-plane hint (and vice-versa on return)
15125
15436
  refreshPropLabels3d();updatePropHint(); // push the label set to whichever view is now live (3D shows them; 2D hides the 3D host) + refresh the corner note
15126
15437
  updCS();if(typeof csSyncF3d==='function')csSyncF3d(); // the Axes chip is view-scoped (2D=P.frame, 3D=frame3d) — resync it + the 3D-frame fields on every switch (applyViewState alone doesn't; Codex MAJOR 6)
@@ -15619,13 +15930,14 @@ function openRFI(focusId){focusId=(typeof focusId==='string')?focusId:null; //
15619
15930
  g.innerHTML=list.length?('<div class=hint style="margin-bottom:10px">'+list.length+' member'+(list.length>1?'s have':' has')+' no resolved AISC size, so their weight is excluded from the BOM. A green <b>✓ Verified</b> means someone has already confirmed that designation by hand — it is right, it just isn’t in the AISC table. Assign a profile to clear it; for <b>MF/BF</b> marks use the <b>Frames</b> schedule. Edits here update the contract.</div><table class=ftab><thead><tr><th>#</th><th>Profile / mark</th><th>Role</th><th>Length</th><th>Why it’s flagged</th><th>Verified</th><th></th></tr></thead><tbody>'+
15620
15931
  list.map((m,i)=>{ensureMeta(m);const L=_lenFt(m).toFixed(1);const v=m.verified===true; // #628: verified ≠ resolved — a hand-confirmed member with no AISC size STAYS on this list (its weight is still out of the BOM); the marker only says a human has been here, so "checked, the library just can’t price it" stops reading like "not looked at yet"
15621
15932
  return `<tr${v?' class=rfi-verified':''}><td><span class="rfichip${v?' verified':''}"${v?` data-tip="${RFI_VTIP}"`:''}>${i+1}</span></td>
15622
- <td><input data-command-id="steel.rfi-profile#${esc(m.id)}" aria-label="Profile for ${esc(m.id)}" class=combo data-src=profiles data-mid="${esc(m.id)}" value="${esc(m.profile||'')}" placeholder="e.g. W16X26" autocomplete=off style="width:124px"></td>
15933
+ <td><div style="display:flex;gap:5px"><input data-command-id="steel.rfi-profile#${esc(m.id)}" aria-label="Profile for ${esc(m.id)}" class=combo data-src=profiles data-mid="${esc(m.id)}" value="${esc(m.profile||'')}" placeholder="e.g. W16X26" autocomplete=off style="width:124px"><button data-command-id="steel.browse-profile-catalog#${esc(m.id)}" class="ghost rfiProfileBrowse" data-mid="${esc(m.id)}" data-tip="Browse the active environment profile catalog">Browse</button></div></td>
15623
15934
  <td>${m.role==='column'?'Column':'Beam'}</td><td>${L} ft</td><td class=rea>${esc(rfiReason(m))}</td>
15624
15935
  <td class=vcell>${v?`<span class="chip verified" data-tip="${RFI_VTIP}">✓ Verified</span>`:''}</td>
15625
15936
  <td><button data-command-id="steel.locate-member#${esc(m.id)}" class=ghost data-loc="${esc(m.id)}">Locate</button></td></tr>`;}).join('')+'</tbody></table>')
15626
15937
  :'<div class=hint>No unresolved members — every member has a resolved AISC size. ✓</div>';
15627
15938
  g.querySelectorAll('input.combo[data-mid]').forEach(inp=>inp.onchange=e=>{const m=byId(inp.dataset.mid);if(!m)return;
15628
15939
  const v=_canonDes(e.target.value);edit(()=>{ModelCmd.patchMember(m,{profile:v,rfi:_wt(v)==null});if(v&&!profs.includes(v)){profs.push(v);profs.sort();}});openRFI();});
15940
+ g.querySelectorAll('button.rfiProfileBrowse').forEach(b=>b.onclick=()=>{const m=byId(b.dataset.mid);if(!m)return;openProfilePicker({ids:[m.id],current:m.profile,scope:`Resolve ${m.id}`,invoker:b,onApply:v=>{applyProfileChoice([m.id],v);openRFI(m.id);}});});
15629
15941
  g.querySelectorAll('button[data-loc]').forEach(b=>b.onclick=()=>{const m=byId(b.dataset.loc);if(!m)return;selDimIds.clear();selIds=new Set([m.id]);geoMode=null;setGeo();closeRFI();render();zoomToMember(m);});
15630
15942
  document.getElementById('rfiModal').style.display='flex';
15631
15943
  if(focusId){const inp=[...g.querySelectorAll('input.combo[data-mid]')].find(i=>i.dataset.mid===focusId);const row=inp&&inp.closest('tr'); // find via the row's profile input — avoids CSS-escaping the id
@@ -15850,6 +16162,7 @@ lbView.addEventListener('dblclick',lbReset);
15850
16162
  // --- custom dark combobox (replaces the native white datalist dropdown) ---
15851
16163
  const COMBO_SRC={
15852
16164
  profiles:()=>profs,
16165
+ materials:()=>materialCatalogRows.map(r=>r.value),
15853
16166
  membertypes:()=>memberTypeRecords().map(t=>t.label),
15854
16167
  conntypes:()=>['moment','drag','shear','braced','pinned','fixed'],
15855
16168
  details:()=>detTexts(), // the SAME list the Details modal shows — see detTexts (#397)
@@ -16308,7 +16621,7 @@ function resetPlanViewState(i){
16308
16621
  // The profile list, read from the native document root. Deriving it from
16309
16622
  // `P.members` would be the silent-empty this design refuses; deriving it from `weights` alone would be a
16310
16623
  // truthful-but-partial list, which is the same defect one size down.
16311
- profs=[...new Set([...(C.members||[]).map(m=>m&&m.profile).filter(Boolean),...Object.keys(WT)])].sort();
16624
+ profs=[...new Set([...profileCatalogValues(),...(C.members||[]).map(m=>m&&m.profile).filter(Boolean)])].sort(CatalogPicker.naturalProfileCompare);
16312
16625
  selIds=new Set();findHits=new Set();selGridIds=new Set();picking=false;pickKind='profile';pickEnd=null;mode='sel';geoMode=null;setGeo();qdPick=null;setQdPickCls();
16313
16626
  dimMode=false;dimChain=false;dimSplitMode=false;selDimIds=new Set();setDimMode();
16314
16627
  setMode();
@@ -16319,6 +16632,8 @@ function resetPlanViewState(i){
16319
16632
  syncPlanSwitcher(i);}
16320
16633
  // --- multi-plan: switch between all steel plan views ---
16321
16634
  function setPlan(i){
16635
+ if(memberEndReview&&memberEndReview.busy){memberEndReview.live='Finish the current member-end action before changing views.';panel();return;}
16636
+ if(memberEndReview&&C.plans&&C.plans[i]&&memberEndReview.scope.kind==='active-view'&&memberEndReview.scope.viewId!==C.plans[i].sheet)invalidateMemberEndReview('The view changed — check member ends again.');
16322
16637
  const canonical=C.plans[i];
16323
16638
  if(!canonical){
16324
16639
  NO_PLAN_VIEW=true;C.active=0;P={sheet:'',members:[],segments:[],dims:[],details:[],callouts:[],tos_callouts:[],grid:null,default_tos:0};
@@ -16350,7 +16665,7 @@ function setPlan(i){
16350
16665
  else clip=[0,0,1000,1000];}
16351
16666
  X0=clip[0];Y0=clip[1];X1=clip[2];Y1=clip[3];FT=P.pt_per_ft||12;RB64=P.raster_b64||'';EXTX=X1-X0;EXTY=Y1-Y0;
16352
16667
  svg.setAttribute('viewBox',`${X0} ${Y0} ${X1-X0} ${Y1-Y0}`);
16353
- profs=[...new Set([...P.members.map(m=>m.profile), ...Object.keys(WT)])].sort();
16668
+ profs=[...new Set([...profileCatalogValues(),...P.members.map(m=>m.profile).filter(Boolean)])].sort(CatalogPicker.naturalProfileCompare);
16354
16669
  // undo/redo is one GLOBAL stack (module-level, declared once) — NOT swapped per plane. A plane switch
16355
16670
  // must not reset or re-scope undo, since snapshots are whole-model and selection/edits span sheets.
16356
16671
  selIds=new Set();findHits=new Set();selGridIds=new Set();picking=false;pickKind='profile';pickEnd=null;mode='sel';geoMode=null;setGeo();qdPick=null;setQdPickCls(); // findHits + selGridIds reset per plan like selIds — a stale highlight (or, for grids, an index-based id) must not bleed onto another sheet (grids are per-plan). setGeo() clears body.geo/geoel so an armed Extend/Trim tool doesn't leave the grid crosshair on the next sheet; the F7 station pick is plan-local too