@floless/app 0.154.0 → 0.155.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/floless-server.cjs +49502 -37986
  2. package/dist/schemas/steel.model.v2.schema.json +19 -5
  3. package/dist/skills/floless-app-onboarding/SKILL.md +22 -13
  4. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +12 -8
  5. package/dist/skills/floless-app-steel-model/SKILL.md +23 -2
  6. package/dist/skills/floless-app-steel-takeoff/SKILL.md +158 -65
  7. package/dist/skills/floless-app-workflows/SKILL.md +23 -5
  8. package/dist/skills/floless-app-workflows/references/blender-exec.md +183 -0
  9. package/dist/skills/floless-app-workflows/references/dev-server-and-run-trace.md +27 -12
  10. package/dist/templates/blender-construction-sequence.flo +96 -0
  11. package/dist/web/agents.js +33 -13
  12. package/dist/web/app.css +275 -33
  13. package/dist/web/aware.js +745 -82
  14. package/dist/web/chat-question-card.js +477 -0
  15. package/dist/web/chat.css +177 -12
  16. package/dist/web/chat.js +1537 -717
  17. package/dist/web/commands-shell.js +424 -7
  18. package/dist/web/commands-steel.js +105 -4
  19. package/dist/web/guide.js +4 -3
  20. package/dist/web/index.html +96 -7
  21. package/dist/web/instructor.js +10 -9
  22. package/dist/web/left-pane.js +40 -3
  23. package/dist/web/media-player.js +234 -0
  24. package/dist/web/model-editor-contract.js +2 -0
  25. package/dist/web/model-editor-revit-adapter.js +1 -0
  26. package/dist/web/model-editor-steel-adapter.js +89 -1
  27. package/dist/web/model-panel-bridge.js +16 -2
  28. package/dist/web/model-view-query.js +590 -0
  29. package/dist/web/model-viewport-revit-adapter.js +15 -1
  30. package/dist/web/model-viewport-toolbar.js +5 -2
  31. package/dist/web/pages.js +592 -0
  32. package/dist/web/panels.js +2 -1
  33. package/dist/web/revit-editor.js +181 -16
  34. package/dist/web/run-progress.js +193 -0
  35. package/dist/web/run-strip.js +173 -0
  36. package/dist/web/steel-3d-core.js +70 -0
  37. package/dist/web/steel-editor.html +2751 -219
  38. package/dist/web/steel-frames-core.js +958 -0
  39. package/dist/web/steel-last-seen.js +315 -0
  40. package/dist/web/steel-marks-core.js +530 -0
  41. package/dist/web/steel-model-slim.js +95 -0
  42. package/dist/web/steel-model-v2-client-validation.js +14 -2
  43. package/dist/web/steel-model-v2-commands.js +258 -27
  44. package/dist/web/steel-model-v2-projection.js +78 -18
  45. package/dist/web/steel-read-confidence.js +11 -2
  46. package/dist/web/workspaces.js +416 -26
  47. package/package.json +3 -2
@@ -162,6 +162,7 @@
162
162
  [data-theme="light"] #stage,[data-theme="light"] #stage3d,[data-theme="light"] #pane2d,[data-theme="light"] #pane3d,
163
163
  [data-theme="light"] #viewBar2d,[data-theme="light"] #connCrumb,[data-theme="light"] #bottomDock,
164
164
  [data-theme="light"] #selFly,[data-theme="light"] #m3dBar,[data-theme="light"] #m3dToolBar,
165
+ [data-theme="light"] #calloutPop,[data-theme="light"] #viewFly,[data-theme="light"] #comboPop.on-stage,
165
166
  [data-theme="light"] #propPop,[data-theme="light"] #snapMenu,[data-theme="light"] #dimEditPop,[data-theme="light"] #cmHud,
166
167
  [data-theme="light"] #m3dCube,[data-theme="light"] #m3dAxes,[data-theme="light"] #plHint,
167
168
  [data-theme="light"] #gridReadout,[data-theme="light"] #gridLabelEdit,[data-theme="light"] #m3dReadout,[data-theme="light"] #m3dRubber,
@@ -388,6 +389,39 @@
388
389
  a screen reader. Collapsed by default so the plain-English lead reads first. */
389
390
  #regBanner .rgdet{display:none;margin-top:6px;padding-top:6px;border-top:1px solid var(--warn);color:var(--mut);font:11px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-wrap:anywhere}
390
391
  #regBanner.det .rgdet{display:block}
392
+ /* #2214 — a plan with no floor level. The NEUTRAL tier of #regBanner (a level nobody has stated is unfinished
393
+ work, not a fault), same position, chrome and layer; #regBanner wins when both would show, so there is only
394
+ ever one stage notice. Existing tokens only. `Enter a level…` is the primary action, in the brand ink. */
395
+ #cutBanner,#cutPill{position:absolute;left:12px;top:12px;display:none;z-index:58;box-shadow:0 4px 14px rgba(0,0,0,.45)}
396
+ #cutBanner{right:12px;border:1px solid var(--line);border-radius:8px;background:var(--panel);color:var(--mut);padding:8px 10px;font-size:12px;line-height:1.5}
397
+ #cutBanner.on{display:block}
398
+ #cutBanner .rgline{overflow-wrap:anywhere}
399
+ #cutBanner .rgact{display:flex;gap:6px;align-items:center;margin-top:6px;flex-wrap:wrap}
400
+ #cutBanner .rgcta{color:var(--mut);font-size:11px;flex:1;min-width:0}
401
+ #cutBanner button,#cutPill{background:transparent;border:1px solid var(--line);color:var(--mut);border-radius:6px;padding:2px 8px;font:11px var(--ui);cursor:pointer}
402
+ #cutBanner button:hover,#cutPill:hover{background:rgba(148,163,184,.12)}
403
+ #cutBanner button:active,#cutPill:active{transform:translateY(1px)}
404
+ #cutBanner button:focus-visible,#cutPill:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
405
+ #cutBanner button.cutprimary{border-color:var(--brand);color:var(--brand)}
406
+ #cutPill.on{display:inline-flex;align-items:center;background:var(--panel);border-radius:999px;padding:3px 10px}
407
+ #cutForm{margin-top:8px;padding-top:8px;border-top:1px solid var(--line)}
408
+ #cutForm[hidden]{display:none}
409
+ #cutForm .cutlab{display:block;color:var(--text);margin-bottom:4px}
410
+ #cutForm .cutrow{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
411
+ #cutForm input{flex:0 1 180px;min-width:110px;background:var(--field);border:1px solid var(--ctrl-border);border-radius:4px;padding:3px 6px;font:12px var(--ui);color:var(--text)}
412
+ #cutForm input:focus{outline:none;border-color:var(--brand)}
413
+ #cutForm input:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
414
+ #cutForm input[aria-invalid=true]{border-color:var(--warn)}
415
+ #cutForm .cutecho{margin-top:4px;color:var(--mut);font-size:11px;min-height:15px}
416
+ #cutForm .cutstat{margin-top:2px;color:var(--mut);font-size:11px;min-height:15px;overflow-wrap:anywhere}
417
+ #cutForm .cutstat.bad{color:var(--warn)}
418
+ /* The Inspector's floor-level field (#2214): the banner's input, in the Properties panel's own field language. */
419
+ #panel #flInput{width:100%;box-sizing:border-box}
420
+ #panel #flEcho{text-align:left}
421
+ #panel .flstat{margin:2px 0 6px;font-size:11px}
422
+ #panel #flSet{margin-bottom:8px}
423
+ #panel #flInput[aria-invalid=true]{border-color:var(--warn)}
424
+ #panel .flstat.bad{color:var(--warn)}
391
425
  #connCrumb{position:absolute;left:50%;top:48px;transform:translateX(-50%);display:none;align-items:center;gap:1px;max-width:min(72%,560px);background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:4px 10px;box-shadow:0 4px 14px rgba(0,0,0,.45);z-index:58;font-size:12px;white-space:nowrap;overflow:hidden} /* below #m3dBar (top:12,h~29,z:59); z:58 keeps it clickable above the model-glued label chips, which sit under the 3D chrome at z:3-4 (#614) */
392
426
  #connCrumb .seg{color:var(--mut);cursor:pointer;padding:1px 4px;border-radius:4px;background:none;border:0;font:inherit;max-width:260px;overflow:hidden;text-overflow:ellipsis}
393
427
  #connCrumb .seg:hover{color:var(--text);text-decoration:underline}
@@ -663,7 +697,19 @@
663
697
  and still well short of a resolved one (mean ink 63 vs 106 on the same sample). #519 item 1. */
664
698
  polygon.member{cursor:pointer;stroke-width:1.5;fill-opacity:.7;stroke-linejoin:round;vector-effect:non-scaling-stroke}
665
699
  body.dragmove polygon.member{cursor:move}
700
+ /* A COLUMN BELOW the floor of this sheet (#2214) — the drafting convention for a framing plan: the column that
701
+ carries the beam from under the floor, shown dashed and lighter. Two cues, and the FILL is the one that
702
+ carries at fit zoom: a true-size footprint is ~7px across there, too small for any dash to resolve, so the
703
+ ink order is solid .7 > RFI .15 > below .08. The dash is the brace-below language already in the legend
704
+ (`9 4 3 4`) and is deliberately NOT the RFI dash (`6 4`, "the size is unresolved") and NOT the grid's
705
+ dash-dot, which this canvas reserves. No stroke-width here: it would tie with `.sel` and cancel it. The
706
+ rule sits BEFORE `.sel` and `.rfi` so a column that is both below and unresolved still reads as an RFI.
707
+ The colour is the profile's own, so it follows both themes with no new colour. */
708
+ polygon.member.colbelow{fill-opacity:.08;stroke-dasharray:9 4 3 4}
709
+ /* A column below whose footprint could not be built is drawn as a plain line: same dash, and lighter. */
710
+ line.member.colbelow{stroke-dasharray:9 4 3 4;stroke-opacity:.5}
666
711
  polygon.member.sel{stroke-width:2} polygon.member.rfi{fill-opacity:.15;stroke-dasharray:6 4}
712
+ polygon.member.colbelow.sel{fill-opacity:.3}
667
713
  circle.handle{fill:var(--bg);stroke:#f8fafc;stroke-width:3;cursor:grab}
668
714
  line.seg{stroke:#475569;stroke-width:2;opacity:0;cursor:crosshair} body.add line.seg{opacity:.5}
669
715
  line.seg:hover{stroke:#fbbf24;opacity:1;stroke-width:4}
@@ -941,6 +987,65 @@ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stro
941
987
  g.pdfvec path{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.82;stroke-linecap:round;stroke-linejoin:round}
942
988
  g.pdfvec circle{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.55}
943
989
  g.cohot:hover text.cotx{opacity:1}
990
+ /* ── Callouts (#2211): reachable from the keyboard, a draft while one is being added, and the + Callout tool ── */
991
+ g.cohot:focus-visible{outline:none}
992
+ g.cohot:focus-visible circle.cobub{opacity:1;stroke-width:2.5;filter:drop-shadow(0 0 4px var(--brand))}
993
+ g.cohot:focus-visible text.cotx{opacity:1}
994
+ circle.cobub.draft{opacity:1;pointer-events:none}
995
+ body.calloutedit #svg,body.calloutedit line.member,body.calloutedit line.seg,body.calloutedit image,body.calloutedit polygon.member,body.calloutedit rect.pdfsheet{cursor:crosshair}
996
+ body.calloutedit g.cohot{cursor:pointer}
997
+ #calloutB:disabled{opacity:.4;cursor:default}
998
+ #calloutToggleB .conote{margin-left:auto;padding-left:10px;color:var(--mut);font-size:11px}
999
+ /* The add/edit form floats ON the drawing, so it is a dark-island member (see the list near the top) and sits one
1000
+ layer BELOW the combobox list (#comboPop, z 30) so the sheet list opens over it, never under it. */
1001
+ #calloutPop{position:fixed;z-index:29;display:none;width:min(288px,calc(100vw - 24px));box-sizing:border-box;background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;box-shadow:var(--shadow-md);padding:10px 12px;font:12px/1.4 var(--ui)}
1002
+ #calloutPop.open{display:block}
1003
+ #calloutPop .copTitle{margin:0 0 2px;font-size:13px;font-weight:600}
1004
+ #calloutPop .elab{display:block;margin:8px 0 3px}
1005
+ #calloutPop input[type=text]{height:26px;padding:0 8px;font:12px var(--ui);box-sizing:border-box}
1006
+ #calloutPop input[type=text]:focus{outline:none;border-color:var(--brand)}
1007
+ #calloutPop input[aria-invalid=true]{border-color:var(--err-border,var(--err))}
1008
+ #calloutPop .gerr{margin-top:3px}
1009
+ #calloutPop .hint{margin:8px 0 0;font-size:11px;line-height:1.45}
1010
+ #calloutPop .seg2{margin-top:0;height:26px}
1011
+ #calloutPop .seg2 button{font-size:11.5px;padding:0 4px}
1012
+ #calloutPop .seg2 button:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
1013
+ #calloutPop .copFoot{display:flex;align-items:center;gap:8px;margin-top:10px}
1014
+ #calloutPop .copFoot .copSpacer{flex:1}
1015
+ #calloutPop button.copPrimary,.cocard button.copPrimary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink)}
1016
+ #calloutPop button.copPrimary:hover,.cocard button.copPrimary:hover{background:var(--brand-hover);border-color:var(--brand-hover)}
1017
+ #calloutPop button.copDelete{background:transparent;border-color:transparent;color:var(--err);padding-left:0;text-decoration:underline}
1018
+ #calloutPop button:focus-visible,.cocard button:focus-visible{outline:2px solid var(--brand);outline-offset:2px}
1019
+ /* The "this callout leads nowhere" card, the chooser and the picture viewer: neutral surface, no alarm colour,
1020
+ because a sheet that is not in the model is a complete answer, not a failure of ours. */
1021
+ #coCardModal{position:fixed;inset:0;z-index:60;display:none;align-items:center;justify-content:center}
1022
+ #coCardModal .mpanel{width:min(480px,92vw)}
1023
+ #coCardModal .cocard-body{padding:14px 16px 4px;color:var(--text);font-size:13px;line-height:1.55}
1024
+ #coCardModal .cocard-body p{margin:0 0 8px}
1025
+ #coCardModal .cocard-note{color:var(--mut);font-size:12px}
1026
+ #coCardModal .cocard-status{padding:0 16px;min-height:0;color:var(--mut);font-size:12px;line-height:1.5}
1027
+ #coCardModal .cocard-actions{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid var(--line);margin-top:8px}
1028
+ #detailsGrid .coempty{grid-column:1/-1;padding:22px 8px;text-align:center;color:var(--mut);font-size:12px;line-height:1.6}
1029
+ #detailsGrid .coempty b{display:block;color:var(--text);font-size:13px;margin-bottom:4px}
1030
+ #detailsGrid .coempty p{margin:0 auto 10px;max-width:46ch}
1031
+ #detailsGrid .coempty button.copPrimary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink)}
1032
+ #detailsGrid .coempty button.copPrimary:hover{background:var(--brand-hover);border-color:var(--brand-hover)}
1033
+ #detailsGrid .dask{margin:6px -9px -6px;padding:7px 9px 9px;border-top:1px solid var(--err-border);background:var(--err-bg);font-size:12px;line-height:1.45;color:var(--text)}
1034
+ #detailsGrid .dask p{margin:0 0 7px}
1035
+ #detailsGrid .dask .dbtns{display:flex;flex-wrap:wrap;gap:6px}
1036
+ #detailsGrid .dask button{padding:3px 10px;font-size:12px}
1037
+ #detailsGrid .dask button.danger{background:transparent;border-color:var(--err-border)}
1038
+ #detailsGrid .dask button.danger:hover{background:var(--err-border)}
1039
+ #detailsGrid .dask button:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
1040
+ #viewFly{position:fixed;z-index:59;min-width:230px;max-width:min(340px,calc(100vw - 24px));background:var(--panel);border:1px solid var(--line);border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.55);padding:6px;display:none;color:var(--text)}
1041
+ #viewFly.open{display:block}
1042
+ #viewFly .fhdr{padding:4px 8px 6px;font-size:12px;font-weight:600;letter-spacing:.02em}
1043
+ #viewFly .frow{display:flex;align-items:baseline;gap:9px;width:100%;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--text);cursor:pointer;font:13px var(--ui);text-align:left}
1044
+ #viewFly .frow:hover,#viewFly .frow:focus-visible{background:rgba(148,163,184,.12);outline:none}
1045
+ #viewFly .frow:focus-visible{box-shadow:inset 0 0 0 2px var(--brand)}
1046
+ #viewFly .frow .nm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1047
+ #viewFly .frow .sub{color:var(--mut);font-size:11px;white-space:nowrap}
1048
+ #viewFly .ffoot{padding:6px 8px 2px;color:var(--mut);font-size:11px}
944
1049
  #detailsModal,#framesModal,#rfiModal,#confModal,#askAiModal,#connModal,#connImportModal,#favConnModal,#viewGenModal,#hostBakeModal{position:fixed;inset:0;z-index:20;display:none;align-items:center;justify-content:center}
945
1050
  #askAiDrop:hover{border-color:var(--brand);color:var(--text)} #askAiDrop.has{border-style:solid;border-color:var(--brand)}
946
1051
  /* Ask AI is a CAD-style modeless palette: the canvas stays selectable while it is open. */
@@ -1090,6 +1195,20 @@ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stro
1090
1195
  #moreMenu .mrow .mlbl{color:var(--mut);font-size:11px;flex:0 0 100%}
1091
1196
  #moreMenu .mrow input[type=range]{flex:1 1 60px;min-width:0}
1092
1197
  #moreMenu .mrow .mval{color:var(--mut);font-size:11px;flex:none;min-width:38px;text-align:right;font-variant-numeric:tabular-nums}
1198
+ /* "Columns ending below the floor" (the project setting): a typed length shaped like the Snapping step field, its reading and error
1199
+ lines under it in the menu's muted 11px, a Reset button only while the value is not the default. All themed; no native control. */
1200
+ #moreMenu #reachRow input{flex:1 1 92px;min-width:0;max-width:140px;height:24px;background:var(--bg);color:var(--text);border:1px solid var(--line);border-radius:5px;padding:0 7px;font:12px var(--ui);box-sizing:border-box}
1201
+ #moreMenu #reachRow input:focus{outline:none;border-color:var(--brand)} /* the ring the other fields in this menu use: the border takes the brand colour */
1202
+ #moreMenu #reachRow input[aria-invalid=true]{border-color:var(--warn)}
1203
+ #moreMenu #reachRow input:disabled{opacity:.45}
1204
+ #moreMenu #reachRow #reachDef[hidden]{display:none}
1205
+ #moreMenu #reachRow .reachline{flex-basis:100%;color:var(--mut);font-size:11px;line-height:1.4;overflow-wrap:anywhere}
1206
+ #moreMenu #reachRow .reachline:empty{display:none}
1207
+ #moreMenu #reachRow #reachStatus.bad{color:var(--warn)}
1208
+ #moreMenu #reachRow #reachReset{display:inline-block;width:auto;flex:none;padding:2px 8px;border:1px solid var(--line);border-radius:6px;background:transparent;color:var(--mut);font:11px var(--ui);cursor:pointer}
1209
+ #moreMenu #reachRow #reachReset[hidden]{display:none}
1210
+ #moreMenu #reachRow #reachReset:hover{background:rgba(148,163,184,.12);color:var(--text)}
1211
+ #moreMenu #reachRow #reachReset:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
1093
1212
  /* Pointer-behaviour bars, bottom-right of the canvas (both views): [ Select filter ] [ Snap ]. Both reuse the brand-fill "on" toolbar language. */
1094
1213
  /* One bottom dock owns both sides of the canvas chrome. The hint may shrink; Select/Snap never do, so
1095
1214
  the two surfaces cannot overlap at narrower widths. In 3D the whole dock stops before the world-axis
@@ -1502,6 +1621,44 @@ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stro
1502
1621
  .hbgroup h4{margin:0 0 6px;color:var(--mut);font-size:11px}.hbgroup ul{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:4px 12px;margin:0;padding:0;list-style:none}.hbgroup li{overflow-wrap:anywhere;font:11px/1.45 ui-monospace,SFMono-Regular,Consolas,monospace}
1503
1622
  #hostBakeActions{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid var(--line)}
1504
1623
  #hostBakeCancel{background:var(--brand);border-color:var(--brand);color:var(--brand-ink);font-weight:700}
1624
+ /* ── "See what changed" (#2209): the model-changed bar's extra button, and the list it opens. Every colour is an
1625
+ existing token, so the dark and light themes follow without a second set. The bar's scroll behaviour comes
1626
+ from the page's global `*` scrollbar rules; this adds no scroll theming of its own. ── */
1627
+ #aiUpdateBanner button{white-space:nowrap}
1628
+ #aiUpdateBanner button:focus-visible{outline:2px solid #e0f2fe;outline-offset:2px} /* the bar's own text colour: --brand on this blue is under 2.5:1 */
1629
+ #changeListModal{position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center}
1630
+ #changeListModal .mpanel{width:min(640px,94vw);outline:none}
1631
+ #changeListModal .mhead{display:block;padding:14px 16px 2px;border-bottom:0}
1632
+ #changeListModal .mhead h2{margin:0;font-size:14px;font-weight:600}
1633
+ #changeListSub{margin:0;padding:2px 16px 10px;color:var(--mut);font-size:12px;line-height:1.55;border-bottom:1px solid var(--line)}
1634
+ #changeListSummary{padding:10px 16px;border-bottom:1px solid var(--line);font-size:13px;line-height:1.5}
1635
+ #changeListSummary:empty{display:none}
1636
+ #changeListSummary b{font-weight:600}
1637
+ #changeListSummary .clweight{display:block;margin-top:2px;color:var(--mut);font-size:12px}
1638
+ #changeListBody{flex:1;min-height:140px;overflow:auto;padding:4px 12px 12px 16px;overscroll-behavior:contain}
1639
+ #changeListBody:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
1640
+ #changeListBody .clnote{margin:8px 0 0;padding:7px 10px;border:1px solid var(--line);border-radius:7px;color:var(--mut);font-size:11.5px;line-height:1.55}
1641
+ #changeListBody .clnote.warn{border-color:var(--warn-edge);color:var(--warn)}
1642
+ #changeListBody .clmsg{margin:12px 0 0;color:var(--text);font-size:13px;line-height:1.6}
1643
+ #changeListBody .clmsg.quiet{color:var(--mut);font-size:12px}
1644
+ #changeListBody section+section{margin-top:10px}
1645
+ #changeListBody h3{position:sticky;top:0;z-index:1;display:flex;align-items:center;gap:8px;margin:0;padding:8px 0 4px;background:var(--panel);font-size:12px;font-weight:600}
1646
+ #changeListBody .clchip{display:inline-flex;align-items:center;gap:4px;padding:1px 7px;border-radius:5px;border:1px solid transparent;font-size:11px;line-height:1.6}
1647
+ #changeListBody .clchip.add{color:var(--ok);background:var(--ok-bg);border-color:var(--ok-edge)}
1648
+ #changeListBody .clchip.rem{color:var(--err);background:var(--err-bg);border-color:var(--err-edge)}
1649
+ #changeListBody .clchip.chg{color:var(--warn);background:var(--warn-bg);border-color:var(--warn-edge)}
1650
+ #changeListBody .clcount{color:var(--mut);font-weight:400;font-variant-numeric:tabular-nums}
1651
+ #changeListBody ul{list-style:none;margin:0;padding:0}
1652
+ #changeListBody li{display:grid;grid-template-columns:minmax(0,13em) 1fr;gap:2px 12px;padding:5px 8px;font-size:12px;line-height:1.5}
1653
+ #changeListBody .clkind{color:var(--mut)}
1654
+ #changeListBody .clname{color:var(--text);font-weight:600;overflow-wrap:anywhere}
1655
+ #changeListBody .cldetail{font-variant-numeric:tabular-nums;overflow-wrap:anywhere}
1656
+ #changeListBody .cldetail .num{white-space:nowrap}
1657
+ #changeListBody .clpill{display:inline-block;margin-left:8px;padding:0 6px;border:1px dashed var(--line);border-radius:4px;color:var(--mut);font-size:10.5px;line-height:1.6;white-space:nowrap}
1658
+ #changeListBody li.clcap{display:block;color:var(--mut);font-size:11px;padding-top:2px}
1659
+ #changeListActions{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid var(--line)}
1660
+ #changeListActions .primary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink);font-weight:600}
1661
+ @media (max-width:520px){#changeListBody li{grid-template-columns:1fr}}
1505
1662
  .mhead{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--line)}
1506
1663
  .mhead b{font-size:14px} .mhead button{padding:2px 9px}
1507
1664
  .conf-tgt{display:flex;align-items:center;gap:6px;margin-left:auto;margin-right:12px;font-size:12px;color:var(--mut)}
@@ -1532,6 +1689,72 @@ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stro
1532
1689
  .ftab th{text-align:left;color:var(--mut);font-size:11px;text-transform:uppercase;letter-spacing:.04em;padding:7px 10px;border-bottom:1px solid var(--line)}
1533
1690
  .ftab td{padding:7px 10px;border-bottom:1px solid var(--line);font-variant-numeric:tabular-nums}
1534
1691
  .ftab tbody tr:hover{background:var(--sunken)} .ftab .gcell{font-weight:600;color:var(--brand)}
1692
+ /* ── Moment frame schedule (#2210) ───────────────────────────────────────────────────────────────────────
1693
+ Existing tokens only. The table is a scroll container, so it wears the same thin themed scrollbar as every other
1694
+ list here; the grid column and the delete column stick while a schedule with many levels scrolls sideways, and
1695
+ sticky cells carry an OPAQUE panel background (and the row-hover colour) or the cells scrolling under them show through. */
1696
+ #framesModal{z-index:60} /* the 3D toolbar is z:59: the dialog must fully cover it in 3D and Split, like #viewGenModal; the level pickers' list rises with it (below) and toasts (z:60, appended later) and tooltips (z:80) still win */
1697
+ #comboPop.over-modal{z-index:61}
1698
+ #framesModal .mpanel{width:min(1040px,94vw)}
1699
+ #framesGrid{padding:14px;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}
1700
+ #framesGrid .fr-hint{margin:0 0 8px;font-size:12px;color:var(--mut)}
1701
+ #framesGrid .fr-scroll{max-height:min(52vh,460px);overflow:auto;border:1px solid var(--line);border-radius:8px;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}
1702
+ .frtab{width:100%;border-collapse:separate;border-spacing:0;table-layout:auto;font-size:13px}
1703
+ .frtab th,.frtab td{white-space:nowrap;border-bottom:1px solid var(--line);font-variant-numeric:tabular-nums}
1704
+ .frtab thead th{position:sticky;top:0;z-index:3;background:var(--panel);text-align:left;font-size:11px;font-weight:600;color:var(--mut);padding:6px 6px;vertical-align:bottom}
1705
+ .frtab td{padding:4px 6px}
1706
+ .frtab tbody tr:last-child td{border-bottom:0}
1707
+ .frtab .fr-stl{position:sticky;left:0;z-index:2;background:var(--panel);box-shadow:1px 0 0 var(--line)}
1708
+ .frtab thead .fr-stl{z-index:4}
1709
+ .frtab .fr-str{position:sticky;right:0;z-index:2;background:var(--panel);box-shadow:-1px 0 0 var(--line);text-align:center}
1710
+ .frtab thead .fr-str{z-index:4}
1711
+ .frtab tbody tr:hover td{background:var(--sunken)}
1712
+ .frtab tbody tr.editing td{background:var(--brand-wash)}
1713
+ .frtab tbody tr.editing td:first-child{box-shadow:inset 3px 0 0 var(--brand),1px 0 0 var(--line)}
1714
+ .frtab tbody tr.editing td.fr-stl,.frtab tbody tr.editing td.fr-str{background:linear-gradient(var(--brand-wash),var(--brand-wash)),var(--panel)} /* the wash is translucent: laid over the panel colour so a sticky cell still hides what scrolls under it */
1715
+ .frtab .ftab-inp{height:28px;padding:4px 6px;font-size:13px}
1716
+ .frtab .ftab-inp:focus{box-shadow:inset 0 0 0 1px var(--brand)}
1717
+ .frtab .ftab-inp.fr-warn{border-style:dashed;border-color:var(--warn)}
1718
+ .frtab .fr-g{width:64px;min-width:64px;font-weight:600}
1719
+ .frtab .fr-e{width:64px;min-width:64px}
1720
+ .frtab .fr-lvcell{min-width:150px}
1721
+ .frtab .fr-colcell{min-width:160px}
1722
+ .frtab .fr-lv{min-width:150px;vertical-align:top}
1723
+ .frtab .fr-lvhead{display:flex;align-items:center;gap:4px}
1724
+ .frtab .fr-lvname{font-size:12px;font-weight:600;text-transform:none;letter-spacing:0;color:var(--text)}
1725
+ .frtab .fr-lvsheets{margin-top:2px;font-size:10.5px;font-weight:400;color:var(--mut);white-space:normal;max-width:190px;text-transform:none;letter-spacing:0}
1726
+ .frtab .fr-lvsheets.none{color:var(--warn-soft)}
1727
+ .frtab .fr-lvdel,.frtab .fr-del{padding:2px 6px;font-size:11px;line-height:1.4}
1728
+ .frtab .fr-del{color:var(--mut)} .frtab .fr-del:hover{color:var(--err)}
1729
+ .frtab .fr-merge{text-transform:none;letter-spacing:0;margin-top:4px;display:flex;flex-wrap:wrap;gap:4px;white-space:normal;font-size:11px;font-weight:400;color:var(--warn-soft)}
1730
+ .frtab .fr-mwarn{flex-basis:100%;font-weight:500}
1731
+ .frtab tr.fr-note td{padding:2px 6px 8px;border-bottom:0;font-size:11px;color:var(--mut);white-space:normal}
1732
+ .frtab tr.fr-note.warn td{color:var(--warn-soft)}
1733
+ .frtab tr.fr-note .ghost{margin-left:6px}
1734
+ #framesGrid .fr-sheets{margin-top:16px}
1735
+ #framesGrid .fr-sheets h4{margin:0 0 6px;font-size:12px;font-weight:600;color:var(--text)}
1736
+ #framesGrid .fr-sheet{display:grid;grid-template-columns:minmax(0,1fr) minmax(160px,240px);gap:8px;align-items:center;padding:3px 0}
1737
+ #framesGrid .fr-sheet.editing{background:var(--brand-wash);box-shadow:inset 3px 0 0 var(--brand);padding-left:8px;border-radius:4px}
1738
+ #framesGrid .fr-sheetname{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}
1739
+ #framesGrid .fr-sheet .ftab-inp{height:28px;cursor:pointer}
1740
+ #framesGrid .fr-sheet .ftab-inp.fr-warn{border-style:dashed;border-color:var(--warn)}
1741
+ #framesGrid .fr-sheetmsg{grid-column:2;font-size:11px;color:var(--warn-soft)}
1742
+ #framesGrid .fr-empty{text-align:center;padding:36px 16px}
1743
+ #framesGrid .fr-empty b{display:block;font-size:14px;margin-bottom:6px}
1744
+ #framesGrid .fr-empty p{margin:0 auto 14px;max-width:46ch;font-size:12px;line-height:1.5;color:var(--mut)}
1745
+ #framesGrid .fr-empty .fr-acts{display:flex;gap:8px;justify-content:center;flex-wrap:wrap}
1746
+ .fr-primary{background:var(--brand);border-color:var(--brand);color:var(--brand-ink);font-weight:500}
1747
+ .fr-primary:hover{background:var(--brand);border-color:var(--brand);filter:brightness(1.1)}
1748
+ #panel .mfhint{font-size:11px;line-height:1.4;color:var(--mut);margin:0 0 6px}
1749
+ #panel .mfopen{margin-top:6px}
1750
+ /* #2210 — the question about a new moment-frame girder's automatic shear plates. Quiet on purpose: nothing is wrong, a person is being asked. The info wash (not the warning amber), the purple girder box below keeps the section's identity. */
1751
+ .mfoffer{margin:6px 0;border:1px solid var(--line);border-radius:6px;padding:7px 8px;background:var(--brand-wash-faint)}
1752
+ .mfoffer .dmsg{color:var(--text);font-size:12px}
1753
+ .mfoffer .mfhint{margin:4px 0 0}
1754
+ .mfoffer .mfoffer-acts{display:flex;gap:6px;margin-top:6px}
1755
+ .mfoffer .mfrm{border-color:var(--brand);color:var(--brand)}
1756
+ /* the same question as a bar, for an action taken where the Properties panel does not show those beams */
1757
+ #mfOfferBar{position:fixed;left:50%;bottom:58px;transform:translateX(-50%);z-index:60;max-width:min(520px,92vw);margin:0;padding:8px 14px;border-radius:8px;background:var(--panel);box-shadow:var(--shadow-md)}
1535
1758
  #comboPop{position:fixed;z-index:30;background:var(--panel);border:1px solid var(--ctrl-border);border-radius:6px;max-height:240px;overflow:auto;box-shadow:var(--shadow-lg);display:none}
1536
1759
  #comboPop .opt{padding:6px 10px;cursor:pointer;font-size:13px;color:var(--text);white-space:nowrap}
1537
1760
  #comboPop .opt:hover,#comboPop .opt.active{background:var(--btn)}
@@ -1619,7 +1842,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1619
1842
  .dprevwrap{height:120px} .dprevwrap[data-det]{cursor:zoom-in} .dcard:hover .dprevwrap[data-det]{filter:brightness(1.04)}
1620
1843
  .dname{width:100%;background:var(--field);border:1px solid var(--ctrl-border);border-radius:4px;padding:3px 6px;font-weight:600;font-size:12px;color:var(--text)}
1621
1844
  .dname:focus{outline:none;border-color:var(--brand)} .dmeta .ds .ddel{color:var(--err);text-decoration:underline}
1622
- #lightbox{position:fixed;inset:0;z-index:40;display:none;align-items:center;justify-content:center}
1845
+ #lightbox{position:fixed;inset:0;z-index:60;display:none;align-items:center;justify-content:center}
1623
1846
  .lbpanel{position:relative;background:var(--panel);border:1px solid var(--line);border-radius:10px;display:flex;flex-direction:column;box-shadow:var(--shadow-xl)}
1624
1847
  #lbView{position:relative;overflow:hidden;background:#fff;width:88vw;height:82vh;cursor:grab;touch-action:none}
1625
1848
  #lbView.drag{cursor:grabbing}
@@ -1818,7 +2041,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1818
2041
  .plan-caret{color:var(--mut);flex:none;transition:transform .15s}
1819
2042
  .plan-trigger.open .plan-caret{transform:rotate(180deg)}
1820
2043
  /* Panel matched to #moreMenu/.cmmenu — the other dropdowns hanging off this same header row. */
1821
- .plan-popover{position:absolute;top:calc(100% + 6px);left:0;min-width:100%;width:max-content;max-width:400px;background:var(--panel);border:1px solid var(--ctrl-border);border-radius:8px;box-shadow:var(--shadow-lg);padding:4px 0;z-index:30}
2044
+ .plan-popover{position:absolute;top:calc(100% + 6px);left:0;min-width:100%;width:max-content;max-width:400px;background:var(--panel);border:1px solid var(--ctrl-border);border-radius:8px;box-shadow:var(--shadow-lg);padding:4px 0;z-index:61} /* above the stage notices (#regBanner, #cutBanner: z:58) that sit under the header, like #moreMenu — a z:30 list was covered by the no-floor-level banner and its lower rows could not be clicked */
1822
2045
  /* This page has no global [hidden] rule, so an author `display` on a hidden element wins by ORIGIN over
1823
2046
  the UA's own [hidden] and `planPopover.hidden = true` would quietly do nothing. .plan-popover declares
1824
2047
  no `display` TODAY, so this is redundant right now — it stays as insurance, because the moment anyone
@@ -1925,9 +2148,9 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1925
2148
  matches that anchor too and carries no z-index. */
1926
2149
  #viewBar2d{position:absolute;top:12px;left:12px;display:flex;flex-direction:row;flex-wrap:wrap;gap:2px;align-items:center;z-index:59;
1927
2150
  padding:4px;background:var(--panel);border:1px solid var(--line);border-radius:9px;box-shadow:0 6px 20px rgba(0,0,0,.5)}
1928
- #m3dToolBar{left:calc(var(--v2d-view-w, 72px) + 22px)} /* 2D-only: beside #viewBar2d (the v3d / split rules above win by specificity); 72 is nominal — sync2d() overwrites it before first paint */
2151
+ #m3dToolBar{left:calc(var(--v2d-view-w, 117px) + 22px)} /* 2D-only: beside #viewBar2d (the v3d / split rules above win by specificity); 117 is nominal — sync2d() overwrites it before first paint */
1929
2152
  /* Flat inside the card - the band carries the one shadow now. */
1930
- #m3dToolBar .m3dwrap>button,#m3dToolBar>button,#m3dToolBar .cmwrap>button,#m3dDim,#viewBar2d>button{width:30px;height:30px;padding:0;display:flex;align-items:center;justify-content:center;
2153
+ #m3dToolBar .m3dwrap>button,#m3dToolBar>button,#m3dToolBar .cmwrap>button,#m3dDim,#viewBar2d .m3dwrap>button,#viewBar2d>button{width:30px;height:30px;padding:0;display:flex;align-items:center;justify-content:center;
1931
2154
  background:transparent;border:1px solid transparent;border-radius:6px;box-shadow:none;color:var(--mut)}
1932
2155
  #m3dToolBar button:hover,#viewBar2d button:hover{background:var(--btn-hover);color:var(--text)}
1933
2156
  /* ONE ACTIVE LOOK for every kind of 'this is on': a mode that is armed (.on), a menu that is open,
@@ -1937,6 +2160,22 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1937
2160
  #m3dToolBar .m3dwrap:has(> .m3dmenu.open) > button,
1938
2161
  #m3dToolBar .cmwrap:has(> .cmmenu.open) > button{background:#16243d;color:var(--brand);border-color:var(--brand)}
1939
2162
  #m3dToolBar svg,#viewBar2d svg{width:16px;height:16px;display:block;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
2163
+ /* The 2D band's Labels button (#2216) — a menu trigger like the 3D band's, so it gets the same three things that
2164
+ band's CSS (model-editor.css, under #m3dBar) gives its own: the OPEN look, the cyan "something is on" corner dot,
2165
+ and the rule before it. The values are copied from there, not invented: the open look is the model band's, the
2166
+ dot is the 3D one's (6px, cyan, ringed in the panel colour) and the rule is the same 22px hairline. */
2167
+ #viewBar2d .m3dwrap{position:static;display:block;width:30px;flex:none} /* static: the menu below anchors to the BAR, so it opens from the band's left edge and stays inside the plan pane */
2168
+ #viewBar2d .m3dwrap>button[aria-expanded=true],#viewBar2d .m3dwrap:has(> .m3dmenu.open) > button{background:#16243d;color:var(--brand);border-color:var(--brand)} /* the TRIGGER only: a menu row that announces aria-expanded (the Property labels disclosure) must not take the armed look */
2169
+ #viewBar2d button[data-state-on]{position:relative}
2170
+ #viewBar2d button[data-state-on]::after{content:"";position:absolute;right:2px;bottom:2px;width:6px;height:6px;border-radius:50%;background:var(--cyan,#22d3ee);box-shadow:0 0 0 2px var(--panel);pointer-events:none}
2171
+ #viewBar2dLabels{display:contents} /* the slot only carries the rule and the button into the band's own flex row */
2172
+ #viewBar2d .m3dmenu{left:0;top:calc(100% + 2px);max-height:calc(100vh - 140px);overflow:auto} /* drops just under the band; a short pane scrolls it (the global scrollbar rule themes that) */
2173
+ #viewBar2d .m3dmenu button:not(:disabled):hover{background:var(--btn);color:var(--text)} /* the band's icon-button hover must not recolour the menu rows (it outranks .m3dmenu button:hover) */
2174
+ #viewBar2d .m3dmenu button:disabled:hover{background:transparent;color:var(--text)} /* …and a disabled row (For selected with nothing selected) must not light up under the pointer at all: the band's own button:hover would, so it is reset to the .m3dmenu button:disabled look */
2175
+ /* One band open at a time sits above the other: both are z-index 59, so the later one in the DOM would cover an
2176
+ open menu of the earlier. The band with no open menu steps down one (58), as the 3D / model bands already do. */
2177
+ body:has(#viewBar2d .m3dmenu.open) :is(#m3dToolBar,#m3dBar):not(:has(.m3dmenu.open,.cmmenu.open)){z-index:58}
2178
+ body:has(#m3dToolBar .m3dmenu.open,#m3dToolBar .cmmenu.open,#m3dBar .m3dmenu.open) #viewBar2d:not(:has(.m3dmenu.open)){z-index:58}
1940
2179
  /* STATE IS THE ICON on the two buttons that have modes. CSS cannot compare one attribute to
1941
2180
  another, so each pairing is spelled out; the button carries data-proj / data-mode and only the
1942
2181
  matching glyph is drawn. Enumerated rather than swapped in JS because innerHTML would fight
@@ -2056,7 +2295,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2056
2295
  /* A DIVIDER HAS TO DIVIDE. --line on --panel is a 1e293b hairline on 131a25 — technically present,
2057
2296
  invisible at arm's length, so the rail read as ten undifferentiated buttons. Wider, brighter,
2058
2297
  and with room either side so it reads as a break rather than a squeezed-in line. */
2059
- #m3dToolBar .tb-sep{width:1px;height:22px;background:color-mix(in srgb, var(--text-dim) 60%, transparent);flex:0 0 auto;align-self:center;margin:0 5px}
2298
+ #m3dToolBar .tb-sep,#viewBar2d .tb-sep{width:1px;height:22px;background:color-mix(in srgb, var(--text-dim) 60%, transparent);flex:0 0 auto;align-self:center;margin:0 5px}
2060
2299
  /* Themed tooltip — replaces native title= so no OS-default tooltip leaks the dark theme. */
2061
2300
  #tooltip{position:fixed;z-index:80;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:11.5px;line-height:1.35;color:var(--text);pointer-events:none;max-width:260px;box-shadow:var(--shadow-tip);opacity:0;transition:opacity .12s}
2062
2301
  #tooltip.show{opacity:1}
@@ -2586,8 +2825,8 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2586
2825
  .pl-context,.pl-note{color:var(--mut);font-size:11px;line-height:1.4;padding:2px 12px 6px;max-width:260px;white-space:normal}
2587
2826
  #moreMenu .pl-context{padding-left:61px}
2588
2827
  #moreMenu .pl-note{padding-left:61px;padding-right:6px} /* the helper note starts at the switch labels too, like the context line above (#1393); the 210px menu leaves ~100px, so trim the right side to keep short notes on one line */
2589
- #m3dViewMenu .pl-context{padding-left:47px} /* under the "Property labels" text, as in ⋯ ▸ Display (measured: switch + gap = 47px here) */
2590
- #m3dViewMenu .pl-note{padding-left:47px;padding-right:6px} /* the note shares the context line's indent — 12px row padding + 26px switch + 9px gap — or it sits 35px left of its siblings (#1393). While #1423 collapses the 3D switches to 2px, the labels render ~24px further left than this — the fix belongs there, not in this indent. */
2828
+ #m3dViewMenu .pl-context,#pl2dMenu .pl-context{padding-left:47px} /* under the "Property labels" text, as in ⋯ ▸ Display (measured: switch + gap = 47px here) */
2829
+ #m3dViewMenu .pl-note,#pl2dMenu .pl-note{padding-left:47px;padding-right:6px} /* the note shares the context line's indent — 12px row padding + 26px switch + 9px gap — or it sits 35px left of its siblings (#1393). While #1423 collapses the 3D switches to 2px, the labels render ~24px further left than this — the fix belongs there, not in this indent. */
2591
2830
  .pl-context{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} /* one line naming the set these rows edit; a long saved-view name ellipsises (full text in data-tip) */
2592
2831
  .pl-section button:focus-visible,#m3dRef:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
2593
2832
 
@@ -2741,8 +2980,20 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2741
2980
  state until the project's own preference arrives — this page's idiom for an unknown value is a
2742
2981
  placeholder, never a plausible guess (see #endsCount). -->
2743
2982
  <div class=mrow id=unitsRow><span class=mlbl>Units</span><div id=unitsToggle role=group aria-label="Display units"><button data-command-id="steel.display-units#ft-in" id=unitsFt class=seg role=menuitemradio aria-checked=false disabled data-blocked-reason="Still reading this project&#39;s saved display units" data-tip="Loading this project&#39;s display units…">ft-in</button><button data-command-id="steel.display-units#mm" id=unitsMm class=seg role=menuitemradio aria-checked=false disabled data-blocked-reason="Still reading this project&#39;s saved display units" data-tip="Loading this project&#39;s display units…">mm</button></div></div>
2983
+ <!-- A PROJECT setting (saved with the model, one value for every sheet), so it sits with Units: both are things the rest of
2984
+ the menu reads against. A typed length in the project's units, committed on Enter or blur as one undoable step.
2985
+ Disabled with a placeholder until the model is loaded: this page's idiom for an unknown value is never a plausible guess. -->
2986
+ <div class=mrow id=reachRow role=group aria-labelledby=reachLbl>
2987
+ <label class=mlbl id=reachLbl for=reachInput data-tip="How far under a sheet’s floor level a column can end and still be drawn on that sheet, dashed. The same for every sheet. Type 6&quot; or 2'-0&quot; (150 mm also works). Enter applies it.">Columns ending below the floor</label>
2988
+ <input data-command-id="steel.column-below-reach" id=reachInput type=text inputmode=text autocomplete=off spellcheck=false disabled placeholder="Loading…" aria-label="Columns ending below the floor" aria-describedby="reachHelp reachEcho">
2989
+ <span id=reachDef class=mval>default</span>
2990
+ <button data-command-id="steel.column-below-reach-reset" id=reachReset type=button hidden>Reset</button>
2991
+ <div class=reachline id=reachHelp>A column that ends this far under a sheet’s floor level is still drawn on that sheet, dashed.</div>
2992
+ <div class=reachline id=reachEcho></div>
2993
+ <div class=reachline id=reachStatus role=status aria-live=polite></div>
2994
+ </div>
2744
2995
  <button data-command-id="steel.show-dimensions" id=dimToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide all placed dimensions on the plan"><span class=mck aria-hidden=true></span>Dimensions</button>
2745
- <button data-command-id="steel.show-callouts" id=calloutToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the clickable callout bubbles (section / elevation / detail references) on the plan"><span class=mck aria-hidden=true></span>Callouts</button>
2996
+ <button data-command-id="steel.show-callouts" id=calloutToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the clickable callout bubbles (section / elevation / detail references) on the plan. Click a bubble to go to the sheet it points to."><span class=mck aria-hidden=true></span>Callouts<span class=conote id=calloutNote></span></button>
2746
2997
  <button data-command-id="steel.show-grid" id=gridToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show or hide the grid lines in 2D and 3D"><span class=mck aria-hidden=true></span>Grid lines</button>
2747
2998
  <!-- step=1, NOT 2: clampGridLabelPx rounds to an integer and the key is user-writable, so a coarser
2748
2999
  step would let a stored odd value draw at 15 and read "15 px" while the browser snapped the thumb
@@ -2772,7 +3023,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2772
3023
  <div id=m3dInsertMenu class=m3dmenu role=menu data-reveal-by=#m3dInsert></div>
2773
3024
  <input data-command-id="steel.insert-detail" id=insFile type=file accept="image/*" style="display:none">
2774
3025
  </div>
2775
- <button data-command-id="steel.build-from-details" id=dApplyBtn data-tip="Build the connection each detail callout describes, everywhere that callout appears. Ends someone confirmed, tuned by hand, or imported are left alone and listed.">Build from details</button>
3026
+ <button data-command-id="steel.build-from-details" id=dApplyBtn data-tip="Build the connection each detail callout describes, everywhere that callout appears. Connections someone confirmed, tuned by hand, linked to a detail earlier or imported are left alone and listed, and so is anything nothing can be built on (a brace, say). Connections it built itself are updated when the detail changes.">Build from details</button>
2776
3027
  <button data-command-id="steel.base-plates" id=bpBtn data-tip="Auto-detail base plates on every column (a plate + anchor kit + weld, shown in 3D). Tune sizes per the schedule via the AI or per-column params.">Base plates</button>
2777
3028
  <button data-command-id="steel.shear-plates" id=spBtn data-tip="Auto-detail bolted shear (fin) plates on eligible beam ends (a fin plate + bolt group + weld, shown in 3D). Tune sizes per the schedule via the AI or per-end params.">Shear plates</button>
2778
3029
  <button data-command-id="steel.frames" id=framesBtn>Frames…</button>
@@ -2833,6 +3084,31 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2833
3084
  <button data-command-id="steel.provisional-source" id=provisionalSourceBtn type=button hidden>Open source</button>
2834
3085
  </div>
2835
3086
  </div>
3087
+ <!-- #2214: this PLAN has no floor level, so no column is placed on it by height and the sheet draws only the
3088
+ columns the read bound. Says so in plain words and offers the two ways out: state the level, or place the
3089
+ columns by hand. Neutral tier (a level nobody has stated is unfinished work, not a fault), the same chrome
3090
+ and layer as #regBanner, which wins when both would show. "Not now" folds it into #cutPill for this page
3091
+ session; the condition stays visible, nothing is hidden for good. -->
3092
+ <div id=cutBanner role=status aria-live=polite aria-atomic=true>
3093
+ <div class=rgline id=cutLead></div>
3094
+ <div class=rgact id=cutActions>
3095
+ <span class=rgcta id=cutCta></span>
3096
+ <button data-command-id="steel.cut-level-enter" id=cutEnterBtn class=cutprimary type=button aria-expanded=false aria-controls=cutForm>Enter a level…</button>
3097
+ <button data-command-id="steel.show-all-columns" id=cutShowBtn type=button>Show all columns here</button>
3098
+ <button data-command-id="steel.cut-banner-hide" id=cutHideBtn type=button data-tip="Fold this into a small label. It comes back when you open it.">Not now</button>
3099
+ </div>
3100
+ <form id=cutForm hidden novalidate>
3101
+ <label class=cutlab for=cutInput id=cutFormLabel>Floor level</label>
3102
+ <div class=cutrow>
3103
+ <input data-command-id="steel.cut-level-field" id=cutInput type=text inputmode=decimal autocomplete=off spellcheck=false aria-describedby="cutEcho cutStatus">
3104
+ <button data-command-id="steel.cut-level-set" id=cutSetBtn class=cutprimary type=submit>Set level</button>
3105
+ <button data-command-id="steel.cut-level-cancel" id=cutCancelBtn type=button>Cancel</button>
3106
+ </div>
3107
+ <div class=cutecho id=cutEcho></div>
3108
+ <div class=cutstat id=cutStatus role=status aria-live=polite></div>
3109
+ </form>
3110
+ </div>
3111
+ <button data-command-id="steel.cut-banner-show" id=cutPill type=button data-tip="This sheet has no floor level. Open the notice.">No floor level</button>
2836
3112
  <!-- The 2D VIEW band (#1428): the same two view controls the 3D band leads with, in the same corner, with
2837
3113
  the same glyphs and the same words, so the plan and the model read as one editor. It replaced the
2838
3114
  bottom-left zoom bar (−/slider/+/percent/Fit) — the tester asked for parity with 3D, which has no
@@ -2842,6 +3118,11 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2842
3118
  <div id=viewBar2d role=toolbar aria-label="2D view controls">
2843
3119
  <button data-command-id="steel.zoom-fit" id=fit2d type=button data-tip="Fit all to view (Home)"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M2 6V2h4M14 6V2h-4M2 10v4h4M14 10v4h-4"/></svg><span class=rlbl>Fit all to view</span></button>
2844
3120
  <button data-command-id="steel.zoom-selection" id=fitSel2d type=button data-tip="Zoom to selected — frame just the selected members (Alt+Z)"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M2 5.5V2h3.5M14 5.5V2h-3.5M2 10.5V14h3.5M14 10.5V14h-3.5"/><path d="M5.9 6.3h4.2v3.4H5.9z"/></svg><span class=rlbl>Zoom to selected</span></button>
3121
+ <!-- The Labels button (#2216): the 3D band's tag glyph and its Property labels rows, minus the 3D-only Ref line,
3122
+ always editing the 2D plan. Drawn at boot into this slot from the same section spec the 3D menu uses
3123
+ (steelLabels2dPlan in web/model-editor-steel-adapter.js), so the two cannot drift. The slot is
3124
+ display:contents: the rule and the button it draws are flex children of the band itself. -->
3125
+ <span id=viewBar2dLabels></span>
2845
3126
  </div>
2846
3127
  </div>
2847
3128
  <div id=splitBar role=separator aria-orientation=vertical aria-label="Resize the plan and model panes" tabindex=0 aria-valuemin=15 aria-valuemax=85 aria-valuenow=50 data-tip="Drag to resize · double-click to reset"></div>
@@ -2886,6 +3167,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2886
3167
  <div class=seg-group id=m3dDimAxis role=group aria-label="Dimension measure axis (X/Y/Z combine)" style="display:none"><button data-command-id="steel.dimension-axis#free measurement" data-d3axis=free class=on aria-pressed=true data-tip="Free 3D measurement — clears the axis lock (F)">Free</button><button data-command-id="steel.dimension-axis#the X axis" data-d3axis=x data-tip="Lock measurement to X (X)">X</button><button data-command-id="steel.dimension-axis#the Y axis" data-d3axis=y data-tip="Lock measurement to Y (Y)">Y</button><button data-command-id="steel.dimension-axis#the Z axis" data-d3axis=z data-tip="Lock to Z / vertical (Z); Alt = quick vertical">Z</button></div>
2887
3168
  <button data-command-id="steel.dimension-show" id=m3dDimShow data-tip="Show or hide placed 3D dimensions" style="display:none">Hide dims</button>
2888
3169
  </span>
3170
+ <button data-command-id="steel.callout-edit" id=calloutB aria-pressed=false data-tip="Add a callout. Click the plan where a detail, section or elevation mark is drawn, then say which sheet it points to. Click an existing mark to edit it."><svg viewBox="0 0 16 16" aria-hidden=true><circle cx="7" cy="7" r="4"/><path d="M12.6 10.2v4.4M10.4 12.4h4.4"/></svg><span class=rlbl>Add a callout</span></button>
2889
3171
  <div class=cmwrap>
2890
3172
  <button data-command-id="steel.transform-menu" id=xfB aria-haspopup=menu aria-expanded=false data-tip="Move, Copy, array and to-level, plus how left-dragging a member behaves. Move (M) / Copy (C) also arm from the keyboard."><svg viewBox="0 0 16 16" aria-hidden=true><path d="M8 2.4v11.2M2.4 8h11.2"/><path d="M6.6 3.8 8 2.4l1.4 1.4M6.6 12.2 8 13.6l1.4-1.4M3.8 6.6 2.4 8l1.4 1.4M12.2 6.6 13.6 8l-1.4 1.4"/></svg><span class=rlbl>Move / Copy</span></button>
2891
3173
  <div class=cmmenu id=xfMenu role=menu data-reveal-by=#xfB>
@@ -2933,6 +3215,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2933
3215
  </div>
2934
3216
  <div id=panelResizer class=model-inspector-resizer role=separator aria-orientation=vertical aria-label="Resize properties panel" tabindex=0 data-tip="Drag to resize · double-click to reset"></div>
2935
3217
  <span id=connectionTruthStatus class=sr-only role=status aria-live=polite aria-atomic=true></span>
3218
+ <span id=mfOfferStatus class=sr-only role=status aria-live=polite aria-atomic=true></span>
2936
3219
  <aside id=panel class=model-inspector-panel></aside>
2937
3220
  <div id=panelStub class=model-inspector-stub aria-hidden=true><span class=vertical-label>Properties</span></div>
2938
3221
  <button data-command-id="steel.inspector-collapse" type=button id=panelToggle class=model-inspector-toggle aria-label="Collapse Properties" aria-controls=panel aria-expanded=true data-tip="Collapse Properties"><svg viewBox="0 0 16 16" aria-hidden=true><path d="m6 3 5 5-5 5"/></svg></button>
@@ -2977,9 +3260,12 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2977
3260
  <div style="overflow:auto;flex:1;padding:14px;scrollbar-width:thin">
2978
3261
  <table class=ftab><thead><tr><th style="width:24%">Type</th><th style="width:24%">Detail #</th><th id=connCompHead style="width:24%">Tekla id</th><th style="width:18%">Source</th><th style="width:10%"></th></tr></thead><tbody id=connBody></tbody></table>
2979
3262
  </div></div></div>
2980
- <div id=framesModal><div class=mbackdrop id=framesBackdrop></div>
2981
- <div class=mpanel><div class=mhead><b>Moment frame schedule</b><button data-command-id="steel.dialog-close#Frames" id=framesClose>✕</button></div>
2982
- <div id=framesGrid style="padding:14px;overflow:auto"></div></div></div>
3263
+ <!-- #2210 — the moment-frame schedule: add, edit and delete frames, name the levels, and say which sheet is which level.
3264
+ `role=dialog` + the Tab trap copy #rfiModal. The header buttons are HIDDEN (not disabled) while the schedule is empty:
3265
+ the empty state carries its own two actions. -->
3266
+ <div id=framesModal role=dialog aria-modal=true aria-labelledby=framesTitle><div class=mbackdrop id=framesBackdrop></div>
3267
+ <div class=mpanel><div class=mhead><b id=framesTitle>Moment frame schedule</b><div style="display:flex;gap:8px;align-items:center"><button data-command-id="steel.frames-new" id=framesNew hidden>+ New frame</button><button data-command-id="steel.frames-level-new" id=framesLevelNew hidden>+ New level</button><button data-command-id="steel.dialog-close#Frames" id=framesClose aria-label="Close the moment frame schedule">✕</button></div></div>
3268
+ <div id=framesGrid></div></div></div>
2983
3269
  <!-- #1090 — the ONE RFI list. Every filed record on the project, plus every member whose size the
2984
3270
  catalogue cannot price and which nobody has filed yet. It replaces BOTH this dialog's old
2985
3271
  unresolved-members fold and the separate open-questions panel.
@@ -3203,6 +3489,15 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
3203
3489
  <div id=hostBakeActions><button data-command-id="steel.dialog-cancel#the send review" id=hostBakeCancel>Cancel</button><button data-command-id="steel.host-bake-continue#the chosen CAD app" id=hostBakeContinue>Continue</button></div>
3204
3490
  </div>
3205
3491
  </div>
3492
+ <!-- #2211 — what a callout says when it leads nowhere: a sheet that is not in the model, or a sheet with no picture to show.
3493
+ A neutral card (no alarm colour), with the way forward, never a vanished toast. Filled by openCalloutCard(). -->
3494
+ <div id=coCardModal role=dialog aria-modal=true aria-labelledby=coCardTitle aria-describedby=coCardBody><div class=mbackdrop id=coCardBackdrop></div>
3495
+ <div class="mpanel cocard"><div class=mhead><b id=coCardTitle></b><button data-command-id="steel.dialog-close#the callout notice" id=coCardClose aria-label="Close this notice" data-tip="Close">✕</button></div>
3496
+ <div class=cocard-body id=coCardBody></div>
3497
+ <div class=cocard-status id=coCardStatus role=status aria-live=polite></div>
3498
+ <div class=cocard-actions id=coCardActions></div>
3499
+ </div>
3500
+ </div>
3206
3501
  <div id=lightbox><div class=mbackdrop id=lbBackdrop></div>
3207
3502
  <div class=lbpanel><div class=mhead><b id=lbCap></b><div style="display:flex;gap:10px;align-items:center"><span class=hint>scroll = zoom · drag = pan · dbl-click = reset</span><button data-command-id="steel.dialog-close#the image viewer" id=lbClose>✕</button></div></div><div id=lbView><img id=lbImg></div></div></div>
3208
3503
  <script>
@@ -3565,6 +3860,8 @@ let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded befo
3565
3860
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
3566
3861
  let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null, ProfileColours = null, ReferenceSheet = null, ReadConfidence = null;
3567
3862
  let ChatQuestions = null; // model-chat-questions.js — the Questions in chat card and chat labels, shared with every model viewer
3863
+ let FramesCore = null; // steel-frames-core.js — the moment-frame schedule rules the server shares: what a frame row is, which girder sizes a sheet shows, how a read may add (#2210)
3864
+ let MarksCore = null; // steel-marks-core.js — the callout rules the server shares: where a callout leads, what a new one must say, when two marks are the same (#2211)
3568
3865
  let ModelPanelBridge = null; // model-panel-bridge.js — feeds the workspace's left Model section (see modelPanelSnapshot)
3569
3866
  let modelPanelBridge = null, modelPanelGeneration = -1, modelPanelSelKey = null; // see modelPanelPublishPick
3570
3867
  // The 3D panel's container and its four tab bodies, found once and then HELD: in the main window they move
@@ -3800,8 +4097,8 @@ function handleContractChanged(m){
3800
4097
  if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
3801
4098
  if(editorHasUnsavedWork()){
3802
4099
  const parked=parkDraftForExternalChange();
3803
- const lead=(typeof m.reason==='string'&&CHANGE_LEAD[m.reason])||'The AI updated this model';
3804
- 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});
4100
+ const lead=(typeof m.reason==='string'&&CHANGE_LEAD[m.reason])||'This model was changed';
4101
+ showAiUpdateBanner(parked?lead+'. Reload to see the newest version. Your unsaved edits are kept on this computer.':lead+', but your unsaved edits could not be kept on this computer, so reloading now would lose them. Write down or take a screenshot of what you changed first.',parked?{onSeeChanges:seeChangesFromOpenTab}:{noReload:true,onSeeChanges:seeChangesFromOpenTab});
3805
4102
  }else location.reload();
3806
4103
  }
3807
4104
  function bufferContractEvent(m){
@@ -3936,7 +4233,7 @@ async function rebootstrapContractEvents(epoch,attempt=0){
3936
4233
  if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
3937
4234
  if(editorHasUnsavedWork()){
3938
4235
  const parked=parkDraftForExternalChange();
3939
- 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});
4236
+ showAiUpdateBanner(parked?'A newer version of this model is available. Your edits are still here. Reload to see it, then check the member ends again.':'A newer version of this model is available, but your unsaved edits could not be kept on this computer. Write down or take a screenshot of what you changed before you reload.',parked?{onSeeChanges:seeChangesFromOpenTab}:{noReload:true,onSeeChanges:seeChangesFromOpenTab});
3940
4237
  }else{location.reload();return;}
3941
4238
  }
3942
4239
  // The reconnect snapshot carries the review summary too, and installing it here is what stops a
@@ -3952,7 +4249,7 @@ async function rebootstrapContractEvents(epoch,attempt=0){
3952
4249
  const delay=CONTRACT_EVENT_BOOTSTRAP_RETRY_MS*Math.pow(2,attempt);
3953
4250
  setTimeout(()=>epoch===contractEventEpoch&&!contractEventReady?rebootstrapContractEvents(epoch,nextAttempt):undefined,delay);
3954
4251
  }else{
3955
- showAiUpdateBanner('Live updates disconnected — reconnecting could not verify the latest model. Retrying on a fresh connection.');
4252
+ showAiUpdateBanner('FloLess lost its connection and could not check whether this model has changed. It is trying again.');
3956
4253
  const failedSource=contractEventSource;
3957
4254
  if(failedSource){failedSource.onopen=null;failedSource.onmessage=null;failedSource.onerror=null;failedSource.close();}
3958
4255
  contractEventSource=null;startContractEvents();
@@ -4205,7 +4502,7 @@ async function boot() {
4205
4502
  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; }
4206
4503
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
4207
4504
  startContractEvents(); // subscribe first; contract events buffer until the atomic snapshot is installed
4208
- [DisplayUnits, GridDisplay, SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ModelEditor, ViewportToolbar, ModelLighting, PointerDock, EditorShell, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence, CkStd, ModelPanelBridge, ChatQuestions] = await Promise.all([
4505
+ [DisplayUnits, GridDisplay, SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ModelEditor, ViewportToolbar, ModelLighting, PointerDock, EditorShell, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence, CkStd, ModelPanelBridge, ChatQuestions, SteelSlim, LastSeen, MarksCore, FramesCore] = await Promise.all([
4209
4506
  import('./display-units.js'), import('./grid-display.js'),
4210
4507
  import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'),
4211
4508
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
@@ -4216,6 +4513,7 @@ async function boot() {
4216
4513
  import('./connection-review-client.js'), import('./steel-profile-colours.js'),
4217
4514
  import('./steel-reference-sheet.js'), import('./steel-read-confidence.js'),
4218
4515
  import('./checkpoint-standard.js'), import('./model-panel-bridge.js'), import('./model-chat-questions.js'),
4516
+ import('./steel-model-slim.js'), import('./steel-last-seen.js'), import('./steel-marks-core.js'), import('./steel-frames-core.js'),
4219
4517
  ]);
4220
4518
  ({ FT_TO_MM, IN_TO_MM, LB_PER_FT_TO_KG_PER_M } = SteelCore); // the shared unit constants, bound before main() and every reader of them
4221
4519
  // BEFORE the first paint, deliberately. Every length on this page reads through it, so resolving it
@@ -4364,6 +4662,11 @@ async function boot() {
4364
4662
  // The server's tag for the contract we just read. Every write echoes it back, so a write that would
4365
4663
  // land on top of someone else's is refused instead of silently winning.
4366
4664
  serverEtag = snapshotPayload.etag || res.headers.get('ETag');
4665
+ /* The model exactly as the server sent it, kept as this tab's first 'model as I last had it' (#2209). Taken HERE, before
4666
+ the normalisation below touches `C` (which is this very object), and in a guarded helper: a copy is a convenience
4667
+ and must never be able to stop the editor opening. */
4668
+ try { lastSeenStore = LastSeen.createPageLastSeenStore({ scope: draftKey(), indexedDB: window.indexedDB, warn: (e) => console.warn('steel-editor: the last-seen copy store is unavailable', e && e.message ? e.message : e) }); } catch (e) { lastSeenStore = null; lastSeenWarn('the copy store could not be created', e); }
4669
+ lastSeenCommit(serverEtag, lastSeenText(loaded));
4367
4670
  /* The answer to the question above, and it stays a LOCAL on purpose. `serverEtag` advances through
4368
4671
  every write path on this page; a module-level copy of a boot-time verdict would outlive the
4369
4672
  generation it describes, and a later restore could then overlay a draft from generation A onto
@@ -4537,7 +4840,7 @@ function showAiUpdateBanner(message, opts) {
4537
4840
  if (opts && opts.kind) bar.dataset.kind = opts.kind;
4538
4841
  bar.style.cssText = [
4539
4842
  'position:fixed', 'bottom:0', 'left:0', 'right:0', 'z-index:50',
4540
- 'display:flex', 'align-items:center', 'gap:10px',
4843
+ 'display:flex', 'flex-wrap:wrap', 'align-items:center', 'gap:10px',
4541
4844
  'padding:10px 16px',
4542
4845
  'background:#1e40af', 'color:#e0f2fe',
4543
4846
  'font:13px var(--ui)', 'border-top:1px solid #3b82f6',
@@ -4545,7 +4848,7 @@ function showAiUpdateBanner(message, opts) {
4545
4848
  ].join(';');
4546
4849
 
4547
4850
  const msg = document.createElement('span');
4548
- msg.style.cssText = 'flex:1';
4851
+ msg.style.cssText = 'flex:1 1 280px';
4549
4852
  // The fallback is deliberately CAUSE-FREE. All five callers pass a message, so this is unreachable
4550
4853
  // today — but it was the last place in the file still asserting "the AI" about a change nobody has
4551
4854
  // established the AI made, which is the claim this bar stopped making. A caller that forgets its
@@ -4555,7 +4858,7 @@ function showAiUpdateBanner(message, opts) {
4555
4858
  // A live region that is inserted ALREADY POPULATED is announced inconsistently across screen
4556
4859
  // readers — the announcement hangs off a mutation INSIDE an existing region — so setting it up
4557
4860
  // front made role=status decorative. Review caught that; `sentence` carries it to the append.
4558
- const sentence = message || 'This model changed — reload to see the latest version.';
4861
+ const sentence = message || 'This model was changed. Reload to see the newest version.';
4559
4862
 
4560
4863
  // `noReload` — the one caller that must NOT offer it: an unsaved edit that reached no storage.
4561
4864
  // Suppressing the button beats disabling it; a dead control invites a hunt for why.
@@ -4584,6 +4887,22 @@ function showAiUpdateBanner(message, opts) {
4584
4887
  dismissBtn.onclick = () => bar.remove();
4585
4888
 
4586
4889
  bar.appendChild(msg);
4890
+ // "See what changed" (#2209), FIRST. It only looks: it never rewinds a tag, restamps a draft or writes
4891
+ // anything, so it sits beside the buttons that do without touching them. Outline like the other secondary
4892
+ // actions, and filled only when it is the bar's one real action (the bar that cannot offer a reload).
4893
+ if (opts && opts.onSeeChanges) {
4894
+ const seeBtn = document.createElement('button');
4895
+ const lone = !reloadBtn && !opts.onOverwrite;
4896
+ seeBtn.style.cssText = lone
4897
+ ? 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px var(--ui)'
4898
+ : 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px var(--ui)';
4899
+ seeBtn.textContent = 'See what changed';
4900
+ seeBtn.dataset.tip = 'See what changed. This only looks; nothing in your model changes.';
4901
+ seeBtn.setAttribute('aria-haspopup', 'dialog');
4902
+ seeBtn.setAttribute('data-command-id', 'steel.see-what-changed');
4903
+ seeBtn.onclick = () => opts.onSeeChanges(seeBtn);
4904
+ bar.appendChild(seeBtn);
4905
+ }
4587
4906
  if (reloadBtn) bar.appendChild(reloadBtn);
4588
4907
  if (opts && opts.onOverwrite) {
4589
4908
  // Visually subordinate to Reload — it is the destructive option, and it still has to pass a confirm.
@@ -4602,6 +4921,246 @@ function showAiUpdateBanner(message, opts) {
4602
4921
  msg.textContent = sentence;
4603
4922
  }
4604
4923
 
4924
+ /* ── "See what changed" (#2209) ───────────────────────────────────────────────────────────────────────
4925
+ The model-changed bar tells you THAT the model moved; this tells you WHAT changed. It needs the model as this
4926
+ tab last had it, which the server does not keep, so the tab keeps a slim copy (steel-last-seen.js) and asks the
4927
+ server to compare it with the model as it is now (POST .../changes-since). The page renders what the server
4928
+ wrote and composes no sentence about the model itself.
4929
+
4930
+ WHAT THIS BLOCK MAY NEVER DO: it only READS. It never assigns `serverEtag`, never calls restampDraftBase,
4931
+ persist or applyDraftFields, and never writes localStorage. "Show my earlier edits" is a different button
4932
+ on a different path with a long data-loss history; a differential test (steel-editor-last-seen-no-side-
4933
+ effects.test.ts) runs both against master's editor to prove this block changed nothing there.
4934
+
4935
+ THE COPY. A copy is taken only where the document in hand is PROVEN to be the model for the tag:
4936
+ - the document the server sent (boot, a member-end install, a save reply that carries its document);
4937
+ - the document THIS tab sent, taken in the same tick as the request body, and only when the server's
4938
+ reply says it published exactly that (`publishedAsSent`). Any write-boundary rewrite makes it false.
4939
+ Every other place the tag moves (a placement, a reference import, an event echo, a member-end scan, a
4940
+ rewind) captures nothing: a missing copy degrades to a plain sentence, a wrong one would be a false list. */
4941
+ let SteelSlim = null, LastSeen = null, lastSeenStore = null;
4942
+ /** One console line per reason, ever: a copy that is not kept is a convenience lost, but never one nobody can find out about. */
4943
+ const lastSeenWarned = {};
4944
+ function lastSeenWarn(why, detail) {
4945
+ if (lastSeenWarned[why]) return;
4946
+ lastSeenWarned[why] = true;
4947
+ try { console.warn('steel-editor: no copy of the model was kept for "See what changed": ' + why, detail && detail.message ? detail.message : (detail === undefined ? '' : detail)); } catch (_) { /* a log line is a courtesy */ }
4948
+ }
4949
+ /** The slim copy of a v2 document as JSON text, or null. Never throws (it runs inside the save path). */
4950
+ function lastSeenText(doc) {
4951
+ try {
4952
+ const slim = SteelSlim && SteelSlim.slimForChangeList(doc);
4953
+ if (!slim) { if (SteelSlim) lastSeenWarn('the document is not a steel model v2 document'); return null; }
4954
+ return JSON.stringify(slim);
4955
+ } catch (e) { lastSeenWarn('the copy could not be made', e); return null; }
4956
+ }
4957
+ function lastSeenCommit(tag, text) {
4958
+ try {
4959
+ if (lastSeenStore && tag && text && lastSeenStore.commit(tag, text) === false) lastSeenWarn('the copy was refused (over the size limit or not usable)', { bytes: text.length });
4960
+ } catch (e) { lastSeenWarn('the copy could not be stored', e); }
4961
+ }
4962
+ /** After the tab's own save: keep the copy it SENT, but only if the reply proves the server published exactly that. */
4963
+ function lastSeenCommitOwnSave(tag, reply, readable, sentText) {
4964
+ try { if (readable && reply && typeof reply === 'object' && reply.publishedAsSent === true && typeof tag === 'string') lastSeenCommit(tag, sentText); }
4965
+ catch (_) { /* never reaches the save */ }
4966
+ }
4967
+
4968
+ const CHANGE_LIST_TEXT = {
4969
+ noCopy: "FloLess doesn't have a usable copy of the model as you last saw it, so it can't list what changed.",
4970
+ cannotCompare: "FloLess can't compare the two versions.",
4971
+ failed: "FloLess couldn't compare the two versions just now.",
4972
+ failedHint: ' If it keeps happening, compare with the last approved version in History.',
4973
+ cantShow: "FloLess found the changes but couldn't show them just now.",
4974
+ // 402 collapses several causes (signed out, expired session, seat taken, subscription), so the sentence names none of them and the
4975
+ // pointer is the same one the page already gives for a refused model read ("Check your FloLess account").
4976
+ account: "FloLess can't compare right now. Check your FloLess account (top right), then try again.",
4977
+ wayForward: 'To see the differences, compare with the last approved version: open History, or use Review & approve.',
4978
+ loading: 'Looking at what changed…',
4979
+ changedAgain: 'It has changed again since this page opened.',
4980
+ subA: "Compared with the model as it was when you last worked on it. Your own edits aren't included.",
4981
+ subB: "Compared with the model as this page last had it. Your unsaved edits aren't included.",
4982
+ };
4983
+ const CHANGE_LIST_TIMEOUT_MS = 30000;
4984
+ const CHANGE_LIST_BACKDROP_GRACE_MS = 600; // longer than a typical double-click gap (the Windows default is 500 ms)
4985
+ let changeListOpen = null; // the one open list, so a second click on the bar finds it instead of stacking another
4986
+
4987
+ function openChangeList(ctx) {
4988
+ if (changeListOpen) { try { changeListOpen.focusClose(); } catch (_) { /* fine */ } return; }
4989
+ const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; };
4990
+ const opener = ctx && ctx.opener ? ctx.opener : null;
4991
+ const modal = el('div'); modal.id = 'changeListModal';
4992
+ modal.setAttribute('role', 'dialog'); modal.setAttribute('aria-modal', 'true');
4993
+ modal.setAttribute('aria-labelledby', 'changeListTitle'); modal.setAttribute('aria-describedby', 'changeListSummary');
4994
+ const backdrop = el('div', 'mbackdrop');
4995
+ const panel = el('div', 'mpanel'); panel.tabIndex = -1;
4996
+ const head = el('div', 'mhead'); const title = el('h2', null, 'What changed in this model'); title.id = 'changeListTitle'; head.appendChild(title);
4997
+ const sub = el('p', null, ctx && ctx.situation === 'A' ? CHANGE_LIST_TEXT.subA : CHANGE_LIST_TEXT.subB); sub.id = 'changeListSub';
4998
+ const summary = el('div'); summary.id = 'changeListSummary';
4999
+ const body = el('div'); body.id = 'changeListBody'; body.tabIndex = 0; body.setAttribute('role', 'region'); body.setAttribute('aria-label', 'What changed');
5000
+ const live = el('div', 'sr-only'); live.setAttribute('role', 'status');
5001
+ const actions = el('div'); actions.id = 'changeListActions';
5002
+ const closeBtn = el('button', 'primary', 'Close'); closeBtn.id = 'changeListClose'; closeBtn.setAttribute('data-command-id', 'steel.dialog-close#the list of changes');
5003
+ const retryBtn = el('button', 'primary', 'Try again'); retryBtn.id = 'changeListRetry'; retryBtn.setAttribute('data-command-id', 'steel.change-list-retry'); retryBtn.style.display = 'none';
5004
+ actions.append(retryBtn, closeBtn);
5005
+ panel.append(head, sub, summary, body, live, actions);
5006
+ modal.append(backdrop, panel);
5007
+ document.body.appendChild(modal);
5008
+
5009
+ let run = 0, controller = null, timer = null, closed = false;
5010
+ const stopRequest = () => { if (timer) { clearTimeout(timer); timer = null; } if (controller) { try { controller.abort(); } catch (_) { /* fine */ } controller = null; } };
5011
+ const close = () => {
5012
+ if (closed) return;
5013
+ closed = true; run++; stopRequest(); changeListOpen = null;
5014
+ modal.removeEventListener('keydown', keys);
5015
+ window.removeEventListener('keydown', guard, true);
5016
+ document.removeEventListener('focusin', refocus, true);
5017
+ modal.remove();
5018
+ // Back to where the person was: the button that opened this, or - if the bar was rebuilt meanwhile - the new bar's first button.
5019
+ try {
5020
+ const target = opener && opener.isConnected !== false ? opener : document.querySelector('#aiUpdateBanner button');
5021
+ if (target && target.focus) target.focus();
5022
+ } catch (_) { /* focus is a courtesy */ }
5023
+ };
5024
+ const focusable = () => [body, retryBtn, closeBtn].filter((n) => n.style.display !== 'none');
5025
+ const keys = (e) => {
5026
+ e.stopPropagation(); // editor shortcuts (Delete, Ctrl+Z ...) must not fire behind an open list
5027
+ if (e.key === 'Escape') { e.preventDefault(); close(); return; }
5028
+ if (e.key !== 'Tab') return;
5029
+ const f = focusable(); if (!f.length) return;
5030
+ const at = f.indexOf(document.activeElement);
5031
+ const next = e.shiftKey ? (at <= 0 ? f.length - 1 : at - 1) : (at < 0 || at === f.length - 1 ? 0 : at + 1);
5032
+ e.preventDefault(); f[next].focus();
5033
+ };
5034
+ modal.addEventListener('keydown', keys);
5035
+ // While the list is up NOTHING behind it may see a key. `keys` covers focus inside the dialog; this covers focus that has
5036
+ // left it (a click on the page behind moves focus to the page), where Delete would otherwise reach the editor. It runs at
5037
+ // window CAPTURE, before every editor handler, and brings focus back into the dialog.
5038
+ const insideDialog = (n) => !!n && (n === modal || (typeof modal.contains === 'function' && modal.contains(n)));
5039
+ const guard = (e) => {
5040
+ if (closed || insideDialog(e.target)) return;
5041
+ e.stopPropagation();
5042
+ if (e.key === 'Escape') { e.preventDefault(); close(); return; }
5043
+ if (e.key === 'Tab') { e.preventDefault(); const f = focusable(); if (f.length) (e.shiftKey ? f[f.length - 1] : f[0]).focus(); return; }
5044
+ if (e.key === 'Delete' || e.key === 'Backspace') e.preventDefault();
5045
+ if (!insideDialog(document.activeElement)) closeBtn.focus();
5046
+ };
5047
+ const refocus = (e) => { if (!closed && !insideDialog(e.target)) closeBtn.focus(); };
5048
+ window.addEventListener('keydown', guard, true);
5049
+ document.addEventListener('focusin', refocus, true);
5050
+ backdrop.addEventListener('mousedown', (e) => { e.preventDefault(); }); // a click on the backdrop must not even move focus off the dialog
5051
+ // A double click on the bar's button lands its SECOND click on this backdrop (the list is already up and covers the
5052
+ // bar), which would close the list the moment it opened. A click in the first moments is that second click, not a choice.
5053
+ const openedAt = Date.now();
5054
+ backdrop.onclick = () => { if (Date.now() - openedAt >= CHANGE_LIST_BACKDROP_GRACE_MS) close(); };
5055
+ closeBtn.onclick = close;
5056
+
5057
+ const say = (text) => { live.textContent = text; };
5058
+ const showMessage = (lead, opts) => {
5059
+ // One plain sentence, then a way forward - never a blank, never a dead end. Neutral styling: not an error.
5060
+ summary.replaceChildren(); body.replaceChildren(); body.removeAttribute('aria-busy');
5061
+ const inWorkspace = document.body.classList.contains('in-workspace');
5062
+ const p = el('p', 'clmsg', lead + (opts && opts.hint && inWorkspace ? opts.hint : '')); body.appendChild(p);
5063
+ if (!opts || opts.forward !== false) { if (inWorkspace) body.appendChild(el('p', 'clmsg quiet', CHANGE_LIST_TEXT.wayForward)); }
5064
+ retryBtn.style.display = opts && opts.retry ? '' : 'none';
5065
+ say(lead);
5066
+ (opts && opts.retry ? retryBtn : closeBtn).focus();
5067
+ };
5068
+ const showResult = (r, requestedTag) => {
5069
+ summary.replaceChildren(); body.replaceChildren(); body.removeAttribute('aria-busy'); retryBtn.style.display = 'none';
5070
+ const headline = el('b', null, String(r.headline || '')); summary.appendChild(headline);
5071
+ if (typeof r.weight === 'string' && r.weight) summary.appendChild(el('span', 'clweight', r.weight));
5072
+ for (const n of (Array.isArray(r.notes) ? r.notes : [])) body.appendChild(el('div', 'clnote warn', String(n && n.text || '')));
5073
+ if (ctx && ctx.situation === 'A' && typeof r.targetEtag === 'string' && r.targetEtag !== serverEtag) body.appendChild(el('div', 'clnote', CHANGE_LIST_TEXT.changedAgain));
5074
+ if (r.nothingChanged && typeof r.emptyBody === 'string') body.appendChild(el('p', 'clmsg quiet', r.emptyBody));
5075
+ for (const g of (Array.isArray(r.groups) ? r.groups : [])) {
5076
+ const section = el('section'); const h = el('h3');
5077
+ const chip = el('span', 'clchip ' + (g.key === 'added' ? 'add' : g.key === 'removed' ? 'rem' : 'chg'));
5078
+ const glyph = el('span', null, g.key === 'added' ? '+' : g.key === 'removed' ? '-' : '~'); glyph.setAttribute('aria-hidden', 'true');
5079
+ chip.append(glyph, el('span', null, String(g.title || '')));
5080
+ h.append(chip, el('span', 'clcount', String(g.count)));
5081
+ const ul = el('ul'); ul.setAttribute('role', 'list');
5082
+ for (const item of (Array.isArray(g.items) ? g.items : [])) {
5083
+ const li = el('li'); li.setAttribute('aria-label', String(item.text || ''));
5084
+ const subject = el('div'); subject.append(el('span', 'clkind', String(item.kind || '') + ' '), el('span', 'clname', String(item.name || '') + (item.place ? ', ' + item.place : '')));
5085
+ const detail = el('div', 'cldetail', String(item.detail || ''));
5086
+ if (item.notPlaced) detail.appendChild(el('span', 'clpill', 'Not placed in 3D yet'));
5087
+ li.append(subject, detail); ul.appendChild(li);
5088
+ }
5089
+ if (g.more > 0) ul.appendChild(el('li', 'clcap', '…and ' + g.more + ' more not shown.'));
5090
+ section.append(h, ul); body.appendChild(section);
5091
+ }
5092
+ // One line on what was and was not compared, so a short list is not read as "that is everything" (the empty body says it itself).
5093
+ if (typeof r.footnote === 'string' && r.footnote) body.appendChild(el('p', 'clmsg quiet clfoot', r.footnote));
5094
+ // What a screen-reader user hears also carries how many members could not be fully checked.
5095
+ const unchecked = Number.isSafeInteger(r.unchecked) && r.unchecked > 0 ? ' ' + r.unchecked + (r.unchecked === 1 ? ' member' : ' members') + ' could not be fully checked.' : '';
5096
+ say((r.nothingChanged ? String(r.headline || '') : String(r.headline || '') + ' found.') + unchecked);
5097
+ closeBtn.focus();
5098
+ };
5099
+
5100
+ async function load() {
5101
+ const token = ++run; stopRequest();
5102
+ summary.replaceChildren(); retryBtn.style.display = 'none';
5103
+ body.replaceChildren(el('p', 'clmsg quiet', CHANGE_LIST_TEXT.loading)); body.setAttribute('aria-busy', 'true'); say(CHANGE_LIST_TEXT.loading);
5104
+ const tag = ctx && ctx.situation === 'A' ? (ctx.baseTag || null) : serverEtag;
5105
+ let recalled = { ok: false };
5106
+ try { recalled = (tag && lastSeenStore) ? await lastSeenStore.recall(tag) : { ok: false }; } catch (_) { recalled = { ok: false, reason: 'unavailable' }; }
5107
+ if (token !== run || closed) return;
5108
+ // No copy for exactly this tag: say so and send nothing. Never a nearer or newer copy. When the store could not ANSWER (it
5109
+ // timed out or failed, which is not the same as "never stored"), trying again can help, so that is offered.
5110
+ if (!recalled.ok) { showMessage(CHANGE_LIST_TEXT.noCopy, { retry: recalled.reason === 'unavailable' }); return; }
5111
+ controller = typeof AbortController === 'function' ? new AbortController() : null;
5112
+ // The deadline always ends in a message. With AbortController it aborts the request; without one the request cannot be
5113
+ // aborted, so the dialog gives up on it (run++ makes any late answer harmless) instead of sitting on "Looking..." forever.
5114
+ timer = setTimeout(() => {
5115
+ if (controller) { controller.abort(); return; }
5116
+ run++; showMessage(CHANGE_LIST_TEXT.failed, { hint: CHANGE_LIST_TEXT.failedHint, retry: true, forward: false });
5117
+ }, CHANGE_LIST_TIMEOUT_MS);
5118
+ const failedMessage = () => showMessage(CHANGE_LIST_TEXT.failed, { hint: CHANGE_LIST_TEXT.failedHint, retry: true, forward: false });
5119
+ let r = null;
5120
+ try {
5121
+ const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + '/changes-since' + PROJECT_QS, {
5122
+ method: 'POST', headers: { 'content-type': 'application/json' }, signal: controller ? controller.signal : undefined,
5123
+ body: '{"baseEtag":' + JSON.stringify(tag) + ',"base":' + recalled.model + ',"units":' + JSON.stringify(displayUnits()) + '}',
5124
+ });
5125
+ if (token !== run || closed) return;
5126
+ if (!res.ok) {
5127
+ // Read what the server said and keep it in the console: the person gets one plain sentence, support gets the status and code.
5128
+ let detail = null; try { detail = await res.json(); } catch (_) { /* a refusal with no body */ }
5129
+ if (token !== run || closed) return;
5130
+ console.warn('steel-editor: the change list request was refused', { status: res.status, code: detail && detail.code, error: detail && detail.error });
5131
+ if (res.status === 402) { showMessage(CHANGE_LIST_TEXT.account, { forward: false, retry: true }); return; }
5132
+ if (res.status === 413) { showMessage(CHANGE_LIST_TEXT.cannotCompare); return; }
5133
+ // Forbidden: the server's own plain sentence says why, and asking again changes nothing.
5134
+ if (res.status === 403) { showMessage(detail && typeof detail.error === 'string' && detail.error ? detail.error : CHANGE_LIST_TEXT.cannotCompare, { forward: false }); return; }
5135
+ // A malformed request or a project that is not this app's cannot be fixed by retrying.
5136
+ if (res.status === 400 || res.status === 404) { showMessage(CHANGE_LIST_TEXT.cannotCompare); return; }
5137
+ failedMessage(); return;
5138
+ }
5139
+ r = await res.json();
5140
+ } catch (e) {
5141
+ if (token !== run || closed) return;
5142
+ console.warn('steel-editor: the change list request failed', e && e.message ? e.message : e);
5143
+ failedMessage(); return;
5144
+ } finally { if (token === run) stopRequest(); }
5145
+ if (token !== run || closed) return;
5146
+ if (!r || r.baseEtag !== tag) { failedMessage(); return; }
5147
+ if (r.status === 'available' && Array.isArray(r.groups)) {
5148
+ // Drawing the answer is not part of the network call: a render bug must not be shown as a lost connection.
5149
+ try { showResult(r, tag); }
5150
+ catch (e) { console.warn('steel-editor: the change list could not be shown', e && e.message ? e.message : e); showMessage(CHANGE_LIST_TEXT.cantShow); }
5151
+ return;
5152
+ }
5153
+ showMessage(r.reason === 'base-invalid' ? CHANGE_LIST_TEXT.noCopy : CHANGE_LIST_TEXT.cannotCompare);
5154
+ }
5155
+ retryBtn.onclick = () => { load(); };
5156
+ changeListOpen = { focusClose: () => closeBtn.focus(), close };
5157
+ closeBtn.focus();
5158
+ load();
5159
+ }
5160
+ /** The two bar entry points. The tab's own draft and tags are read-only to these. */
5161
+ function seeChangesFromStaleDraft(d) { return (opener) => openChangeList({ situation: 'A', baseTag: d && d.baseEtag ? d.baseEtag : null, opener }); }
5162
+ function seeChangesFromOpenTab(opener) { openChangeList({ situation: 'B', baseTag: null, opener }); }
5163
+
4605
5164
  function main(bootRecordedBase) {
4606
5165
  let P, X0,Y0,X1,Y1, FT, RB64, EXTX, EXTY, profs, NO_PLAN_VIEW=false; // per-plan, set by setPlan()
4607
5166
  let v2IdSeq=0;
@@ -4642,6 +5201,7 @@ let gridLabelPx=(()=>{try{const raw=localStorage.getItem('steel:gridLabelPx:v2')
4642
5201
  let gridMode=false, gridPick=false, gridLinePick=null; // Grid lines: panel-takeover editing mode + armed pick-origin / single-line clicks
4643
5202
  let dimStyleMode=false; // Dimension style: panel-takeover pane for the model-global defaults (⋯ → Display → Dimension style…)
4644
5203
  let csaxisMode=false, csDraft=null; // Local coordinate system "set axes" tool: armed flag + in-progress origin [x,y] (null until click 1). P.frame={o,u} holds the committed local frame (null = global).
5204
+ let calloutEditMode=false, calloutDraft=null; // "Add a callout" tool (#2211): armed flag + the open form's draft {at:[x,y] in sheet px, list:'callouts', index:null|n, kind}. Armed does not mean the form is open.
4645
5205
  // Un-collapse the Inspector so a takeover pane the user just summoned is actually on screen. The real
4646
5206
  // implementation is installed by the Inspector toggle below, which owns the collapsed flag; this stub
4647
5207
  // keeps every caller safe if that toggle is absent (no #panelToggle → nothing can collapse the panel
@@ -4656,6 +5216,19 @@ let provisionalSelId=null; // Source-view identity is separate from physical me
4656
5216
  let provisionalSelTraceId=null;
4657
5217
  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
4658
5218
  let undo=[], redo=[];
5219
+ // #2210: the pending question "remove this new moment-frame girder's automatic shear plates?" (see mfOfferAfterEdit). Declared HERE with the other state
5220
+ // the early paint reads, not beside its functions: apply() and panel() run during boot, before a declaration that far down has executed.
5221
+ const MF_OFFER_BAR_ID='mfOfferBar';
5222
+ let mfOffer=null; // {marked:[beam ids this one action turned into girders], selKey: the selection it was asked under, floating: asked as a bar because those beams are not what is selected}
5223
+ // The custom-detail LIBRARY (name -> picture bytes) rides the undo history, but by KEY: every snapshot records
5224
+ // {name: key} and each distinct picture is kept ONCE in `picStore` under that key, so a 200 KB picture adds a few characters
5225
+ // to a step instead of 200 KB. A key is the picture's short fingerprint, with a suffix when another, different picture already
5226
+ // holds that fingerprint (two pictures can share one), so a key always names exactly one picture. A rename, a delete and an
5227
+ // import are each one edit(), so undo and redo put back exactly the pictures that were under each name at that point, and the
5228
+ // placed copies (also in the snapshot, by name) follow. A picture nothing can reach any more (not in the library, not in any
5229
+ // undo or redo step) is released when history is discarded. See libraryPrints / restoreLibrary / prunePictures.
5230
+ // `picSeen` is only a cache of the last key taken per name.
5231
+ const picStore=new Map();let picSeen=new Map();
4659
5232
  let memberEndReview=null;
4660
5233
  let memberEndScan=null;
4661
5234
  let merCollapsed=new Set((()=>{try{return JSON.parse(localStorage.getItem('floless.merCollapsed')||'[]');}catch{return [];}})()); // member types the review list has folded; its own key, so the Objects list's folds stay the Objects list's
@@ -4733,6 +5306,7 @@ function memberEndDistance(f,t){const a=f.currentPoint,z=a&&a.z&&Number.isFinite
4733
5306
  // snapshot that only recorded the page still collapses two views on one sheet onto each other.
4734
5307
  function memberEndSnapshot(doc){return {v2:true,members:doc.members,provisional_members:doc.provisional_members||[],grid:doc.grid||null,plans:(doc.plans||[]).map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],...(Object.hasOwn(p,'frame')?{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}:{})};}
4735
5308
  function installMemberEndContract(doc,etag,revision,keepHistory){
5309
+ const seenCopy=lastSeenText(doc); // #2209 - the server's document for this tag, taken BEFORE the session adopts (and later mutates) its parts
4736
5310
  V2_SESSION.restoreSnapshot(memberEndSnapshot(doc));V2_PROJECTIONS.clear();
4737
5311
  bumpRfiEpoch(); // #1090 — a server command replaced the model; the unresolved-size count is stale
4738
5312
  const activePlan=C.plans&&C.plans[C.active];
@@ -4743,14 +5317,14 @@ function installMemberEndContract(doc,etag,revision,keepHistory){
4743
5317
  // would let Ctrl+Z resurrect pre-command geometry without the server-owned decision/audit metadata.
4744
5318
  // A save reply (`keepHistory`) is not a command: it is our own document with decisions staled, and
4745
5319
  // apply() restores decisions from `serverDecided`, so its history stays valid (see adoptSaveReply).
4746
- if(!keepHistory){undo.length=0;redo.length=0;updUR();}
5320
+ if(!keepHistory){undo.length=0;redo.length=0;picStore.clear();picSeen=new Map();updUR();} // nothing left to undo to, so the pictures kept for it go too (the live library is fingerprinted again at the next snapshot)
4747
5321
  serverDecided=decidedMembers(doc.members);
4748
5322
  bumpModelEditGeneration(); // the server replaced the document under the editor; nothing captured before this describes what is now on screen
4749
5323
  // A restamped row is rewritten too: it still holds the document from BEFORE the server's change, and a
4750
5324
  // reload would put that back — a staled decision returning live, refused on the next save. A row from
4751
5325
  // another generation (a stale draft that could not be parked) is not ours to touch: only the user's own
4752
5326
  // next edit may replace it.
4753
- const prev=serverEtag;serverEtag=etag;serverRevision=revision;if(restampDraftBase(prev,etag))persist();conflicted=false;render();sync3D();
5327
+ const prev=serverEtag;serverEtag=etag;serverRevision=revision;if(restampDraftBase(prev,etag))persist();conflicted=false;lastSeenCommit(etag,seenCopy);render();sync3D();
4754
5328
  }
4755
5329
  // A save reply carries `contract` only when the write boundary staled retained work-point decisions — our
4756
5330
  // own document with server-owned fields changed. Wiping history here made the first edit after a drawing
@@ -4758,7 +5332,8 @@ function installMemberEndContract(doc,etag,revision,keepHistory){
4758
5332
  // would revert it, so only the decisions are taken; that edit's own save then sends them back unchanged.
4759
5333
  function adoptSaveReply(doc,etag,revision,seq){
4760
5334
  if(seq===saveSeq)return installMemberEndContract(doc,etag,revision,true);
4761
- const prev=serverEtag;serverEtag=etag;serverRevision=Math.max(serverRevision,revision);const ours=restampDraftBase(prev,etag);
5335
+ const seenCopy=lastSeenText(doc); // #2209 - only the decisions are adopted below, but the tag now names this whole server document
5336
+ const prev=serverEtag;serverEtag=etag;serverRevision=Math.max(serverRevision,revision);const ours=restampDraftBase(prev,etag);lastSeenCommit(etag,seenCopy);
4762
5337
  serverDecided=decidedMembers(doc.members);reconcileDecisions(); // after the tag: the write committed, whatever reconciling does
4763
5338
  if(ours)persist();
4764
5339
  }
@@ -4775,7 +5350,7 @@ function adoptSaveReply(doc,etag,revision,seq){
4775
5350
  // browser draft first (the one the stale-draft banner restores). If it cannot be parked, say so instead.
4776
5351
  function reloadKeepingPendingEdit(){
4777
5352
  if(editorHasUnsavedWork()&&!parkDraftForExternalChange()){
4778
- showAiUpdateBanner('Your latest edit could not be kept on this device, so reloading would lose it. Copy it out first.',{noReload:true});
5353
+ showAiUpdateBanner('Your latest edit could not be kept on this computer, so reloading now would lose it. Write down or take a screenshot of what you changed first.',{noReload:true});
4779
5354
  return;
4780
5355
  }
4781
5356
  location.reload();
@@ -4783,7 +5358,7 @@ function reloadKeepingPendingEdit(){
4783
5358
  async function recoverStoredDecisions(seq=saveSeq){
4784
5359
  const unreadable=(why)=>{
4785
5360
  console.warn('steel-editor: could not re-read the stored decisions after a lost save reply',why);
4786
- showAiUpdateBanner('That save went through, but FloLess could not read back what the server kept — reload to pick up the latest version.',{onReload:reloadKeepingPendingEdit});
5361
+ showAiUpdateBanner('Your change was saved, but FloLess could not check what was saved. Reload to see the newest version.',{onReload:reloadKeepingPendingEdit});
4787
5362
  return 'failed';
4788
5363
  };
4789
5364
  let body;
@@ -4919,7 +5494,7 @@ function v2ProjectedMember(id){
4919
5494
  }
4920
5495
  return undefined;}
4921
5496
  const allMembers=()=>modelMembersV2();
4922
- const projectedAllMembers=()=>(C.members||[]).map(m=>v2ProjectedMember(m.id)).filter(Boolean);
5497
+ const projectedAllMembers=()=>selectionNoticeMembers((C.members||[]).map(m=>m.id),V2Projection.createMemberPresenceIndex(C));
4923
5498
  const byId=id=>v2ProjectedMember(id);
4924
5499
  // Same rule as v2ProjectedMember, for the same reason: a refused sheet's plan carries no usable
4925
5500
  // transform, so returning it would do coordinate maths against a registration the runtime just refused.
@@ -4938,7 +5513,8 @@ const planeOf=id=>{
4938
5513
  if(active&&eligible.includes(active))return v2ProjectionForView(active).plan;
4939
5514
  return v2ProjectionForView([...eligible].sort(compareViewIdsUtf8)[0]).plan;};
4940
5515
  const planeOfMember=m=>{const link=V2Projection.projectionLink(m);return link?.viewId?v2ProjectionForView(link.viewId).plan:null;};
4941
- const selArr=()=>[...selIds].map(byId).filter(Boolean);
5516
+ // Bulk selection reads share fresh presence and projected-row lookups for this call only.
5517
+ const selArr=(presence=V2Projection.createMemberPresenceIndex(C))=>selectionNoticeMembers([...selIds],presence);
4942
5518
  // The active-sheet subset of the selection — for 2D coordinate/decoration ops (handles, badges, move/copy,
4943
5519
  // 2D drag/zoom) that draw or compute in THIS sheet's px space, where an off-sheet member's wp is meaningless.
4944
5520
  const sel2d=()=>P.members.filter(m=>selIds.has(m.id));
@@ -4993,9 +5569,9 @@ function selCanonicalArr(){return [...selIds].map(canonicalMemberProps).filter(B
4993
5569
  whether it is refused has no single answer. Keyed by view id; the caller names them with
4994
5570
  `viewLabel` rather than printing the key, because a raw view id is the one string the author never
4995
5571
  typed. */
4996
- function blockingViewsFor(ids){const out=new Map();
5572
+ function blockingViewsFor(ids,presence){const out=new Map();
4997
5573
  if(!V2Projection)return out;
4998
- for(const id of ids){for(const viewId of V2Projection.memberPlanViewIds(C,id)){
5574
+ for(const id of ids){for(const viewId of V2Projection.memberPlanViewIds(C,id,presence)){
4999
5575
  const plan=v2ProjectionForView(viewId).plan;
5000
5576
  if(plan.registrationRefusal)out.set(viewId,plan.registrationRefusal);}}
5001
5577
  return out;}
@@ -5003,13 +5579,13 @@ function blockingViewsFor(ids){const out=new Map();
5003
5579
  elevation. Elevations and sections are read for steel the plans do not carry, and the 2D plan transform
5004
5580
  cannot draw them, so these members reach the user through 3D and the inspector alone — and every
5005
5581
  plan-space lookup (`byId`, `selArr`) answers nothing for them. Nothing here builds a projection. */
5006
- function sourceOnlyIds(ids){
5582
+ function sourceOnlyIds(ids,presence){
5007
5583
  if(!V2Projection)return [];
5008
- return ids.filter(id=>!V2Projection.memberPlanViewIds(C,id).length&&V2Projection.memberViewIds(C,id).length>0);}
5584
+ return ids.filter(id=>!V2Projection.memberPlanViewIds(C,id,presence).length&&V2Projection.memberViewIds(C,id,presence).length>0);}
5009
5585
  /* view id -> its row, deduped, for the views showing those members. The rows are what the copy names. */
5010
- function sourceOnlyViewsFor(ids){const out=new Map();
5011
- for(const id of sourceOnlyIds(ids)){
5012
- for(const viewId of V2Projection.memberViewIds(C,id)){const pl=(C.plans||[]).find(x=>viewIdOf(x)===viewId);if(pl)out.set(viewId,pl);}}
5586
+ function sourceOnlyViewsFor(ids,presence){const out=new Map();
5587
+ for(const id of sourceOnlyIds(ids,presence)){
5588
+ for(const viewId of V2Projection.memberViewIds(C,id,presence)){const pl=(C.plans||[]).find(x=>viewIdOf(x)===viewId);if(pl)out.set(viewId,pl);}}
5013
5589
  return out;}
5014
5590
  /* "S-302 · S-302-3, an elevation" / "A (an elevation) and B (a section)". An elevation or section with no
5015
5591
  `sourceRegistration` is not aligned to the model grid, and saying so matters: its members are still
@@ -5243,7 +5819,7 @@ function posHDefault(m){return SteelCore.effectiveWidthPosition(m.positionH);}
5243
5819
  // refusal the bake no longer makes: `partFrame`'s degenerate branch hands a plumb member the frame's own X
5244
5820
  // as its width axis (Tekla's column convention), so a plumb column or brace has a determinate left and
5245
5821
  // right after all. KEEP IN LOCK-STEP: the inspector must offer the control exactly where the bake honours it.
5246
- function posEligible(m){return profileDimsIn(m&&m.profile)!=null||!!(m&&m.section&&m.section.w>0&&m.section.d>0);}
5822
+ function posEligible(m,dimensions=profileDimsIn(m&&m.profile)){return dimensions!=null||!!(m&&m.section&&m.section.w>0&&m.section.d>0);}
5247
5823
  // Profile Position copy, in ONE place so the single- and multi-select panels cannot drift (they already
5248
5824
  // described the same control two different ways). Per-button tips, not one heading tip carrying
5249
5825
  // everything: with two axes under one heading the two "Middle" buttons sit adjacent, and each button
@@ -5969,7 +6545,10 @@ function syncDefaults(){for(const m of P.members)ModelCmd.syncToDefault(m,defaul
5969
6545
  // authored statement ("this control point is the model origin"), and JSON drops the undefined key, so
5970
6546
  // absence survives the round trip rather than being materialised.
5971
6547
  function snapshot(){
5972
- return JSON.stringify({v2:true,members:C.members,provisional_members:C.provisional_members||[],grid:C.grid||null,plans:C.plans.map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],...(Object.hasOwn(p,'frame')?{frame:p.frame||null}:{}),datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:C.joints||[],connections:C.connections||[],details:C.detail_placements||[],views:C.views||[],member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{},clips:window.Steel3DView?.clipState?.()??null,...(Array.isArray(C.reference_models)?{reference_models:C.reference_models}:{})});
6548
+ // `library` is the FIRST key on purpose: prunePictures reads which pictures a step needs from the front of the string without parsing the whole model.
6549
+ // `marks` / `rootMarks` (#2211): the sheet's callouts, details and top-of-steel callouts and the root detail anchors, each
6550
+ // recorded as present-with-value or ABSENT, so undoing the first mark added to a sheet puts the missing key back.
6551
+ return JSON.stringify({library:libraryPrints(),v2:true,members:C.members,provisional_members:C.provisional_members||[],grid:C.grid||null,plans:C.plans.map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],...(Object.hasOwn(p,'frame')?{frame:p.frame||null}:{}),marks:V2Commands.captureAnnotations(p),datum_ref:p.datum_ref,control2_ref:p.control2_ref})),rootMarks:V2Commands.captureRootAnnotations(C),joints:C.joints||[],connections:C.connections||[],details:C.detail_placements||[],views:C.views||[],member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{},clips:window.Steel3DView?.clipState?.()??null,...(Array.isArray(C.reference_models)?{reference_models:C.reference_models}:{})});
5973
6552
  }
5974
6553
  // Undo/redo is a SINGLE GLOBAL stack (not per-plane): snapshot() above captures EVERY plane's
5975
6554
  // members, so one whole-model stack is coherent — undo restores all planes at once, and a cross-
@@ -5992,11 +6571,12 @@ function refreshOverlayDims3d(){if(window.Steel3DView&&window.Steel3DView.refres
5992
6571
  // switching sheet, toggling a display option. The header's RFI count is now PROJECT-WIDE, so
5993
6572
  // recomputing it there would scan every member in the model on every click on a beam. The count is a
5994
6573
  // function of the MODEL, and this is the one place the model changes.
5995
- function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();bumpRfiEpoch();updUR();}
6574
+ function pushUndo(prev){undo.push(prev);let dropped=redo.length>0;if(undo.length>200){undo.shift();dropped=true;}redo.length=0;if(dropped)prunePictures();scheduleSave();bumpRfiEpoch();updUR();}
5996
6575
  // `noSave` — a restore back to a state that is already the saved one (a refused edit, #1947) must not queue a
5997
6576
  // draft write: nothing changed, and an undo entry-less write would only churn the save pill.
5998
6577
  function apply(json,noSave){
5999
6578
  const d=JSON.parse(json);
6579
+ if('library' in d)restoreLibrary(d.library); // first, so the restored placed copies below find the pictures their names had (a partial member-end snapshot has no `library` and leaves it alone)
6000
6580
  V2_SESSION.restoreSnapshot(d,{decisionsFrom:serverDecided}); // server-owned decisions come back as the server last confirmed them; a snapshot's own copy may be one the save boundary has since retired
6001
6581
  bumpRfiEpoch(); // #1090 — an undo/redo changes which sizes are unresolved; see bumpRfiEpoch
6002
6582
  // #1880 — the active view can be an ELEVATION (a 3D edit made while one is shown), and the plan
@@ -6018,8 +6598,13 @@ function apply(json,noSave){
6018
6598
  if('reference_models' in d)pushReferences(); // native sync3D cannot repaint the editor-only reference layer
6019
6599
  if('member_types' in d)C.member_types=sanitizeMemberTypes(d.member_types);
6020
6600
  if('member_styles' in d)C.member_styles=(d.member_styles&&typeof d.member_styles==='object'&&!Array.isArray(d.member_styles))?d.member_styles:{}; // F5: model-global per-type line styles ride the undo stack (like dim_style) so a setMemberLineStyle() edit() is undoable
6601
+ closeViewFly();closeCalloutForm();if(detailsOpen())openDetails(); // #2211: an undo/redo can add or remove marks under an open form, chooser or Details list
6602
+ if(framesOpen())framesRepaint(true); // #2210: ...and frames, levels and sheet links under an open Frames dialog
6021
6603
  if(!noSave)scheduleSave();render();sync3D();}
6022
- function doUndo(){if(!undo.length)return;return runSteelAuthoring('undo',{source:'history'},()=>{redo.push(snapshotLike());apply(undo.pop());});}
6604
+ // An undo steps back through an action; it is not one. So a pending question about a new moment-frame girder's automatic plates is dropped here (and a Ctrl+Z of
6605
+ // Remove must not bring it back). A redo needs no line of its own: it is only possible after an undo, and nothing can ask in between (an edit empties the redo stack).
6606
+ // Not in apply(): a refused edit and a cancelled gesture restore through apply() too, and neither answers the question.
6607
+ function doUndo(){if(!undo.length)return;mfOfferClose();return runSteelAuthoring('undo',{source:'history'},()=>{redo.push(snapshotLike());apply(undo.pop());});}
6023
6608
  function doRedo(){if(!redo.length)return;return runSteelAuthoring('redo',{source:'history'},()=>{undo.push(snapshotLike());apply(redo.pop());});}
6024
6609
  /**
6025
6610
  * The grid transaction routes through the same canonical command session as every other edit.
@@ -6044,11 +6629,12 @@ function editGridTopology(fn){
6044
6629
  }
6045
6630
  function edit(fn){
6046
6631
  // The stale-draft offer stops being safe the moment they build on the CURRENT version instead: clicking
6047
- // "View my edits instead" afterwards would overlay the old edits on top of this new work and discard it
6632
+ // "Show my earlier edits" afterwards would overlay the old edits on top of this new work and discard it
6048
6633
  // silently. Only that banner is dismissed — the AI-update and conflict bars MUST survive edits, which is
6049
6634
  // the entire reason the conflict bar exists. (unit 5, P1c-3)
6050
6635
  const _b=document.getElementById('aiUpdateBanner'); if(_b&&_b.dataset.kind==='staleBase')_b.remove();
6051
6636
  const pv=snapshot();
6637
+ const girdersBefore=mfGirderIds(); // which beams are moment-frame girders NOW — so the one that BECOMES one in this edit, by any route, can be offered its automatic shear plates' removal (mfOfferAfterEdit)
6052
6638
  try{fn();}
6053
6639
  catch(err){
6054
6640
  if(err&&err.name==='V2CommandError'){
@@ -6070,7 +6656,7 @@ function edit(fn){
6070
6656
  try{apply(pv,true);}catch(restoreErr){console.error('steel: restoring the pre-edit model after a refused edit failed; repainting the current model instead',restoreErr);render();}
6071
6657
  toast(text);return false;}
6072
6658
  throw err;}
6073
- pushUndo(pv);render();sync3D();return true;}
6659
+ pushUndo(pv);mfOfferAfterEdit(girdersBefore);render();sync3D();return true;}
6074
6660
  // The common engine owns gesture lifecycle and immutable authoring intents; Steel remains the provider
6075
6661
  // that validates and mutates its contract. `runSteelAuthoring` is deliberately the only bridge between
6076
6662
  // the two: shared code never learns about members, sheets, connections or the undo snapshot shape.
@@ -6154,11 +6740,21 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
6154
6740
  // serverEtag here is right, and why it must be re-stamped when a write lands.
6155
6741
  // The root grid rides in the draft with the rest of the native document. Omitting it would lose an
6156
6742
  // unsaved grid edit on reload or when the server version moves.
6157
- function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
6158
- members:C.members,
6159
- grid:C.grid,
6160
- custom_details:C.custom_details, profile_colors:C.profile_colors, member_styles:C.member_styles, member_types:C.member_types, target_confidence:C.target_confidence, dims3d:C.dims3d, dim_overlays:C.dim_overlays, dim_style:C.dim_style, prop_labels:C.prop_labels, joints:C.joints, connections:C.connections, detail_placements:C.detail_placements, views:C.views, reference_models:C.reference_models,
6161
- plans:C.plans}));return true;}catch(e){setSaved('err');console.error('local autosave failed',e);return false;}}
6743
+ // THE ROOT KEYS A BROWSER DRAFT CARRIES — one list, read by persist() (what is written) AND applyDraftFields() (what comes
6744
+ // back). They were two hand-kept lists, and a root key one of them forgot was lost silently: an edit pending at a reload, after
6745
+ // a refused save, or behind "Show my earlier edits" simply did not come back. The annotation roots the undo snapshot records
6746
+ // (`ANNOTATION_ROOT_KEYS`: the moment-frame schedule, detail bubbles) ride along by construction, so the next one added there
6747
+ // cannot be forgotten here (#2210 review). `reference_models` and `plans` are written below and restored by their own rules.
6748
+ function draftRootKeys(){return ['members','grid','custom_details','profile_colors','member_styles','member_types','target_confidence','dims3d','dim_overlays','dim_style','prop_labels','joints','connections','detail_placements','views',...((V2Commands&&V2Commands.ANNOTATION_ROOT_KEYS)||[])];}
6749
+ // Set once the person changes or resets the "columns below a floor" setting on this page, or a restored draft carried a Reset.
6750
+ let reachTouched=false;
6751
+ function persist(){try{const draft={sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active};
6752
+ // `column_below_reach_mm` is saved as `null` when the model has none AND the person touched it: a missing key in a draft means
6753
+ // "not touched", so a Reset (the key taken away) would otherwise come back from the server's copy on the next restore. A model
6754
+ // nobody touched writes no key, so its draft keeps master's bytes (#2209's recorded traces pin them).
6755
+ for(const k of draftRootKeys())draft[k]=(k==='column_below_reach_mm'&&C[k]===undefined&&reachTouched)?null:C[k];
6756
+ draft.reference_models=C.reference_models;draft.plans=C.plans; // last, as before #2210: the written draft keeps its byte order
6757
+ localStorage.setItem(LSKEY,JSON.stringify(draft));return true;}catch(e){setSaved('err');console.error('local autosave failed',e);return false;}}
6162
6758
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
6163
6759
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
6164
6760
  // fetch does NOT reject on HTTP 400 (schema rejection), so treat !res.ok as 'err' (not a false 'Saved ✓'). ---
@@ -6193,7 +6789,7 @@ function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),
6193
6789
  * No auto-retry: an unchanged request would be refused identically.
6194
6790
  */
6195
6791
  function showSaveRefusedBanner(){
6196
- showAiUpdateBanner('FloLess couldn’t save that change. Reload and try again — if it keeps happening, please report it.');
6792
+ showAiUpdateBanner('FloLess couldn’t save that change. Reload the page and try again. If it keeps happening, please report it.');
6197
6793
  }
6198
6794
  function showConflictBanner(){
6199
6795
  showAiUpdateBanner(
@@ -6205,6 +6801,7 @@ function showConflictBanner(){
6205
6801
  // instead of re-applying them, so the reason for throwing away the user's only copy is gone.
6206
6802
  onReload: () => { location.reload(); },
6207
6803
  onOverwrite: confirmOverwrite,
6804
+ onSeeChanges: seeChangesFromOpenTab, // #2209 - the ONLY addition here: a read-only list of what the other writer changed. Nothing above or below it changed.
6208
6805
  });
6209
6806
  }
6210
6807
 
@@ -6370,6 +6967,7 @@ async function persistServer(force,token){const seq=saveSeq;
6370
6967
  else if(serverEtag)headers['if-match']=serverEtag;
6371
6968
  else headers['if-none-match']='*';
6372
6969
  const sentDecided=decidedMembers(C.members); // what this write will make the server hold, if it commits without a transformed reply
6970
+ const sentCopy=lastSeenText(C); // #2209 - the model this write carries, taken in the SAME tick as the body below; kept only if the reply proves it was published as sent
6373
6971
  const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+PROJECT_QS,{method:'PUT',headers,body:JSON.stringify(C)});
6374
6972
  // A REFUSED write produces no broadcast, so its id would sit in ownWrites forever — where the only
6375
6973
  // thing it can still do is wrongly suppress somebody else's event. Released on every leg below.
@@ -6391,7 +6989,7 @@ async function persistServer(force,token){const seq=saveSeq;
6391
6989
  // write is usually still in flight — the server broadcasts before it replies — so releasing here would
6392
6990
  // make the tab read its OWN echo as external and reload itself mid-edit. The id is released when the
6393
6991
  // echo consumes it, when the write fails, or when the SSE channel closes (nothing can echo after that).
6394
- if(res.ok){let d={},bodyReadable=true;try{d=await res.json();}catch(_){bodyReadable=false;}const t=d.etag||res.headers.get('ETag');if(d.contract&&t&&Number.isSafeInteger(d.storeRevision))adoptSaveReply(d.contract,t,d.storeRevision,seq);else{if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}if(Number.isSafeInteger(d.storeRevision))serverRevision=Math.max(serverRevision,d.storeRevision);serverDecided=sentDecided;if(seq!==saveSeq)reconcileDecisions();}conflicted=false;
6992
+ if(res.ok){let d={},bodyReadable=true;try{d=await res.json();}catch(_){bodyReadable=false;}const t=d.etag||res.headers.get('ETag');if(d.contract&&t&&Number.isSafeInteger(d.storeRevision))adoptSaveReply(d.contract,t,d.storeRevision,seq);else{if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}if(Number.isSafeInteger(d.storeRevision))serverRevision=Math.max(serverRevision,d.storeRevision);serverDecided=sentDecided;if(seq!==saveSeq)reconcileDecisions();}conflicted=false;lastSeenCommitOwnSave(t,d,bodyReadable,sentCopy);
6395
6993
  // The write COMMITTED. Apply its revalidation report ONLY when we can prove it describes the live `C`:
6396
6994
  // the body was readable AND `seq===saveSeq` (no newer edit landed while this PUT was in flight). Otherwise
6397
6995
  // do NOTHING — no merge, no bookkeeping. That is safe because a joint whose removal we then miss is
@@ -6451,7 +7049,7 @@ async function flushContractWith(token, signal) {
6451
7049
  let adoptedTag = null; // the tag THIS write produced, reported back for the sign-off's precondition
6452
7050
  let publishedGeneration = modelEditGeneration;
6453
7051
  const tagAtSend = serverEtag;
6454
- let res, sentDecided = serverDecided;
7052
+ let res, sentDecided = serverDecided, sentCopy = null; // sentCopy: see persistServer (#2209)
6455
7053
  try {
6456
7054
  // Conditional like every other write, and it MUST refresh the tag on success. Getting this wrong is
6457
7055
  // not theoretical — the first cut omitted both, so an Approve-time flush bypassed the precondition
@@ -6464,6 +7062,7 @@ async function flushContractWith(token, signal) {
6464
7062
  // document this PUT actually carried — not one an edit produced while the request was in flight.
6465
7063
  publishedGeneration = modelEditGeneration;
6466
7064
  sentDecided = decidedMembers(C.members); // same moment, same reason — see persistServer
7065
+ sentCopy = lastSeenText(C); // …and the copy the reply may prove
6467
7066
  res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C), signal });
6468
7067
  } catch (e) {
6469
7068
  if(signal&&signal.aborted){quarantineMutation(mid, seq);throw e;}
@@ -6490,7 +7089,7 @@ async function flushContractWith(token, signal) {
6490
7089
  showConflictBanner();
6491
7090
  throw new Error('save conflict');
6492
7091
  }
6493
- if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } if(signal&&signal.aborted)quarantineMutation(mid, seq); const t = d.etag || res.headers.get('ETag'); adoptedTag = t || null; if (d.contract && t && Number.isSafeInteger(d.storeRevision)) { const generationBefore = modelEditGeneration; adoptSaveReply(d.contract, t, d.storeRevision, seq); /* #1936 - installing the reply re-bumps the generation although nothing the person looked at changed; report the post-install generation, but ONLY when nothing visible moved between the PUT and the install (a genuine concurrent edit still shows as a mismatch) */ if (generationBefore === publishedGeneration && modelEditGeneration === generationBefore + 1) publishedGeneration = modelEditGeneration; } else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); serverDecided = sentDecided; if (seq !== saveSeq) reconcileDecisions(); } conflicted = false;
7092
+ if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } if(signal&&signal.aborted)quarantineMutation(mid, seq); const t = d.etag || res.headers.get('ETag'); adoptedTag = t || null; if (d.contract && t && Number.isSafeInteger(d.storeRevision)) { const generationBefore = modelEditGeneration; adoptSaveReply(d.contract, t, d.storeRevision, seq); /* #1936 - installing the reply re-bumps the generation although nothing the person looked at changed; report the post-install generation, but ONLY when nothing visible moved between the PUT and the install (a genuine concurrent edit still shows as a mismatch) */ if (generationBefore === publishedGeneration && modelEditGeneration === generationBefore + 1) publishedGeneration = modelEditGeneration; } else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); serverDecided = sentDecided; if (seq !== saveSeq) reconcileDecisions(); } conflicted = false; lastSeenCommitOwnSave(t, d, bodyReadable, sentCopy);
6494
7093
  // The flush committed. Same rule as persistServer: apply the report only when the body was readable and
6495
7094
  // `seq===saveSeq` (Approve awaits this flush, so the user CAN edit meanwhile and make it stale). Otherwise
6496
7095
  // do nothing — the next save re-introduces any joint whose removal we missed, and the server re-decides it.
@@ -6585,7 +7184,7 @@ function reconcileReferences(server,draft){
6585
7184
  */
6586
7185
  function applyDraftFields(d){
6587
7186
  const candidate=structuredClone(C);
6588
- const rootKeys=['members','grid','custom_details','profile_colors','member_styles','member_types','target_confidence','dims3d','dim_overlays','dim_style','prop_labels','joints','connections','detail_placements','views'];
7187
+ const rootKeys=draftRootKeys();
6589
7188
  // A draft is unvalidated localStorage, and this restore runs AFTER the boot-time sanitise — so a raw
6590
7189
  // copy re-introduces exactly the shapes the sanitisers exist to prevent, one link past the guard.
6591
7190
  // `prop_labels` was wired for that reason (#614) and the others were not (#851): `sanitizeConnections`
@@ -6650,6 +7249,12 @@ function applyDraftFields(d){
6650
7249
  // autosave. The renderer already tolerates junk tokens (`memberLineStyle` falls back per token), so
6651
7250
  // nothing downstream needed the clamp either. (Codex, #853.)
6652
7251
  member_styles:rec,
7252
+ // The schema types these two roots (an array, a record) and nothing else, so that is all a draft is held to: a stored
7253
+ // frame is never re-validated (the legacy row passes through untouched), and a wrong-typed root is left alone.
7254
+ moment_frames:arr,
7255
+ detail_bubbles:rec,
7256
+ // The project's reach setting: a legal number, or `null` meaning "the model has none" (a Reset). Anything else is a malformed draft value.
7257
+ column_below_reach_mm:v=>(v===null||SteelCore.isValidColumnBelowReach(v))?v:undefined,
6653
7258
  // canonicalise axisDir (SteelCore, resolved at call time — boot() awaits the module before main()),
6654
7259
  // then let $defs.dim3 itself reject the rows it cannot hold: id/a/b/axis are required, id is
6655
7260
  // minLength 1, axis is an enum and the row is additionalProperties:false, NONE of which
@@ -6677,6 +7282,7 @@ function applyDraftFields(d){
6677
7282
  if(clean&&Array.isArray(raw)&&Array.isArray(candidate[key])&&candidate[key].length<raw.length)
6678
7283
  console.warn('steel-editor: dropped '+(raw.length-candidate[key].length)+' unusable '+key+' row(s) restoring the browser draft — the rest of the draft was kept');
6679
7284
  }
7285
+ if(candidate.column_below_reach_mm===null){delete candidate.column_below_reach_mm;reachTouched=true;} // the draft's way of saying "none": take the key away, and keep saying it
6680
7286
  // Louder than a dropped row, because a whole collection did not come back: whatever the user changed
6681
7287
  // under these keys is not on screen, and the document's version is showing in its place.
6682
7288
  if(unusableRoots.length)
@@ -6750,16 +7356,17 @@ function applyDraftFields(d){
6750
7356
  *
6751
7357
  */
6752
7358
  function showStaleDraftBanner(d){
6753
- showAiUpdateBanner('This model has changed since you last edited it here — you’re viewing the current version. Your edits from before are still saved on this computer.',{
7359
+ showAiUpdateBanner('This model was changed after you last worked on it, and you’re now looking at the newest version. Your earlier edits are still saved on this computer.',{
6754
7360
  kind:'staleBase',
6755
- reloadLabel:'View my edits instead',
6756
- reloadTip:'Switch to the changes you made before. The version on the server won’t change unless you edit and save again.',
7361
+ onSeeChanges:seeChangesFromStaleDraft(d), // #2209 - the ONLY addition to this call: a read-only list; nothing below it changed
7362
+ reloadLabel:'Show my earlier edits',
7363
+ reloadTip:'Go back to the edits you made before. The newest version is only replaced if you confirm it.',
6757
7364
  onReload:()=>{
6758
7365
  // The RETURN VALUE, which this caller used to drop on the floor. The three model-global writers are
6759
7366
  // ungated, so the user can move the document to match the draft while the bar is still up — and
6760
7367
  // rewinding `serverEtag` then arms a 412 for a restore that put nothing back.
6761
7368
  if(!applyDraftFields(d)){
6762
- toast('Those earlier edits no longer apply to this model — nothing was changed.');
7369
+ toast('Your earlier edits don’t fit this model any more, so nothing was changed.');
6763
7370
  const b0=document.getElementById('aiUpdateBanner'); if(b0)b0.remove();
6764
7371
  return;}
6765
7372
  // REWIND the tag to the one those edits were built on. Without this the next autosave would carry
@@ -6776,7 +7383,7 @@ function showStaleDraftBanner(d){
6776
7383
  // same stale base and put the bar straight back up. Deliberately no scheduleSave() — merely LOOKING
6777
7384
  // at the old edits must not fire a write (and a conflict banner) on their behalf.
6778
7385
  render();sync3D();
6779
- toast('Showing your earlier edits — not yet saved to the server.');
7386
+ toast('Showing your earlier edits. They are only saved on this computer so far.');
6780
7387
  },
6781
7388
  });
6782
7389
  }
@@ -8100,14 +8707,12 @@ function gridReadFromDrawing(keep){
8100
8707
  // PDF and PUTs the labels back as a contract revision.
8101
8708
  function gridAskAiLabels(){
8102
8709
  const geo=gridGeo();if(!geo)return;
8103
- const t=document.getElementById('askAiText');
8710
+ const t={};
8104
8711
  t.value='Read the structural grid bubble labels on '+(viewLabel(P)||P.sheet)+' from the source drawing and set them on the model grid. '
8105
8712
  +'Write each name to its axis row as grid.axes[].label — that is what the bubbles print and what sheet registration matches — and mirror the same tokens into grid.labels_x / grid.labels_y. '
8106
8713
  +'The grid line positions are already detected: '+geo.v.length+' X lines (labels run left→right) and '+geo.h.length+' Y lines (labels run bottom→up). '
8107
8714
  +'Give each as whitespace-separated tokens in that order, exactly as printed on the bubbles (e.g. "K J H G F.2 F D C B A").';
8108
- if(typeof askAiSetMode==='function')askAiSetMode('modify');
8109
- if(typeof askAiSyncSend==='function')askAiSyncSend();
8110
- askAiOpen();}
8715
+ askAiOpen({mode:'modify',text:t.value});} // askAiOpen sets the mode and keeps anything already typed; setting them BEFORE it was undone by its own reset to a question
8111
8716
  function gridDefaultOrigin(){const xs=[],ys=[];for(const m of ((P&&P.members)||[]))if(Array.isArray(m.wp)&&m.wp.length>=2){xs.push(m.wp[0][0],m.wp[1][0]);ys.push(m.wp[0][1],m.wp[1][1]);}
8112
8717
  if(xs.length)return [Math.min(...xs),Math.max(...ys)]; // bottom-left of the steel
8113
8718
  return [(typeof X0==='number'?X0:0)+50,(typeof Y1==='number'?Y1:300)-50];} // empty plan → near the sheet corner
@@ -8140,9 +8745,147 @@ function updatePlanDims(fn){
8140
8745
  V2_SESSION.patchPlan(viewIdOf(P),{dims});
8141
8746
  return true;}
8142
8747
  function updatePlanDim(id,fn){return updatePlanDims(dims=>{const d=dims.find(row=>row&&row.id===id);if(d)fn(d);});}
8748
+ /* Delete on a selection that includes columns this sheet draws only because of the floor level it states (the cut
8749
+ passes through them, or they end just under it, #2214): those are not this sheet's to remove, so they STAY, and
8750
+ saying so plainly matters more than the number of things that went. The old toast ("crossing", "cut", "no
8751
+ geometry was deleted") was jargon, and false for a mixed selection: the members that were not derived ARE deleted
8752
+ in the same step. Counts both, and says why nothing on the sheet can be deleted for the ones that stayed. */
8753
+ function deleteStayedText(stayed,deleted){
8754
+ const n=stayed,one=n===1,col=one?'1 column stays':n+' columns stay';
8755
+ const why='This sheet draws '+(one?'it':'them')+' from its floor level';
8756
+ const tail=' Hiding a column on just one sheet isn’t available yet.';
8757
+ if(deleted>0)return 'Deleted '+deleted+' member'+(deleted===1?'':'s')+'. '+col+': '+why.charAt(0).toLowerCase()+why.slice(1)+'.'+tail;
8758
+ return col+'. '+why+', so there is nothing on the sheet to delete.'+tail;
8759
+ }
8760
+ /** The members among `ids` that THIS 2D sheet draws only because of the floor level it states (the cut passes through
8761
+ them, or they end just under it): not observed, not in memberRefs. There is no such thing in 3D, which has no sheet. */
8762
+ function sheetDerivedIds(ids,presence){
8763
+ const plan=C&&C.plans&&C.plans[C.active];
8764
+ if(view3d||!plan||plan.viewKind!=='plan'||NO_PLAN_VIEW||!V2Projection)return [];
8765
+ const byMemberId=presence?presence.members:new Map();if(!presence)for(const x of C.members||[])if(x&&!byMemberId.has(x.id))byMemberId.set(x.id,x);
8766
+ return [...new Set(ids)].filter(id=>{
8767
+ const m=byMemberId.get(id);if(!m||m.role!=='column')return false;
8768
+ const pr=V2Projection.memberPresence(C,plan,m,presence);return (pr.crossing||pr.below)&&!pr.observed&&!pr.explicit;});
8769
+ }
8770
+ /** True (and said) when a Delete asks only about columns this sheet derives: there is nothing to delete, so NO edit is
8771
+ opened at all (no empty undo step, no "unsaved" mark) and the selection stays, which keeps the explaining notice up. */
8772
+ function deleteStaysOnSheet(args){
8773
+ const ids=[...new Set(args&&args.memberIds?[...args.memberIds]:[])];
8774
+ const nothingElse=!(args&&((args.dimIds&&args.dimIds.size)||(args.jointIds&&args.jointIds.size)||(args.gridLineIds&&args.gridLineIds.size)));
8775
+ if(!ids.length||!nothingElse)return false;
8776
+ const derived=sheetDerivedIds(ids),derivedSet=new Set(derived);
8777
+ // Held ONLY by the drawing read (and not merely derived here): Delete leaves them and ASKS (Delete anyway, owner 2026-10-12).
8778
+ const holds=heldIndex(ids),held=readHeldIds(ids,holds).filter(id=>!derivedSet.has(id));
8779
+ if(derived.length+held.length!==ids.length)return false;
8780
+ if(held.length){askToDeleteAnyway(held);toast(deleteHeldText(held,0,holds),false,7000);}
8781
+ else toast(deleteStayedText(derived.length,0),false,7000);
8782
+ return true;}
8783
+ /** The members among `ids` that ONLY the drawing read holds: the model would delete them but for the observations that name them,
8784
+ and nothing else (no connection, dimension, placed detail, brace or saved view) is attached. These are the ones Delete anyway
8785
+ can take: the command layer's own question (`deleteAnywayBlockers`), so the offer and the act cannot disagree. */
8786
+ function readHeldIds(ids,holds){
8787
+ const want=[...new Set(ids)],index=holds||heldIndex(want),have=new Set((C.members||[]).map(m=>m&&m.id));
8788
+ return want.filter(id=>have.has(id)&&V2Commands.heldOnlyByRead(index.get(id)||[]));}
8789
+ /** What holds each of these members, for all of them from ONE walk of the model (id -> blockers). Build it once per refresh or
8790
+ action and pass it on, instead of asking per member: that walked the whole model, twice, for every selected member. */
8791
+ function heldIndex(ids){return V2_SESSION.deleteBlockerIndex([...new Set(ids)]);}
8792
+ /** Members a Delete just left because the read holds them; the Inspector offers Delete anyway for the ones still selected. */
8793
+ let deleteAsk=new Set();
8794
+ /** The same, for the delete that is running: once the rest is gone the selection keeps these so the ask stays in view. */
8795
+ let deleteLeft=[];
8796
+ function askToDeleteAnyway(ids){for(const id of ids)deleteAsk.add(id);try{panel();}catch(_){}}
8797
+ /** After a Delete: nothing is selected any more, except what Delete left because the drawing read holds it. */
8798
+ function clearMembersAfterDelete(){
8799
+ modelSelection.clearMembers();
8800
+ const keep=deleteLeft.filter(id=>!!(C.members||[]).find(m=>m&&m.id===id));deleteLeft=[];
8801
+ if(keep.length)modelSelection.replaceMembers(keep);}
8802
+ /** The sheets, by the name a person knows them by, whose drawing read recorded these members. */
8803
+ function readSheetNames(ids,holds){
8804
+ const names=[],index=holds||heldIndex(ids);
8805
+ for(const id of ids)for(const b of index.get(id)||[])if(b.kind==='observation'){const n=viewNameById(b.viewId);if(!names.includes(n))names.push(n);}
8806
+ return names;}
8807
+ /** Said when Delete leaves members only the drawing read holds: which stay, why, and the way to remove them. */
8808
+ function deleteHeldText(held,deleted,holds){
8809
+ const one=held.length===1,sheets=readSheetNames(held,holds),where=sheets.length?' on '+plainList(sheets,3):'';
8810
+ return (deleted>0?'Deleted '+deleted+'. ':'')+(one?held[0]+' stays':held.length+' members stay')+': the drawing read'+where+' recorded '+(one?'it':'them')
8811
+ +'. Use Delete anyway in the panel to remove '+(one?'it':'them')+' and drop that link.';}
8812
+ /** DELETE ANYWAY: the explicit act. Removes the members the drawing read holds, drops the read's link to each and records that
8813
+ Delete anyway did, in ONE undo step. Re-asked at click time: the model may have moved since the button was drawn. */
8814
+ function deleteAnyway(ids){
8815
+ ids=readHeldIds(ids);
8816
+ if(!ids.length)return false;
8817
+ let done=false;
8818
+ runSteelAuthoring('delete',{source:'inspector',selection:ids},()=>{done=edit(()=>{V2_SESSION.deleteMembersAnyway(ids);modelSelection.clearMembers();});});
8819
+ if(done){
8820
+ for(const id of ids)deleteAsk.delete(id);
8821
+ const one=ids.length===1;
8822
+ toast('Deleted '+(one?ids[0]:ids.length+' members')+' from the model. The drawing read’s '+(one?'link to it was':'links to them were')+' dropped and noted. Ctrl+Z brings '+(one?'it':'them')+' back.',false,7000);
8823
+ try{svg.focus({preventScroll:true});}catch(_){}}
8824
+ return done;}
8825
+ /** The ask in the Inspector: what Delete anyway does, in words, and the one button. */
8826
+ function deleteAnywayRow(ids,holds){
8827
+ const row=document.createElement('div');row.className='v2-selection-notice v2-delete-anyway';row.style.marginTop='8px';
8828
+ const one=ids.length===1,sheets=readSheetNames(ids,holds),where=sheets.length?' on '+plainList(sheets,3):'';
8829
+ const msg=document.createElement('div');msg.className='hint';msg.setAttribute('role','status');msg.setAttribute('aria-live','polite');
8830
+ msg.textContent=(one?ids[0]+' was':plainList(ids,3)+' were')+' read from the drawing'+where+'. Deleting '+(one?'it':'them')+' removes the member'+(one?'':'s')+' and drops that link; the read keeps its record, with a note that it was deleted on purpose.';
8831
+ row.appendChild(msg);
8832
+ const act=document.createElement('div');act.className='row';act.style.marginTop='6px';
8833
+ const b=document.createElement('button');b.type='button';b.className='ghostw';b.setAttribute('data-command-id','steel.delete-anyway');b.setAttribute('data-delete-anyway','');
8834
+ b.dataset.tip='Removes '+(one?ids[0]:'these '+ids.length+' members')+' from the model and every sheet, and drops the drawing read’s link. Ctrl+Z undoes it.';
8835
+ b.textContent=one?'Delete anyway':'Delete '+ids.length+' anyway';
8836
+ b.onclick=()=>{deleteAnyway(ids);};keyActivates(b);
8837
+ act.appendChild(b);row.appendChild(act);
8838
+ return row;}
8839
+ /** The name a person knows a view by, from its id. */
8840
+ function viewNameById(id){const pl=(C.plans||[]).find(x=>viewIdOf(x)===id);return pl?(viewLabel(pl)||id):String(id);}
8841
+ /** In plain words what holds `count` members in the model, from their blockers: what is attached to them (delete those first) and
8842
+ the drawing read that names them. `one` = a single column is selected; `either` = the sentence follows the "Delete leaves it" one. */
8843
+ function deleteBlockedText(blockers,count,one,either){
8844
+ const uniq=kind=>{const seen=new Set();return blockers.filter(b=>b.kind===kind&&!seen.has(b.id)&&seen.add(b.id));};
8845
+ const joints=uniq('joint'),dims=uniq('dimension'),obs=uniq('observation'),has=k=>blockers.some(b=>b.kind===k);
8846
+ const placed=blockers.filter(b=>b.kind==='detail-placements').reduce((t,b)=>t+(b.count||1),0);
8847
+ const items=[];let plural=false;
8848
+ const add=(text,n)=>{items.push(text);if(n>1)plural=true;};
8849
+ if(joints.length)add(joints.length===1?(one?'its '+connKindLabel(joints[0].jointKind).toLowerCase()+' connection':'1 connection'):joints.length+' connections',joints.length);
8850
+ if(has('member-connection'))add(one?'its end connection':'an end connection',1);
8851
+ if(has('connections'))add('a connection record',1);
8852
+ if(dims.length)add(dims.length===1?'1 dimension':dims.length+' dimensions',dims.length);
8853
+ if(placed)add(placed===1?'1 placed detail':placed+' placed details',placed);
8854
+ if(has('brace'))add('a brace',1);
8855
+ if(has('views'))add('a saved view',1);
8856
+ const pron=count===1?'it':'them',many=plural||items.length>1,parts=[];
8857
+ if(items.length)parts.push(plainList(items,9)+(many?' are':' is')+' attached to '+pron);
8858
+ if(obs.length)parts.push('the drawing read'+(one?' on '+plainList([...new Set(obs.map(b=>viewNameById(b.viewId)))]):'')+' names '+pron);
8859
+ return (one?'It':count+' of them')+' can’t be deleted from the model'+(either?' either':'')+': '+parts.join(', and ')
8860
+ +(items.length?' — delete '+(many?'those':'that')+' first'+(one?' to delete the column':'')+'.':'.');
8861
+ }
8862
+ /** The explicit way out of "Delete leaves it": remove the column from the model, and so from every sheet. A column the model would
8863
+ refuse (something is attached to it, or the drawing read names it) is not offered this: the notice says what holds it, and it is
8864
+ explained here too (and left out) rather than letting the model refuse in its own words. */
8865
+ function deleteFromWholeModel(ids){
8866
+ const have=new Set((C.members||[]).map(m=>m&&m.id));
8867
+ ids=[...new Set(ids)].filter(id=>have.has(id));
8868
+ const holds=heldIndex(ids),held=ids.filter(id=>(holds.get(id)||[]).length);
8869
+ ids=ids.filter(id=>!held.includes(id));
8870
+ if(!ids.length){if(held.length)toast(deleteBlockedText(held.flatMap(id=>holds.get(id)||[]),held.length,held.length===1,false),false,7000);return false;}
8871
+ let done=false;
8872
+ runSteelAuthoring('delete',{source:'inspector',selection:ids},()=>{done=edit(()=>{V2_SESSION.deleteMembers(ids);modelSelection.clearMembers();});});
8873
+ if(done)toast((ids.length===1?'Deleted '+ids[0]:'Deleted '+ids.length+' columns')+' from the whole model: '+(ids.length===1?'it is':'they are')+' gone from every sheet. Ctrl+Z undoes it.',false,7000);
8874
+ return done;}
8143
8875
  function deleteV2Selection(args){
8144
- const effect=V2_SESSION.deleteSelection(viewIdOf(P),args),n=effect&&effect.value&&effect.value.presentationOnly?effect.value.presentationOnly.length:0;
8145
- if(n)toast(`${n} crossing column${n===1?' is':'s are'} derived from this sheet's cut and remain visible; no geometry was deleted.`);
8876
+ // From the 3D view there is no sheet to judge presence against (null), so every member is an ordinary delete.
8877
+ // Members ONLY the drawing read holds are left where they are and ASKED about (Delete anyway); the rest of the selection is deleted as
8878
+ // before. A column this sheet merely derives is the sheet rule's business (it is "presentation only" below), so it is not counted here.
8879
+ const requested=[...new Set(args&&args.memberIds?[...args.memberIds]:[])];
8880
+ const derivedHere=new Set(sheetDerivedIds(requested));
8881
+ const holds=heldIndex(requested),held=readHeldIds(requested,holds).filter(id=>!derivedHere.has(id));
8882
+ deleteLeft=held;
8883
+ if(held.length)for(const id of held)deleteAsk.add(id);
8884
+ const memberIds=held.length?new Set(requested.filter(id=>!held.includes(id))):(args&&args.memberIds);
8885
+ const effect=V2_SESSION.deleteSelection(view3d?null:viewIdOf(P),held.length?{...args,memberIds}:args),stayed=effect&&effect.value&&effect.value.presentationOnly?effect.value.presentationOnly.length:0;
8886
+ const askedN=held.length?memberIds.size:requested.length;
8887
+ if(stayed)toast(deleteStayedText(stayed,Math.max(0,askedN-stayed)),false,7000);
8888
+ if(held.length)toast(deleteHeldText(held,Math.max(0,askedN-stayed),holds),false,7000);
8146
8889
  return effect;}
8147
8890
  function renderDimStylePanel(p){
8148
8891
  const g=C.dim_style,over=(P.dims||[]).filter(dimHasOverride).length;
@@ -8373,7 +9116,7 @@ function setGeo(){document.body.classList.toggle('geo',!!geoMode);document.body.
8373
9116
  let lastCmd=null;
8374
9117
  function setLastCmd(label,run){lastCmd={label,run};}
8375
9118
  function anyToolActive(){
8376
- if(dimMode||dimChain||dimSplitMode||geoMode||csaxisMode||gridMode||gridPick||gridLinePick||dimStyleMode||mode==='add'||picking||cmTool||qdPick)return true; // 2D tools armed (cmTool = Move/Copy; qdPick = the F7 grid station pick)
9119
+ if(dimMode||dimChain||dimSplitMode||geoMode||csaxisMode||gridMode||gridPick||gridLinePick||dimStyleMode||mode==='add'||picking||cmTool||qdPick||calloutEditMode)return true; // 2D tools armed (cmTool = Move/Copy; qdPick = the F7 grid station pick)
8377
9120
  if(view3d&&window.Steel3DView){if(window.Steel3DView.clipMode&&window.Steel3DView.clipMode())return true;
8378
9121
  if(window.Steel3DView.refMeasureState&&window.Steel3DView.refMeasureState().armed)return true; // the reference measure owns the left-click too, so Space/Enter must not re-invoke the last command over it
8379
9122
  if(window.Steel3DView.connMemberPick&&window.Steel3DView.connMemberPick())return true; // the member pick owns ENTER (it confirms) — without this, Enter also fires repeatLast() and arms an unrelated tool behind the user
@@ -9045,8 +9788,27 @@ function provisionalMembersSvg(){
9045
9788
  return `<g class="provisional-member${selected}" tabindex="0" role="button" aria-pressed="${selected?'true':'false'}" aria-label="Source-view member ${esc(m.id)}. Exact source trace. Placement unresolved." data-command-id="steel.provisional-select#${esc(instance)}" data-command-instance-label="${esc(instance)}" data-provisional-id="${esc(m.id)}" data-provisional-trace="${esc(traceId)}" data-view-id="${esc(g.viewId)}" data-tip="Exact source trace — inspect its evidence and placement question"><line class="pv-hit" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}"/><line class="pv-under" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}"/><line class="pv-line" x1="${a.x}" y1="${a.y}" x2="${b.x}" y2="${b.y}"/><circle class="pv-end" cx="${a.x}" cy="${a.y}" r="5"/><circle class="pv-end" cx="${b.x}" cy="${b.y}" r="5"/><text class="pv-mark" x="${mx}" y="${my}">!</text></g>`;
9046
9789
  }).join('');
9047
9790
  }
9791
+ /* #2214 — how a column drawn BELOW this sheet's floor came to be on the sheet, and the words for it.
9792
+ `derived` = it is here only because of where it stands (no observation, no memberRefs). A column the read
9793
+ bound, or one a person added with "Add to this sheet", is PLACED: it is the sheet's own member, and Delete
9794
+ removes it like any other. Never mentions the reach: that is a drafting default, not something to learn. */
9795
+ function underFloorText(mm){return displayUnits()===DisplayUnits.MM?fmtEcho(mm):fmtDisp(mm);}
9796
+ function colBelowInfo(m){
9797
+ const plan=C&&C.plans&&C.plans[C.active],canon=((C&&C.members)||[]).find(x=>x&&x.id===m.id);
9798
+ if(!plan||!canon)return null;
9799
+ const pres=V2Projection.memberPresence(C,plan,canon),derived=!pres.observed&&!pres.explicit;
9800
+ const za=canon.from&&canon.from.z&&canon.from.z.known,zb=canon.to&&canon.to.z&&canon.to.z.known,cut=plan.elevation_mm;
9801
+ const under=(Number.isFinite(za)&&Number.isFinite(zb)&&Number.isFinite(cut))?cut-Math.max(za,zb):null;
9802
+ const ends=under!==null&&under>0?' It ends '+underFloorText(under)+' under it.':'';
9803
+ return {derived,under,tip:'Column below this floor.'+ends+(derived?' Drawn here from the floor level.':' Placed on this sheet.')};
9804
+ }
9048
9805
  function render(){
9049
9806
  const profileFocusToken=profilePickerFocusToken();
9807
+ // Arming ANY other tool ends the + Callout tool. Every tool arm ends in a render(), so this one line covers them
9808
+ // all, instead of a disarm call at every arm site (and the next tool added needs no edit here).
9809
+ if(calloutEditMode&&(mode!=='sel'||dimMode||dimChain||dimSplitMode||csaxisMode||gridMode||gridPick||gridLinePick||dimStyleMode||cmTool||picking||geoMode||qdPick||view3d||NO_PLAN_VIEW)){
9810
+ calloutEditMode=false;document.body.classList.remove('calloutedit');closeCalloutForm();}
9811
+ syncCalloutButton();
9050
9812
  reflectTakeoverButtons();
9051
9813
  /* The Instructor's second publish trigger, and the one that catches what input
9052
9814
  events cannot: an arm or disarm inside a PROMISE callback (an async contract
@@ -9084,12 +9846,19 @@ function render(){
9084
9846
  if(m.role==='column'){const pts=columnSectionPoly(m); // a column draws as its profile-section footprint, not a line
9085
9847
  // A placeholder footprint on a member that is NOT an RFI reads as a real, small section — the size is
9086
9848
  // the one thing on this canvas it cannot be trusted for, so it says so rather than looking resolved.
9087
- const _ph=(pts&&pts.placeholder&&!rfi)?` data-tip="Footprint shown as a placeholder — the ${_catalogLabel()} table gives no footprint for this shape. Its weight and length are still exact."`:'';
9088
- 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;}}
9849
+ const _phText=(pts&&pts.placeholder&&!rfi)?`Footprint shown as a placeholder — the ${_catalogLabel()} table gives no footprint for this shape. Its weight and length are still exact.`:'';
9850
+ // #2214: a column that ends under this sheet's floor is drawn dashed and lighter. It has ONE tooltip, so the
9851
+ // below-the-floor sentence and the placeholder sentence are composed rather than competing attributes.
9852
+ const _cb=m.belowCut?colBelowInfo(m):null;
9853
+ const _tipText=[_cb&&_cb.tip,_phText].filter(Boolean).join(' ');
9854
+ const _ph=_tipText?` data-tip="${esc(_tipText)}"`:'';
9855
+ if(pts){const components=pts.components||[pts];s+=components.map((part,index)=>`<polygon class="member${rfi?' rfi':''}${m.belowCut?' colbelow':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" data-part="${index}" points="${_polyStr(part)}" fill="${c}" stroke="${c}"${g}${_ph}/>`).join('');continue;}}
9089
9856
  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.
9090
9857
  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};stroke-linecap:butt;`:''; /* butt WITH a dash: line.member's round cap adds half the stroke width at EACH end of every dash, so at thick (9px) it ate every gap — dashed 14/8 and dotted 2/8 both left -1px of gap and drew solid. Round caps stay on solid lines, where they have nothing to close. */ // RFI keeps its semantic 10 6 dash
9091
9858
  const _sty=(_fx||_sw||_sd)?` style="${_fx}${_sw}${_sd}"`:'';
9092
- s+=`<line class="member${rfi?' rfi':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" x1="${m.wp[0][0]}" y1="${m.wp[0][1]}" x2="${m.wp[1][0]}" y2="${m.wp[1][1]}" stroke="${c}"${_sty}/>`;}
9859
+ // A column below the floor whose footprint cannot be built falls to this line, and must still say what it is (#2214).
9860
+ const _lcb=(m.role==='column'&&m.belowCut)?colBelowInfo(m):null,_lt=_lcb?` data-tip="${esc(_lcb.tip)}"`:'';
9861
+ s+=`<line class="member${rfi?' rfi':''}${_lcb?' colbelow':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}"${_lt} x1="${m.wp[0][0]}" y1="${m.wp[0][1]}" x2="${m.wp[1][0]}" y2="${m.wp[1][1]}" stroke="${c}"${_sty}/>`;}
9093
9862
  {const hsel=sel2d().filter(visible2d);if(hsel.length>=1){const HR=epR();for(const sm of hsel)for(let i=0;i<2;i++) s+=`<circle class="handle ${i===0?'ep-start':'ep-end'}" data-mid="${sm.id}" data-h="${i}" cx="${sm.wp[i][0]}" cy="${sm.wp[i][1]}" r="${HR}"/>`;}} // end 1 (start) yellow, end 2 (end) magenta · shown for every selected member · radius grows with zoom (epR) so it stays visible against the thick line
9094
9863
  if(mode==='add'||(picking&&pickKind==='profile')){
9095
9864
  const armed=picking&&pickKind==='profile';profileLabelState=profileLabelQuery(armed);
@@ -9106,17 +9875,10 @@ function render(){
9106
9875
  // data-co-sheet drives the smart jump (loaded plan → switch; else data-co-prev → detail lightbox).
9107
9876
  // hidden while a sub-tool is armed (dim-split / geo extend-trim-split) so the bubbles never distract
9108
9877
  // or shadow a tool click — those handlers run earlier in pointerdown, but don't draw navigables mid-tool.
9109
- if(calloutsVisible&&mode==='sel'&&!picking&&!dimMode&&!csaxisMode&&!dimSplitMode&&!geoMode){
9110
- const sheetLoaded=sh=>!!sh&&C.plans.some(p=>p.sheet&&p.sheet.toUpperCase()===String(sh).toUpperCase());
9111
- // honest destination hint: loaded → no suffix (jumps); a resolvable preview → "(lightbox)"; else "(not loaded)".
9112
- const hint=(sh,prev)=>sheetLoaded(sh)?'':(prev&&previewFor(prev)?' (lightbox)':' (not loaded)');
9113
- const cob=(kc,mark,disp,sheet,prev,tip)=>`<g class=cohot data-co-sheet="${esc(sheet||'')}" data-co-prev="${esc(prev||'')}"><title>${esc(tip)}</title><circle class="cobub k-${kc}" cx="${disp[0]}" cy="${disp[1]}" r="11"/><text class=cotx x="${disp[0]}" y="${disp[1]}">${esc(String(mark==null?'':mark).slice(0,3))}</text></g>`;
9114
- for(const d of (P.details||[])){if(!Array.isArray(d.disp))continue;const sh=sheetOf(d.text),nu=numOf(d.text);
9115
- s+=cob('detail',nu||d.text,d.disp,sh,d.text,'Detail '+(nu||d.text||'')+(sh?' → '+sh:'')+hint(sh,d.text));}
9116
- for(const co of (P.callouts||[])){if(!Array.isArray(co.disp))continue;const sh=co.target&&co.target.sheet,nu=co.target&&co.target.number;
9117
- const kc=co.kind==='section'?'section':co.kind==='elevation'?'elev':'detailref';const kl=co.kind==='section'?'Section':co.kind==='elevation'?'Elevation':'Detail ref';
9118
- const prev=(nu&&sh)?(nu+'-'+sh):(co.text||'');
9119
- s+=cob(kc,co.text||nu,co.disp,sh,prev,kl+' '+(co.text||nu||'')+(sh?' → '+sh:'')+hint(sh,prev));}
9878
+ // While the + Callout tool is armed the marks are drawn even when Display ▸ Callouts is off (without flipping that
9879
+ // toggle): a tool that edits marks you cannot see would be a trap. Every other sub-tool still hides them.
9880
+ if((calloutsVisible||calloutEditMode)&&mode==='sel'&&!picking&&!dimMode&&!csaxisMode&&!dimSplitMode&&!geoMode){
9881
+ s+=calloutBubblesSvg();
9120
9882
  }
9121
9883
  // numbered badges on the selected members (1..N left→right then bottom→up, see orderForSelectionBadges; coincident ones fan out so duplicates are countable)
9122
9884
  // sized in 1/zoom units → constant on screen at any zoom (updateBadges keeps them in sync while zooming)
@@ -9137,7 +9899,7 @@ function render(){
9137
9899
  // `profs` and `detTexts()` live — so the combobox offers the same list with no mirror to keep filled.
9138
9900
  // Deleting the elements while these two writes stayed made render() throw on null here, which also
9139
9901
  // killed every call after it on this line (stats/panel/upd*/syncDisplayRows). Measured in Chromium.
9140
- svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updRegistration(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows(); syncUnitsRow();syncEnvChip();restoreProfilePickerFocus(profileFocusToken);if(typeof askAiRefreshSelection==='function')askAiRefreshSelection();
9902
+ svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updRegistration(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncReachRow(); syncDisplayRows(); syncUnitsRow();syncEnvChip();restoreProfilePickerFocus(profileFocusToken);if(typeof askAiRefreshSelection==='function')askAiRefreshSelection();
9141
9903
  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()).
9142
9904
  if(view3dShown&&window.Steel3DView){updateIsolateBtn();if((selIds.size||selGridIds.size)&&modelEditor.steel.selectedClips&&modelEditor.steel.selectedClips().length)modelEditor.steel.setSelectedClips([]);} // canonical commits keep member + grid highlight in sync; selecting geometry still clears clip-tool selection (exclusive)
9143
9905
  syncLegendToPane(); // the Objects list: the selection, and in 2D the sheet it lists
@@ -9176,7 +9938,8 @@ function updRegistration(){
9176
9938
  const pill=document.getElementById('regStat'),count=document.getElementById('regCount');
9177
9939
  if(pill&&count){count.textContent=String(regRefusals.length);pill.hidden=regRefusals.length===0;
9178
9940
  if(!regRefusals.length&&reviewFlyKind==='registration')closeReviewFly();}
9179
- paintRegBanner();}
9941
+ paintRegBanner();
9942
+ paintCutBanner();} // #2214: AFTER the registration notice, because that one wins when both would show
9180
9943
  /** The active sheet's banner. Reads the memoised `_planXfCache.refusal` rather than transforming again —
9181
9944
  render() already asked planRegistration() for this exact key. */
9182
9945
  function paintRegBanner(){
@@ -9272,6 +10035,171 @@ function regLeadText(sheet,refusal){
9272
10035
  +'Nothing is wrong — this part of the read is simply not finished.';}
9273
10036
  return name+' states a registration that does not hold: its two registration points do not agree with the grid lines they name, '
9274
10037
  +'so steel taken off this sheet would be metres out of place. No steel is placed on it until that is corrected.';}
10038
+ /* ══ #2214 — A PLAN WITH NO FLOOR LEVEL ═══════════════════════════════════════════════════════════════════════
10039
+ A plan view with no `elevation_mm` has no cut plane, so no column is placed on it by its height: the sheet draws
10040
+ the columns the read bound and nothing else (on Take 5's roof plan, none of 26). Silence was the failure: a column
10041
+ that is in the model and in 3D is simply absent from the sheet it belongs to. So the sheet says so, in plain
10042
+ words, and offers the two things a detailer can do about it: state the level (typed in the project's units, with a
10043
+ live reading of what it would draw) or place the columns by hand. Both go through `edit()`, so both are undoable;
10044
+ undo takes `elevation_mm` away again rather than leaving a zero (ANNOTATION_PLAN_KEYS). Nothing is hidden for good:
10045
+ "Not now" folds the notice into a small label for this page session and the condition stays visible. */
10046
+ const cutPutAway=new Set(); // views whose notice was folded away with "Not now": this page session only, never saved
10047
+ const cutOpened=new Set(); // views whose QUIET label the person opened into the full notice, likewise
10048
+ let cutPaintKey='',cutFormView=null;
10049
+ /** The active plan view's columns and how many of them it draws. null unless this is a plan view. */
10050
+ function sheetColumns(){
10051
+ const plan=C&&C.plans&&C.plans[C.active];
10052
+ if(!plan||plan.viewKind!=='plan'||NO_PLAN_VIEW||!V2Projection)return null;
10053
+ const cols=(C.members||[]).filter(m=>m&&m.role==='column');
10054
+ const hidden=cols.filter(m=>!V2Projection.memberPresence(C,plan,m).visible);
10055
+ return {plan,cols,hidden,shown:cols.length-hidden.length};
10056
+ }
10057
+ /* What the notice is about, or null when there is nothing to say:
10058
+ 'no-level' the sheet states no floor level and some column is not drawn on it;
10059
+ 'quiet' it states none, but every column is drawn (placed by hand): only a small label remains, because the
10060
+ sheet is still without a level and "Show all columns here" must not make that invisible;
10061
+ 'no-reach' it states a level, the model has columns, and NONE of them is drawn: a level that reaches nothing
10062
+ (bare `8839` in a metric project is 8 839 m) is accepted, and must not then go unmentioned. */
10063
+ function cutNoticeFor(){
10064
+ const st=sheetColumns();if(!st||!st.cols.length)return null;
10065
+ // ONE stage notice at a time, and the registration one wins: a sheet whose registration is refused draws nothing
10066
+ // at all, so a floor level is not what it is missing.
10067
+ if((P&&P.registrationRefusal)||provisionalMembersForActiveView().length)return null;
10068
+ if(!Number.isFinite(st.plan.elevation_mm))return {...st,kind:st.hidden.length?'no-level':'quiet'};
10069
+ return st.shown===0?{...st,kind:'no-reach'}:null;
10070
+ }
10071
+ function levelExample(){return displayUnits()===DisplayUnits.MM?`+8.839 · 8.839 m · 8839 mm`:`29'-0" · 29' · 8839 mm`;}
10072
+ function cutLeadText(name,total,shown){
10073
+ const head=name+' has no floor level, so FloLess can’t tell which columns belong on it. ';
10074
+ if(shown===0)return head+(total===1?'The model has 1 column and this sheet does not show it.':'The model has '+total+' columns; this sheet shows none of them.');
10075
+ return head+'The model has '+total+' columns; this sheet shows '+shown+' of them.';
10076
+ }
10077
+ function cutNoticeText(st,name){
10078
+ if(st.kind==='no-level')return {lead:cutLeadText(name,st.cols.length,st.shown),cta:'A level draws the columns that reach it. Show all places every column here by hand.',enter:'Enter a level…',pill:name+' has no floor level'};
10079
+ if(st.kind==='quiet')return {lead:name+' has no floor level. '+(st.cols.length===1?'Its column is':'Its '+st.cols.length+' columns are')+' drawn because '+(st.cols.length===1?'it was':'they were')+' placed on it by hand.',cta:'A level also draws the columns that reach it.',enter:'Enter a level…',pill:name+' has no floor level'};
10080
+ const level=fmtDispElev(st.plan.elevation_mm);
10081
+ return {lead:name+' is at '+level+' and no column reaches it. The model has '+st.cols.length+' column'+(st.cols.length===1?'':'s')+'.',cta:'Check the level, or place the columns by hand. Show all places every column here by hand.',enter:'Change level…',pill:'No column reaches '+name+'’s level'};
10082
+ }
10083
+ function paintCutBanner(){
10084
+ const bar=document.getElementById('cutBanner'),pill=document.getElementById('cutPill');if(!bar||!pill)return;
10085
+ const st=cutNoticeFor();
10086
+ if(!st){bar.classList.remove('on');pill.classList.remove('on');closeCutForm(false);cutPaintKey='';return;}
10087
+ const viewId=viewIdOf(P),name=viewLabel(P)||'This sheet';
10088
+ // A quiet sheet shows its label until the person opens it; the others show the notice until the person puts it away.
10089
+ const away=st.kind==='quiet'?!cutOpened.has(viewId):cutPutAway.has(viewId);
10090
+ if(cutFormView&&cutFormView!==viewId)closeCutForm(false); // a half-typed level belongs to the sheet it was typed for
10091
+ // Text only when it CHANGED. The notice is an atomic live region: rewriting it with the same words on every
10092
+ // repaint would have a screen reader read it out again each time anything on the sheet moved.
10093
+ const words=cutNoticeText(st,name),key=viewId+'|'+st.kind+'|'+words.lead+'|'+st.hidden.length;
10094
+ if(key!==cutPaintKey){cutPaintKey=key;
10095
+ document.getElementById('cutLead').textContent=words.lead;
10096
+ document.getElementById('cutCta').textContent=words.cta;
10097
+ document.getElementById('cutEnterBtn').textContent=words.enter;
10098
+ const show=document.getElementById('cutShowBtn');
10099
+ show.hidden=st.hidden.length===0;
10100
+ show.dataset.tip='Places '+(st.hidden.length===1?'the missing column':'every missing column')+' on this sheet by hand. They stay even if you set a level later.';
10101
+ pill.textContent=words.pill;
10102
+ pill.dataset.tip=st.kind==='no-reach'?'No column reaches this sheet’s floor level. Open the notice.':'This sheet has no floor level. Open the notice.';}
10103
+ bar.classList.toggle('on',!away);pill.classList.toggle('on',away);
10104
+ placeRegBanner(away?pill:bar);
10105
+ }
10106
+ function openCutForm(){
10107
+ const st=cutNoticeFor();if(!st)return;
10108
+ const inp=document.getElementById('cutInput');
10109
+ document.getElementById('cutForm').hidden=false;
10110
+ document.getElementById('cutEnterBtn').setAttribute('aria-expanded','true');
10111
+ document.getElementById('cutFormLabel').textContent='Floor level of '+(viewLabel(P)||'this sheet');
10112
+ inp.value='';inp.placeholder=levelExample().split(' · ')[0];cutFormView=viewIdOf(P);
10113
+ cutFormFeedback('banner');inp.focus();
10114
+ }
10115
+ function closeCutForm(returnFocus){
10116
+ const form=document.getElementById('cutForm');if(!form)return;
10117
+ const was=!form.hidden;form.hidden=true;cutFormView=null;
10118
+ const btn=document.getElementById('cutEnterBtn');if(btn)btn.setAttribute('aria-expanded','false');
10119
+ if(was&&returnFocus&&btn)btn.focus();
10120
+ }
10121
+ /** The three elements of a floor-level form: the banner's, or the Inspector's (the same parser, reading and count). */
10122
+ function cutEls(which){
10123
+ const $=id=>document.getElementById(id);
10124
+ return which==='inspector'?{inp:$('flInput'),echo:$('flEcho'),stat:$('flStatus')}:{inp:$('cutInput'),echo:$('cutEcho'),stat:$('cutStatus')};
10125
+ }
10126
+ /** What the typed level reads as, and how many columns it would draw. Returns the millimetres, or null while it is unreadable. */
10127
+ function cutFormFeedback(which){
10128
+ const st=sheetColumns(),els=cutEls(which||'banner'),inp=els.inp,echo=els.echo,stat=els.stat;
10129
+ if(!st||!inp)return null;
10130
+ const typed=inp.value.trim();stat.classList.remove('bad');
10131
+ if(!typed){inp.removeAttribute('aria-invalid');echo.textContent='';stat.textContent='Type a height, like '+levelExample().split(' · ')[0]+'.';return null;}
10132
+ const mm=parseElevMm(typed);
10133
+ if(mm==null||!Number.isFinite(mm)){inp.setAttribute('aria-invalid','true');echo.textContent='';stat.classList.add('bad');stat.textContent='Couldn’t read “'+typed+'”. Try '+levelExample()+'.';return null;}
10134
+ inp.removeAttribute('aria-invalid');
10135
+ // A bare number is read in the project's own units (inches in feet-and-inches, metres in metric): say so BEFORE it
10136
+ // is applied, because `29` meaning 29 inches is the easiest wrong level to set.
10137
+ const bare=/^[+-]?\d+(\.\d+)?$/.test(typed),unitNote=bare?(displayUnits()===DisplayUnits.MM?' No unit: read as metres.':' No unit: read as inches. Type 29\' for feet.'):'';
10138
+ echo.textContent='Reads as '+fmtDispElev(mm)+' ('+fmtEcho(mm)+').'+unitNote;
10139
+ const total=st.cols.length;
10140
+ if(Number.isFinite(st.plan.elevation_mm)&&mm===st.plan.elevation_mm){
10141
+ stat.textContent=total?'This level shows '+st.shown+' of '+total+' column'+(total===1?'':'s')+' on this sheet.':'This is the level the sheet already has.';return mm;}
10142
+ const probe={...st.plan,elevation_mm:mm},n=st.cols.filter(m=>V2Projection.memberPresence(C,probe,m).visible).length;
10143
+ // What the typed level would draw, whether that is more than the sheet draws now (no level yet), the same, or FEWER (a level
10144
+ // being corrected): the sentence must never promise a count the level would not give.
10145
+ stat.textContent=n===0?(st.shown===0?'No column reaches this height, so this sheet would still show none.':'No column reaches this height, so this sheet would show none.')
10146
+ :(n===st.shown?'No more columns reach this height, so this sheet would still show '+n+'.'
10147
+ :'At this height '+n+' of '+total+' column'+(total===1?'':'s')+' would show.');
10148
+ return mm;
10149
+ }
10150
+ function applyCutLevel(which){
10151
+ which=which||'banner';
10152
+ const st=sheetColumns(),inp=cutEls(which).inp;if(!st||!inp)return;
10153
+ const typed=inp.value,mm=cutFormFeedback(which);if(mm==null){inp.focus();return;}
10154
+ const viewId=viewIdOf(P),name=viewLabel(P)||'this sheet',probe={...st.plan,elevation_mm:mm};
10155
+ const n=st.cols.filter(m=>V2Projection.memberPresence(C,probe,m).visible).length;
10156
+ if(Number.isFinite(st.plan.elevation_mm)&&mm===st.plan.elevation_mm){toast(name+' is already at '+fmtDispElev(mm)+'.');return;}
10157
+ if(which==='banner')closeCutForm(false);
10158
+ if(!edit(()=>V2_SESSION.patchPlan(viewId,{elevation_mm:mm}))){
10159
+ // edit() has already said why. The field gets back what was TYPED, never the stored millimetres: in a feet-and-inches
10160
+ // project a bare number is inches, so refilling `8839.2` would read as 8839 inches.
10161
+ if(which==='banner')openCutForm();
10162
+ const again=cutEls(which).inp;if(again){again.value=typed;cutFormFeedback(which);}
10163
+ return;}
10164
+ toast('Floor level of '+name+' set to '+fmtDispElev(mm)+'. '+(n?n+' column'+(n===1?'':'s')+' now show'+(n===1?'s':'')+'.':'No column reaches it yet.')+' Ctrl+Z undoes it.');
10165
+ try{svg.focus({preventScroll:true});}catch(_){}
10166
+ }
10167
+ function showAllColumnsHere(){
10168
+ const st=cutNoticeFor();if(!st||!st.hidden.length)return;
10169
+ const ids=st.hidden.map(m=>m.id),name=viewLabel(P)||'this sheet';
10170
+ if(!edit(()=>V2_SESSION.presentOnSheet(viewIdOf(P),ids,true)))return;
10171
+ toast('Placed '+ids.length+' column'+(ids.length===1?'':'s')+' on '+name+'. Ctrl+Z undoes it.');
10172
+ try{svg.focus({preventScroll:true});}catch(_){}
10173
+ }
10174
+ /** A button a keyboard user presses: Enter or Space activates THIS button. Without it the editor's idle handler takes the
10175
+ key first and re-arms the last tool instead (`repeatLast`), so the button never fires. */
10176
+ function keyActivates(root){
10177
+ root.addEventListener('keydown',e=>{
10178
+ if((e.key==='Enter'||e.key===' ')&&e.target&&e.target.tagName==='BUTTON'&&e.target.type!=='submit'){e.preventDefault();e.stopPropagation();if(!e.repeat)e.target.click();}});
10179
+ }
10180
+ {const $=id=>document.getElementById(id);
10181
+ $('cutEnterBtn').onclick=()=>{if($('cutForm').hidden)openCutForm();else closeCutForm(true);};
10182
+ $('cutShowBtn').onclick=showAllColumnsHere;
10183
+ $('cutHideBtn').onclick=()=>{const id=viewIdOf(P);if(cutNoticeFor()&&cutNoticeFor().kind==='quiet')cutOpened.delete(id);else cutPutAway.add(id);paintCutBanner();$('cutPill').focus();};
10184
+ $('cutPill').onclick=()=>{const id=viewIdOf(P);if(cutNoticeFor()&&cutNoticeFor().kind==='quiet')cutOpened.add(id);else cutPutAway.delete(id);paintCutBanner();$('cutEnterBtn').focus();};
10185
+ $('cutCancelBtn').onclick=()=>closeCutForm(true);
10186
+ $('cutForm').addEventListener('submit',e=>{e.preventDefault();applyCutLevel('banner');});
10187
+ $('cutInput').addEventListener('input',()=>cutFormFeedback('banner'));
10188
+ // The form owns its keys: typing `8839 mm` must never arm Move, Dimension or Copy, and Escape closes the form, not the editor.
10189
+ $('cutForm').addEventListener('keydown',e=>{e.stopPropagation();
10190
+ if(e.key==='Escape'){e.preventDefault();if(window.OverlayEscape)window.OverlayEscape.markUsed(e);closeCutForm(true);}});
10191
+ keyActivates($('cutBanner'));keyActivates($('cutPill'));
10192
+ }
10193
+ /** The Inspector's floor-level field (always available, whether or not the sheet states a level): the same reading, the
10194
+ same count and the same undoable write as the banner, so a level can be corrected after it was set. */
10195
+ function wireFloorLevelEditor(){
10196
+ const inp=document.getElementById('flInput'),set=document.getElementById('flSet');if(!inp||!set)return;
10197
+ inp.addEventListener('input',()=>cutFormFeedback('inspector'));
10198
+ inp.addEventListener('keydown',e=>{e.stopPropagation();if(e.key==='Enter'){e.preventDefault();applyCutLevel('inspector');}});
10199
+ set.onclick=()=>applyCutLevel('inspector');
10200
+ keyActivates(set);
10201
+ cutFormFeedback('inspector');
10202
+ }
9275
10203
  // keep selection-number badges constant on screen while zooming; the end dots grow with zoom (epR) so
9276
10204
  // they stay readable against the thick member line — both must track zoom live as the user zooms.
9277
10205
  function updateBadges(){const R=12/zoom,F=13/zoom,ox=el=>(+el.dataset.fi-(+el.dataset.gn-1)/2)*R*2;
@@ -9464,26 +10392,131 @@ async function connModifyRequest(j){
9464
10392
  toast(res.ok?'Change queued for your terminal AI session':'Could not queue the request');
9465
10393
  }catch(_){toast('Could not queue the request');}
9466
10394
  }
10395
+ /* #2214 — THE SELECTED MEMBERS THIS PLAN VIEW DOES NOT DISPLAY, and what to say about them.
10396
+ Presence is asked of the CANONICAL row, never of `P.members`: that list is empty on a refused sheet and is
10397
+ filtered by the Objects list, and "not drawn" is a question about the model. A member hidden or isolated away
10398
+ in the Objects list IS drawn (just not shown), which is a different thing and no reason to offer to add it. */
10399
+ function selectionNotOnView(ids,presence){
10400
+ const plan=C&&C.plans&&C.plans[C.active];
10401
+ if(!plan||plan.viewKind!=='plan'||NO_PLAN_VIEW||!V2Projection)return [];
10402
+ const out=[];
10403
+ for(const id of ids){const m=presence?presence.members.get(id):(C.members||[]).find(x=>x&&x.id===id);if(m&&!V2Projection.memberPresence(C,plan,m,presence).visible)out.push(id);}
10404
+ return out;}
10405
+ /** 'S-201', 'S-201 and S-701', 'S-201, S-701 and S-703'; past `cap` names, 'and N more'. */
10406
+ function plainList(items,cap=4){
10407
+ const a=items.slice();if(a.length<=1)return a.join('');
10408
+ if(a.length<=cap)return a.slice(0,-1).join(', ')+' and '+a[a.length-1];
10409
+ return a.slice(0,cap).join(', ')+' and '+(a.length-cap)+' more';}
10410
+ /** The views (by the name a person knows them by) that DO display any of these members, in document order. */
10411
+ function viewsShowing(ids,presence){
10412
+ const want=new Set();for(const id of ids)for(const v of V2Projection.memberViewIds(C,id,presence))want.add(v);
10413
+ return (C.plans||[]).filter(pl=>want.has(viewIdOf(pl))).map(pl=>viewLabel(pl)||viewIdOf(pl));}
10414
+ /** The sentence, plain: where the member is when none of the selection is drawn here, a count when only some is. */
10415
+ function notOnViewText(missing,total,presence){
10416
+ if(missing.length===total){
10417
+ const where=viewsShowing(missing,presence),one=total===1;
10418
+ return 'Not shown on this sheet. '+(where.length?(one?'It’s on ':'They’re on ')+plainList(where)+'.':(one?'It isn’t on any sheet yet.':'They aren’t on any sheet yet.'));}
10419
+ return missing.length+' of the '+total+' selected members '+(missing.length===1?'isn’t':'aren’t')+' drawn on this sheet.';}
10420
+ function addToSheetLabel(n){return n===1?'Add to this sheet':'Add '+n+' to this sheet';}
10421
+ /** Add the members to THIS sheet through `memberRefs`: the sheet's own list, so it is undoable and kept. */
10422
+ function addToThisSheet(missing){
10423
+ const viewId=viewIdOf(P),name=viewLabel(P)||'this sheet';
10424
+ if(!edit(()=>V2_SESSION.presentOnSheet(viewId,missing,true)))return false;
10425
+ toast('Added '+(missing.length===1?'1 member':missing.length+' members')+' to '+name+'.'+(P&&P.registrationRefusal?' It will show once the sheet’s registration is fixed.':'')+' Ctrl+Z undoes it.');
10426
+ try{svg.focus({preventScroll:true});}catch(_){}
10427
+ return true;}
10428
+ function notOnViewHtml(missing,total,presence){
10429
+ // A sheet whose registration is refused or unfinished draws NOTHING, so adding a member to it shows nothing yet. It is
10430
+ // still allowed (nothing refuses), and the notice says plainly when the member will appear.
10431
+ const noDraw=P&&P.registrationRefusal?' It will show here once the sheet’s registration is fixed.':'';
10432
+ return '<div class="dmsg" role="status" aria-live="polite" style="margin-top:8px;flex:none">'+esc(notOnViewText(missing,total,presence)+noDraw)+'</div>'
10433
+ +'<div class=row style="margin-top:8px"><button data-command-id="steel.add-to-view" class=ghostw data-add-to-sheet type=button data-tip="Draws '+(missing.length===1?'it':'them')+' on this sheet. Ctrl+Z undoes it.">'+esc(addToSheetLabel(missing.length))+'</button></div>';}
10434
+ function wireAddToSheet(root,missing){const b=root.querySelector('[data-add-to-sheet]');if(b){b.onclick=()=>{addToThisSheet(missing);};keyActivates(b);}}
10435
+ /** Resolve selected projected rows once for this refresh; lazy projections build their own fresh presence data. */
10436
+ function selectionNoticeMembers(ids,presence){
10437
+ const rows=new Map();
10438
+ const mapRows=plan=>{const map=new Map();for(const row of plan.members||[])if(row&&!map.has(row.id))map.set(row.id,row);return map;};
10439
+ const here=mapRows(P||{}),out=[];
10440
+ for(const id of ids){let member=here.get(id);
10441
+ if(!member)for(const viewId of V2Projection.memberPlanViewIds(C,id,presence)){
10442
+ if(!rows.has(viewId))rows.set(viewId,mapRows(v2ProjectionForView(viewId).plan));
10443
+ member=rows.get(viewId).get(id);if(member)break;
10444
+ }
10445
+ if(member)out.push(member);
10446
+ }
10447
+ return out;}
9467
10448
  function syncV2SelectionNotice(p){
9468
10449
  if(!p||!selIds.size||viewPropsId)return; // a view in the panel keeps the selection, not its notices
9469
10450
  p.querySelectorAll('.v2-selection-notice,.v2-elevation-warning,.v2-elevation-proposal,.v2-elevation-answered').forEach(el=>el.remove());
9470
- const ids=[...selIds].filter(id=>!!(C.members||[]).find(m=>m&&m.id===id));
10451
+ const presence=V2Projection.createMemberPresenceIndex(C);
10452
+ const ids=[...selIds].filter(id=>presence.members.has(id));
9471
10453
  if(!ids.length)return;
9472
10454
  const other=[];
9473
10455
  // Membership is asked by VIEW and answered by PAGE (#938): "also on S5.1" must say the page once,
9474
10456
  // however many of its views draw the member, while whether it is drawn there is a per-view question.
9475
10457
  // `memberPhysicalSheets` owns the dedupe so this file and the projection cannot drift apart on it.
9476
10458
  const herePage=(P&&P.sheet)||'';
9477
- for(const id of ids)for(const page of V2Projection.memberPhysicalSheets(C,id)){
10459
+ for(const id of ids)for(const page of V2Projection.memberPhysicalSheets(C,id,presence)){
9478
10460
  if(page!==herePage&&!other.includes(page))other.push(page);
9479
10461
  }
9480
10462
  const anchor=p.querySelector(':scope > h3,:scope > .badge');
9481
10463
  let after=anchor;
9482
- if(other.length){
10464
+ // #2214: a selected member this sheet does not draw is said so, in those words, with the way to fix it. A member is
10465
+ // inspected through ANY sheet that draws it (`byId` walks them all), so the ordinary editable panel is what the
10466
+ // person sees for a member picked in 3D, and this notice is what tells them it is not on THIS sheet.
10467
+ const missing=selectionNotOnView(ids,presence);
10468
+ if(missing.length){
10469
+ const n=document.createElement('div');n.className='v2-selection-notice';n.innerHTML=notOnViewHtml(missing,ids.length,presence);wireAddToSheet(n,missing);
10470
+ if(after)after.after(n);else p.prepend(n);after=n;
10471
+ }else if(other.length){
9483
10472
  const n=document.createElement('div');n.className='hint v2-selection-notice';n.setAttribute('role','status');n.setAttribute('aria-live','polite');n.style.marginTop='8px';
9484
10473
  n.textContent=(ids.length===1?'Also on ':'Selected members also appear on ')+[...new Set(other)].join(', ')+'.';
9485
10474
  if(after)after.after(n);else p.prepend(n);after=n;
9486
10475
  }
10476
+ // #2214 (UX 20): a column drawn here only because of this sheet's floor level has no sheet-level thing to delete, so
10477
+ // Delete leaves it. Said while it is selected, not only after the key was pressed: dashed does NOT mean derived
10478
+ // (a column the read bound is dashed too, and Delete removes that one).
10479
+ // What holds the members this refresh asks about (the sheet's derived columns, and the ones Delete just left for the drawing
10480
+ // read), for ALL of them from one walk of the model. Nothing is walked when no member is asked about.
10481
+ const derivedAll=sheetDerivedIds(ids,presence),derivedHere=new Set(derivedAll);
10482
+ const askWanted=ids.filter(id=>derivedHere.has(id)||deleteAsk.has(id));
10483
+ const holds=askWanted.length?heldIndex(askWanted):null;
10484
+ {const derivedIds=derivedAll;
10485
+ if(derivedIds.length){
10486
+ // Delete leaves these on the sheet, and a person who really means to remove one is not left without a way: an explicit
10487
+ // button deletes it from the WHOLE model (undoable, and it says it left every sheet).
10488
+ const row=document.createElement('div');row.className='v2-selection-notice';row.style.marginTop='8px';
10489
+ const one=derivedIds.length===1,info=one?colBelowInfo({id:derivedIds[0]}):null,belowBit=info&&info.under!==null&&info.under>0?' (it ends '+underFloorText(info.under)+' below it)':'';
10490
+ const msg=document.createElement('div');msg.className='hint';msg.setAttribute('role','status');msg.setAttribute('aria-live','polite');
10491
+ msg.textContent=(one?'Drawn here from this sheet’s floor level'+belowBit+'. Delete leaves it on this sheet.'
10492
+ :derivedIds.length+' of the selected columns are drawn here from this sheet’s floor level. Delete leaves them on this sheet.');
10493
+ row.appendChild(msg);
10494
+ // The way out is offered for the columns the model WILL delete, asked of the command layer's own check. One it would refuse
10495
+ // (a connection, a dimension, a placed detail or the drawing read holds it) gets no button that could only fail: the
10496
+ // sentence says what holds it instead, and what to delete first.
10497
+ const blockersOf=new Map(derivedIds.map(id=>[id,holds.get(id)||[]]));
10498
+ // A column ONLY the drawing read holds is not "named" here: it gets Delete anyway (the row after this block), not a refusal.
10499
+ const readOnly=new Set(readHeldIds(derivedIds,holds));
10500
+ const free=derivedIds.filter(id=>!blockersOf.get(id).length),named=derivedIds.filter(id=>blockersOf.get(id).length&&!readOnly.has(id));
10501
+ if(free.length){
10502
+ const act=document.createElement('div');act.className='row';act.style.marginTop='6px';
10503
+ const del=document.createElement('button');del.type='button';del.className='ghostw';del.setAttribute('data-command-id','steel.delete-from-model');del.setAttribute('data-delete-from-model','');
10504
+ del.dataset.tip='Removes '+(free.length===1?'it':'them')+' from the model, so from every sheet. Ctrl+Z undoes it.';
10505
+ del.textContent=free.length===1?'Delete it from the whole model':'Delete '+free.length+' from the whole model';
10506
+ del.onclick=()=>{deleteFromWholeModel(free);};keyActivates(del);
10507
+ act.appendChild(del);row.appendChild(act);}
10508
+ if(named.length){
10509
+ const why=document.createElement('div');why.className='hint';why.style.marginTop='6px';
10510
+ why.textContent=deleteBlockedText(named.flatMap(id=>blockersOf.get(id)),named.length,derivedIds.length===1,true);
10511
+ row.appendChild(why);}
10512
+ if(after)after.after(row);else p.prepend(row);after=row;
10513
+ }}
10514
+ // DELETE ANYWAY (owner 2026-10-12): members ONLY the drawing read holds. A column this sheet derives gets the ask at once (Delete
10515
+ // leaves it, and the read is the only thing in the way of removing it); any other member gets it after a Delete just left it.
10516
+ // Held by a connection, a dimension or a placed detail as well, there is no button: the sentence above says to delete those first.
10517
+ {for(const id of [...deleteAsk])if(!selIds.has(id))deleteAsk.delete(id);
10518
+ const askIds=holds?readHeldIds(askWanted,holds):[];
10519
+ if(askIds.length){const row=deleteAnywayRow(askIds,holds);if(after)after.after(row);else p.prepend(row);after=row;}}
9487
10520
  /*
9488
10521
  * A PARTLY-resolvable selection, which is the case the refused-sheet panel branch cannot see (#942).
9489
10522
  *
@@ -9496,7 +10529,8 @@ function syncV2SelectionNotice(p){
9496
10529
  * unprojected rows INTO the editable panel means handing a dozen `wp` call sites a row without one,
9497
10530
  * which is the audit-and-split refactor #942 deliberately defers. (Codex review.)
9498
10531
  */
9499
- {const resolved=new Set(selArr().map(m=>m&&m.id));
10532
+ const projected=selectionNoticeMembers(ids,presence);
10533
+ {const resolved=new Set(projected.map(m=>m&&m.id));
9500
10534
  const lost=ids.filter(id=>!resolved.has(id));
9501
10535
  if(lost.length&&resolved.size){
9502
10536
  const row=document.createElement('div');row.className='drow v2-selection-notice';row.setAttribute('role','status');row.setAttribute('aria-live','polite');row.style.marginTop='8px';
@@ -9505,24 +10539,23 @@ function syncV2SelectionNotice(p){
9505
10539
  // valid while the member that vanished belongs to a refused one, and naming `P` there would blame the
9506
10540
  // wrong drawing. See `blockingViewsFor` — keyed by VIEW since #938, and NAMED with `viewLabel`,
9507
10541
  // because the key is a view id and a bare view id is not what any other surface calls this view.
9508
- const blocking=blockingViewsFor(lost),reason=blocking.size
10542
+ const blocking=blockingViewsFor(lost,presence),reason=blocking.size
9509
10543
  ?(' '+[...blocking.keys()].map(v=>{const pl=(C&&C.plans||[]).find(x=>viewIdOf(x)===v);
9510
10544
  return regLeadText((pl&&viewLabel(pl))||v,blocking.get(v));}).join(' ')):'';
9511
10545
  // #1880 — a member read from an elevation is "lost" for a different reason, and the registration
9512
10546
  // sentence above would be false for it: say which view it came from and that the edits below skip it.
9513
- const onlyLost=sourceOnlyIds(lost),sourceReason=onlyLost.length
9514
- ?' '+(onlyLost.length===1?onlyLost[0]+' was':onlyLost.join(', ')+' were')+' read from '+sourceViewList([...sourceOnlyViewsFor(onlyLost).values()])
10547
+ const onlyLost=sourceOnlyIds(lost,presence),sourceReason=onlyLost.length
10548
+ ?' '+(onlyLost.length===1?onlyLost[0]+' was':onlyLost.join(', ')+' were')+' read from '+sourceViewList([...sourceOnlyViewsFor(onlyLost,presence).values()])
9515
10549
  +'; only plan views are drawn in 2D for now, so the edits below don’t change '+(onlyLost.length===1?'it':'them')+'.':'';
9516
10550
  msg.textContent=lost.length+' more selected member'+(lost.length===1?' is':'s are')+' not shown below ('+lost.join(', ')+') — '+(lost.length===1?'it':'they')+' cannot be drawn on this sheet.'+reason+sourceReason;
9517
10551
  row.appendChild(msg);if(after)after.after(row);else p.prepend(row);after=row;}}
9518
- const selected=(C.members||[]).filter(m=>ids.includes(m.id));
10552
+ const selectedIds=new Set(ids),selected=[...presence.members.values()].filter(m=>selectedIds.has(m.id));
9519
10553
  const unknown=selected.reduce((n,m)=>n+(!Number.isFinite(m?.from?.z?.known)?1:0)+(!Number.isFinite(m?.to?.z?.known)?1:0),0);
9520
10554
  if(unknown){
9521
10555
  const row=document.createElement('div');row.className='drow v2-elevation-warning';row.setAttribute('role','status');row.setAttribute('aria-live','polite');row.style.marginTop='8px';
9522
10556
  const msg=document.createElement('div');msg.className='dmsg warn';msg.textContent=`${unknown} selected endpoint${unknown===1?' has':'s have'} unknown elevation. Enter TOS or BOS before using an elevation-dependent command.`;
9523
10557
  row.appendChild(msg);if(after)after.after(row);else p.prepend(row);
9524
10558
  }
9525
- const projected=selArr();
9526
10559
  const mark=(id,on)=>{const input=document.getElementById(id);if(!input||!on)return;input.value='';input.placeholder='Unknown';input.setAttribute('aria-label',(input.getAttribute('aria-label')||id)+' — unknown elevation');};
9527
10560
  if(projected.length===1){
9528
10561
  const m=projected[0],canonical=selected[0];
@@ -9868,9 +10901,20 @@ function nativeElevationContextHtml(){
9868
10901
  for(const member of P.members||[])for(const end of member.ends||[]){const raw=end&&end.tosMm,value=raw==null?NaN:Number(raw);if(Number.isFinite(value))values.push(value);else unknown++;}
9869
10902
  const range=!values.length?'No finite visible endpoints':(Math.min(...values)===Math.max(...values)
9870
10903
  ?fmtDispElev(values[0]):fmtDispElev(Math.min(...values))+' to '+fmtDispElev(Math.max(...values)));
9871
- const planElevation=Number.isFinite(plan.elevation_mm)?fmtDispElev(plan.elevation_mm):'Not recorded';
10904
+ // The floor level is a FIELD here, available whether or not the sheet states one (#2214): a level set from the banner
10905
+ // could otherwise never be corrected, and "Show all columns here" removes the banner. Same parser, reading, count
10906
+ // and undoable write as the banner's form (cutFormFeedback / applyCutLevel with `inspector`).
10907
+ const planElevation=Number.isFinite(plan.elevation_mm)?fmtDispElev(plan.elevation_mm):'Not recorded',sheetName=viewLabel(P)||P.sheet||'this sheet';
9872
10908
  return '<div style="border-top:1px solid var(--line);margin-top:12px;padding-top:12px"><div class=sect>Elevation context</div>'+
9873
10909
  '<div class=hint style="margin:0 0 5px;font-size:11px">Plan elevation <b>'+esc(planElevation)+'</b> ('+esc(P.sheet)+')</div>'+
10910
+ // A STACKED row of its own (`prow stack`): applyPanelRows would otherwise pair the label with the field and squeeze the field
10911
+ // between the label and the echo, which here is a sentence rather than a short decoration.
10912
+ '<div class="prow stack"><div class=elab>'+(Number.isFinite(plan.elevation_mm)?'Change floor level of ':'Floor level of ')+esc(sheetName)+'</div>'+
10913
+ '<input data-command-id="steel.floor-level-field" aria-label="Floor level of '+esc(sheetName)+'" id=flInput inputmode=decimal autocomplete=off spellcheck=false aria-describedby="flEcho flStatus" placeholder="'+esc(levelExample().split(' · ')[0])+'">'+
10914
+ '<span class=edec id=flEcho></span><div class="hint flstat" id=flStatus role=status aria-live=polite></div>'+
10915
+ '<button data-command-id="steel.floor-level-set" id=flSet class=ghostw type=button data-tip="Sets this sheet’s floor level. Ctrl+Z undoes it.">Set level</button></div>'+
10916
+ // The distance is a PROJECT setting, not this sheet's: said here, in the words the setting uses, so nobody looks for it on the sheet.
10917
+ (Number.isFinite(plan.elevation_mm)?'<div class=hint style="margin:0 0 5px;font-size:11px">Columns ending up to <b>'+esc(underFloorText(reachNow()))+'</b> under this level are drawn dashed. Change it in ⋯ › Display.</div>':'')+
9874
10918
  '<div class=hint style="margin:0 0 5px;font-size:11px">Visible member endpoints <b>'+esc(range)+'</b>'+ (unknown?' · '+unknown+' unknown':'') +'</div>'+
9875
10919
  '<div class=hint style="margin:0;font-size:11px">Member elevations are explicit in this model. Select a member to inspect or edit its endpoints.</div></div>';
9876
10920
  }
@@ -10010,6 +11054,7 @@ function refusedSheetPropsHtml(rows){
10010
11054
  return out;}
10011
11055
  function panel(){
10012
11056
  const p=document.getElementById('panel');
11057
+ mfOfferSync(); // a question about the beams that were just marked is only asked while they are what is selected; selecting something else is the answer "keep"
10013
11058
  p.removeAttribute('aria-busy');p.removeAttribute('aria-labelledby');
10014
11059
  queueMicrotask(()=>syncV2SelectionNotice(p));
10015
11060
  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
@@ -10354,7 +11399,10 @@ function panel(){
10354
11399
  {const db=document.getElementById('gridDelFree');if(db)db.onclick=()=>deleteSelGrids();}
10355
11400
  {const qb=document.getElementById('qdPlaceG');if(qb)qb.onclick=()=>quickDimSpacing(qdAnchorPt);}
10356
11401
  return;}
10357
- const arr=selArr();
11402
+ // One fresh synchronous Inspector read; the queued notice reads again when it actually runs.
11403
+ // Event handlers below still resolve the live selection when activated.
11404
+ const inspectorPresence=V2Projection.createMemberPresenceIndex(C);
11405
+ const arr=selectionNoticeMembers([...selIds],inspectorPresence);
10358
11406
  /* A selection that resolved to NOTHING is not an empty selection, and showing the legend for it tells
10359
11407
  the user their click did nothing. It happens on a sheet whose registration is refused: the plan
10360
11408
  projects no members, so a member picked in the 3D view — which draws from the canonical model and is
@@ -10363,7 +11411,7 @@ function panel(){
10363
11411
  are read from the canonical model (`selCanonicalArr`) and shown read-only beneath the reason. Only the
10364
11412
  coordinate-dependent half — drawing it, dragging it, dimensioning it — is genuinely blocked here. */
10365
11413
  {const canon=(arr.length===0&&selIds.size)?selCanonicalArr():[];
10366
- const blocking=canon.length?blockingViewsFor(canon.map(m=>m.id)):new Map();
11414
+ const blocking=canon.length?blockingViewsFor(canon.map(m=>m.id),inspectorPresence):new Map();
10367
11415
  /* Keyed on the SELECTION's own views, not on `P` — see `blockingViewsFor`. An empty map means this is
10368
11416
  not a registration problem, so the existing behaviour below is left exactly as it was. */
10369
11417
  if(blocking.size){
@@ -10410,10 +11458,10 @@ function panel(){
10410
11458
  properties come from the model itself, so they are shown read-only, with the views it was read from
10411
11459
  named in plain words. Without this branch the click fell through to the legend below, which tells the
10412
11460
  user their click did nothing. */
10413
- const onlyIds=new Set(sourceOnlyIds(canon.map(m=>m.id))),onlyRows=canon.filter(m=>onlyIds.has(m.id));
11461
+ const onlyIds=new Set(sourceOnlyIds(canon.map(m=>m.id),inspectorPresence)),onlyRows=canon.filter(m=>onlyIds.has(m.id));
10414
11462
  if(onlyRows.length){
10415
11463
  p.innerHTML='<h3>Shown in 3D only</h3><div class="dmsg" style="margin-top:8px;flex:none">'
10416
- +esc(sourceOnlyLead(onlyRows.length,[...sourceOnlyViewsFor([...onlyIds]).values()]))+'</div>'
11464
+ +esc(sourceOnlyLead(onlyRows.length,[...sourceOnlyViewsFor([...onlyIds],inspectorPresence).values()]))+'</div>'
10417
11465
  +'<div class="row hint" style="margin-top:8px">Read-only — these come from the model itself. To change one, ask your terminal AI; this editor can&rsquo;t yet edit a member shown only on an elevation or section.</div>'
10418
11466
  +refusedSheetPropsHtml(onlyRows);
10419
11467
  return;}}
@@ -10422,7 +11470,8 @@ function panel(){
10422
11470
  '<div class=hint style="margin:0 0 6px;font-size:11px">Level <b>'+esc(fmtDispElev(defaultTosMm))+'</b> ('+esc(P.sheet)+'). '+((P.tos_callouts&&P.tos_callouts.length)?'Per-zone T.O. STEEL callouts from the drawing applied to each member; ':'')+'ends ticked <b>default</b> follow the level.</div>'+
10423
11471
  '<div class=elab>Default TOS</div><input data-command-id="steel.default-tos" aria-label="Default TOS" id=defTos inputmode=decimal placeholder="'+esc(elevExample())+'" value="'+esc(fmtDispElev(defaultTosMm))+'"><span class=edec>'+esc(fmtEcho(defaultTosMm))+'</span>'+
10424
11472
  '<button data-command-id="steel.ends-reset-default" class="ghostw f" id=applyTos>Reset all ends to default</button></div>';
10425
- p.innerHTML='<div class=divrow><hr><span class=sect style=\"margin:0\">Select</span><hr></div><div class=krow><span class=kk><kbd>Click</kbd></span><span class=kv>A member</span></div><div class=krow><span class=kk><kbd>Ctrl/Shift</kbd></span><span class=kv>With a click, adds or removes</span></div><div class=krow><span class=kk><kbd>Drag</kbd></span><span class=kv>Box-select from empty space — <b>left→right</b> encloses, <b>right→left</b> touches</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">Edit</span><hr></div><div class=krow><span class=kk><kbd>Drag</kbd></span><span class=kv>Moves the selection; snaps to grid and endpoints</span></div><div class=krow><span class=kk><kbd>Alt</kbd></span><span class=kv>Ignores the snap</span></div><div class=krow><span class=kk><kbd>Shift</kbd></span><span class=kv>Keeps it straight</span></div><div class=krow><span class=kk><kbd>Ctrl+D</kbd></span><span class=kv>Duplicate</span></div><div class=krow><span class=kk><kbd>Ctrl+Z</kbd></span><span class=kv>Undo, <b>Ctrl+Y</b> redo</span></div><div class=krow><span class=kk><kbd>Del</kbd></span><span class=kv>Delete, <b>Esc</b> deselects</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">Move around</span><hr></div><div class=krow><span class=kk><kbd>Scroll</kbd></span><span class=kv>Zoom</span></div><div class=krow><span class=kk><kbd>Home</kbd></span><span class=kv>Fit — middle-drag pans</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">What the lines mean</span><hr></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1=1 y1=5 x2=61 y2=5 stroke-dasharray="4 4"/></svg></span><span class=kv><b>RFI</b> — the size is unresolved</span></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1="7" y1="5" x2="55" y2="5"/><path d="M1 5 7 2.4 7 7.6z" fill=currentColor stroke=none/><path d="M61 5 55 2.4 55 7.6z" fill=currentColor stroke=none/></svg></span><span class=kv>A <b>brace</b> above the floor</span></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1=13 y1=5 x2=55 y2=5 stroke-dasharray="9 4 3 4"/><path d="M1 5 7 2.4 7 7.6z" fill=currentColor stroke=none/><path d="M7 5 13 2.4 13 7.6z" fill=currentColor stroke=none/><path d="M61 5 55 2.4 55 7.6z" fill=currentColor stroke=none/></svg></span><span class=kv>A <b>brace</b> below — double arrowhead marks its lower end</span></div>'+elevationContext;
11473
+ p.innerHTML='<div class=divrow><hr><span class=sect style=\"margin:0\">Select</span><hr></div><div class=krow><span class=kk><kbd>Click</kbd></span><span class=kv>A member</span></div><div class=krow><span class=kk><kbd>Ctrl/Shift</kbd></span><span class=kv>With a click, adds or removes</span></div><div class=krow><span class=kk><kbd>Drag</kbd></span><span class=kv>Box-select from empty space — <b>left→right</b> encloses, <b>right→left</b> touches</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">Edit</span><hr></div><div class=krow><span class=kk><kbd>Drag</kbd></span><span class=kv>Moves the selection; snaps to grid and endpoints</span></div><div class=krow><span class=kk><kbd>Alt</kbd></span><span class=kv>Ignores the snap</span></div><div class=krow><span class=kk><kbd>Shift</kbd></span><span class=kv>Keeps it straight</span></div><div class=krow><span class=kk><kbd>Ctrl+D</kbd></span><span class=kv>Duplicate</span></div><div class=krow><span class=kk><kbd>Ctrl+Z</kbd></span><span class=kv>Undo, <b>Ctrl+Y</b> redo</span></div><div class=krow><span class=kk><kbd>Del</kbd></span><span class=kv>Delete, <b>Esc</b> deselects</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">Move around</span><hr></div><div class=krow><span class=kk><kbd>Scroll</kbd></span><span class=kv>Zoom</span></div><div class=krow><span class=kk><kbd>Home</kbd></span><span class=kv>Fit — middle-drag pans</span></div><div class=divrow><hr><span class=sect style=\"margin:0\">What the lines mean</span><hr></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1=1 y1=5 x2=61 y2=5 stroke-dasharray="4 4"/></svg></span><span class=kv><b>RFI</b> — the size is unresolved</span></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1="7" y1="5" x2="55" y2="5"/><path d="M1 5 7 2.4 7 7.6z" fill=currentColor stroke=none/><path d="M61 5 55 2.4 55 7.6z" fill=currentColor stroke=none/></svg></span><span class=kv>A <b>brace</b> above the floor</span></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.6" stroke-linecap=butt><line x1=13 y1=5 x2=55 y2=5 stroke-dasharray="9 4 3 4"/><path d="M1 5 7 2.4 7 7.6z" fill=currentColor stroke=none/><path d="M7 5 13 2.4 13 7.6z" fill=currentColor stroke=none/><path d="M61 5 55 2.4 55 7.6z" fill=currentColor stroke=none/></svg></span><span class=kv>A <b>brace</b> below — double arrowhead marks its lower end</span></div><div class=lgdrow><span class=kk><svg width="62" height="10" viewBox="0 0 62 10" aria-hidden=true stroke=currentColor fill=none stroke-width="1.4" stroke-linecap=butt><rect x="27" y="1.5" width="8" height="7" stroke-dasharray="3 2"/></svg></span><span class=kv>A <b>column</b> below: it ends just under this floor</span></div>'+elevationContext;
11474
+ if(nativeElevationModel())wireFloorLevelEditor(); // #2214: the Inspector's floor-level field (the context block above carries it)
10426
11475
  const defTos=document.getElementById('defTos'),applyTos=document.getElementById('applyTos');
10427
11476
  if(defTos)defTos.onchange=e=>{const v=elevOrRefuse(e.target.value);if(v==null)return;defaultTosMm=v;ModelCmd.setPlanDefaultTosMm(P,defaultTosMm);syncDefaults();scheduleSave();render();sync3D();};
10428
11477
  if(applyTos)applyTos.onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTosMm);});
@@ -10472,7 +11521,10 @@ function panel(){
10472
11521
  // is skipped by the bake entirely, so folding it in would report a Varies (or a value) for a member
10473
11522
  // nothing applies to. ONE subset for both axes and both offsets, because the bake has one answer for all
10474
11523
  // four. Columns are IN it now: they take a Profile Position like every other member (design §4).
10475
- const hOk=arr,hSkip=arr.filter(m=>!posEligible(m)).length;
11524
+ // Resolve each distinct designation once in this synchronous refresh; no result survives a repaint.
11525
+ const profileDimensions=new Map();
11526
+ const dimensionsFor=profile=>{if(!profileDimensions.has(profile))profileDimensions.set(profile,profileDimsIn(profile));return profileDimensions.get(profile);};
11527
+ const hOk=arr,hSkip=arr.filter(m=>!posEligible(m,dimensionsFor(m&&m.profile))).length;
10476
11528
  const posA=hOk.length?agg(hOk,m=>posDefault(m)):null;
10477
11529
  const posHA=hOk.length?agg(hOk,m=>posHDefault(m)):null;
10478
11530
  // A mixed selection must read BLANK, not the first member's value — an offset silently inherited across a
@@ -10490,14 +11542,22 @@ function panel(){
10490
11542
  const d=Math.atan2(Math.sin(th),Math.cos(th))*180/Math.PI;return +(((d%360)+360)%360).toFixed(6);};
10491
11543
  const rotAgg=agg(arr,m=>rollDeg(positionAuthoringRoll(m))); // 3b.2: shared roll RE-EXPRESSED into the current frame (rollDeg reads the geometry quantity + normalises), or VARIES
10492
11544
  const qdElig=(sel2d()||[]).filter(isDimAnchorableMember),qdN=qdElig.length+selGridIds.size,qdHasBeam=qdElig.some(m=>(m.role||'beam')!=='column'); // F7: active-plan beams + columns + co-selected grid lines; the Start/Mid/End toggle only matters when a beam is in the set
11545
+ // #2210 — "Mark N beams as moment frame": beams only (a column or a brace is never a moment-frame girder). Marking them all
11546
+ // when some already are turns the rest on rather than flipping each; the hint says how many were already.
11547
+ const mfBeams=arr.filter(mfBeam),mfOn=mfBeams.filter(b=>b.mf===true||mfByMark(b)).length,mfAll=mfBeams.length>0&&mfOn===mfBeams.length,mfFlag=mfBeams.filter(b=>b.mf===true).length;
11548
+ // Beams that are moment frames only by their MF mark cannot be cleared from here (the mark is their profile), so when that is ALL of them there is nothing to click.
11549
+ const mfMulti=!mfBeams.length?'':(mfAll&&!mfFlag
11550
+ ?`<div class="hint mfhint" id=mfAllMarked>${mfBeams.length===1?'It is a':`All ${mfBeams.length} are`} moment frame, from ${mfBeams.length===1?'its':'their'} MF mark${mfBeams.length===1?'':'s'}. Change the profile to clear ${mfBeams.length===1?'it':'them'}.</div>`
11551
+ :`<div class=row><button type=button data-command-id="steel.selection-moment-frame" class=ghostw id=mfBtnM aria-pressed="${mfAll?'true':'false'}"${mfAll?' style="border-color:var(--brand);color:var(--brand)"':''}>${mfAll?`✓ ${mfBeams.length===1?'It is a':`All ${mfBeams.length} are`} moment frame — click to clear`:`Mark ${mfBeams.length} beam${mfBeams.length===1?'':'s'} as moment frame`}</button></div>${mfOn&&!mfAll?`<div class="hint mfhint">${mfOn} of ${mfBeams.length} already ${mfOn===1?'is':'are'}.</div>`:''}`);
10493
11552
  p.innerHTML=`<h3>${arr.length} members selected</h3>
10494
- ${typeFilterHTML()}
11553
+ ${typeFilterHTML(arr)}
10495
11554
  <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>
10496
11555
  ${memberTypeField('mTypeM',arr)}
10497
11556
  <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>
10498
11557
  <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>
10499
11558
  <div class="row hint">Total length <b>${totalL}</b>${totalW!=null?` · <b>${totalW.toLocaleString()} ${_uw().weight}</b>`:''}${dupSel?` · <span style="color:var(--err)">${dupSel} duplicate${dupSel>1?'s':''}</span> (overlap a kept member — deleting these dedupes)`:''}</div>
10500
11559
  <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>
11560
+ ${mfMulti}${mfOfferHtml()}
10501
11561
  ${elev}
10502
11562
  <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>
10503
11563
  ${positionFrameHTML()}
@@ -10528,6 +11588,8 @@ function panel(){
10528
11588
  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});
10529
11589
  document.getElementById('mTypeM').onchange=e=>{const v=e.target.value;if(!normMemberTypeKey(v)){e.target.value=memberTypeValueFor(selArr());return;}const known=memberTypeKnownKey(v);if(known&&selArr().every(x=>memberTypeSettled(x,known))){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
10530
11590
  document.getElementById('verifyBtn').onclick=()=>edit(()=>{const v=!allVerified;for(const m of selArr())ModelCmd.patchMember(m,{verified:v});});
11591
+ {const b=document.getElementById('mfBtnM');if(b)b.onclick=mfSelectionToggle;}
11592
+ mfWireOffer();
10531
11593
  {const _gel=document.getElementById('geoEL');if(_gel)_gel.onclick=()=>{geoMode=(geoMode==='el'?null:'el');setGeo();render();};}
10532
11594
  {const _sw=document.getElementById('swapEnds');if(_sw)_sw.onclick=()=>swapSelectionEnds();} // reverse eligible beams for the whole selection (2D + 3D via render+sync3D); columns/braces excluded, and it owns its edit()/toast
10533
11595
  {const setQd=k=>{qdAnchorPt=k;try{localStorage.setItem('steel:qdAnchor:v2',k);}catch(_){}for(const [id,kk] of [['qdPtA','a'],['qdPtMid','mid'],['qdPtB','b']]){const b=document.getElementById(id);if(b)b.classList.toggle('on',qdAnchorPt===kk);}}; // F7 anchor-point toggle (persisted)
@@ -10535,8 +11597,8 @@ function panel(){
10535
11597
  const _qm=document.getElementById('qdPtMid');if(_qm)_qm.onclick=()=>setQd('mid');
10536
11598
  const _qb=document.getElementById('qdPtB');if(_qb)_qb.onclick=()=>setQd('b');
10537
11599
  const _qp=document.getElementById('qdPlace');if(_qp)_qp.onclick=()=>quickDimSpacing(qdAnchorPt);}
10538
- document.getElementById('del').onclick=()=>edit(()=>{deleteV2Selection({memberIds:selIds,dimIds:selDimIds});
10539
- modelSelection.clearMembers();selDimIds.clear();});
11600
+ document.getElementById('del').onclick=()=>{if(deleteStaysOnSheet({memberIds:selIds,dimIds:selDimIds}))return;edit(()=>{deleteV2Selection({memberIds:selIds,dimIds:selDimIds});
11601
+ clearMembersAfterDelete();selDimIds.clear();});};
10540
11602
  // The placement commits to the eligible members only and SAYS how many were left out — a control that
10541
11603
  // silently no-ops on part of the selection is the failure this panel exists to avoid. The
10542
11604
  // `targets.length` guard is the same one Match → both ends carries: edit() pushes undo unconditionally,
@@ -10592,8 +11654,7 @@ function panel(){
10592
11654
  const posH=posHDefault(m), hEl=posEligible(m);
10593
11655
  const hWhy=POSTIP.noProf(posStored(m));
10594
11656
  const hApprox=hEl&&widthEstimated(m.profile)?POSTIP.approx(esc(m.profile)):'';
10595
- const _lvl=({'S-202':'second','S-203':'roof'})[P.sheet];
10596
- const mfSug=((m.mf||/^MF/i.test(m.profile))&&_lvl&&C.moment_frames)?[...new Set(C.moment_frames.flatMap(f=>f[_lvl]||[]))].filter(Boolean):[];
11657
+ const mfSect=mfSectionHtml(m); // #2210: the Moment frame switch, and the box that offers the girder sizes the schedule gives THIS sheet's level
10597
11658
  const endName2=id=>({bosMm:'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;
10598
11659
  const ftFld=(id,label,v)=>`<div class=elab>${label}</div><input data-command-id="steel.end-elevation#${esc(endName2(id))}" aria-label="Elevation for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="${esc(elevExample())}" value="${esc(fmtDispElev(v))}"><span class=edec>${esc(fmtEcho(v))}</span>`;
10599
11660
  const tosFld=(id,label,o)=>{const native=nativeElevationModel(),def=!native&&o.tosDef!==false,v=def?defaultTosMm:o.tosMm;
@@ -10690,7 +11751,8 @@ function panel(){
10690
11751
  // Both parametric END kinds. A gusset reaching this panel and finding no section for it was a dead end:
10691
11752
  // the whole-connection inspector renders “✎ Edit parameters on <member> →” for every parametric kind.
10692
11753
  const spjs=col?[]:[0,1].map(e=>({e,j:(C.joints||[]).find(j=>j&&(j.kind==='shear-plate'||j.kind==='brace-gusset')&&j.main===m.id&&j.at==='end'+e)})).filter(x=>x.j);
10693
- const spAllAuto=spjs.length>0&&spjs.every(x=>x.j.source==='auto');
11754
+ const spAllAuto=spjs.length>0&&spjs.every(x=>isPlainAutoJoint(x.j)); // the toolbar's own plates; one Build from details made is 'auto' too but is not cleared by the toolbar, so its intro must not say it is
11755
+ const spAllBuilt=spjs.length>0&&spjs.every(x=>isDetailBuiltJoint(x.j));
10694
11756
  // DOM ids key on the END INDEX (0/1), NEVER the joint id (a free-string schema field) — so a crafted
10695
11757
  // joints[].id can't inject into an attribute position; the handlers below close over the real joint.
10696
11758
  const spF=(e,j,key,label,ph,unit)=>{const raw=j&&j.params&&j.params[key]!=null?j.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtDisp(Number(raw))):esc(String(raw)));
@@ -10716,6 +11778,8 @@ function panel(){
10716
11778
  const spAllGus=spjs.length>0&&spjs.every(x=>x.j.kind==='brace-gusset');
10717
11779
  const spIntro=spAllGus
10718
11780
  ? 'Tune this end&#39;s gusset — millimetres; empty = engine default. The brace is set back to the support face automatically; <b>Lapped side</b> picks which face of the angle leg the plates sandwich.'
11781
+ : spAllBuilt
11782
+ ? 'Built from its connection detail — millimetres; empty = engine default. <b>Build from details</b> updates it when the detail changes; change a value here and it stays as you set it.'
10719
11783
  : (spAllAuto?'Auto-added — millimetres; empty = engine default. <b>Clearance</b> = the gap (≈½–¾") so the beam clears the support; <b>Web side</b> picks which face of the web the plate laps. Clear all via <b>Clear shear plates</b> in the toolbar (AI-tuned plates are kept).':'Tune this end&#39;s shear plate — millimetres; empty = engine default. <b>Clearance</b> = the gap (≈½–¾") so the beam clears the support; <b>Web side</b> picks which face of the web the plate laps.');
10720
11784
  const spSect=spjs.length?`<div class=hint style="margin:8px 0 0">${spIntro}</div>${spjs.map(spBlock).join('')}`:'';
10721
11785
  const _cps=(!col&&copesByMember[m.id])?copesByMember[m.id]:[]; // auto cope(s) on this beam (from the rendered scene)
@@ -10826,15 +11890,15 @@ function panel(){
10826
11890
  // below, where a backtick and a ${...} in the prose are not prose at all: they closed the literal and
10827
11891
  // the rest parsed as code. An HTML comment inside a template literal is still template text.
10828
11892
  p.innerHTML=`<h3>Member ${esc(m.id)}</h3>
10829
- ${typeFilterHTML()}
11893
+ ${typeFilterHTML(arr)}
10830
11894
  ${memberTypeField('mTypeS',[m])}
10831
11895
  <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 aria-label="Search the profile catalog" data-tip="Search the profile catalog — 4,516 profiles, by designation or alias"><svg viewBox="0 0 16 16" aria-hidden=true width=13 height=13 fill=none stroke=currentColor stroke-width=1.4 stroke-linecap=round><circle cx="6.9" cy="6.9" r="4.3"/><path d="M10.1 10.1 13.7 13.7"/></svg></button><button data-command-id="steel.pick-profile" id=pickProf class="ghost${(picking&&pickKind==='profile')?' on':''}" aria-pressed="${(picking&&pickKind==='profile')?'true':'false'}" aria-label="Pick profile from a drawing label" data-tip="Pick profile from drawing labels by click, Enter, or Space">⌖</button></div>${(picking&&pickKind==='profile')?'<div class="hint" data-profile-pick-status role=status aria-live=polite style="margin-top:4px;font-style:italic;color:var(--brand)">'+esc(profilePickGuidance())+'</div>':''}</div>
10832
11896
  <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 data-tip="${m.material?'This member carries its own grade, so it will not follow a profile change':'Empty — follows the profile’s default grade. Type or browse to give this member its own.'}"><button data-command-id="steel.browse-material-catalog" id=materialBrowseS class=ghost aria-label="Search material grades" data-tip="Search the material catalog by name or alias"><svg viewBox="0 0 16 16" aria-hidden=true width=13 height=13 fill=none stroke=currentColor stroke-width=1.4 stroke-linecap=round><circle cx="6.9" cy="6.9" r="4.3"/><path d="M10.1 10.1 13.7 13.7"/></svg></button><span class=pslot aria-hidden=true></span></div></div>
10833
11897
  <div class="row hint">Length <b>${L}</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> · '+_plf2(wpf)+' lb/ft'}</div>
10834
11898
  <div class=elab>Verified</div><span class=vwrap data-panel-control><button data-command-id="steel.member-verified" id=verifyBtn class="vbtn${m.verified?' on':''}" aria-pressed="${m.verified?'true':'false'}" data-tip="Mark this member human-confirmed">${m.verified?'✓ Human-confirmed':'Mark verified'}</button></span>
11899
+ ${mfSect}
10835
11900
  ${appearanceSect}
10836
11901
  ${braceSect}
10837
- ${mfSug.length?`<div class="row" style="border:1px solid var(--purple);border-radius:6px;padding:7px 8px;background:rgba(168,85,247,.07)"><div class=elab style="color:var(--purple-ink);margin:0">Moment-frame girder · ${_lvl==='roof'?'roof':'2nd floor'} (from Frames)</div><div style="display:flex;flex-wrap:wrap;gap:5px;margin-top:5px">${mfSug.map(s=>`<button data-command-id="steel.member-profile-suggestion#${esc(s)}" class="ghost mfsug${s===m.profile?' on':''}" data-s="${esc(s)}">${esc(s)}</button>`).join('')}</div></div>`:''}
10838
11902
  ${elev}
10839
11903
  ${defPts}
10840
11904
  ${bpSect}${spSect}${copeSect}
@@ -10882,7 +11946,10 @@ function panel(){
10882
11946
  }
10883
11947
  document.querySelectorAll('.msW').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'weight',b.dataset.w)); // F5: per member-type line weight
10884
11948
  document.querySelectorAll('.msD').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'dash',b.dataset.d)); // F5: per member-type line dash
10885
- document.querySelectorAll('.mfsug').forEach(b=>b.onclick=()=>edit(()=>{const profile=b.dataset.s;ModelCmd.patchMember(m,{profile,mf:true,rfi:_wtPlf(profile)==null});if(!profs.includes(profile)){profs.push(profile);profs.sort();}})); // record the moment-frame provenance (drives the confidence "schedule-resolved" factor)
11949
+ document.querySelectorAll('.mfsug').forEach(b=>b.onclick=()=>mfPickSize(m,b.dataset.s,profs)); // mf:true marks the beam as a moment frame: the automatic shear-plate pass skips its ends. No confidence code reads it.
11950
+ {const t=document.getElementById('mfToggle');if(t)t.onclick=()=>mfToggleMember(m);} // #2210: absent when off, never false — the shear-plate skip and the schedule read `mf===true`
11951
+ mfWireOffer();
11952
+ document.querySelectorAll('.mfopen').forEach(b=>b.onclick=()=>{const plan=C.plans&&C.plans[C.active];openFrames({invoker:b,focus:b.dataset.focus,focusView:plan?viewIdOf(plan):null,levelName:b.dataset.level||''});});
10886
11953
  const _gel=document.getElementById('geoEL'),_gsp=document.getElementById('geoSplit');
10887
11954
  if(_gel)_gel.onclick=()=>{geoMode=(geoMode==='el'?null:'el');setGeo();render();};
10888
11955
  if(_gsp)_gsp.onclick=()=>{geoMode=(geoMode==='split'?null:'split');setGeo();render();};
@@ -10962,16 +12029,16 @@ function panel(){
10962
12029
  const wireDetailBuild=(id,o,which)=>{
10963
12030
  const ap=document.getElementById(id+'_ap');
10964
12031
  if(ap)ap.onclick=()=>{
10965
- const r=resolveDetail(m,which);
10966
- if(!r.ok){toast(r.message);render();return;} // the model can move under an open panel — re-resolve, never build a stale answer
10967
- // Same guard the bulk sweep applies: a malformed model with repeated member ids would make a
10968
- // model-wide main+at match ambiguous. One button must not be laxer than the other.
10969
- if(duplicateMemberIds().has(m.id)){toast('More than one member is called '+m.id+', so this connection could land on the wrong one — rename one of them first.');return;}
10970
- const blk=detailApplyBlocker(m,which,r,false);
10971
- if(blk){toast('Not built — '+blk.text+'. Remove it first, or tune this one by hand.');return;}
10972
- let jid=null;edit(()=>{jid=buildJointFromDetail(m,which,r);});
10973
- pendingConnSel=jid; // its parts only exist after the 3D rebuild → select the whole connection there
10974
- toast('Built a '+kindLabel(r.kind)+' on '+m.id+' '+whichLabel(which)+' from '+(o.detail||'its connection'));
12032
+ // One decision for this button and the bulk sweep (applySingleDetail → detailEndDecision): the button must
12033
+ // not be laxer than the sweep — it once turned a person's matching connection into the action's own work.
12034
+ const out=applySingleDetail(m,which);
12035
+ if(out.outcome==='unresolved'){toast(out.message);render();return;} // the model can move under an open panel — re-resolved at click time, never a stale answer
12036
+ if(out.outcome==='duplicate-id'){toast('More than one member is called '+m.id+', so this connection could land on the wrong one — rename one of them first.');return;}
12037
+ if(out.outcome==='blocked'){toast('Not built — '+out.text+'. Remove it first, or tune this one by hand.');return;}
12038
+ if(out.outcome==='kept'){toast('Left as it is — this end already matches '+(o.detail||'its detail')+' and the connection is yours. Remove it first if you want it rebuilt from the detail.');return;}
12039
+ if(out.outcome==='refused')return; // edit() has already said why; nothing was built, so nothing is claimed
12040
+ pendingConnSel=out.id; // its parts only exist after the 3D rebuild → select the whole connection there
12041
+ toast('Built a '+kindLabel(out.res.kind)+' on '+m.id+' '+whichLabel(which)+' from '+(o.detail||'its connection'));
10975
12042
  };
10976
12043
  const cap=document.getElementById(id+'_cap');
10977
12044
  if(cap)cap.onclick=()=>openCaptureModal(m,which);
@@ -10997,7 +12064,7 @@ function panel(){
10997
12064
  edit(()=>{if(!bpj.params)bpj.params={};
10998
12065
  if(isFinite(n)&&n>0)bpj.params[key]=Math.min(isInt?MAXCOUNT:MAXDIM,n);
10999
12066
  else delete bpj.params[key]; // empty / invalid / ≤0 → drop the override so the engine falls back to its default
11000
- bpj.source='user';});};}; // through edit() → the param change is undoable; editing also makes the plate user-owned (survives the auto-detail "Clear")
12067
+ markJointTuned(bpj);});};}; // through edit() → the param change is undoable; editing also makes the plate user-owned (survives the auto-detail "Clear" and a later Build from details)
11001
12068
  ['plateWidth','plateDepth','thickness','boltDia','weldLeg','embedment','grout'].forEach(k=>wireBp(k,false));['boltCols','boltRows'].forEach(k=>wireBp(k,true));
11002
12069
  {const rm=document.getElementById('bpRemove');if(rm)rm.onclick=()=>edit(()=>{C.joints=(C.joints||[]).filter(j=>j!==bpj);});}
11003
12070
  {const tb=document.getElementById('bpTrim');if(tb)tb.onclick=()=>armBaseTrim(m.id);}} // Remove is undoable; Trim arms the 3D base pick
@@ -11026,19 +12093,19 @@ function panel(){
11026
12093
  // Enabling multiple columns: seed the column pitch from the current row pitch so the two axes are
11027
12094
  // DECOUPLED (else an absent boltColPitch silently inherits boltPitch and later row-pitch edits move both).
11028
12095
  if((Number(jj.params.boltCols)||1)>1&&jj.params.boltColPitch==null)jj.params.boltColPitch=jj.params.boltPitch!=null?jj.params.boltPitch:70;
11029
- jj.source='user';});};};
12096
+ markJointTuned(jj);});};};
11030
12097
  ['plateWidth','plateHeight','plateThickness','weldLeg','clearance','boltDia','boltPitch','boltColPitch'].forEach(k=>wsp(k,false));['boltCols','boltRows','plateCount'].forEach(k=>wsp(k,true));
11031
- {const setSide=(s)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.webSide=s;jj.source='user';}); // which face of the web the plate laps
12098
+ {const setSide=(s)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.webSide=s;markJointTuned(jj);}); // which face of the web the plate laps
11032
12099
  const n=document.getElementById('spside_e'+e+'_n');if(n)n.onclick=()=>setSide(1);
11033
12100
  const f=document.getElementById('spside_e'+e+'_f');if(f)f.onclick=()=>setSide(-1);}
11034
- {const setWeld=(s)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.weldSide=s;jj.source='user';}); // AISC fillet: which face(s) of the fin plate are welded to the support
12101
+ {const setWeld=(s)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.weldSide=s;markJointTuned(jj);}); // AISC fillet: which face(s) of the fin plate are welded to the support
11035
12102
  const wn=document.getElementById('spw_e'+e+'_n');if(wn)wn.onclick=()=>setWeld('near');
11036
12103
  const wf=document.getElementById('spw_e'+e+'_f');if(wf)wf.onclick=()=>setWeld('far');
11037
12104
  const wb=document.getElementById('spw_e'+e+'_b');if(wb)wb.onclick=()=>setWeld('both');}
11038
- {const setGrade=(g)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.boltGrade=g;jj.source='user';}); // AISC bolt grade (length auto-sizes from grip in the engine)
12105
+ {const setGrade=(g)=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.boltGrade=g;markJointTuned(jj);}); // AISC bolt grade (length auto-sizes from grip in the engine)
11039
12106
  const a=document.getElementById('spg_e'+e+'_325');if(a)a.onclick=()=>setGrade('A325');
11040
12107
  const b=document.getElementById('spg_e'+e+'_490');if(b)b.onclick=()=>setGrade('A490');}
11041
- {const ck=document.getElementById('spck_e'+e);if(ck)ck.onchange=ev=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.stiffener=ev.target.checked;jj.source='user';});}
12108
+ {const ck=document.getElementById('spck_e'+e);if(ck)ck.onchange=ev=>edit(()=>{const jj=(C.joints||[]).find(x=>x&&x.id===jid);if(!jj)return;if(!jj.params)jj.params={};jj.params.stiffener=ev.target.checked;markJointTuned(jj);});}
11042
12109
  {const rm=document.getElementById('sprm_e'+e);if(rm)rm.onclick=()=>edit(()=>{C.joints=(C.joints||[]).filter(x=>x!==j);});}} // Remove is undoable
11043
12110
  }
11044
12111
  // Definition points (F14) — each coord commits through edit() (undo + 2D + 3D + autosave). Enter = commit(blur),
@@ -11055,7 +12122,7 @@ function panel(){
11055
12122
  if(Pt)_dpCommit(i,Pt);};};
11056
12123
  const wireEnd=i=>_dpAxes.forEach((ax,a)=>{dpWire('dpG_'+i+'_'+a,i,a,false);if(_dpLocal)dpWire('dpL_'+i+'_'+a,i,a,true);});
11057
12124
  wireEnd(0);wireEnd(1);} // both points (beam Start/End, column Bottom/Top)
11058
- document.getElementById('del').onclick=()=>runSteelAuthoring('delete',{source:'inspector',selection:[m.id]},()=>edit(()=>{deleteV2Selection({memberIds:[m.id],dimIds:selDimIds});modelSelection.clearMembers();selDimIds.clear();}));
12125
+ document.getElementById('del').onclick=()=>{if(deleteStaysOnSheet({memberIds:[m.id],dimIds:selDimIds}))return;runSteelAuthoring('delete',{source:'inspector',selection:[m.id]},()=>edit(()=>{deleteV2Selection({memberIds:[m.id],dimIds:selDimIds});clearMembersAfterDelete();selDimIds.clear();}));};
11059
12126
  {const vb=document.getElementById('verifyBtn');if(vb)vb.onclick=()=>edit(()=>{ModelCmd.patchMember(m,{verified:!m.verified});});}
11060
12127
  }
11061
12128
 
@@ -12776,6 +13843,7 @@ function applyProfileLabel(prof){
12776
13843
  svg.addEventListener('keydown',e=>{const t=e.target;if(!t)return;
12777
13844
  const provisional=typeof t.closest==='function'?t.closest('[data-provisional-id]'):null;
12778
13845
  if(provisional&&(e.key==='Enter'||e.key===' ')){e.preventDefault();e.stopPropagation();selectProvisional(provisional.dataset.provisionalId,true,provisional.dataset.provisionalTrace);return;}
13846
+ if(t.classList&&t.classList.contains('cohot')&&(e.key==='Enter'||e.key===' ')){e.preventDefault();e.stopPropagation();if(calloutEditMode)calloutOpenForMark(t);else followCallout(t);return;} // a callout is a button: Enter / Space do what a click does (#2211)
12779
13847
  if(!t.classList||!t.classList.contains('lblhot'))return;
12780
13848
  if(e.key!=='Enter'&&e.key!==' ')return;e.preventDefault();e.stopPropagation();applyProfileLabel(t.dataset.prof);});
12781
13849
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
@@ -12784,6 +13852,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
12784
13852
  if(provisional){e.preventDefault();selectProvisional(provisional.dataset.provisionalId,false,provisional.dataset.provisionalTrace);return;}
12785
13853
  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;}
12786
13854
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
13855
+ if(calloutEditMode){calloutClick(e);e.preventDefault();return;} // + Callout armed → a click on a mark edits it, a click anywhere else adds one there (BEFORE the bubble-navigation branch below, and members/segments are inert)
12787
13856
  if(dimMode){dimClick(e);e.preventDefault();return;} // tool armed → all clicks place dimension points
12788
13857
  if(cmTool){cmClick(e);e.preventDefault();return;} // Move/Copy armed → clicks pick base/destination
12789
13858
  if(gridLinePick){let q=toSvg(e),x=q.x,y=q.y;if(!e.altKey){buildSnap(null);const sn=snap(x,y);x=sn.x;y=sn.y;}snapClear();
@@ -12846,12 +13915,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
12846
13915
  if(t.classList.contains('lblhot')){applyProfileLabel(t.dataset.prof);return;} // Add mode adopts it; an armed inspector applies it. Enter/Space call the same path above.
12847
13916
  if(t.classList.contains('dethot')){const det=t.dataset.det;
12848
13917
  if(picking&&pickKind==='detail'&&pickEnd){const o=pickEnd;picking=false;pickEnd=null;edit(()=>{ModelCmd.patchEnd(o,{detail:det});});}return;}
12849
- {const cg=t.closest('g.cohot');if(cg){const sheet=cg.dataset.coSheet,prev=cg.dataset.coPrev; // Workstream B smart jump
12850
- const idx=sheet?C.plans.findIndex(p=>p.sheet&&p.sheet.toUpperCase()===sheet.toUpperCase()):-1;
12851
- if(idx>=0){if(idx!==C.active)setPlan(idx);else fitToWindow();} // referenced sheet is loaded → switch to it (or re-frame if already here)
12852
- else if(sheet)tryDetailVector(sheet,prev); // not loaded → crisp VECTOR of the referenced sheet (else raster preview, else a toast)
12853
- else toast('No target sheet for this callout');
12854
- return;}}
13918
+ {const cg=t.closest('g.cohot');if(cg){followCallout(cg);e.preventDefault();return;}} // click a callout: go where it points (#2211: one view → go; several → pick; none → say so, never guess)
12855
13919
  if(t.classList.contains('seg')&&mode==='add'&&!drawDraft){addFromSeg(t.dataset.seg);return;} // segment quick-add ONLY when no draw is in progress; mid-draw a seg click falls through to drawClick → places the end ON that segment
12856
13920
  if(mode==='add'){drawClick(e);e.preventDefault();return;} // Add-member is click-to-place (like the Dimension tool): every canvas click drops a start/end point (snapped, incl. onto the traced overlay). Runs AFTER the label-pick (lblhot) and detected-segment (seg) branches above, so those still work.
12857
13921
  if(t.classList.contains('member')&&mode==='sel'&&selMemberOK(byId(t.dataset.id))){const id=t.dataset.id,ctrl=(e.ctrlKey||e.metaKey),add=(ctrl||e.shiftKey),p=toSvg(e); // Members select-switch (+ its per-type switch) gates the click; a filtered member is inert to the click
@@ -13094,6 +14158,90 @@ document.getElementById('csArm3dB').onclick=()=>{const d3=window.Steel3DView;if(
13094
14158
  * same place they do (render()'s trailing batch) so a change from ANY source — a click here, another
13095
14159
  * tab's event, a failed PUT reverting — repaints the control.
13096
14160
  */
14161
+ /* ── Columns ending below the floor: the PROJECT setting in ⋯ → Display (owner 2026-10-12) ─────────────────────────────────────────
14162
+ How far under a sheet's floor level a column can end and still be drawn on that sheet, dashed. Saved with the model
14163
+ (`column_below_reach_mm`, absent = the 1 ft default), so every sheet, "See what changed" and Review & approve read the same
14164
+ number. A typed LENGTH in the project's units (`parseLenMm`: a bare number is inches in a feet-and-inches project and
14165
+ millimetres in a metric one), committed on Enter or blur as ONE undoable step. A value that cannot be used (empty, unreadable,
14166
+ below zero, over 100 ft) says what is wrong and KEEPS the old one: nothing refuses, and nothing throws. */
14167
+ function reachEls(){const $=id=>document.getElementById(id);return {inp:$('reachInput'),def:$('reachDef'),reset:$('reachReset'),echo:$('reachEcho'),stat:$('reachStatus')};}
14168
+ function reachNow(){return SteelCore.columnBelowReachOf(C);}
14169
+ function reachExample(){return displayUnits()===DisplayUnits.MM?'150 · 0.3 m · 6"':'6" · 2\'-0" · 150 mm';}
14170
+ /** What a typed distance reads as: {ok, mm} or {ok:false, text} (the sentence that says what is wrong, ending with the value kept). */
14171
+ function reachRead(typed){
14172
+ const kept=' Kept '+underFloorText(reachNow())+'.';
14173
+ if(!typed)return {ok:false,text:'Type a distance, like '+reachExample().split(' · ')[0]+'.'+kept};
14174
+ const raw=parseLenMm(typed);
14175
+ if(raw==null||!Number.isFinite(raw))return {ok:false,text:'Couldn’t read “'+typed+'”. Try '+reachExample()+'.'+kept};
14176
+ // Nanometres: 12" parses as 304.79999999999995, which is not the default 304.8 it means, and 3" is 76.19999999999999.
14177
+ const mm=Math.round(raw*1e6)/1e6;
14178
+ if(mm<0)return {ok:false,text:'That’s below zero. Use 0 or more.'+kept};
14179
+ if(mm>SteelCore.COLUMN_BELOW_REACH_MAX_MM)return {ok:false,text:'That’s more than '+underFloorText(SteelCore.COLUMN_BELOW_REACH_MAX_MM)+'.'+kept};
14180
+ return {ok:true,mm};}
14181
+ /** What this distance would do on the sheet that is open: how many of its columns it would show, against how many it shows now. */
14182
+ function reachConsequence(mm){
14183
+ const plan=C&&C.plans&&C.plans[C.active];
14184
+ if(view3d||NO_PLAN_VIEW||!plan||plan.viewKind!=='plan'||!Number.isFinite(plan.elevation_mm))return '';
14185
+ const cols=(C.members||[]).filter(m=>m&&m.role==='column');if(!cols.length)return '';
14186
+ const shown=model=>cols.filter(m=>V2Projection.memberPresence(model,plan,m).visible).length;
14187
+ const was=shown(C),will=shown({...C,column_below_reach_mm:mm}),name=viewLabel(plan)||'this sheet';
14188
+ return was===will?'No change on '+name+': it keeps showing '+was+' of '+cols.length+' column'+(cols.length===1?'':'s')+'.'
14189
+ :'On '+name+', '+will+' of '+cols.length+' column'+(cols.length===1?'':'s')+' would show (now '+was+').';}
14190
+ function reachSay(text,bad){const e=reachEls();if(!e.stat)return;e.stat.textContent=text||'';e.stat.classList.toggle('bad',!!bad);
14191
+ if(bad)e.inp.setAttribute('aria-invalid','true');else e.inp.removeAttribute('aria-invalid');}
14192
+ /** The non-live reading under the field while a distance is being typed (the live line is only the commit and the error). */
14193
+ function reachPaintEcho(){
14194
+ const e=reachEls();if(!e.inp||!e.echo)return;
14195
+ const typed=e.inp.value.trim(),r=typed?reachRead(typed):null;
14196
+ if(!r||!r.ok){e.echo.textContent='';return;}
14197
+ const bare=/^[+-]?\d+(\.\d+)?$/.test(typed),unitNote=bare?(displayUnits()===DisplayUnits.MM?' No unit: read as millimetres.':' No unit: read as inches. Type 1\' for feet.'):'';
14198
+ e.echo.textContent=('Reads as '+fmtEcho(r.mm)+'.'+unitNote+' '+reachConsequence(r.mm)).trim();}
14199
+ /** The row follows the model: the stored value (or the default) in the field, "default" or Reset beside it. */
14200
+ function syncReachRow(){
14201
+ const e=reachEls();if(!e.inp||!e.def||!e.reset)return;
14202
+ const ready=!!C&&!!SteelCore; // boot() resolves the units before the first render; with no project and none stored, ft-in is the documented default
14203
+ e.inp.disabled=!ready;
14204
+ if(!ready)return; // the markup's "Loading…" placeholder stands: never a plausible guess
14205
+ const mm=reachNow(),isDefault=mm===SteelCore.COLUMN_BELOW_REACH_MM;
14206
+ if(document.activeElement!==e.inp){e.inp.value=fmtDisp(mm);e.echo.textContent='';e.inp.removeAttribute('aria-invalid');}
14207
+ e.inp.placeholder=reachExample().split(' · ')[0];
14208
+ e.def.hidden=!isDefault;e.reset.hidden=isDefault;
14209
+ e.reset.dataset.tip='Back to the default, '+underFloorText(SteelCore.COLUMN_BELOW_REACH_MM)+'.';}
14210
+ /** Enter or blur: apply what is typed. A bad value keeps the old one and says why; the same value writes nothing. */
14211
+ function commitReach(){
14212
+ const e=reachEls();if(!e.inp||e.inp.disabled)return false;
14213
+ const typed=e.inp.value.trim(),r=reachRead(typed);
14214
+ if(!r.ok){reachSay(r.text,true);return false;}
14215
+ if(r.mm===reachNow()){reachSay('');reachPaintEcho();return true;}
14216
+ reachTouched=true;
14217
+ if(!edit(()=>V2_SESSION.setColumnBelowReach(r.mm))){reachSay('That couldn’t be saved. Kept '+underFloorText(reachNow())+'.',true);return false;}
14218
+ reachSay('');
14219
+ toast(r.mm===0?'Only columns that reach a floor level are drawn on a sheet now. Ctrl+Z undoes it.'
14220
+ :'Columns ending up to '+underFloorText(r.mm)+' under a floor level are now drawn dashed on every sheet. Ctrl+Z undoes it.');
14221
+ syncReachRow();return true;}
14222
+ function resetReach(){
14223
+ reachTouched=true;
14224
+ if(!edit(()=>V2_SESSION.setColumnBelowReach(null)))return false;
14225
+ reachSay('');
14226
+ toast('Columns ending below a floor are back to the default of '+underFloorText(SteelCore.COLUMN_BELOW_REACH_MM)+'. Ctrl+Z undoes it.');
14227
+ syncReachRow();const e=reachEls();if(e.inp)e.inp.focus(); // the Reset button hides itself, so focus goes to the field
14228
+ return true;}
14229
+ {const e=reachEls();
14230
+ if(e.inp){
14231
+ // The field owns its keys: typing 6" must never arm a tool, and Escape puts the stored value back before it closes the menu.
14232
+ e.inp.addEventListener('keydown',ev=>{
14233
+ if(ev.key==='Escape'){ // the first Escape puts the stored value back; with nothing typed it is not ours, and closes the menu
14234
+ if(e.inp.value.trim()===fmtDisp(reachNow())&&!e.stat.textContent)return;
14235
+ ev.stopPropagation();ev.preventDefault();if(window.OverlayEscape)window.OverlayEscape.markUsed(ev);
14236
+ e.inp.value=fmtDisp(reachNow());reachSay('');e.echo.textContent='';return;}
14237
+ ev.stopPropagation();
14238
+ if(ev.key==='Enter'){ev.preventDefault();commitReach();}});
14239
+ e.inp.addEventListener('input',()=>{reachSay('');reachPaintEcho();});
14240
+ e.inp.addEventListener('change',()=>{if(document.activeElement!==e.inp){ // a blur: a value that cannot be used snaps back and says so once
14241
+ const ok=commitReach();if(!ok){const text=e.stat.textContent;e.inp.value=fmtDisp(reachNow());e.echo.textContent='';if(text)toast(text);}}});
14242
+ e.inp.addEventListener('click',ev=>ev.stopPropagation()); // clicking the field must not close the ⋯ menu
14243
+ }
14244
+ if(e.reset){e.reset.onclick=ev=>{ev.stopPropagation();resetReach();};keyActivates(e.reset);}}
13097
14245
  function syncUnitsRow(){
13098
14246
  const ft=document.getElementById('unitsFt'),mm=document.getElementById('unitsMm');
13099
14247
  // `displayUnitsPref` is null only before boot() has resolved it. NEITHER segment is marked then — this
@@ -13203,7 +14351,7 @@ function syncEnvChip(){
13203
14351
  // pair used elsewhere in this file; without it a switch arriving from another tab left an open report
13204
14352
  // stating the old system's word beside the new system's numbers. (The picker `refresh()` calls are
13205
14353
  // here for the same reason, found the same way — an open control cannot repaint itself.)
13206
- redrawForUnitsFn=()=>{syncUnitsRow();syncEnvChip();render();sync3D();viewGenRebaseUnits();profilePicker.refresh();materialPicker.refresh();if(confOpen())renderConf();};
14354
+ redrawForUnitsFn=()=>{syncUnitsRow();syncReachRow();syncEnvChip();render();sync3D();viewGenRebaseUnits();profilePicker.refresh();materialPicker.refresh();if(confOpen())renderConf();};
13207
14355
  {const pick=(id,units)=>{const b=document.getElementById(id);if(!b)return;
13208
14356
  b.onclick=e=>{e.stopPropagation();if(b.disabled||displayUnits()===units)return;commitDisplayUnits(units);};};
13209
14357
  pick('unitsFt',DisplayUnits.FT_IN);pick('unitsMm',DisplayUnits.MM);
@@ -13236,11 +14384,14 @@ document.getElementById('posGizmoToggleB').onclick=e=>{e.stopPropagation();showP
13236
14384
  sizeGridBubbles();
13237
14385
  if(window.Steel3DView&&window.Steel3DView.setGridLabelPx)window.Steel3DView.setGridLabelPx(gridLabelPx);});}}
13238
14386
  let gridLabelPxSaveWarned=false;
13239
- function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(!b)return;b.disabled=false;b.classList.toggle('on',calloutsVisible);b.setAttribute('aria-checked',String(calloutsVisible));}
14387
+ function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(!b)return;b.disabled=false;b.classList.toggle('on',calloutsVisible);b.setAttribute('aria-checked',String(calloutsVisible));
14388
+ // A quiet note on the row, not a banner on the canvas: "Callouts" ticked with nothing to show reads as broken.
14389
+ const note=document.getElementById('calloutNote');if(note)note.textContent=(P&&!NO_PLAN_VIEW&&MarksCore&&(P.details||[]).length+(P.callouts||[]).length===0)?'none on this sheet':'';}
13240
14390
  document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
13241
14391
  // Property SELECTION (props, placement) is shared; visibility and scope belong to the view the menu targets.
13242
- // ⋯ ▸ Display targets the active pane (2D plan, or 3D); the 3D toolbar menu always targets 3D. Both 3D menus
13243
- // therefore edit one set — the active saved view's, or the 3D default when none is active.
14392
+ // ⋯ ▸ Display targets the active pane (2D plan, or 3D); the 3D toolbar menu always targets 3D, and the 2D toolbar's
14393
+ // Labels menu (#2216) always targets the 2D plan. So with 3D active, ⋯ ▸ Display and the 3D menu edit one set — the
14394
+ // active saved view's, or the 3D default when none is active — and the 2D menu edits the plan's own.
13244
14395
  function setPropLabelScope(key,is3d){const viewId=is3d?activeViewId:null;
13245
14396
  if(key==='selected_only'&&!labelTarget(is3d,viewId).scope.selected_only&&!propLabelSelection().length)return; // checked BEFORE the write target, so a refused click never materialises a view's copy
13246
14397
  const pl=C.prop_labels,sc=labelWriteTarget(is3d,viewId).scope,on=!sc[key];
@@ -13250,13 +14401,27 @@ function setPropLabelScope(key,is3d){const viewId=is3d?activeViewId:null;
13250
14401
  if(key==='selected_only')sc.ids=on?propLabelSelection().map(m=>m.id):[];
13251
14402
  if(key==='on_selection'&&on&&!knownPropCount(pl))pl.props.push('profile');
13252
14403
  refreshPropLabels();}
14404
+ // The property-label menus, keyed by element prefix: prefix -> {vis, pane}. wirePropLabelSection fills it and
14405
+ // updPlToggle reads it, so a menu that is wired is by construction a menu that is kept in step, and a menu
14406
+ // cannot be one without the other. `pane` says which label set the menu edits:
14407
+ // 'active' - whatever pane is on screen (⋯ ▸ Display: the 2D plan, or 3D when 3D is active)
14408
+ // '3d' - always 3D (the 3D toolbar's Labels menu)
14409
+ // '2d' - always the 2D plan (the 2D toolbar's Labels button, #2216), even in Split with 3D active
14410
+ // A Map, so re-wiring a menu (wire3DBar re-renders the 3D shell) replaces its entry instead of doubling it.
14411
+ const propLabelMenus=new Map();
14412
+ function labelPaneIs3d(pane){return pane==='3d'||(pane==='active'&&view3d);}
13253
14413
  function updPlToggle(){const pl=C.prop_labels;if(!pl)return;reconcileActiveView();
13254
- for(const [prefix,vis,is3d] of [['pl','plToggleB',view3d],['m3dPl','m3dPropLabels',true]]){
14414
+ for(const [prefix,{vis,pane}] of propLabelMenus){
14415
+ const is3d=labelPaneIs3d(pane);
13255
14416
  const t=labelTarget(is3d,is3d?activeViewId:null),sc=t.scope,name=labelTargetName(is3d);
13256
14417
  const b=document.getElementById(vis);
13257
14418
  if(b){b.classList.toggle('on',t.vis);b.setAttribute('aria-checked',String(t.vis));b.setAttribute('aria-label','Property labels in '+name);}
13258
14419
  // Names the set the rows below edit. Written by id, unguarded, so losing either line fails loudly.
13259
- const ctx=document.getElementById(prefix+'Context');ctx.textContent=name;ctx.setAttribute('data-tip','These settings apply to: '+name);
14420
+ // ⋯ ▸ Display alone follows the pane you last clicked, and in Split both panes are on screen, so it says so
14421
+ // there: the same words in the two Labels buttons would otherwise read as one control.
14422
+ const follows=pane==='active'&&viewMode==='split';
14423
+ const ctx=document.getElementById(prefix+'Context');ctx.textContent=follows?name+' · active pane':name;
14424
+ ctx.setAttribute('data-tip','These settings apply to: '+name+(follows?' (the pane you last clicked). The Labels button in each pane edits that pane’s own labels.':''));
13260
14425
  for(const [suffix,key] of [['All','for_all'],['Selected','selected_only'],['OnSelection','on_selection']]){
13261
14426
  const el=document.getElementById(prefix+suffix);el.classList.toggle('on',!!sc[key]);el.setAttribute('aria-checked',String(!!sc[key]));
13262
14427
  const blocked=key==='selected_only'&&!sc.selected_only&&!propLabelSelection().length;el.disabled=blocked;
@@ -13264,17 +14429,36 @@ function updPlToggle(){const pl=C.prop_labels;if(!pl)return;reconcileActiveView(
13264
14429
  }
13265
14430
  document.getElementById(prefix+'Pinned').textContent=sc.selected_only?sc.ids.length+' pinned · turn off and on to replace':!propLabelSelection().length?'Select members first':'Keeps the selection made when enabled';
13266
14431
  }
13267
- }
13268
- function wirePropLabelSection(prefix,vis,disclosure,scope,is3d){
14432
+ updateLabelsBandMarks();
14433
+ }
14434
+ // The corner dot on a Labels button says "something is on" without opening the menu. It reads the same
14435
+ // switches the menus show, so it cannot disagree with them: the 3D button follows Ref line + the 3D property-label
14436
+ // switch, the 2D button follows the 2D plan's property-label switch only, whichever pane is active.
14437
+ function updateLabelsBandMarks(){
14438
+ for(const [btnId,switchIds] of [['m3dView',['m3dRef','m3dPropLabels']],['pl2dBtn',['pl2dPropLabels']]]){
14439
+ // The 2D button is wired after the 3D shell at boot, so it is skipped until it is registered. Once registered it is
14440
+ // required: a missing button then means the menu was wired against markup that was never drawn.
14441
+ if(btnId==='pl2dBtn'&&!propLabelMenus.has('pl2d'))continue;
14442
+ const btn=document.getElementById(btnId);
14443
+ if(!btn){if(btnId==='pl2dBtn')throw new Error('The 2D toolbar Labels button is missing, so its state mark cannot be kept');continue;}
14444
+ const on=switchIds.some(id=>{const e=document.getElementById(id);return e&&(e.checked||(e.classList&&e.classList.contains('on'))||e.getAttribute('aria-checked')==='true');});
14445
+ if(on)btn.setAttribute('data-state-on','');else btn.removeAttribute('data-state-on');}
14446
+ }
14447
+ function wirePropLabelSection(prefix,vis,disclosure,scope,pane){
13269
14448
  const section=document.getElementById(prefix+'Section'),d=document.getElementById(disclosure),body=document.getElementById(scope);
13270
14449
  if(!section||!d||!body)throw new Error('Property-label controls are missing for '+prefix);
14450
+ // Every id the handlers and updPlToggle will address, checked BEFORE anything is wired or registered: a menu that is
14451
+ // half-drawn must fail loudly here, not as a TypeError inside the first click or the next render.
14452
+ const missing=[vis,prefix+'All',prefix+'Selected',prefix+'OnSelection',prefix+'Pinned',prefix+'Context'].filter(id=>!document.getElementById(id));
14453
+ if(missing.length)throw new Error('Property-label controls are missing for '+prefix+': '+missing.join(', '));
14454
+ propLabelMenus.set(prefix,{vis,pane});
13271
14455
  section.onclick=e=>e.stopPropagation();
13272
14456
  section.onkeydown=e=>{if((e.key==='Enter'||e.key===' ')&&e.target.tagName==='BUTTON'){e.preventDefault();e.stopPropagation();if(!e.repeat)e.target.click();}};
13273
14457
  d.onclick=()=>{const open=d.getAttribute('aria-expanded')!=='true';d.setAttribute('aria-expanded',String(open));body.hidden=!open;d.querySelector('.pl-chevron').textContent=open?'▾':'▸';if(!open)d.focus();};
13274
- document.getElementById(vis).onclick=()=>{const in3d=is3d||view3d,w=labelWriteTarget(in3d,in3d?activeViewId:null);w.host[w.visKey]=!plVis(in3d);refreshPropLabels();};
13275
- for(const [suffix,key] of [['All','for_all'],['Selected','selected_only'],['OnSelection','on_selection']])document.getElementById(prefix+suffix).onclick=()=>setPropLabelScope(key,is3d||view3d);
14458
+ document.getElementById(vis).onclick=()=>{const in3d=labelPaneIs3d(pane),w=labelWriteTarget(in3d,in3d?activeViewId:null);w.host[w.visKey]=!plVis(in3d);refreshPropLabels();};
14459
+ for(const [suffix,key] of [['All','for_all'],['Selected','selected_only'],['OnSelection','on_selection']])document.getElementById(prefix+suffix).onclick=()=>setPropLabelScope(key,labelPaneIs3d(pane));
13276
14460
  }
13277
- wirePropLabelSection('pl','plToggleB','plDisclosure','plScope',false);
14461
+ wirePropLabelSection('pl','plToggleB','plDisclosure','plScope','active');
13278
14462
  // Materialise the hidden 3D toolbar shell during normal editor boot. Property-label scope is shared
13279
14463
  // between 2D and 3D, so both menus must remain live even before WebGL has started. wire3DBar() renders
13280
14464
  // the shell again when the 3D provider exists, then attaches the provider-dependent controls.
@@ -13283,11 +14467,32 @@ function render3DToolbarShell(){
13283
14467
  // The pinned master is the visual oracle; the shared renderer is now the only implementation of its
13284
14468
  // common view band. Steel contributes its Labels menu through the adapter instead of owning a copy.
13285
14469
  bar.innerHTML=ViewportToolbar.renderToolbarMarkup(ModelEditor.steelRenderPlan());
13286
- wirePropLabelSection('m3dPl','m3dPropLabels','m3dPlDisclosure','m3dPlScope',true);
14470
+ wirePropLabelSection('m3dPl','m3dPropLabels','m3dPlDisclosure','m3dPlScope','3d');
13287
14471
  updPlToggle();
13288
14472
  return bar;
13289
14473
  }
13290
14474
  render3DToolbarShell();
14475
+ // The 2D plan toolbar's Labels button (#2216). Unlike the 3D shell it needs no provider, so it is drawn and wired
14476
+ // once, here: the slot in #viewBar2d is filled from the same section spec the 3D menu uses (minus its Ref line), the
14477
+ // section is wired to the 2D plan whichever pane is active, and the shared toolbar chrome gives it the same open /
14478
+ // Escape / outside-click / arrow-key behaviour as the 3D menus.
14479
+ function render2DLabelsMenu(){
14480
+ const slot=document.getElementById('viewBar2dLabels'),bar=document.getElementById('viewBar2d');
14481
+ slot.innerHTML=ViewportToolbar.renderToolbarMarkup(ModelEditor.steelLabels2dPlan());
14482
+ wirePropLabelSection('pl2d','pl2dPropLabels','pl2dDisclosure','pl2dScope','2d');
14483
+ updPlToggle();
14484
+ const items=()=>['fit2d','fitSel2d','pl2dBtn'].map(id=>document.getElementById(id)).filter(el=>el&&el.offsetParent!==null);
14485
+ return ViewportToolbar.mountToolbarChrome({toolbar:bar,getItems:items,onBeforeOpen:()=>updPlToggle()});
14486
+ }
14487
+ const labels2dChrome=render2DLabelsMenu();
14488
+ function labels2dOpen(){const m=document.getElementById('pl2dMenu');return !!m&&m.classList.contains('open');}
14489
+ // Outside-click dismissal on POINTERDOWN. The shared chrome dismisses on mousedown, but the plan canvas (like the 3D one)
14490
+ // cancels its pointerdown, and a cancelled pointerdown suppresses the compatibility mousedown, so a click on the plan
14491
+ // never reached it and the menu stayed hanging over the drawing. The Labels menu sits ON the plan, so it must close
14492
+ // when you go back to the plan.
14493
+ document.addEventListener('pointerdown',e=>{if(!labels2dOpen())return;
14494
+ if(document.getElementById('pl2dMenu').contains(e.target)||document.getElementById('pl2dBtn').contains(e.target))return;
14495
+ labels2dChrome.closeMenus();},true);
13291
14496
 
13292
14497
  const REF_TIP='Show or hide the source drawing under the model. The source image is visual context; traced lines—not the raster—provide snap points.';
13293
14498
  function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;const on=refSheetOn;b.disabled=!hasOverlay();b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));
@@ -13342,7 +14547,7 @@ addEventListener('keydown',e=>{
13342
14547
  // This listener is mounted before the shared 3D arbiter. If an editor-owned Escape rung below
13343
14548
  // has work to do, stop later listeners now so one keypress cannot also clear a selected clip.
13344
14549
  const editorOwnsEscape=e.key==='Escape'&&view3d&&(
13345
- !!memberEndReview||!!dimEdit||moreOpen()||xfMenuC.isOpen()||lvOpen()||lightboxOpen()||askAiIsOpen()||favModalIsOpen()||detailsOpen()||connLibOpen()||framesOpen()||rfiOpen()||confOpen()||snapMenuOpen()||selFly.classList.contains('open')||
14550
+ !!memberEndReview||!!dimEdit||moreOpen()||xfMenuC.isOpen()||labels2dOpen()||lvOpen()||lightboxOpen()||askAiIsOpen()||favModalIsOpen()||detailsOpen()||connLibOpen()||framesOpen()||rfiOpen()||confOpen()||snapMenuOpen()||selFly.classList.contains('open')||
13346
14551
  !!drag||!!gridLinePick||!!gridPick||!!gridMode||!!dimStyleMode||!!cmTool||!!csaxisMode||!!qdPick||!!dimMode||!!selDimIds.size||mode==='add'||
13347
14552
  modelEditor.steel.teklaDragging()||modelEditor.steel.refMeasureArmed()||!!geoMode);
13348
14553
  if(editorOwnsEscape)e.stopImmediatePropagation();
@@ -13354,6 +14559,7 @@ addEventListener('keydown',e=>{
13354
14559
  if(e.key==='Escape'&&modelEditor.steel.teklaDragging())return;
13355
14560
  if(e.key==='Escape'&&moreOpen()){closeMore();moreBtn.focus();return;}
13356
14561
  if(e.key==='Escape'&&xfMenuC.isOpen()){xfMenuC.close();return;}
14562
+ if(e.key==='Escape'&&labels2dOpen()){labels2dChrome.closeMenus();document.getElementById('pl2dBtn').focus();return;} // the 2D Labels menu closes first and leaves the selection alone (#2216)
13357
14563
  if(lvOpen()){if(e.key==='Escape')closeLevelModal();return;} // the level modal is modal: no Delete/undo/tool keys mutate state underneath it
13358
14564
  if(e.key==='Escape'&&lightboxOpen()){closeLightbox();return;}
13359
14565
  if(e.key==='Escape'&&askAiIsOpen()&&document.getElementById('askAiModal').contains(_ae)){askAiClose();return;}
@@ -13386,6 +14592,7 @@ addEventListener('keydown',e=>{
13386
14592
  else if(view3d&&window.Steel3DView&&window.Steel3DView.cmEscape&&window.Steel3DView.cmEscape()){} // 3D: step the pick back (array dir A → base) before exiting
13387
14593
  else if(cmDraft&&cmDraft.vA){cmDraft.vA=null;cmRefreshPrev();panel();}else if(cmDraft){cmDraft=null;cmPrevClear();panel();}else{disarmCm();render();}return;} // Move/Copy Esc ladder: HUD → array dir A → base pick → exit tool
13388
14594
  if(e.key==='Escape'&&csaxisMode){if(csDraft){csDraft=null;csPrevClear();}else{csaxisMode=false;setCsMode();}render();return;} // 1st Esc drops the in-progress origin, 2nd exits set-axes
14595
+ if(e.key==='Escape'&&calloutEditMode){calloutDisarmByKey();return;} // + Callout: 1st Esc closes the open form (the tool stays armed), 2nd disarms it (a form's own Esc never reaches here: it stops the key)
13389
14596
  if(e.key==='Enter'&&dimMode&&dimChainPrev){e.preventDefault();dimChainPrev=null;dimPrevClear();render();return;} // Enter ends a running chain
13390
14597
  if(e.key==='Escape'&&qdPick){qdPick=null;setQdPickCls();toast('Quick-dim cancelled');return;} // Esc disarms the F7 grid station pick (selection stays)
13391
14598
  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
@@ -13416,10 +14623,13 @@ addEventListener('keydown',e=>{
13416
14623
  const _kg=gridOf();const freeToDelete=(_kg&&Array.isArray(_kg.lines))?_kg.lines.filter(l=>glLids.has(String(l.id))):[]; // only lines that actually still exist → also guards the phantom-undo case (list cleared out from under the selection)
13417
14624
  const hadReg=[...selGridIds].some(id=>id.startsWith('gv:')||id.startsWith('gh:')); // regular (spacing-generated) lines can't be individually deleted
13418
14625
  const willMutate=selDimIds.size||selIds.size||freeToDelete.length;
14626
+ // #2214: only columns this sheet DERIVES from its floor level are selected: there is nothing to delete, so say so
14627
+ // WITHOUT an edit (no empty undo step, no unsaved mark) and keep the selection, which keeps the notice up.
14628
+ if(willMutate&&deleteStaysOnSheet({memberIds:new Set([...selIds].filter(id=>!!byId(id))),dimIds:selDimIds,jointIds:selJointIds(),gridLineIds:new Set(freeToDelete.map(line=>String(line.id)))}))return;
13419
14629
  if(willMutate)runSteelAuthoring('delete',{source:'keyboard',selection:[...selIds],dimensions:[...selDimIds],gridLines:[...glLids]},()=>edit(()=>{
13420
14630
  const jids=selJointIds(),memberIds=new Set([...selIds].filter(id=>!!byId(id)));
13421
14631
  deleteV2Selection({memberIds,dimIds:selDimIds,jointIds:jids,gridLineIds:new Set(freeToDelete.map(line=>String(line.id)))});
13422
- modelSelection.clearMembers();selDimIds.clear();modelSelection.clearGrids();}));
14632
+ clearMembersAfterDelete();selDimIds.clear();modelSelection.clearGrids();}));
13423
14633
  else{modelSelection.clearGrids();render();} // only regular grid lines were selected → nothing to delete (no phantom undo step); repaint to drop the highlight
13424
14634
  if(hadReg)toast('Regular grid lines come from the grid spacing — remove them in “Grid lines…”. Only free grid lines are deletable here.');
13425
14635
  return;}
@@ -14793,7 +16003,7 @@ const chatQuestionsUi={moreOpen:false,orphansOpen:false}; // stays open across
14793
16003
  function paintChatQuestions(p){
14794
16004
  p.querySelector(':scope > .chat-questions')?.remove();
14795
16005
  if(!ChatQuestions||!chatLinksAvailable()||chatLinks.state==='idle')return;
14796
- const takeover=gridMode||memberEndScan||memberEndReview||viewPropsId||dimStyleMode||NO_PLAN_VIEW||provisionalSelId||refSelectedObjIdx!==null||mode!=='sel';
16006
+ const takeover=gridMode||memberEndScan||memberEndReview||viewPropsId||dimStyleMode||NO_PLAN_VIEW||provisionalSelId||refSelectedObjIdx!==null||mode!=='sel'||calloutEditMode;
14797
16007
  if(takeover)return;
14798
16008
  const selected=canonicalTargetItems([...selIds]).items;
14799
16009
  const nothing=!selIds.size&&!selGridIds.size&&!selDimIds.size;
@@ -15471,17 +16681,17 @@ function memberTypeField(id,ms){
15471
16681
  // 2D glow/badges, the 3D highlight, AND re-runs panel(), which re-derives the strip from the now-smaller selection.
15472
16682
  // GRIDS: selected regular/free grid lines participate through selGridIds, alongside members and dimensions.
15473
16683
  function gridSelSet(){return (typeof selGridIds!=='undefined'&&selGridIds&&typeof selGridIds.size==='number')?selGridIds:null;}
15474
- function typeFilterGroups(){
16684
+ function typeFilterGroups(members=selArr()){
15475
16685
  const g=[],by=new Map();
15476
- for(const m of selArr()){const k=memberTypeOf(m);if(!by.has(k))by.set(k,[]);by.get(k).push(m.id);}
16686
+ for(const m of members){const k=memberTypeOf(m);if(!by.has(k))by.set(k,[]);by.get(k).push(m.id);}
15477
16687
  for(const rec of memberTypeRecords())if(by.has(rec.k))g.push({kind:'member',key:rec.k,label:rec.label,ids:by.get(rec.k)}); // canonical member-type order (Column, Beam, Brace, Ledger, Frame, then custom)
15478
16688
  for(const [k,ids] of by)if(!g.some(x=>x.key===k))g.push({kind:'member',key:k,label:memberTypeLabel(k),ids}); // any stray key not in the records list (defensive)
15479
16689
  if(selDimIds.size)g.push({kind:'dim',key:'__dims',label:'Dimensions',ids:[...selDimIds]});
15480
16690
  const G=gridSelSet();if(G&&G.size)g.push({kind:'grid',key:'__grids',label:'Grids',ids:[...G]});
15481
16691
  return g;
15482
16692
  }
15483
- function typeFilterHTML(){
15484
- const g=typeFilterGroups();if(g.length<2)return ''; // one type only → nothing to filter → no strip (the >1-type gate)
16693
+ function typeFilterHTML(members){
16694
+ const g=typeFilterGroups(members);if(g.length<2)return ''; // one type only → nothing to filter → no strip (the >1-type gate)
15485
16695
  const chips=g.map(x=>{const tip=`Click to drop ${x.label} · Alt-click to isolate ${x.label}`;
15486
16696
  const aria=`${x.label}, ${x.ids.length} selected. Activate to drop, hold Alt to isolate.`; // accessible name keeps the COUNT (visible-text override would lose it) + gesture-neutral wording; data-tip carries the pointer copy
15487
16697
  return `<button data-command-id="steel.selection-drop-type#${esc(x.label)}" type=button class="tfchip${x.kind!=='member'?' tfdim':''}" data-tfkind="${x.kind}" data-tfkey="${esc(x.key)}" data-tip="${esc(tip)}" aria-label="${esc(aria)}">${esc(x.label)} · ${x.ids.length}</button>`;}).join(''); // dashed = a non-member (annotation/reference) group: Dimensions, Grids
@@ -20699,10 +21909,9 @@ function updateBandStateMarks(){
20699
21909
  const n=modelEditor.isReady()?modelEditor.steel.clips().filter(c=>c&&c.enabled).length:0;
20700
21910
  if(n>0){clipBtn.setAttribute('data-state-count',String(n));}else clipBtn.removeAttribute('data-state-count');}
20701
21911
  // The Display toggles are sliders, not checkboxes, so this state is a class and an
20702
- // aria-checked, not `.checked` — reading only the old shape would leave the badge permanently dark.
20703
- if(labelBtn){const on=['m3dRef','m3dPropLabels'].filter(id=>{const e=document.getElementById(id);
20704
- return e&&(e.checked||(e.classList&&e.classList.contains('on'))||e.getAttribute('aria-checked')==='true');});
20705
- if(on.length){labelBtn.setAttribute('data-state-on','');}else labelBtn.removeAttribute('data-state-on');}
21912
+ // aria-checked, not `.checked` — updateLabelsBandMarks reads that shape (reading only the old one would leave
21913
+ // the badge permanently dark), and it covers the 2D plan's Labels button too.
21914
+ if(labelBtn)updateLabelsBandMarks();
20706
21915
  }
20707
21916
  function updateWorkBtn(){const b=document.getElementById('m3dWork'),ck=document.getElementById('m3dWorkOn'),wh=document.getElementById('m3dWorkWhole');if(!b||!window.Steel3DView||!window.Steel3DView.workAreaState)return;
20708
21917
  const st=window.Steel3DView.workAreaState(),on=!!(st&&st.on);
@@ -20888,7 +22097,7 @@ function wire3DBar(){if(bar3dWired||!window.Steel3DView)return;
20888
22097
  document.getElementById('insFile').onchange=e=>{const f=e.target.files&&e.target.files[0];e.target.value='';if(!f)return;
20889
22098
  readImageCompressed(f,b64=>{if(!b64){toast('Could not read that image — try another.');return;}
20890
22099
  let base=(f.name||'Detail').replace(/\.[^.]+$/,'').trim()||'Detail',name=base,i=2;while(C.custom_details[name]!=null)name=base+' '+(i++);
20891
- edit(()=>{C.custom_details[name]=b64;});armInsert(name);});};
22100
+ addCustomDetail(name,b64);armInsert(name);});};
20892
22101
  // ── Import a connection from IFC (slice B): dropzone → parse → pick → extract → arm the crosshair
20893
22102
  // place. The reader runs in AWARE (web-ifc) via /api/import-connection; the UI renders + relays. Staged
20894
22103
  // states swap in one modal (never a disabled Place button — the whole body swaps). ──
@@ -21076,6 +22285,7 @@ function reflectViewChrome(){
21076
22285
  if(tb&&host&&tb.parentElement!==host)host.appendChild(tb);}
21077
22286
  if(view3dShown)try{updateBandStateMarks();}catch(_){} // state the band already holds on arrival
21078
22287
  document.getElementById('viewBar2d').style.display=chrome.viewBar2d?'':'none'; // the 2D view band addresses the plan canvas
22288
+ if(!chrome.viewBar2d&&labels2dOpen())labels2dChrome.closeMenus(); // its Labels menu goes with it: an open menu on a hidden band would own the next Escape (editorOwnsEscape) with nothing on screen to close
21079
22289
  // Plan switcher is 2D-only (3D shows the whole model). Hidden by `display`, not the `hidden` attribute:
21080
22290
  // .plan-combo carries an author `display:inline-flex`, which beats the UA's [hidden] rule by ORIGIN, so
21081
22291
  // `hidden = true` would quietly do nothing here.
@@ -21095,6 +22305,7 @@ function reflectViewChrome(){
21095
22305
  if(ae&&!chrome.dim2d&&dimB&&dimB.contains(ae)&&chrome.dim3d&&dim3d){const t=dim3d.querySelector('button');if(t)t.focus();}
21096
22306
  else if(ae&&!chrome.dim3d&&dim3d&&dim3d.contains(ae)&&chrome.dim2d&&dimB)dimB.focus();
21097
22307
  dimB.style.display=chrome.dim2d?'':'none'; // 2D Dimension button — the ACTIVE pane's
22308
+ {const coB=document.getElementById('calloutB');if(coB)coB.style.display=chrome.dim2d?'':'none';} // + Callout is a plan tool, shown with the 2D Dimension button and hidden (not disabled) with the 3D cluster
21098
22309
  dim3d.style.display=chrome.dim3d?'inline-flex':'none'; // 3D Dimension cluster (moved to header) — likewise
21099
22310
  document.body.classList.toggle('v3d',chrome.v3d); // 3D-only chrome (e.g. ⋯ → Detailing → Insert detail) keys off this
21100
22311
  document.getElementById('ptrBars').classList.toggle('s3d',view3dShown); // the bars clear the world-axis TRIAD, which is drawn whenever the 3D pane is on screen; see #ptrBars.s3d
@@ -21156,6 +22367,7 @@ function onActivePaneChange(){
21156
22367
  if(csaxisMode){csaxisMode=false;setCsMode();}
21157
22368
  if(picking){picking=false;pickKind='profile';pickEnd=null;}
21158
22369
  if(activePane==='2d'){ // about to LEAVE 2D: these share keys with the 3D dim tool
22370
+ if(calloutEditMode){disarmed2d=true;calloutEditMode=false;document.body.classList.remove('calloutedit');closeCalloutForm();} // the + Callout tool is a plan tool too
21159
22371
  if(dimMode||dimChain||dimSplitMode){disarmed2d=true;dimMode=dimChain=dimSplitMode=false;selDimIds.clear();setDimMode();document.body.classList.remove('dimsplit');}
21160
22372
  if(dimStyleMode){disarmed2d=true;dimStyleMode=false;}
21161
22373
  if(qdPick){disarmed2d=true;qdPick=null;setQdPickCls();}
@@ -21586,28 +22798,116 @@ function detThumb(text,imgEl){const key=(sheetOf(text)||'')+'|'+(numOf(text)||''
21586
22798
  cv.getContext('2d').drawImage(im,left,top,cw,ch,0,0,cw,ch);
21587
22799
  try{const u=cv.toDataURL('image/jpeg',0.85);THUMBS[key]=u;imgEl.src=u;}catch(_){}};
21588
22800
  im.src='data:image/jpeg;base64,'+b64;}
22801
+ /** A short fingerprint of a picture (its length and a 32-bit FNV-1a of its text): enough to tell "the same picture" from "another one". */
22802
+ function picFp(v){const s=String(v==null?'':v);let h=0x811c9dc5;for(let i=0;i<s.length;i++){h^=s.charCodeAt(i);h=Math.imul(h,0x01000193)>>>0;}return s.length+':'+h.toString(36);}
22803
+ /** The key a picture is kept under in `picStore`: its fingerprint, with a `#n` suffix when a DIFFERENT picture already holds that fingerprint. Never two pictures under one key. */
22804
+ function pictureKey(bytes){
22805
+ const fp=picFp(bytes);
22806
+ for(let n=0;;n++){const key=n?fp+'#'+n:fp;if(!picStore.has(key)){picStore.set(key,bytes);return key;}if(picStore.get(key)===bytes)return key;}
22807
+ }
22808
+ /** The library as the undo snapshot records it: {name: key}. Each distinct picture is also kept once in `picStore`, which is where a later undo or redo finds its bytes. */
22809
+ function libraryPrints(){
22810
+ const out={},lib=C.custom_details||{},seen=new Map();
22811
+ for(const name of Object.keys(lib)){
22812
+ const bytes=lib[name],last=picSeen.get(name),key=last&&last.bytes===bytes&&picStore.get(last.key)===bytes?last.key:pictureKey(bytes); // a picture that has not changed is not looked up again
22813
+ seen.set(name,{bytes,key});out[name]=key;
22814
+ }
22815
+ picSeen=seen;return out;
22816
+ }
22817
+ /** The keys one undo or redo step needs, read from the front of its snapshot (see snapshot()). A string that is not a snapshot needs none. */
22818
+ function snapshotPictureKeys(snap){
22819
+ const head='{"library":',end=typeof snap==='string'&&snap.startsWith(head)?snap.indexOf('},"v2":true'):-1;
22820
+ if(end<0)return [];
22821
+ try{return Object.values(JSON.parse(snap.slice(head.length,end+1)));}catch(e){return [];}
22822
+ }
22823
+ /** Release every kept picture that nothing can reach: not in the live library and not in any undo or redo step. Called when history is discarded. */
22824
+ function prunePictures(){
22825
+ const keep=new Set(Object.values(libraryPrints()));
22826
+ for(const stack of [undo,redo])for(const snap of stack)for(const key of snapshotPictureKeys(snap))keep.add(key);
22827
+ for(const key of [...picStore.keys()])if(!keep.has(key))picStore.delete(key);
22828
+ }
22829
+ /** Put the library back as a snapshot recorded it: exactly those names, each holding the picture it held. */
22830
+ function restoreLibrary(prints){
22831
+ const lib={};
22832
+ for(const name of Object.keys(prints||{})){const bytes=picStore.get(prints[name]);if(bytes!==undefined)lib[name]=bytes;}
22833
+ C.custom_details=lib;
22834
+ }
22835
+ /** The placed copies (detail_placements rows) made from one library picture. */
22836
+ function placedCopiesOf(name){return (C.detail_placements||[]).filter(p=>p&&p.detailName===name);}
22837
+ const copiesWord=n=>n===1?'copy':'copies';
22838
+ /** The only writers of the library besides a rename: each is ONE edit(), so each is one undo step. */
22839
+ function addCustomDetail(name,b64){return edit(()=>{C.custom_details[name]=b64;});}
22840
+ /**
22841
+ * Delete a picture AND the placed copies made from it, as ONE undo step. A copy whose picture is gone leaves a model the server refuses
22842
+ * (every save and every 3D scene answers 400), so the copies go with it, and so do the saved views' references to them. Ctrl+Z brings all of it back.
22843
+ * The Details list asks first when copies exist (requestDeleteCustomDetail); this is what a "Delete both" answer, and a picture nobody uses, run.
22844
+ */
22845
+ function deleteCustomDetail(name){
22846
+ const gone=new Set(placedCopiesOf(name).map(p=>String(p.sheet)+'\0'+p.id)),ids=placedCopiesOf(name).map(p=>p.id);
22847
+ const done=edit(()=>{
22848
+ delete C.custom_details[name];
22849
+ if(!gone.size)return;
22850
+ C.detail_placements=(C.detail_placements||[]).filter(p=>!(p&&p.detailName===name));
22851
+ if(Array.isArray(C.views))C.views=C.views.map(v=>{const o=v&&v.objects;if(!o||typeof o!=='object')return v;const next={...o};for(const k of ['isolated','connHidden'])if(Array.isArray(o[k]))next[k]=o[k].filter(r=>!(r&&r.kind==='detail'&&gone.has(String(r.sheet)+'\0'+r.id)));return {...v,objects:next};});
22852
+ });
22853
+ if(done&&ids.length){for(const id of ids)modelSelection.removeMember('det:'+id);toast('Deleted “'+name+'” and its '+ids.length+' placed '+copiesWord(ids.length)+'. Ctrl+Z brings '+(ids.length===1?'it':'them')+' back.');}
22854
+ return done;
22855
+ }
22856
+ // The Details list's delete is asked first when placed copies still use the picture. `detailDeleteAsk` is the picture whose question is open.
22857
+ let detailDeleteAsk=null;
22858
+ function deleteAskText(name,n){return '“'+name+'” is used by '+n+' placed '+copiesWord(n)+'. Delete the picture and '+(n===1?'its copy':'its copies')+'?';}
22859
+ /** The delete link in the Details list: a picture nobody uses goes at once (one undo step); one that placed copies use opens the question and changes nothing yet. */
22860
+ function requestDeleteCustomDetail(name){
22861
+ if(placedCopiesOf(name).length){detailDeleteAsk=name;return 'asked';}
22862
+ deleteCustomDetail(name);return 'deleted';
22863
+ }
22864
+ /** The answer: 'both' deletes the picture and its copies (one undo step); 'keep' leaves everything exactly as it was. */
22865
+ function answerDeleteAsk(choice){const name=detailDeleteAsk;detailDeleteAsk=null;if(name!==null&&choice==='both')deleteCustomDetail(name);}
21589
22866
  // rename a detail EVERYWHERE — across all plans' callout lists, member end/col refs, and the custom store
21590
22867
  function applyDetailRename(old,nw){nw=(nw||'').trim();if(!nw||nw===old)return false;
22868
+ // WHAT TO CHANGE is collected from the model as it is NOW; the writes then go through the command session inside ONE
22869
+ // edit(), so a rename is undoable, the plan projection refreshes, and it saves by the path every other edit takes. (It
22870
+ // used to rewrite the canonical rows in place and call scheduleSave: not undoable, the sheet kept drawing the old
22871
+ // name until something else repainted it, and it THREW on a v2 plan, which has no per-plan `members`.)
22872
+ const planPatches=[];
21591
22873
  for(const pl of C.plans){
21592
- if(pl.details)for(const d of pl.details)if(d.text===old)d.text=nw;
22874
+ const patch={};
22875
+ if(Array.isArray(pl.details)&&pl.details.some(d=>d&&d.text===old))patch.details=pl.details.map(d=>d&&d.text===old?{...d,text:nw}:d);
21593
22876
  // callouts[] carries names too, and the Details list renames from BOTH (#397). Skipping these renamed
21594
22877
  // the ends but not the callout they point at, so the list snapped straight back to the old name while
21595
22878
  // every end silently stopped resolving — the same failure the connection-library note below describes.
21596
22879
  // Setting `text` also covers a callout that had none: it takes precedence over the target-derived name.
21597
- if(pl.callouts)for(const co of pl.callouts)if(co&&DetailRefs.calloutRefText(co)===old)co.text=nw;
21598
- for(const m of pl.members){if(m.ends)for(const en of m.ends)if(en.detail===old)en.detail=nw;if(m.col&&m.col.detail===old)m.col.detail=nw;}}
21599
- if(C.custom_details[old]!=null){C.custom_details[nw]=C.custom_details[old];delete C.custom_details[old];}
21600
- // The connection library is keyed to the callout TEXT, so a rename that skipped it would leave every row
21601
- // pointing at a name nothing uses any more — each end would silently stop resolving ("nothing says what
21602
- // this builds") with no visible cause. Harmless when `detail` was only a display string; not any more,
21603
- // now that the row carries what the detail BUILDS.
21604
- for(const r of (C.connections||[]))if(r&&r.detail===old)r.detail=nw;
21605
- scheduleSave();return true;}
22880
+ if(Array.isArray(pl.callouts)&&pl.callouts.some(co=>co&&DetailRefs.calloutRefText(co)===old))patch.callouts=pl.callouts.map(co=>co&&DetailRefs.calloutRefText(co)===old?{...co,text:nw}:co);
22881
+ if(Object.keys(patch).length)planPatches.push([viewIdOf(pl),patch]);
22882
+ }
22883
+ const endPatches=[],colPatches=[];
22884
+ for(const m of (C.members||[])){if(!m)continue;(m.ends||[]).forEach((en,i)=>{if(en&&en.detail===old)endPatches.push([m.id,i]);});if(m.col&&m.col.detail===old)colPatches.push(m);}
22885
+ return edit(()=>{
22886
+ for(const [viewId,patch] of planPatches)V2_SESSION.patchPlan(viewId,patch);
22887
+ for(const [id,i] of endPatches)V2_SESSION.patchEnd(id,i,{detail:nw});
22888
+ for(const m of colPatches)V2_SESSION.patchMember(m.id,{col:{...m.col,detail:nw}});
22889
+ // A document older than v2 keeps its members on each plan; those are renamed where they live.
22890
+ for(const pl of C.plans)for(const m of (pl.members||[])){if(m.ends)for(const en of m.ends)if(en.detail===old)en.detail=nw;if(m.col&&m.col.detail===old)m.col.detail=nw;}
22891
+ // The custom-detail library key moves with the name and the placed copies that point at it follow. Both ride the undo
22892
+ // snapshot (the library by fingerprint), so undo and redo put the name and the picture back together. A name the library
22893
+ // already uses is never overwritten.
22894
+ if(C.custom_details&&C.custom_details[old]!=null){
22895
+ if(C.custom_details[nw]!=null)toast('A custom detail named “'+nw+'” already exists, so its picture was left as it is.');
22896
+ else{C.custom_details[nw]=C.custom_details[old];delete C.custom_details[old];
22897
+ for(const p of (C.detail_placements||[]))if(p&&p.detailName===old)p.detailName=nw;}
22898
+ }
22899
+ // The connection library is keyed to the callout TEXT, so a rename that skipped it would leave every row
22900
+ // pointing at a name nothing uses any more — each end would silently stop resolving ("nothing says what
22901
+ // this builds") with no visible cause. Harmless when `detail` was only a display string; not any more,
22902
+ // now that the row carries what the detail BUILDS.
22903
+ for(const r of (C.connections||[]))if(r&&r.detail===old)r.detail=nw;
22904
+ });}
21606
22905
  // Every detail name this plan can bind to — the plan's own callouts (details[] ∪ callouts[]) plus the
21607
22906
  // model's custom ones. THE single answer: the Details modal, the ⌖ field's combobox and the native
21608
22907
  // datalist all call this, so none of them can go blind on a shape the others handle (#397).
21609
22908
  function detTexts(){return DetailRefs.planDetailTexts(P,Object.keys(C.custom_details));}
21610
22909
  function openDetails(){const g=document.getElementById('detailsGrid');const uniq=detTexts();
22910
+ if(detailDeleteAsk!==null&&!(C.custom_details[detailDeleteAsk]!=null&&placedCopiesOf(detailDeleteAsk).length))detailDeleteAsk=null; // an undo, a rename or a removed copy can end the question
21611
22911
  // What each name IS on the drawing, so a section is not labelled "detail" — the ⌖ pick tooltip already
21612
22912
  // makes that distinction and the card should agree. First bubble wins; anything unplaced reads as a detail.
21613
22913
  const kindOf={};for(const r of DetailRefs.planDetailRefs(P))if(!(r.text in kindOf))kindOf[r.text]=r.kind;
@@ -21615,15 +22915,22 @@ function openDetails(){const g=document.getElementById('detailsGrid');const uniq
21615
22915
  const prev=pv?(b?`<img class=dthumb data-t="${esc(t)}" alt="${esc(t)}">`:`<img src="data:image/jpeg;base64,${pv}" alt="${esc(t)}">`):`<div class=dprev>Preview pending<br>from sheet ${esc(sheet)}</div>`;
21616
22916
  const kind=kindOf[t]==='section'?'section':kindOf[t]==='elevation'?'elevation':'detail';
21617
22917
  const sub=custom?'Custom detail':('Sheet '+esc(sheet)+(b?' · '+kind+' '+esc(numOf(t)):''));
21618
- return `<div class=dcard><div class=dprevwrap${pv?` data-det="${esc(t)}"`:''}>${prev}</div><div class=dmeta><input data-command-id="steel.detail-rename#${esc(t)}" aria-label="Rename detail ${esc(t)}" class=dname data-old="${esc(t)}" value="${esc(t)}" data-tip="Rename (updates every plan)" autocomplete=off><div class=ds>${sub}${custom?` · <a href="#" class=ddel data-del="${esc(t)}">delete</a>`:''}</div></div></div>`;}).join('')
21619
- :'<div class=hint>No detail callouts detected. Use + New detail to add your own.</div>';
22918
+ const asking=custom&&detailDeleteAsk===t;
22919
+ const ask=asking?`<div class=dask role=group aria-label="${esc('Delete '+t)}"><p>${esc(deleteAskText(t,placedCopiesOf(t).length))}</p><div class=dbtns><button data-command-id="steel.detail-delete-both#${esc(t)}" class=danger data-ask-both data-tip="Delete the picture and its placed copies. Ctrl+Z brings them back">Delete both</button><button data-command-id="steel.detail-delete-keep#${esc(t)}" data-ask-keep data-tip="Leave the picture and its copies as they are">Keep the picture</button></div></div>`:'';
22920
+ return `<div class=dcard><div class=dprevwrap${pv?` data-det="${esc(t)}"`:''}>${prev}</div><div class=dmeta><input data-command-id="steel.detail-rename#${esc(t)}" aria-label="Rename detail ${esc(t)}" class=dname data-old="${esc(t)}" value="${esc(t)}" data-tip="Rename (updates every plan)" autocomplete=off><div class=ds>${sub}${custom&&!asking?` · <a href="#" class=ddel data-del="${esc(t)}">delete</a>`:''}</div>${ask}</div></div>`;}).join('')
22921
+ // An honest empty state (#2211): says what is missing for THIS sheet and gives the way forward. A bare "none
22922
+ // detected" line told nobody that a callout can be added, or that the read can be asked to look again.
22923
+ :`<div class=coempty><b>No callouts on ${esc(viewLabel(P)||P.sheet||'this sheet')} yet</b><p>FloLess hasn’t recorded any detail, section or elevation marks for this sheet. If the drawing has them, add them yourself or ask your AI to read the sheet again.</p>${NO_PLAN_VIEW?'<p>Open a plan view to add one.</p>':'<button data-command-id="steel.details-add-callout" id=detailsAddCallout class=copPrimary>Add a callout</button>'}</div>`;
22924
+ {const add=g.querySelector('#detailsAddCallout');if(add)add.onclick=()=>{closeDetails();setCalloutMode(true);};}
21620
22925
  g.querySelectorAll('img.dthumb').forEach(im=>detThumb(im.dataset.t,im));
21621
22926
  g.querySelectorAll('.dprevwrap[data-det]').forEach(c=>c.onclick=()=>openPreview(c.dataset.det));
21622
22927
  g.querySelectorAll('input.dname').forEach(i=>i.onchange=()=>{if(applyDetailRename(i.dataset.old,i.value)){render();openDetails();}else i.value=i.dataset.old;});
21623
- g.querySelectorAll('a.ddel').forEach(a=>a.onclick=e=>{e.preventDefault();delete C.custom_details[a.dataset.del];scheduleSave();render();openDetails();});
22928
+ g.querySelectorAll('a.ddel').forEach(a=>a.onclick=e=>{e.preventDefault();const answer=requestDeleteCustomDetail(a.dataset.del);if(answer==='deleted')render();openDetails();if(answer==='asked'){const keep=g.querySelector('button[data-ask-keep]');if(keep)keep.focus();}}); // the safe answer takes focus, so Enter cannot delete by accident
22929
+ g.querySelectorAll('button[data-ask-both]').forEach(b=>b.onclick=()=>{answerDeleteAsk('both');render();openDetails();});
22930
+ g.querySelectorAll('button[data-ask-keep]').forEach(b=>b.onclick=()=>{const name=detailDeleteAsk;answerDeleteAsk('keep');openDetails();const link=[...g.querySelectorAll('a.ddel')].find(a=>a.dataset.del===name);if(link)link.focus();});
21624
22931
  document.getElementById('detailsBtn').textContent='Details ('+uniq.length+')…';
21625
22932
  document.getElementById('detailsModal').style.display='flex';}
21626
- function closeDetails(){document.getElementById('detailsModal').style.display='none';showDnForm(false);}
22933
+ function closeDetails(){document.getElementById('detailsModal').style.display='none';detailDeleteAsk=null;showDnForm(false);}
21627
22934
  function detailsOpen(){return document.getElementById('detailsModal').style.display==='flex';}
21628
22935
  document.getElementById('detailsBtn').onclick=openDetails;
21629
22936
  document.getElementById('detailsClose').onclick=closeDetails;
@@ -21645,7 +22952,7 @@ function bpJointId(mid){const ids=new Set((C.joints||[]).map(j=>j&&j.id));let id
21645
22952
  function updBpBtn(){const b=document.getElementById('bpBtn');if(!b)return;
21646
22953
  const allCols=colMemberIds(), tgt=bpTargetIds(), tset=new Set(tgt);
21647
22954
  const scoped=selIds.size>0&&tgt.length>0&&tgt.length<allCols.length; // acting on a selected subset, not every column
21648
- const n=(C.joints||[]).filter(j=>j&&j.kind==='base-plate'&&j.source==='auto'&&tset.has(j.main)).length; // auto plates within the target set
22955
+ const n=(C.joints||[]).filter(j=>j&&j.kind==='base-plate'&&isPlainAutoJoint(j)&&tset.has(j.main)).length; // the toolbar's own auto plates within the target set — a base plate Build from details made is NOT one (detailJointOrigin)
21649
22956
  const covered=new Set((C.joints||[]).filter(j=>j&&j.kind==='base-plate'&&tset.has(j.main)).map(j=>j.main)).size; // target columns already detailed (auto OR user)
21650
22957
  b.disabled=allCols.length===0||(selIds.size>0&&tgt.length===0); // no columns at all, or a selection with no columns in it → nothing to do (empty-state)
21651
22958
  b.dataset.tip=allCols.length===0?'No columns in this model to detail base plates.'
@@ -21662,9 +22969,9 @@ function toggleBasePlates(){
21662
22969
  if(missing.length){ // detail the target columns that don't have a base plate yet
21663
22970
  edit(()=>{if(!Array.isArray(C.joints))C.joints=[];for(const id of missing)C.joints.push({id:bpJointId(id),kind:'base-plate',main:id,at:'base',source:'auto',params:{}});});
21664
22971
  }else{ // every target column detailed → clear the AUTO ones on those columns (keep user/AI + unselected columns)
21665
- const cs=new Set(tgt), rm=(C.joints||[]).filter(j=>j&&j.kind==='base-plate'&&j.source==='auto'&&cs.has(j.main));
21666
- if(rm.length)edit(()=>{C.joints=(C.joints||[]).filter(j=>!(j&&j.kind==='base-plate'&&j.source==='auto'&&cs.has(j.main)));});
21667
- else toast(selIds.size?'The selected column(s) already have base plates placed by hand or the AI — none auto-detailed here to clear.':'Every column already has a base plate placed by hand or the AI — none auto-detailed to clear.'); // nothing to add and no auto plate to clear → say so instead of a silent dead click
22972
+ const cs=new Set(tgt), rm=(C.joints||[]).filter(j=>j&&j.kind==='base-plate'&&isPlainAutoJoint(j)&&cs.has(j.main)); // isPlainAutoJoint, never a bare source==='auto': connections built from a detail are auto too and must survive Clear
22973
+ if(rm.length)edit(()=>{C.joints=(C.joints||[]).filter(j=>!(j&&j.kind==='base-plate'&&isPlainAutoJoint(j)&&cs.has(j.main)));});
22974
+ else toast(selIds.size?'The selected column(s) already have base plates placed by hand, by the AI or from a detail — none auto-detailed here to clear.':'Every column already has a base plate placed by hand, by the AI or from a detail — none auto-detailed to clear.'); // nothing to add and no auto plate to clear → say so instead of a silent dead click
21668
22975
  }
21669
22976
  }
21670
22977
  {const _b=document.getElementById('bpBtn');if(_b)_b.onclick=toggleBasePlates;}
@@ -21701,7 +23008,7 @@ function updSpBtn(){const b=document.getElementById('spBtn');if(!b)return;
21701
23008
  const eligAll=spEligibleEnds(), tgt=spTargetEnds();
21702
23009
  const scoped=selIds.size>0&&tgt.length>0&&tgt.length<eligAll.length; // acting on a selected subset of the eligible ends
21703
23010
  const tbeams=new Set([...spBeamIds()].filter(id=>!selIds.size||selIds.has(id))); // the target beams — the SAME set the Clear path removes from, so the (N) count matches exactly what Clear will remove (incl. an auto plate on a since-ineligible end)
21704
- const n=(C.joints||[]).filter(j=>j&&j.kind==='shear-plate'&&j.source==='auto'&&tbeams.has(j.main)).length;
23011
+ const n=(C.joints||[]).filter(j=>j&&j.kind==='shear-plate'&&isPlainAutoJoint(j)&&tbeams.has(j.main)).length; // the toolbar's own auto plates only — see detailJointOrigin
21705
23012
  const covered=tgt.filter(({beam,endIdx})=>spJointOf(beam.id,endIdx)).length; // target ends already detailed (auto OR user)
21706
23013
  b.disabled=eligAll.length===0||(selIds.size>0&&tgt.length===0); // no eligible ends at all, or a selection with no eligible ends in it (empty-state)
21707
23014
  b.dataset.tip=eligAll.length===0?'No eligible beam ends in this model to detail shear plates.'
@@ -21719,9 +23026,9 @@ function toggleShearPlates(){
21719
23026
  // incl. an end that later became ineligible (so its auto joint stays clearable from the
21720
23027
  // toolbar), keeping user/AI plates + untargeted beams
21721
23028
  const tbeams=new Set([...spBeamIds()].filter(id=>!selIds.size||selIds.has(id)));
21722
- const rm=(C.joints||[]).filter(j=>j&&j.kind==='shear-plate'&&j.source==='auto'&&tbeams.has(j.main));
21723
- if(rm.length)edit(()=>{C.joints=(C.joints||[]).filter(j=>!(j&&j.kind==='shear-plate'&&j.source==='auto'&&tbeams.has(j.main)));});
21724
- else toast(selIds.size?'The selected beam(s) already have shear plates placed by hand or the AI — none auto-detailed here to clear.':'Every eligible end already has a shear plate placed by hand or the AI — none auto-detailed to clear.'); // nothing to add and no auto plate to clear → say so instead of a silent dead click
23029
+ const rm=(C.joints||[]).filter(j=>j&&j.kind==='shear-plate'&&isPlainAutoJoint(j)&&tbeams.has(j.main)); // isPlainAutoJoint, never a bare source==='auto': connections built from a detail are auto too and must survive Clear
23030
+ if(rm.length)edit(()=>{C.joints=(C.joints||[]).filter(j=>!(j&&j.kind==='shear-plate'&&isPlainAutoJoint(j)&&tbeams.has(j.main)));});
23031
+ else toast(selIds.size?'The selected beam(s) already have shear plates placed by hand, by the AI or from a detail — none auto-detailed here to clear.':'Every eligible end already has a shear plate placed by hand, by the AI or from a detail — none auto-detailed to clear.'); // nothing to add and no auto plate to clear → say so instead of a silent dead click
21725
23032
  }
21726
23033
  }
21727
23034
  {const _s=document.getElementById('spBtn');if(_s)_s.onclick=toggleShearPlates;}
@@ -21732,8 +23039,16 @@ const DSKIP_LABEL={'no-row':'Nothing says what the callout means','row-has-no-re
21732
23039
  'kind-mismatch':'The detail builds the wrong kind for that end','conflict':'The callout and the connection reference disagree',
21733
23040
  'ambiguous':'The callout matches more than one connection','no-schedule-match':'That size is not in the detail’s schedule',
21734
23041
  'verified':'Someone confirmed it','custom':'An imported connection is there','tuned':'Tuned by hand','no-detail':'No detail on that end',
23042
+ // saved by an older version of this action (or remembered from a hand-made one): "built and untouched" can't be told from "built, then tuned"
23043
+ 'built-earlier':'Linked to a detail earlier, possibly changed by hand since',
23044
+ 'brace-unsupported':'A brace can’t carry a shear plate or base plate, so nothing was built',
23045
+ 'column-bottom':'Nothing is built from a column’s bottom callout; a base plate comes from its top-end callout',
23046
+ 'not-drawn':'Not drawn on any sheet the editor can place, so nothing can be built from here',
23047
+ 'build-failed':'The model refused the change, so nothing was built',
21735
23048
  'duplicate-id':'More than one member has that name, so the connection could land on the wrong one'};
21736
- const DSKIP_PROTECTED={verified:1,custom:1,tuned:1}; // skipped to protect existing work — the only ones an overwrite could take
23049
+ const DSKIP_PROTECTED={verified:1,custom:1,tuned:1,'built-earlier':1}; // skipped to protect existing work — the only ones an overwrite could take
23050
+ // How each protected reason reads inside the "Replace them?" question, with its count in front.
23051
+ const DSKIP_PROTECTED_WHY={verified:'confirmed by someone',tuned:'tuned by hand',custom:'imported geometry','built-earlier':'linked to a detail earlier, possibly changed by hand since'};
21737
23052
  function describeSkip(s){return (s.m&&s.m.id?s.m.id:'?')+' '+whichLabel(s.which);}
21738
23053
  function runApplyAllDetails(force){
21739
23054
  const res=applyAllDetails({force:force});
@@ -21767,7 +23082,7 @@ function runApplyAllDetails(force){
21767
23082
  over.className='danger';
21768
23083
  over.onclick=async()=>{close();
21769
23084
  if(await confirmDanger({title:'Replace work that was protected?',
21770
- body:protectedN+' end'+(protectedN===1?' was':'s were')+' left alone because someone confirmed '+(protectedN===1?'it':'them')+', tuned '+(protectedN===1?'it':'them')+' by hand, or imported the geometry.\n\nReplacing rebuilds '+(protectedN===1?'it':'them')+' from the detail, and imported geometry cannot be recovered by rebuilding. This can be undone with Ctrl+Z.',
23085
+ body:protectedN+' end'+(protectedN===1?' was':'s were')+' left alone to protect work already there ('+order.filter(k=>DSKIP_PROTECTED[k]).map(k=>groups[k].length+' '+DSKIP_PROTECTED_WHY[k]).join(', ')+').\n\nReplacing rebuilds '+(protectedN===1?'it':'them')+' from the detail, and imported geometry cannot be recovered by rebuilding. This can be undone with Ctrl+Z.',
21771
23086
  confirmLabel:'Replace them'}))runApplyAllDetails(true);};
21772
23087
  foot.append(over);}
21773
23088
  foot.append(done);done.focus();}
@@ -21818,9 +23133,7 @@ function renderConnTable(){const tb=document.getElementById('connBody');if(!tb)r
21818
23133
  lines.push('','The connections already built stay in the model — they just stop saying which detail they came from. This can be undone with Ctrl+Z.');
21819
23134
  if(!await confirmDanger({title:'Delete '+label+'?',body:lines.join('\n'),confirmLabel:'Delete it'}))return;
21820
23135
  }
21821
- edit(()=>{C.connections=C.connections.filter(x=>x.id!==id);
21822
- for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(m.col&&m.col.conn===id)m.col.conn='';for(const en of (m.ends||[]))if(en&&en.conn===id)en.conn='';}
21823
- for(const j of (C.joints||[]))if(j&&j.conn===id)delete j.conn;});renderConnTable();};});
23136
+ removeConnectionRow(id);renderConnTable();};}); // citations are let go of (ends through the command path, joints kept) by releaseRowCitations; see removeConnectionRow
21824
23137
  updConnBtn();}
21825
23138
  document.getElementById('connBtn').onclick=openConnLib;
21826
23139
  document.getElementById('connClose').onclick=closeConnLib;
@@ -21856,18 +23169,617 @@ document.getElementById('dnAdd').onclick=()=>{const name=document.getElementById
21856
23169
  if(!name){dnHint('Please enter a name.');return;}
21857
23170
  if(detTexts().includes(name)){dnHint('That name already exists — pick another.');return;} // checks every name the Details list shows, callouts included — otherwise a new custom detail could duplicate a callout visible in that same list (#397)
21858
23171
  if(!dnPending){dnHint('Paste or choose an image first.');return;}
21859
- C.custom_details[name]=dnPending;scheduleSave();showDnForm(false);render();openDetails();};
21860
- // --- moment frame schedule (read from the Frame Elevations S-301/302/303) ---
21861
- function openFrames(){const g=document.getElementById('framesGrid');const fr=C.moment_frames||[];
21862
- g.innerHTML=fr.length?('<div class=hint style="margin-bottom:10px">From the Frame Elevations (S-301/302/303). Select an MF member and pick its girder size from the Profile list — roof girders for the Roof plan, 2nd-floor girders for the Second-Floor plan.</div><table class=ftab><thead><tr><th>Grid</th><th>Span</th><th>Roof girder</th><th>2nd floor</th><th>Columns</th></tr></thead><tbody>'+
21863
- fr.map(f=>`<tr><td class=gcell>${esc(f.grid||'?')}</td><td>${esc((f.span||[]).join('–'))}</td><td>${esc((f.roof||[]).join(', ')||'—')}</td><td>${esc((f.second||[]).join(', ')||'—')}</td><td>${esc((f.columns||[]).join(', ')||'—')}</td></tr>`).join('')+'</tbody></table>')
21864
- :'<div class=hint>No moment-frame schedule loaded.</div>';
21865
- document.getElementById('framesModal').style.display='flex';}
21866
- function closeFrames(){document.getElementById('framesModal').style.display='none';}
23172
+ addCustomDetail(name,dnPending);showDnForm(false);render();openDetails();};
23173
+ // --- the Moment frame control and box in the member panel (#2210) ---
23174
+ // A moment-frame girder takes a MOMENT connection, so the automatic shear-plate pass skips it (spEndEligible reads `mf===true`
23175
+ // or an "MF" mark). Until #2210 the only ways to set that were clicking a size in the schedule's box or typing an MF profile,
23176
+ // and the box only appeared on two sheets whose NAMES one project used. Now a person can say "this beam is a moment frame"
23177
+ // directly, and the box offers the sizes of whichever level the schedule says THIS sheet is.
23178
+ // The three things the panel's moment-frame controls DO, as named functions. Marking a beam never writes `mf:false` (clearing DELETES the key), because
23179
+ // the shear-plate skip and the schedule read `mf===true`; and it leaves the plates a beam already has alone (the next Shear plates run skips it).
23180
+ function mfToggleMember(m){edit(()=>{ModelCmd.patchMember(m,{mf:m.mf===true?undefined:true});});}
23181
+ // A size clicked in the box: the beam takes that profile and is marked a moment frame (the shear-plate pass then skips its ends). No confidence code reads `mf`.
23182
+ function mfPickSize(m,profile,profs){edit(()=>{ModelCmd.patchMember(m,{profile,mf:true,rfi:_wtPlf(profile)==null});if(!profs.includes(profile)){profs.push(profile);profs.sort();}});}
23183
+ function mfSelectionToggle(){
23184
+ const beams=selArr().filter(mfBeam),all=beams.length>0&&beams.every(x=>x.mf===true||mfByMark(x));
23185
+ if(!all){edit(()=>{for(const x of beams)ModelCmd.patchMember(x,{mf:true});});return;}
23186
+ // Clearing reaches ONLY the beams the flag is on. A beam is a moment frame by its MF mark when its profile starts with MF, and that is not this button's to change:
23187
+ // say so, and write nothing when there is nothing to clear.
23188
+ const flagged=beams.filter(x=>x.mf===true),marked=beams.filter(mfByMark).length;
23189
+ if(flagged.length)edit(()=>{for(const x of flagged)ModelCmd.patchMember(x,{mf:undefined});});
23190
+ if(marked)toast(`${marked===1?'1 beam stays a moment frame':`${marked} beams stay moment frames`} because ${marked===1?'its':'their'} profile starts with MF. Change the profile to clear ${marked===1?'it':'them'}.`);
23191
+ }
23192
+ function mfBeam(m){return !!m&&(m.role||'beam')!=='column'&&!isBrace(m);} // girders are beams: a column or a brace is never "a moment-frame girder"
23193
+ function mfByMark(m){return /^MF/i.test((m&&m.profile)||'');}
23194
+ // --- the offer to clear a new moment-frame girder's AUTOMATIC shear plates ---
23195
+ // A beam that becomes a moment-frame girder takes a moment connection, so the plates the Shear plates button put on its ends earlier no
23196
+ // longer belong. They are not removed behind the person's back (nothing refuses, it asks) and not left as a trap either: a short notice,
23197
+ // where the person acted, says how many there are and lets them Remove (ONE undo step) or Keep. Only the toolbar's own AUTOMATIC plates
23198
+ // are ever offered (`isPlainAutoJoint`, the very set Clear shear plates removes); a plate a person tuned by hand, one built from a detail
23199
+ // and any other stays, and is said to stay.
23200
+ // WHERE IT IS DETECTED: edit() compares which beams are girders before and after, so EVERY route a person has to make a beam a girder
23201
+ // (the member switch, Mark N beams, typing an MF profile in the panel, the catalogue pick, an RFI answer, anything added later) offers once
23202
+ // per action, with no per-route wiring to forget. Undo and redo never offer: they step through an action, not take one.
23203
+ // The question is only a variable, never saved in the model: it is drawn in the panel while the marked beams are what is selected (or as a
23204
+ // small bar when they are not), and re-derived from the live model at every draw, so a stale one draws nothing.
23205
+ function mfIsGirder(m){return mfBeam(m)&&(m.mf===true||mfByMark(m));}
23206
+ function mfGirderIds(){const s=new Set();for(const m of allMembers())if(m&&m.id&&mfIsGirder(m))s.add(m.id);return s;}
23207
+ function mfSelKey(){return [...selIds].sort().join('\u0001');}
23208
+ /** What sits on these beams' ends: the AUTOMATIC plates (the only ones an offer may remove) and, counted, the rest — which all stay. */
23209
+ function mfPlatesOn(ids){
23210
+ const out={auto:[],beams:new Set(),hand:0,detail:0,other:0};
23211
+ for(const j of (C.joints||[])){if(!j||j.kind!=='shear-plate'||!ids.has(j.main))continue;
23212
+ const origin=detailJointOrigin(j);
23213
+ if(origin==='plain'){out.auto.push(j);out.beams.add(j.main);}
23214
+ else if(origin==='hand')out.hand++;
23215
+ else if(origin==='built'||origin==='earlier')out.detail++;
23216
+ else out.other++;}
23217
+ return out;}
23218
+ /** The offer as the model says it is NOW: null once the beams are no longer girders or no automatic plate is left on them. */
23219
+ function mfOfferLive(){
23220
+ if(!mfOffer)return null;
23221
+ const girders=mfGirderIds(),marked=new Set(mfOffer.marked.filter(id=>girders.has(id)));
23222
+ if(!marked.size)return null;
23223
+ const p=mfPlatesOn(marked);
23224
+ return p.auto.length?{markedN:marked.size,beamsN:p.beams.size,plates:p.auto,hand:p.hand,detail:p.detail,other:p.other}:null;}
23225
+ function mfOfferText(o){
23226
+ const n=o.plates.length,plate=`${n} automatic shear plate${n===1?'':'s'}`;
23227
+ const who=o.markedN===1?'This beam has':o.beamsN===o.markedN?`These ${o.beamsN} beams have`:`${o.beamsN} of these ${o.markedN} beams ${o.beamsN===1?'has':'have'}`;
23228
+ const stays=[];
23229
+ const say=(c,what)=>stays.push(`${c} ${what.replace('#',c===1?'shear plate':'shear plates')} ${c===1?'stays':'stay'}.`);
23230
+ if(o.hand)say(o.hand,'# you tuned by hand');
23231
+ if(o.detail)say(o.detail,'# built from a drawing detail');
23232
+ if(o.other)say(o.other,'other #');
23233
+ return {question:`${who} ${plate}. Remove ${n===1?'it':'them'}?`,stays:stays.join(' '),removeLabel:`Remove ${plate}`,keepLabel:`Keep ${n===1?'it':'them'}`};}
23234
+ function mfOfferInner(o){
23235
+ const t=mfOfferText(o);
23236
+ return `<div class=dmsg>${esc(t.question)}</div>${t.stays?`<div class="hint mfhint">${esc(t.stays)}</div>`:''}<div class=mfoffer-acts><button type=button id=mfOfferRemove data-command-id="steel.moment-frame-plates-remove" class="ghost mfrm" aria-label="${esc(t.removeLabel)}">Remove</button><button type=button id=mfOfferKeep data-command-id="steel.moment-frame-plates-keep" class=ghost aria-label="${esc(t.keepLabel)}">Keep</button></div>`;}
23237
+ /** The notice inside the Properties panel — '' unless the beams just marked are what is selected and an automatic plate is still on them. */
23238
+ function mfOfferHtml(){
23239
+ if(!mfOffer||mfOffer.floating)return '';
23240
+ const o=mfOfferLive();
23241
+ return o?`<div id=mfOffer class=mfoffer role=group aria-label="Shear plates on the beams just marked">${mfOfferInner(o)}</div>`:'';}
23242
+ function mfOfferShown(){return !!mfOffer&&!mfOffer.floating&&!!mfOfferLive();}
23243
+ function mfOfferClose(){mfOffer=null;const bar=document.getElementById(MF_OFFER_BAR_ID);if(bar)bar.remove();}
23244
+ /** Called as the panel is drawn: the question belongs to the selection it was asked under and to nothing else. */
23245
+ function mfOfferSync(){if(mfOffer&&mfOffer.selKey!==mfSelKey())mfOfferClose();}
23246
+ function mfOfferRefocus(){const t=document.getElementById('mfToggle')||document.getElementById('mfBtnM');if(t&&typeof t.focus==='function')t.focus();}
23247
+ // Each button acts ONLY for the offer it was drawn for (`mine`, captured when it was wired). A button that outlived its offer, such as an old bar left on screen
23248
+ // while a newer question took over, does nothing: it must never delete the plates of whatever the page is asking about NOW.
23249
+ function mfOfferKeep(mine){if(!mine||mine!==mfOffer)return;mfOfferClose();panel();mfOfferRefocus();} // keeping changes nothing in the model
23250
+ function mfOfferRemove(mine){
23251
+ if(!mine||mine!==mfOffer)return;
23252
+ const o=mfOfferLive();mfOfferClose();
23253
+ if(!o){panel();return;} // nothing left to remove (they were removed or the beams were changed since): just repaint
23254
+ const ids=new Set(o.plates.map(j=>j.id));
23255
+ if(!edit(()=>{C.joints=(C.joints||[]).filter(j=>!(j&&ids.has(j.id)));}))return; // ONE edit() over every beam: one undo step
23256
+ const n=ids.size,depth=undo.length;
23257
+ undoToast(`Removed ${n} automatic shear plate${n===1?'':'s'}. Ctrl+Z brings ${n===1?'it':'them'} back.`,()=>frUndoIfStill(depth));
23258
+ mfOfferRefocus();}
23259
+ /** Make the notice's two buttons (inline or floating) do their one thing each; Esc inside it is "keep". */
23260
+ function mfWireOffer(){
23261
+ const mine=mfOffer,rm=document.getElementById('mfOfferRemove'),keep=document.getElementById('mfOfferKeep');
23262
+ if(rm)rm.onclick=()=>mfOfferRemove(mine);
23263
+ if(keep)keep.onclick=()=>mfOfferKeep(mine);
23264
+ const box=document.getElementById(mfOffer&&mfOffer.floating?MF_OFFER_BAR_ID:'mfOffer'); // the surface THIS question is on: never whichever of the two happens to be on the page
23265
+ if(box)box.onkeydown=e=>{if(e.key==='Escape'){e.preventDefault();e.stopPropagation();mfOfferKeep(mine);}};}
23266
+ /** The bar form: the person acted somewhere the panel does not show those beams (answering a size in the RFI list, say). */
23267
+ function mfOfferFloat(){
23268
+ const o=mfOfferLive();if(!o)return;
23269
+ let bar=document.getElementById(MF_OFFER_BAR_ID);
23270
+ if(!bar){bar=document.createElement('div');bar.id=MF_OFFER_BAR_ID;bar.className='mfoffer';bar.setAttribute('role','group');bar.setAttribute('aria-label','Shear plates on the beams just marked');document.body.appendChild(bar);}
23271
+ bar.innerHTML=mfOfferInner(o);mfWireOffer();}
23272
+ /** The hook edit() calls once an edit has landed: a beam that was not a moment-frame girder and now is, and that still carries an automatic plate, is asked about. */
23273
+ function mfOfferAfterEdit(before){
23274
+ const added=[];for(const id of mfGirderIds())if(!before.has(id))added.push(id);
23275
+ if(!added.length)return;
23276
+ if(!mfPlatesOn(new Set(added)).auto.length)return; // nothing to ask about this time; a question still waiting for an answer stays as it was
23277
+ const inPanel=added.every(id=>selIds.has(id));
23278
+ mfOfferClose(); // the newer question replaces the older one EVERYWHERE: an old bar must not stay on screen asking about other beams
23279
+ mfOffer={marked:added,selKey:mfSelKey(),floating:!inPanel};
23280
+ const o=mfOfferLive();
23281
+ const live=document.getElementById('mfOfferStatus');if(live&&o)live.textContent=mfOfferText(o).question; // the panel is repainted by innerHTML, which a screen reader does not announce: say it once here
23282
+ if(!inPanel)mfOfferFloat();}
23283
+ function mfBoxHtml(m){
23284
+ const plan=C.plans&&C.plans[C.active];
23285
+ // Girder sizes are offered per FLOOR PLAN. On an elevation or a section there is no level to look up, and a "choose level" button with no
23286
+ // sheet to choose for would be a dead end: say what to do, with no action.
23287
+ if(!plan||plan.viewKind!=='plan')return `<div class="row" style="border:1px solid var(--purple);border-radius:6px;padding:7px 8px;background:rgba(168,85,247,.07)"><div class=elab style="color:var(--purple-ink);margin:0">Moment-frame girder</div><div class=dmsg style="margin-top:5px">Open a floor plan to see this level’s sizes.</div></div>`;
23288
+ const sg=FramesCore.suggestionFor(C,plan);
23289
+ const act=(label,focus,level)=>`<button type=button class="ghost mfopen" data-command-id="steel.member-open-frames" data-focus="${focus}"${level?` data-level="${esc(level)}"`:''}>${label}</button>`;
23290
+ let head='Moment-frame girder',body='';
23291
+ if(sg.kind==='sizes'||sg.kind==='sheet-name'){
23292
+ head=`Moment-frame girder · ${esc(sg.levelName)} (from Frames)`;
23293
+ body=`<div style="display:flex;flex-wrap:wrap;gap:5px;margin-top:5px">${sg.sizes.map(s=>`<button type=button data-command-id="steel.member-profile-suggestion#${esc(s)}" class="ghost mfsug${s===m.profile?' on':''}" data-s="${esc(s)}">${esc(s)}</button>`).join('')}</div>`;
23294
+ if(sg.kind==='sheet-name')body+=`<div class=dmsg style="margin-top:5px">Matched by sheet name (${esc(plan.sheet)} → ${esc(sg.levelName)}). Link this sheet in Frames to be sure.</div>${act('Open Frames','view')}`;
23295
+ }
23296
+ else if(sg.kind==='conflict')body=`<div class="dmsg warn" style="margin-top:5px">This sheet is linked to both ${esc(FramesCore.joinNames(sg.names))} in Frames. Choose one.</div>${act('Choose in Frames','view')}`;
23297
+ else if(sg.kind==='no-level')body=`<div class=dmsg style="margin-top:5px">Frames doesn’t say which level this sheet is.</div>${act('Choose level…','view')}`;
23298
+ else if(sg.kind==='no-sizes')body=`<div class=dmsg style="margin-top:5px">Frames has no girder sizes for ${esc(sg.levelName)} yet.</div>${act('Add sizes…','level',sg.levelName)}`;
23299
+ else body=`<div class=dmsg style="margin-top:5px">No moment-frame schedule yet.</div>${act('Add a frame…','frame')}`;
23300
+ return `<div class="row" style="border:1px solid var(--purple);border-radius:6px;padding:7px 8px;background:rgba(168,85,247,.07)"><div class=elab style="color:var(--purple-ink);margin:0">${head}</div>${body}</div>`;
23301
+ }
23302
+ function mfSectionHtml(m){
23303
+ if(!FramesCore||!mfBeam(m))return '';
23304
+ const on=m.mf===true,byMark=mfByMark(m);
23305
+ const asking=mfOfferShown(); // while the question about its automatic plates is up, the hint does not also say they stay: that is what Keep says
23306
+ // A beam whose profile starts "MF" is a moment-frame member by its own mark: a read-only line, not a switch that could not turn it off.
23307
+ const control=byMark
23308
+ ?`<div class="hint mfhint"><b>Moment frame</b> — from its MF mark.</div>`
23309
+ :`<div class=mfrow><div class=elab>Moment frame</div><span class=vwrap data-panel-control><button type=button id=mfToggle data-command-id="steel.member-moment-frame" class="pintog${on?' on':''}" role=switch aria-checked="${on?'true':'false'}" data-tip="Marks this beam as a moment-frame girder. Shear-plate detailing skips its ends, and Frames offers its girder sizes below."><span class=mck aria-hidden=true></span>${on?'On':'Off'}</button></span></div><div class="hint mfhint">Takes a moment connection, not a shear tab.${asking?'':' Shear plates already on it stay until the next Shear plates run.'}</div>`;
23310
+ return `<div class=mfsect>${control}${mfOfferHtml()}${on||byMark?mfBoxHtml(m):''}</div>`; // ONE wrapper: applyPanelRows pairs a label with the siblings that follow it, and must not swallow what comes next
23311
+ }
23312
+ // --- moment frame schedule (#2210) ---
23313
+ // THE DIALOG BEHIND ⋯ → Detailing → Frames…: one row per frame (grid line, span, a girder-size list per floor LEVEL the
23314
+ // person names, columns), and a list that says which sheet is which level. Until #2210 it only drew a table, and
23315
+ // nothing on a v2 model could fill it, so it was a dead end. The rules (what a row is, which sizes a sheet shows, how a
23316
+ // re-read may ADD) live in steel-frames-core.js, which the server shares, so a frame typed here and a frame a read
23317
+ // proposes meet the same checks. Every write goes through V2_SESSION.patchModel inside edit(), the path every other
23318
+ // editor change takes, so each one is a single undo step and is saved with the model.
23319
+ //
23320
+ // STATE THAT IS NOT THE MODEL: a frame being typed is a DRAFT that lives only in this dialog until its grid line and
23321
+ // both span ends are filled in (the checks refuse a row without them, and a half-row in the model would be a
23322
+ // frame nobody can place). Nothing here is saved on close; a non-empty draft says so.
23323
+ let framesDraft=null; // {line (the grid line),from,to,sizes:{levelKey:text},columns,dupAt:null|index,seedName} — never written to the model
23324
+ let framesLevelDraft=false; // the "+ New level" header cell is open
23325
+ let framesMerge=null; // {key,into,intoName,typed,over}: a rename that landed on a level the schedule already has — merge, or keep editing. `over` = the frames where the two levels together would hold more than a level keeps (asked about before anything is written)
23326
+ let framesReturn=null; // what gets focus when the dialog closes
23327
+ let framesFocusView=null; // the sheet whose level box is highlighted (a deep link from the member panel)
23328
+ let framesRepaintTimer=0;
23329
+ let framesRemap=null; // {draft:index}: a draft that just became a row, so a focused cell keeps its place across the repaint
23330
+ let framesPartial=null; // {idx,from,to}: the span end of a stored row that has NO span, typed alone — held and shown, not refused
23331
+ const FRAMES_SEED_LEVEL='Roof'; // the single level a first frame starts with; the person renames it or adds more
23332
+ function framesRows(){return Array.isArray(C&&C.moment_frames)?C.moment_frames:[];}
23333
+ function framesPlanViews(){return (C&&C.plans||[]).filter(p=>p&&p.viewKind==='plan');}
23334
+ function framesMintId(){return 'mf-hand-'+Date.now().toString(36)+Math.random().toString(36).slice(2,7);} // a hand-made frame's id: only ever minted in the browser, so unlike a read's ids it may be random
23335
+ // What every frame edit is given. `carryViews` = the sheets an old-shape frame is placed on ONLY by the sheet-name table: the edit that rewrites that frame
23336
+ // writes them down as explicit links, so the frame keeps feeding its sheets instead of dropping out of the table that placed them (the table answers for old-shape frames alone).
23337
+ function framesCtx(){return {mintId:framesMintId,carryViews:FramesCore.legacyViewLinks(framesRows(),framesPlanViews())};}
23338
+ function frShape(r){const n=FramesCore.normaliseFrameRow(r);return n?JSON.stringify({g:n.grid,s:n.span,l:n.girders.map(x=>[FramesCore.normLevel(x.level),x.level,x.sizes,x.views,x.elevationMm??null]),c:n.columns}):'';} // what a row SAYS, without its id or the old-shape markers — so an edit that changes nothing writes nothing (no empty undo step, and a legacy row stays legacy)
23339
+ function frLevelsNow(){return FramesCore.levelsOf(framesRows());}
23340
+ // The one level a first frame starts with. Its NAME belongs to the draft until the frame exists (a name typed into its header is kept
23341
+ // in `framesDraft.seedName`, never written to the model), and it is not a level yet, so it has no remove button.
23342
+ function frSeedName(){return (framesDraft&&framesDraft.seedName)||FRAMES_SEED_LEVEL;}
23343
+ function frSeedLevels(){const name=frSeedName();return [{key:FramesCore.normLevel(name),name,rows:0,seed:true}];}
23344
+ // Level-keyed text is held in a null-prototype object: a level may be called constructor or __proto__.
23345
+ function frSizesBag(){return Object.create(null);}
23346
+ // Elements are found by their dataset, NEVER through a selector built from a name: a level or sheet called Roof 14'0" or a\b is a
23347
+ // legal name, and putting it inside [data-x="…"] throws.
23348
+ function frAll(sel){return [...document.querySelectorAll('#framesGrid '+sel)];}
23349
+ function frFindCell(row,col){return frAll('.fr-cell').find(x=>x.dataset.row===String(row)&&x.dataset.col===col)||null;}
23350
+ function frFindLevelName(lv){return frAll('.fr-lvname').find(x=>x.dataset.lv===lv)||null;}
23351
+ function frFindView(v){return frAll('.fr-view').find(x=>x.dataset.view===v)||null;}
23352
+ function frWho(row){return FramesCore.normaliseFrameRow(row)?`grid ${FramesCore.frameLabel(row)}`:'a stored row that isn’t a moment frame';}
23353
+ function frName(row){return FramesCore.normaliseFrameRow(row)?FramesCore.frameLabel(row):'a stored row';}
23354
+ function frViewNames(ids){return ids.map(id=>{const p=framesPlanViews().find(x=>viewIdOf(x)===id);return p?viewLabel(p):id;});}
23355
+ // "Roof (linked to S-203 and S-204) and 2nd floor" — the levels a removal took away, and the sheets that were linked to them.
23356
+ function frLostText(lost){return FramesCore.joinNames(lost.map(l=>l.views.length?`${l.name} (linked to ${FramesCore.joinNames(frViewNames(l.views))})`:l.name));}
23357
+ function frDraftRekey(fromKey,toKey){const d=framesDraft;if(!d||fromKey===toKey)return;const a=d.sizes[fromKey];if(a===undefined)return;const b=d.sizes[toKey];d.sizes[toKey]=b?(a?b+', '+a:b):a;delete d.sizes[fromKey];}
23358
+ function frViewLabel(p){return viewLabel(p)+(p&&p.title&&String(p.title).trim()?' · '+String(p.title).trim():'');}
23359
+ function frUndoIfStill(depth){if(undo.length===depth)doUndo();else toast('Other changes were made since. Press Ctrl+Z to step back one at a time.');}
23360
+ function frGridLabels(){const out=new Set();for(const a of ((C&&C.grid&&C.grid.axes)||[])){const l=a&&typeof a.label==='string'?a.label.trim():'';if(l)out.add(FramesCore.normGrid(l));}return out;}
23361
+ function frWarnGrid(label){const set=frGridLabels();return set.size&&label&&!set.has(FramesCore.normGrid(label))?`${label} isn’t a grid line in this model. Kept as typed.`:'';}
23362
+ function frWarnTo(from,to){return from&&to&&FramesCore.normGrid(from)===FramesCore.normGrid(to)?`Both ends of the span are grid line ${to}.`:frWarnGrid(to);} // the warning sits on the end it is about
23363
+ function frWarnSizes(text){
23364
+ const bad=FramesCore.parseSizeText(text).map(_canonDes).filter(s=>_wtPlf(s)==null);
23365
+ if(!bad.length)return '';
23366
+ return `${bad.join(', ')} ${bad.length>1?'aren’t':'isn’t'} in the ${_catalogLabel()} table, so FloLess can’t price ${bad.length>1?'them':'it'}. Kept as you typed ${bad.length>1?'them':'it'}.`;
23367
+ }
23368
+ function frInput(rowKey,col,value,o){
23369
+ const warn=o.warn||'';
23370
+ return `<input class="ftab-inp fr-cell${o.cls?' '+o.cls:''}${warn?' fr-warn':''}" data-row="${rowKey}" data-col="${esc(col)}" data-orig="${esc(value)}" value="${esc(value)}" aria-label="${esc(o.label)}" data-command-id="steel.frames-field#${esc(o.cmd)}"${o.ph?` placeholder="${esc(o.ph)}"`:''}${warn?` data-tip="${esc(warn)}"`:''} autocomplete=off spellcheck=false>`;
23371
+ }
23372
+ function frRowCells(rowKey,v,levels,who){
23373
+ // v = {grid,from,to,sizes:{key:text},columns}
23374
+ const cell=(col,value,o)=>frInput(rowKey,col,value,o);
23375
+ return `<td class="fr-stl">${cell('grid',v.grid,{cls:'fr-g',label:`Grid line for ${who}`,cmd:`${who} grid line`,warn:frWarnGrid(v.grid),ph:'Grid'})}</td>`
23376
+ +`<td>${cell('from',v.from,{cls:'fr-e',label:`Span starts at, for ${who}`,cmd:`${who} span start`,warn:frWarnGrid(v.from),ph:'From'})}</td>`
23377
+ +`<td>${cell('to',v.to,{cls:'fr-e',label:`Span ends at, for ${who}`,cmd:`${who} span end`,warn:frWarnTo(v.from,v.to),ph:'To'})}</td>`
23378
+ +levels.map(l=>`<td class="fr-lvcell">${cell('lv:'+l.key,v.sizes[l.key]||'',{label:`Girder sizes at ${l.name} for ${who}`,cmd:`${who} ${l.name}`,warn:frWarnSizes(v.sizes[l.key]||''),ph:'e.g. W24X68'})}</td>`).join('')
23379
+ +(framesLevelDraft?'<td></td>':'')
23380
+ +`<td class="fr-colcell">${cell('columns',v.columns,{label:`Column sizes for ${who}`,cmd:`${who} columns`,warn:frWarnSizes(v.columns),ph:'e.g. W14X90'})}</td>`;
23381
+ }
23382
+ function frViewOfStored(row,levels){
23383
+ const n=FramesCore.normaliseFrameRow(row)||{grid:'',span:[],girders:[],columns:[]}; // a stored row that is not even a record still gets a line, so the rows after it keep their place
23384
+ const sizes=frSizesBag();
23385
+ for(const l of levels){const g=n.girders.find(x=>FramesCore.normLevel(x.level)===l.key);sizes[l.key]=g?g.sizes.join(', '):'';}
23386
+ return {grid:n.grid,from:n.span[0]||'',to:n.span[1]||'',sizes,columns:n.columns.join(', ')};
23387
+ }
23388
+ function frLevelHead(l,rows){
23389
+ const views=FramesCore.viewsOfLevel(rows,l.key).map(id=>framesPlanViews().find(p=>viewIdOf(p)===id)).filter(Boolean).map(p=>viewLabel(p));
23390
+ const typed=framesMerge&&framesMerge.key===l.key?framesMerge.typed:l.name;
23391
+ // When the two levels together hold more than a level keeps, the offer says so and its button says what it keeps (the choices are: merge and keep what fits, or Keep editing / Escape = leave both as they were).
23392
+ const ask=framesMerge&&framesMerge.key===l.key&&framesMerge.over&&framesMerge.over.length?FramesCore.mergeTrimQuestion(framesMerge.over):null;
23393
+ const merge=framesMerge&&framesMerge.key===l.key
23394
+ ?`<div class=fr-merge>A level called “${esc(framesMerge.intoName)}” already exists.${ask?`<span class=fr-mwarn id=frMergeWarn role=alert>${esc(ask.question)}</span>`:''}<span style="display:flex;gap:4px"><button type=button class=ghost data-command-id="steel.frames-merge-level#${esc(l.name)}" data-fr-merge="${esc(l.key)}"${ask?' aria-describedby=frMergeWarn':''}>${ask?esc(ask.proceed):`Merge into “${esc(framesMerge.intoName)}”`}</button><button type=button class=ghost data-command-id="steel.frames-keep-editing" data-fr-keep="1">Keep editing</button></span></div>`:'';
23395
+ return `<th class="fr-lv"><div class=fr-lvhead><input class="ftab-inp fr-lvname" data-lv="${esc(l.key)}" data-orig="${esc(l.name)}" value="${esc(typed)}" maxlength=40 placeholder="Level name" aria-label="Level name: ${esc(l.name)}" data-command-id="steel.frames-level-name#${esc(l.name)}" autocomplete=off spellcheck=false${l.elevationMm!==undefined?` data-tip="${esc('Stated elevation: '+fmtDispElev(l.elevationMm))}"`:''}>`
23396
+ +(l.seed?'':`<button type=button class="ghost fr-lvdel" data-fr-lvdel="${esc(l.key)}" aria-label="Remove level ${esc(l.name)}" data-tip="Remove this level" data-command-id="steel.frames-level-remove#${esc(l.name)}">✕</button>`)+`</div>`
23397
+ +`<div class="fr-lvsheets${views.length?'':' none'}">${views.length?esc(views.join(', ')):'No sheet linked yet'}</div>${merge}</th>`;
23398
+ }
23399
+ function frTableHtml(rows,levels){
23400
+ const head=`<tr><th class="fr-stl">Grid</th><th>From</th><th>To</th>${levels.map(l=>frLevelHead(l,rows)).join('')}`
23401
+ +(framesLevelDraft?`<th class="fr-lv"><div class=fr-lvhead><input class="ftab-inp fr-lvname" id=frLevelNew data-lv="" value="" maxlength=40 placeholder="Level name" aria-label="Name of the new level" data-command-id="steel.frames-level-name#new level" autocomplete=off spellcheck=false></div></th>`:'')
23402
+ +`<th>Columns</th><th class="fr-str" aria-label="Delete"></th></tr>`;
23403
+ const body=rows.map((row,i)=>{
23404
+ const v=frViewOfStored(row,levels),who=frWho(row),held=framesPartial&&framesPartial.idx===i;
23405
+ if(held){v.from=framesPartial.from;v.to=framesPartial.to;}
23406
+ return `<tr class=fr-row data-fr-row="${i}">${frRowCells(String(i),v,levels,who)}<td class="fr-str"><button type=button class="ghost fr-del" data-fr-del="${i}" aria-label="Delete ${esc(FramesCore.normaliseFrameRow(row)?'the frame on '+who:who)}" data-tip="${FramesCore.normaliseFrameRow(row)?'Delete this frame':'Delete this stored row'}" data-command-id="steel.frames-row-delete#${esc(who)}">✕</button></td></tr>`
23407
+ +(held?`<tr class="fr-note warn"><td colspan="${5+levels.length+(framesLevelDraft?1:0)}">This frame has no span yet. Give it both ends and the span is saved.</td></tr>`:'');
23408
+ }).join('');
23409
+ let draft='';
23410
+ if(framesDraft){
23411
+ const d=framesDraft;
23412
+ const v={grid:d.line,from:d.from,to:d.to,sizes:d.sizes,columns:d.columns};
23413
+ const ready=d.line&&d.from&&d.to;
23414
+ let note='Add the grid line and both ends of the span to save this frame.',warn=false;
23415
+ if(d.dupAt!=null&&d.dupAt>=0){const dup=rows[d.dupAt];warn=true;note=`There’s already a frame on ${esc(FramesCore.frameLabel(dup))}. <button type=button class=ghost data-fr-goto="${d.dupAt}" data-command-id="steel.frames-go-to">Go to it</button>`;}
23416
+ else if(d.problem){warn=true;note=esc(d.problem);}
23417
+ else if(ready)note='Saving this frame…';
23418
+ draft=`<tr class="fr-row editing" data-fr-row="draft">${frRowCells('draft',v,levels,'the new frame')}<td class="fr-str"><button type=button class="ghost fr-del" data-fr-drop="1" aria-label="Discard the new frame" data-tip="Discard this new frame" data-command-id="steel.frames-draft-discard">✕</button></td></tr>`
23419
+ +`<tr class="fr-note${warn?' warn':''}"><td colspan="${5+levels.length+(framesLevelDraft?1:0)}">${note}</td></tr>`;
23420
+ }
23421
+ return `<div class=fr-scroll><table class="ftab frtab"><thead>${head}</thead><tbody>${body}${draft}</tbody></table></div>`;
23422
+ }
23423
+ function frSheetsHtml(rows,levels){
23424
+ const views=framesPlanViews();
23425
+ if(!rows.length||!views.length)return '';
23426
+ if(!levels.length)return `<div class=fr-sheets><h4>Which level is each sheet?</h4><div class=fr-hint>Add a level first (+ New level), then say which sheet is which.</div></div>`;
23427
+ const items=views.map(p=>{
23428
+ const id=viewIdOf(p),lk=FramesCore.linkedLevelOf(rows,id);
23429
+ const conflict=lk.state==='conflict';
23430
+ const val=lk.state==='level'?(levels.find(l=>l.key===lk.key)||{name:lk.name}).name:(conflict?FramesCore.joinNames(lk.names):'Not set');
23431
+ const label=frViewLabel(p);
23432
+ return `<div class="fr-sheet${framesFocusView===id?' editing':''}" data-fr-sheet="${esc(id)}"><span class=fr-sheetname data-tip="${esc(label)}">${esc(label)}</span>`
23433
+ +`<input class="combo ftab-inp fr-view${conflict?' fr-warn':''}" readonly data-src=framelevels data-view="${esc(id)}" data-orig="${esc(val)}" value="${esc(val)}" aria-label="Level of ${esc(viewLabel(p))}" data-command-id="steel.frames-sheet-level#${esc(viewLabel(p))}" autocomplete=off>`
23434
+ +(conflict?`<span class=fr-sheetmsg>Choose one.</span>`:'')+`</div>`;
23435
+ }).join('');
23436
+ return `<div class=fr-sheets><h4>Which level is each sheet?</h4>${items}<div class=fr-hint style="margin-top:6px">A sheet linked to a level gets that level’s girder sizes in the member panel. Its cut elevation is not changed.</div></div>`;
23437
+ }
23438
+ function frEmptyHtml(){
23439
+ return `<div class=fr-empty><b>No moment frames yet.</b><p>Add each frame from the Frame Elevations, or ask your terminal AI to read them from the drawings.</p>`
23440
+ +`<div class=fr-acts><button type=button class=fr-primary id=frEmptyAdd data-command-id="steel.frames-empty-add">Add a frame</button><button type=button class=ghost id=frEmptyAsk data-command-id="steel.frames-ask-ai">Ask the AI to read them</button></div></div>`;
23441
+ }
23442
+ function renderFrames(){
23443
+ const g=document.getElementById('framesGrid');if(!g||!FramesCore)return;
23444
+ const rows=framesRows();
23445
+ const started=rows.length>0||!!framesDraft;
23446
+ document.getElementById('framesNew').hidden=!started;
23447
+ document.getElementById('framesLevelNew').hidden=!rows.length;
23448
+ if(!started){g.innerHTML=frEmptyHtml();return;}
23449
+ const levels=rows.length?frLevelsNow():frSeedLevels();
23450
+ g.innerHTML=`<div class=fr-hint>Separate several sizes with a comma. Name the levels as the drawings do (Roof, 2nd floor, 3rd floor).</div>${frTableHtml(rows,levels)}${frSheetsHtml(rows,levels)}`;
23451
+ }
23452
+ function frLocate(k){
23453
+ if(!k)return null;
23454
+ if(k.row!=null&&k.col!=null)return frFindCell(k.row,k.col);
23455
+ if(k.lv!=null&&k.lv!=='')return frFindLevelName(k.lv);
23456
+ if(k.view)return frFindView(k.view);
23457
+ if(k.id)return document.getElementById(k.id);
23458
+ return null;
23459
+ }
23460
+ // The control that was focused is gone (its row or level was deleted): focus goes to the one that took its place, or to the dialog's own
23461
+ // Add / Close button — never to the page behind, which is where the Tab trap would stop catching it.
23462
+ function frRestoreFocus(keep){
23463
+ const modal=document.getElementById('framesModal');
23464
+ if(!modal||modal.contains(document.activeElement))return;
23465
+ let target=null;
23466
+ if(keep&&keep.del!=null){const dels=frAll('.fr-del[data-fr-del]');target=dels[Math.min(+keep.del,dels.length-1)]||null;}
23467
+ else if(keep&&keep.lvdel!=null){target=frAll('.fr-lvdel')[0]||frAll('.fr-lvname')[0]||null;}
23468
+ else if(keep&&keep.row!=null){const cells=frAll('.fr-cell'),rows=cells.map(c=>+c.dataset.row).filter(n=>Number.isFinite(n));const at=rows.length?Math.min(+keep.row,Math.max(...rows)):null;target=cells.find(c=>at!=null&&+c.dataset.row===at&&c.dataset.col===keep.col)||null;}
23469
+ if(!target)target=frAll('.fr-cell')[0]||null;
23470
+ if(!target){const add=document.getElementById('framesNew');target=add&&!add.hidden?add:document.getElementById('framesClose');}
23471
+ if(target)target.focus({preventScroll:true});
23472
+ }
23473
+ function framesRepaint(now){
23474
+ clearTimeout(framesRepaintTimer);
23475
+ const run=()=>{
23476
+ if(!framesOpen())return;
23477
+ const g=document.getElementById('framesGrid');
23478
+ const a=document.activeElement;
23479
+ let keep=null;
23480
+ if(a&&g.contains(a)&&a.dataset){
23481
+ keep={row:a.dataset.row,col:a.dataset.col,lv:a.dataset.lv,view:a.dataset.view,del:a.dataset.frDel,lvdel:a.dataset.frLvdel,id:a.id||null,start:a.selectionStart,end:a.selectionEnd};
23482
+ if(keep.row==='draft'&&framesRemap&&framesRemap.draft!=null)keep.row=String(framesRemap.draft);
23483
+ }
23484
+ framesRemap=null;
23485
+ const sc=g.querySelector('.fr-scroll'),pos=sc?[sc.scrollLeft,sc.scrollTop]:null,top=g.scrollTop;
23486
+ renderFrames();
23487
+ const sc2=g.querySelector('.fr-scroll');if(sc2&&pos){sc2.scrollLeft=pos[0];sc2.scrollTop=pos[1];}g.scrollTop=top;
23488
+ const el=frLocate(keep);
23489
+ if(el){
23490
+ el.focus({preventScroll:true});
23491
+ const textual=el.type==='text'||el.type==='search'; // a type with no text selection would throw: ask first, never swallow
23492
+ if(keep.start!=null&&textual&&typeof el.setSelectionRange==='function')el.setSelectionRange(keep.start,keep.end);
23493
+ }else if(keep)frRestoreFocus(keep);
23494
+ };
23495
+ if(now)run();else framesRepaintTimer=setTimeout(run,0); // a change fires while the next field is taking focus: repainting inside it would destroy that field
23496
+ }
23497
+ function framesFocusCell(row,col){const el=frFindCell(row,col);if(el){el.focus();el.scrollIntoView({block:'nearest',inline:'nearest'});if(el.select)el.select();}return !!el;}
23498
+ function framesWrite(next){const ok=edit(()=>{V2_SESSION.patchModel({moment_frames:next});});if(ok)framesPartial=null;return ok;} // row numbers move with any write: a held span end belongs to the row it was typed on
23499
+ function frRevertCell(t){t.value=t.dataset.orig||'';}
23500
+ function frProblemText(problems,kept){
23501
+ const k=kept?` Kept ${kept}.`:'';
23502
+ const codes=problems.map(p=>p.code);
23503
+ if(codes.includes('grid'))return `A frame needs a grid line.${k}`;
23504
+ if(codes.includes('span'))return `A span needs both of its ends.${k}`;
23505
+ if(codes.includes('duplicate')){const why=problems.find(p=>p.code==='duplicate').reason;return why.charAt(0).toUpperCase()+why.slice(1)+`.${k}`;}
23506
+ return `Couldn’t change that: ${problems.map(p=>p.reason).join(', and ')}.${k}`;
23507
+ }
23508
+ function frCommitCell(t){
23509
+ const rowKey=t.dataset.row,col=t.dataset.col,val=t.value.trim();
23510
+ if(rowKey==='draft'){framesDraftSet(col,val);return;}
23511
+ const idx=+rowKey,rows=framesRows(),row=rows[idx];
23512
+ const n=row?FramesCore.normaliseFrameRow(row):null;
23513
+ if(!n){frRevertCell(t);toast('This stored row isn’t a moment-frame record, so it can’t be edited here. Delete it and add the frame again.');framesRepaint();return;}
23514
+ const v2=FramesCore.toV2Row(row,framesCtx());
23515
+ const sizes=()=>FramesCore.parseSizeText(val).map(_canonDes);
23516
+ let next;
23517
+ if(col==='grid')next={...v2,grid:val};
23518
+ else if(col==='from'||col==='to'){
23519
+ // A stored row with NO span can only be repaired one end at a time, and each end alone is not a span: the end typed is HELD
23520
+ // (shown, flagged, not saved) until the other one is there, instead of being refused and wiped. A row that has a span keeps
23521
+ // the old rule: clearing one end is refused and the old value comes back.
23522
+ const held=framesPartial&&framesPartial.idx===idx?framesPartial:{from:n.span[0]||'',to:n.span[1]||''};
23523
+ const from=col==='from'?val:held.from,to=col==='to'?val:held.to;
23524
+ if(n.span.length!==2&&(!from||!to)){framesPartial={idx,from,to};framesRepaint();return;}
23525
+ next={...v2,span:[from,to]};
23526
+ }
23527
+ else if(col==='columns')next={...v2,columns:sizes()};
23528
+ else if(col.startsWith('lv:')){const key=col.slice(3),l=frLevelsNow().find(x=>x.key===key);next=FramesCore.setLevelSizes(v2,key,l?l.name:key,sizes());}
23529
+ else return;
23530
+ const chk=FramesCore.checkFrameEdit(rows,idx,next);
23531
+ if(!chk.ok){const kept=t.dataset.orig?`“${t.dataset.orig}”`:'';frRevertCell(t);toast(frProblemText(chk.problems,kept));return;}
23532
+ if(frShape(chk.row)===frShape(v2)){t.value=t.dataset.orig||'';return;} // nothing changed: no undo step (compared with the row AS REWRITTEN: the sheets an old-shape row carries into the new shape are not a change the person made)
23533
+ const out=rows.map((r,i)=>i===idx?chk.row:r);
23534
+ if(!framesWrite(out)){frRevertCell(t);return;}
23535
+ // patch IN PLACE: the person is mid-Tab through the row, and a whole-table repaint here would drop their focus
23536
+ const levels=frLevelsNow(),v=frViewOfStored(chk.row,levels),tr=t.closest('tr');
23537
+ if(tr){
23538
+ for(const inp of tr.querySelectorAll('.fr-cell')){
23539
+ const c=inp.dataset.col,text=c==='grid'?v.grid:c==='from'?v.from:c==='to'?v.to:c==='columns'?v.columns:(c.startsWith('lv:')?(v.sizes[c.slice(3)]||''):null);
23540
+ if(text==null)continue;
23541
+ inp.value=text;inp.dataset.orig=text;
23542
+ const w=c==='grid'?frWarnGrid(v.grid):(c==='from'?frWarnGrid(v.from):(c==='to'?frWarnTo(v.from,v.to):(c==='columns'||c.startsWith('lv:')?frWarnSizes(text):'')));
23543
+ inp.classList.toggle('fr-warn',!!w);if(w)inp.dataset.tip=w;else inp.removeAttribute('data-tip');
23544
+ }
23545
+ }
23546
+ if(col==='grid'||col==='from'||col==='to'||n.legacyShaped)framesRepaint(); // the row's accessible names mention its grid line and span; and rewriting an old-shape row wrote its sheets down as links, which the level headers and the sheet list must now show
23547
+ }
23548
+ function framesDraftSet(col,val){
23549
+ const d=framesDraft;if(!d)return;
23550
+ if(col==='grid')d.line=val;else if(col==='from')d.from=val;else if(col==='to')d.to=val;else if(col==='columns')d.columns=val;else if(col.startsWith('lv:'))d.sizes[col.slice(3)]=val;
23551
+ d.dupAt=null;d.problem='';
23552
+ framesDraftTry();
23553
+ }
23554
+ function framesDraftTry(){
23555
+ const d=framesDraft;if(!d)return false;
23556
+ if(!(d.line&&d.from&&d.to)){framesRepaint();return false;}
23557
+ const rows=framesRows();
23558
+ const levels=rows.length?frLevelsNow():frSeedLevels();
23559
+ const cand={
23560
+ grid:d.line,span:[d.from,d.to],columns:FramesCore.parseSizeText(d.columns).map(_canonDes),
23561
+ // a new frame joins the levels the schedule already has, and the sheets already linked to them
23562
+ girders:levels.map(l=>{const views=FramesCore.viewsOfLevel(rows,l.key);return {level:l.name,sizes:FramesCore.parseSizeText(d.sizes[l.key]||'').map(_canonDes),...(views.length?{views}:{})};}),
23563
+ };
23564
+ const chk=FramesCore.checkFrameEdit(rows,-1,cand);
23565
+ if(!chk.ok){
23566
+ const dup=chk.problems.find(p=>p.code==='duplicate');
23567
+ if(dup)d.dupAt=rows.findIndex(r=>FramesCore.frameKey(r)===FramesCore.frameKey(cand));
23568
+ else d.problem=`Couldn’t save this frame: ${chk.problems.map(p=>p.reason).join(', and ')}.`;
23569
+ framesRepaint();return false;
23570
+ }
23571
+ const row={...chk.row,id:framesMintId(),origin:'manual'};
23572
+ if(!framesWrite([...rows,row])){d.problem='Couldn’t save this frame. Nothing was changed.';framesRepaint();return false;}
23573
+ framesDraft=null;framesRemap={draft:rows.length};
23574
+ framesRepaint();
23575
+ return true;
23576
+ }
23577
+ function framesStartDraft(){
23578
+ if(!framesDraft)framesDraft={line:'',from:'',to:'',sizes:frSizesBag(),columns:'',dupAt:null,problem:'',seedName:''};
23579
+ framesRepaint(true);
23580
+ if(framesFocusCell('draft','grid')){const row=document.querySelector('#framesGrid tr[data-fr-row="draft"]');if(row)row.scrollIntoView({block:'nearest'});}
23581
+ }
23582
+ function frDraftIsEmpty(){const d=framesDraft;return !d||!(d.line||d.from||d.to||d.columns||Object.values(d.sizes).some(Boolean));}
23583
+ function frDeleteRow(idx){
23584
+ const rows=framesRows(),row=rows[idx];if(!row)return;
23585
+ const next=rows.filter((_,i)=>i!==idx),what=FramesCore.normaliseFrameRow(row)?`Frame ${FramesCore.frameLabel(row)}`:'The stored row';
23586
+ const lost=FramesCore.lostLevels(rows,next); // levels only this frame had, and the sheets that were linked to them: said, not silently dropped
23587
+ if(!framesWrite(next))return;
23588
+ framesRepaint(true);
23589
+ const depth=undo.length;
23590
+ undoToast(`${what} deleted.${lost.length?` ${lost.length===1?'The level':'The levels'} ${frLostText(lost)} went with it.`:''}`,()=>frUndoIfStill(depth));
23591
+ }
23592
+ function frLevelNew(){
23593
+ if(!framesRows().length){toast('Add a frame first, then add its levels.');return;}
23594
+ framesLevelDraft=true;framesRepaint(true);
23595
+ const el=document.getElementById('frLevelNew');if(el){el.focus();el.scrollIntoView({block:'nearest',inline:'nearest'});}
23596
+ }
23597
+ function frCommitNewLevel(t){
23598
+ const name=t.value.trim();
23599
+ if(!name){framesLevelDraft=false;framesRepaint();return;}
23600
+ const r=FramesCore.addLevel(framesRows(),name,framesCtx());
23601
+ if(!r.ok){toast(r.reason);t.focus();return;}
23602
+ if(!framesWrite(r.rows))return;
23603
+ framesLevelDraft=false;framesRepaint();
23604
+ if(r.skipped.length)toast(`Added ${name}, but ${FramesCore.joinNames(r.skipped)} already ${r.skipped.length===1?'has':'have'} the most levels a frame keeps (${FramesCore.FRAME_LEVELS_PER_ROW_MAX}) and ${r.skipped.length===1?'was':'were'} left as ${r.skipped.length===1?'it is':'they are'}.`);
23605
+ }
23606
+ function frCommitLevelName(t){
23607
+ if(t.id==='frLevelNew'){frCommitNewLevel(t);return;}
23608
+ const key=t.dataset.lv,orig=t.dataset.orig||'',name=t.value.trim(),rows=framesRows();
23609
+ if(!name){t.value=orig;toast(`A level needs a name. Kept “${orig}”.`);return;}
23610
+ if(name===orig)return;
23611
+ if(!rows.length){ // no frame exists yet: the only level on screen is the draft's seed, so the NAME is the draft's and nothing is written
23612
+ frDraftRekey(key,FramesCore.normLevel(name));
23613
+ if(framesDraft)framesDraft.seedName=name;
23614
+ framesRepaint();return;
23615
+ }
23616
+ const levels=frLevelsNow(),clash=levels.find(l=>l.key===FramesCore.normLevel(name)&&l.key!==key);
23617
+ if(clash){
23618
+ // Would the two levels fit together? A level keeps up to FRAME_SIZES_PER_LEVEL_MAX sizes and FRAME_VIEWS_PER_LEVEL_MAX sheet links. If not, the offer SAYS so up front
23619
+ // and its button says what it keeps: nothing is merged and trimmed behind the person's back.
23620
+ const pre=FramesCore.mergeLevel(rows,key,clash.key,framesCtx());
23621
+ framesMerge={key,into:clash.key,intoName:clash.name,typed:name,over:pre.ok?pre.trimmed:[]};
23622
+ framesRepaint();return;
23623
+ }
23624
+ const r=FramesCore.renameLevel(rows,key,name,framesCtx());
23625
+ if(!r.ok){t.value=orig;toast(r.reason);return;}
23626
+ if(!framesWrite(r.rows)){t.value=orig;return;}
23627
+ frDraftRekey(key,FramesCore.normLevel(name));
23628
+ framesMerge=null;framesRepaint();
23629
+ }
23630
+ function frMergeLevel(key){
23631
+ const m=framesMerge;if(!m||m.key!==key)return;
23632
+ const rows=framesRows(),levels=frLevelsNow(),from=levels.find(l=>l.key===key);
23633
+ const r=FramesCore.mergeLevel(rows,key,m.into,framesCtx());
23634
+ if(!r.ok){framesMerge=null;toast(r.reason);framesRepaint();return;}
23635
+ // What the merge would leave out is not what the offer SAID (the schedule changed under it: more links, other sizes, another frame, or it now fits): redraw the offer
23636
+ // with the question as it stands NOW and ask again, writing nothing. Compared in full, not just "does anything overflow", so the person only ever confirms what they were shown.
23637
+ if(!FramesCore.mergeTrimSame(m.over,r.trimmed)){m.over=r.trimmed;framesRepaint(true);const b=frAll('button').find(x=>x.dataset.frMerge!=null);if(b)b.focus();return;}
23638
+ framesMerge=null;
23639
+ if(!framesWrite(r.rows)){framesRepaint();return;}
23640
+ frDraftRekey(key,m.into);
23641
+ framesRepaint(true);
23642
+ const depth=undo.length;
23643
+ const c=r.elevationConflict; // the two levels stated different elevations: the survivor's is kept, and the person is told which
23644
+ const left=FramesCore.mergeTrimNote(r.trimmed,{viewName:id=>frViewNames([id])[0]}); // what did not fit, said again once it has happened (Undo puts it back)
23645
+ undoToast(`${from?from.name:'The level'} merged into ${m.intoName}.${c?` ${c.from.name} was at ${fmtDispElev(c.from.elevationMm)}, ${c.into.name} at ${fmtDispElev(c.into.elevationMm)}; kept ${fmtDispElev(c.into.elevationMm)}.`:''}${left?` ${left}`:''}`,()=>frUndoIfStill(depth));
23646
+ }
23647
+ function frRemoveLevel(key){
23648
+ const rows=framesRows(),l=frLevelsNow().find(x=>x.key===key);if(!l||!rows.length)return;
23649
+ const links=FramesCore.viewsOfLevel(rows,key);
23650
+ let sizes=0;for(const row of rows){const n=FramesCore.normaliseFrameRow(row);const g=n&&n.girders.find(x=>FramesCore.normLevel(x.level)===key);if(g)sizes+=g.sizes.length;}
23651
+ if(!framesWrite(FramesCore.removeLevel(rows,key,framesCtx())))return;
23652
+ framesRepaint(true);
23653
+ const depth=undo.length;
23654
+ const gone=[sizes?`its ${sizes} ${sizes===1?'size':'sizes'}`:'',links.length?`${links.length===1?'its link':'its links'} to ${FramesCore.joinNames(frViewNames(links))}`:''].filter(Boolean);
23655
+ undoToast(`Removed ${l.name}${gone.length===1?` and ${gone[0]}`:gone.length?`, ${FramesCore.joinNames(gone)}`:''}.`,()=>frUndoIfStill(depth));
23656
+ }
23657
+ function frCommitSheetLevel(t){
23658
+ const viewId=t.dataset.view,rows=framesRows(),levels=frLevelsNow(),val=t.value.trim(),plan=framesPlanViews().find(p=>viewIdOf(p)===viewId);
23659
+ const before=FramesCore.linkedLevelOf(rows,viewId);
23660
+ let key=null;
23661
+ if(val&&val!=='Not set'){const l=levels.find(x=>x.name===val);if(!l){t.value=t.dataset.orig||'';return;}key=l.key;}
23662
+ if((before.state==='level'&&before.key===key)||(before.state==='none'&&key===null))return;
23663
+ const next=FramesCore.linkViewToLevel(rows,viewId,key,framesCtx());
23664
+ const label=plan?viewLabel(plan):viewId;
23665
+ if(!framesWrite(next)){t.value=t.dataset.orig||'';return;}
23666
+ framesRepaint(true);
23667
+ const was=before.state==='level'?before.name:(before.state==='conflict'?FramesCore.joinNames(before.names):'');
23668
+ if(was){
23669
+ const depth=undo.length;
23670
+ undoToast(key===null?`${label} is no longer linked to a level.`:`${label} now belongs to ${val} (it was ${was}).`,()=>frUndoIfStill(depth));
23671
+ }
23672
+ }
23673
+ // Fills Ask AI with a request and opens it in "change the model" mode. NOTHING is sent from here, and nothing is added to the schedule:
23674
+ // the person reads the request and sends it. The request asks for a drawing RE-READ (not an edit of the model), because that is the
23675
+ // door where the read records the schedule and where a person confirms it in Review & approve; the AI never approves it.
23676
+ function frAskAi(){
23677
+ const text='Re-read the Frame Elevations in the source drawings, as a drawing re-read, so the moment-frame schedule comes back as a proposal I can review and confirm in Review and approve. Do not edit the model directly. '
23678
+ +'For each moment frame give the grid line it stands on, the two grid lines it spans, the girder sizes at each floor level using the level names exactly as the drawings print them (for example Roof, 2nd floor, 3rd floor), and the column sizes. '
23679
+ +'If the drawings show no frame schedule, tell me instead of guessing.';
23680
+ closeFrames();
23681
+ askAiOpen({mode:'modify',text});
23682
+ }
23683
+ function openFrames(opts){
23684
+ const o=(opts&&typeof opts==='object'&&!opts.nodeType&&!('target' in opts))?opts:{};
23685
+ framesReturn=o.invoker||(document.activeElement&&document.activeElement.nodeType===1?document.activeElement:null);
23686
+ framesFocusView=o.focus==='view'?(o.focusView||null):null; // the static highlight belongs to a deep link that is ABOUT a sheet's level
23687
+ framesDraft=null;framesLevelDraft=false;framesMerge=null;framesPartial=null;
23688
+ renderFrames();
23689
+ document.getElementById('framesModal').style.display='flex';
23690
+ if(o.focus==='frame'){framesStartDraft();return;}
23691
+ if(o.focus==='view'&&framesFocusView){const el=frFindView(framesFocusView);if(el){el.scrollIntoView({block:'center'});el.focus({preventScroll:true});return;}}
23692
+ if(o.focus==='level'){const lv='lv:'+FramesCore.normLevel(o.levelName||'');const el=frAll('.fr-cell').find(x=>x.dataset.col===lv);if(el){el.focus();return;}}
23693
+ const first=document.getElementById('frEmptyAdd')||document.getElementById('framesClose');if(first)first.focus();
23694
+ }
23695
+ // What closing the dialog drops, said in one toast: an unsaved draft (and exactly why it was not saved), and a merge that was offered and not taken.
23696
+ function frClosingNote(){
23697
+ const parts=[],d=framesDraft;
23698
+ if(d&&!frDraftIsEmpty()){
23699
+ const named=d.line?`The frame on grid ${d.line}`:'The new frame';
23700
+ if(d.dupAt!=null&&d.dupAt>=0)parts.push(`${named} wasn’t saved. There’s already one with that span.`);
23701
+ else if(d.problem)parts.push(`${named} wasn’t saved. ${d.problem}`);
23702
+ else{
23703
+ const missing=[!d.line&&'a grid line',!d.from&&'where the span starts',!d.to&&'where the span ends'].filter(Boolean);
23704
+ parts.push(`${named} wasn’t saved. It needs ${FramesCore.joinNames(missing)}.`);
23705
+ }
23706
+ }
23707
+ if(framesMerge)parts.push(`${framesMerge.typed} wasn’t merged into ${framesMerge.intoName}, so the level kept its old name.`);
23708
+ if(framesPartial)parts.push('A frame still has no span: its change wasn’t saved.');
23709
+ return parts.join(' ');
23710
+ }
23711
+ function closeFrames(){
23712
+ const note=frClosingNote();
23713
+ if(note)toast(note);
23714
+ framesDraft=null;framesLevelDraft=false;framesMerge=null;framesPartial=null;framesFocusView=null;
23715
+ document.getElementById('framesModal').style.display='none';
23716
+ const back=framesReturn&&framesReturn.isConnected&&framesReturn.offsetParent!==null?framesReturn:document.getElementById('moreBtn');
23717
+ framesReturn=null;if(back)back.focus();
23718
+ }
21867
23719
  function framesOpen(){return document.getElementById('framesModal').style.display==='flex';}
21868
- document.getElementById('framesBtn').onclick=openFrames;
23720
+ document.getElementById('framesBtn').onclick=()=>openFrames({invoker:document.getElementById('moreBtn')});
21869
23721
  document.getElementById('framesClose').onclick=closeFrames;
21870
23722
  document.getElementById('framesBackdrop').onclick=closeFrames;
23723
+ document.getElementById('framesNew').onclick=()=>framesStartDraft();
23724
+ document.getElementById('framesLevelNew').onclick=()=>frLevelNew();
23725
+ {const modal=document.getElementById('framesModal'),grid=document.getElementById('framesGrid');
23726
+ // CAPTURE phase: a combo pick commits with a synthetic `change` that does not bubble (see comboCommitChange), and capture reaches the field regardless
23727
+ grid.addEventListener('change',e=>{
23728
+ const t=e.target;if(!t||!t.classList)return;
23729
+ if(t.classList.contains('fr-cell'))frCommitCell(t);
23730
+ else if(t.classList.contains('fr-lvname'))frCommitLevelName(t);
23731
+ else if(t.classList.contains('fr-view'))frCommitSheetLevel(t);
23732
+ },true);
23733
+ grid.addEventListener('focusout',e=>{
23734
+ const t=e.target;
23735
+ if(t&&t.id==='frLevelNew'&&!t.value.trim()&&framesLevelDraft)setTimeout(()=>{if(framesLevelDraft&&document.activeElement!==document.getElementById('frLevelNew')){framesLevelDraft=false;framesRepaint(true);}},0); // an empty name on leaving cancels the new column
23736
+ });
23737
+ grid.addEventListener('click',e=>{
23738
+ const b=e.target.closest&&e.target.closest('button');if(!b)return;
23739
+ if(b.id==='frEmptyAdd')framesStartDraft();
23740
+ else if(b.id==='frEmptyAsk')frAskAi();
23741
+ else if(b.dataset.frDel!=null)frDeleteRow(+b.dataset.frDel);
23742
+ else if(b.dataset.frDrop!=null){framesDraft=null;framesRepaint(true);}
23743
+ else if(b.dataset.frLvdel!=null)frRemoveLevel(b.dataset.frLvdel);
23744
+ else if(b.dataset.frMerge!=null)frMergeLevel(b.dataset.frMerge);
23745
+ else if(b.dataset.frKeep!=null){const m=framesMerge;framesMerge=null;framesRepaint(true);const el=m&&frFindLevelName(m.key);if(el){el.focus();el.select();}}
23746
+ else if(b.dataset.frGoto!=null){const i=+b.dataset.frGoto;framesFocusCell(i,'grid');}
23747
+ });
23748
+ // The Tab trap and Escape, copied from #rfiModal. Enter commits a cell and moves down (Shift+Enter up); Escape on a
23749
+ // cell with an unsaved edit puts the old value back, and only a second Escape closes. Arrow keys are left alone.
23750
+ modal.addEventListener('keydown',e=>{
23751
+ e.stopPropagation();
23752
+ const t=e.target,isField=t&&t.classList&&(t.classList.contains('fr-cell')||t.classList.contains('fr-lvname'));
23753
+ const dirty=isField&&t.value!==(t.dataset.orig!=null?t.dataset.orig:t.value);
23754
+ if(e.key==='Escape'){
23755
+ e.preventDefault();
23756
+ if(t.id==='frLevelNew'){framesLevelDraft=false;framesRepaint(true);document.getElementById('framesLevelNew').focus();return;} // Escape in the new level's name cancels just that column
23757
+ if(dirty){t.value=t.dataset.orig||'';return;}
23758
+ if(framesMerge){framesMerge=null;framesRepaint(true);return;}
23759
+ closeFrames();return;
23760
+ }
23761
+ if((e.ctrlKey||e.metaKey)&&!e.altKey&&/^[zy]$/i.test(e.key)&&!dirty){ // undo/redo with the dialog open: the repaint in apply() redraws it
23762
+ e.preventDefault();
23763
+ if(e.key.toLowerCase()==='y'||e.shiftKey)doRedo();else doUndo();
23764
+ return;
23765
+ }
23766
+ if(e.key==='Enter'&&isField&&t.classList.contains('fr-cell')&&!e.ctrlKey&&!e.metaKey&&!e.altKey){
23767
+ e.preventDefault();
23768
+ const rowKey=t.dataset.row,col=t.dataset.col,dir=e.shiftKey?-1:1;
23769
+ const rows=[...document.querySelectorAll('#framesGrid tr[data-fr-row]')].map(r=>r.dataset.frRow);
23770
+ const at=rows.indexOf(rowKey),next=rows[at+dir];
23771
+ t.blur(); // commits through the change event; the repaint is deferred, so the move below lands after it
23772
+ if(next!=null)setTimeout(()=>framesFocusCell(next==='draft'?'draft':next,col),0);
23773
+ return;
23774
+ }
23775
+ if(e.key!=='Tab')return;
23776
+ const f=[...modal.querySelectorAll('button,input,[tabindex]:not([tabindex="-1"])')].filter(n=>!n.disabled&&!n.hidden&&n.offsetParent!==null);
23777
+ if(!f.length)return;
23778
+ const first=f[0],last=f[f.length-1];
23779
+ if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}
23780
+ else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}
23781
+ });
23782
+ }
21871
23783
  // --- The ONE RFI list (#1090): every filed record on this project, plus every member whose size the
21872
23784
  // catalogue cannot price and which nobody has filed yet. ------------------------------------------
21873
23785
  //
@@ -24896,7 +26808,7 @@ async function openActiveProvisional(memberId,openSource,invoker){
24896
26808
  }
24897
26809
 
24898
26810
  let rfiDialogReturn=null;
24899
- function openRFI(focusId,invoker){focusId=(typeof focusId==='string')?focusId:null; // #rfiStat binds openRFI directly, so the arg is a MouseEvent; only a real id string focuses a row (the profile picker's onApply passes one)
26811
+ function openRFI(focusId,invoker,recordId){focusId=(typeof focusId==='string')?focusId:null; // #rfiStat binds openRFI directly, so the arg is a MouseEvent; only a real id string focuses a row (the profile picker's onApply passes one)
24900
26812
  const isElement=value=>typeof Element!=='undefined'&&value instanceof Element;
24901
26813
  rfiDialogReturn=isElement(invoker)?invoker:(isElement(document.activeElement)?document.activeElement:null);
24902
26814
  renderRfiList();
@@ -24905,6 +26817,10 @@ function openRFI(focusId,invoker){focusId=(typeof focusId==='string')?focusId:nu
24905
26817
  // Records are a file another session may have written, so re-read them each time the list is opened.
24906
26818
  if(PROJECT&&rfiState.status!=='loading')refreshRfiRecords();
24907
26819
  if(PROJECT)refreshRfiGmailReadiness();
26820
+ if(typeof recordId==='string'&&recordId){ // a specific question (the one a callout's "See the question" names)
26821
+ const row=_rfiByAttr(document.getElementById('rfiList'),'data-rfi-row',rfiRowKey('record',recordId));
26822
+ if(row){row.scrollIntoView({block:'center'});const f=row.querySelector('button,input,[tabindex]');if(f)f.focus({preventScroll:true});return;}
26823
+ }
24908
26824
  if(focusId){
24909
26825
  const inp=[...document.querySelectorAll('#rfiList input.combo[data-mid]')].find(i=>i.dataset.mid===focusId);
24910
26826
  const row=inp&&inp.closest('.rfirow');
@@ -25139,13 +27055,25 @@ function openDetailVector(url,sheet){const li=document.getElementById('lbImg');
25139
27055
  li.onload=()=>{li.onload=null;lbReset();};li.src=url;
25140
27056
  document.getElementById('lbCap').textContent=sheet+' · vector';
25141
27057
  document.getElementById('lightbox').style.display='flex';if(li.complete)lbReset();}
25142
- async function tryDetailVector(sheet,prev){
27058
+ // `onMiss` (#2211) replaces the old toast: a callout whose sheet has no picture of any kind now gets a card that
27059
+ // says what is missing and offers a way forward (see openMissingSheetCard), not a line that vanishes.
27060
+ // The vector is only worth asking for when this model carries sheet pictures at all. Nothing in the v2 read writes
27061
+ // <project>/details/<sheet>.svg, so on a v2 model the HEAD below could only ever answer 404 — and a request that
27062
+ // can only fail is a console error on every click of an unresolved callout.
27063
+ async function tryDetailVector(sheet,prev,onMiss){
25143
27064
  const url='/api/contract/'+encodeURIComponent(APP_ID)+'/detail/'+encodeURIComponent(sheet)+PROJECT_QS;
25144
- try{const r=await fetch(url,{method:'HEAD'});if(r.ok){openDetailVector(url,sheet);return;}}catch(_){}
27065
+ if(Object.keys(SHEET_PREV).length){try{const r=await fetch(url,{method:'HEAD'});if(r.ok){openDetailVector(url,sheet);return;}}catch(_){}}
25145
27066
  if(prev&&previewFor(prev))openPreview(prev); // no vector → raster preview
27067
+ else if(onMiss)onMiss();
25146
27068
  else toast('Sheet '+sheet+' isn’t loaded — open it to jump there');
25147
27069
  }
25148
27070
  function closeLightbox(){
27071
+ // A view's own picture (#2211) opens this as a dialog and remembers, ON the element, where focus goes back to.
27072
+ // On the element and not in a variable declared above this function: tests slice this function out of the page.
27073
+ {const lb0=document.getElementById('lightbox'),held=lb0._pictureReturn;
27074
+ if(held){lb0._pictureReturn=null;const cl=document.getElementById('lbClose');
27075
+ lb0.removeAttribute('role');lb0.removeAttribute('aria-modal');lb0.removeAttribute('aria-labelledby');cl.removeAttribute('aria-label');
27076
+ if(held.isConnected)setTimeout(()=>{try{held.focus({preventScroll:true});}catch(_){}},0);}}
25149
27077
  document.getElementById('lightbox').style.display='none';
25150
27078
  const li=document.getElementById('lbImg');li.onload=null;li.src='';li.alt='';delete li.dataset.rfiRegion;
25151
27079
  if(rfiLightboxReturn){
@@ -25180,6 +27108,425 @@ lbView.addEventListener('pointerdown',e=>{e.preventDefault();document.getElement
25180
27108
  lbView.addEventListener('pointermove',e=>{if(!lbDrag)return;lbX=lbDrag.ox+(e.clientX-lbDrag.x);lbY=lbDrag.oy+(e.clientY-lbDrag.y);lbApply();});
25181
27109
  lbView.addEventListener('pointerup',()=>{lbDrag=null;lbView.classList.remove('drag');});
25182
27110
  lbView.addEventListener('dblclick',lbReset);
27111
+
27112
+ // ══════════════════════════════════════════════════════════════════════════════════════════════════════════
27113
+ // CALLOUTS (#2211): following them from sheet to sheet, adding and fixing them by hand, and what to say when one
27114
+ // leads nowhere.
27115
+ //
27116
+ // The rules live in steel-marks-core.js, which the server shares: where a callout leads (resolveCalloutTarget),
27117
+ // what a NEW one must say (cleanCallout), when two are the same mark. The click, the tooltip and the tests
27118
+ // therefore cannot disagree about a destination, and the editor can never accept a callout the read would refuse.
27119
+ //
27120
+ // Nothing here guesses. A callout that names a sheet with one view goes there; one with several views asks
27121
+ // which; one whose sheet is not in the model says so by name and offers a way forward. A section never lands
27122
+ // on a framing plan just because the plan was first in the list.
27123
+ // ══════════════════════════════════════════════════════════════════════════════════════════════════════════
27124
+ const CALLOUT_WORD={detail:'Detail',section:'Section',elevation:'Elevation'};
27125
+ const COALLOUT_TIP='Add a callout. Click the plan where a detail, section or elevation mark is drawn, then say which sheet it points to. Click an existing mark to edit it.';
27126
+ function coFinite(d){return Array.isArray(d)&&d.length>=2&&isFinite(+d[0])&&isFinite(+d[1]);}
27127
+ /** detail | section | elevation, for drawing and wording. A legacy mark with no kind (or the old `detailref`) is a detail. */
27128
+ function coKindOf(co,list){if(list==='details')return 'detail';const k=MarksCore.normKind(co&&co.kind);return k==='section'||k==='elevation'?k:'detail';}
27129
+ /** What is printed inside the bubble: the detail number or letter, else the start of the mark. */
27130
+ function coMarkOf(co,list){return String(list==='details'?(numOf(co.text)||co.text||''):(MarksCore.calloutTargetOf(co).number||numOf(co.text)||co.text||''));}
27131
+ function coPreviewKey(res,co){return (res.number&&res.sheet)?(res.number+'-'+res.sheet):(co.text||'');}
27132
+ function coWords(co,list,res){
27133
+ const kind=coKindOf(co,list),mark=coMarkOf(co,list),named=CALLOUT_WORD[kind]+(mark?' '+mark:'');
27134
+ if(calloutEditMode){const w='Edit callout '+(co.text||named);return {tip:w,aria:w};}
27135
+ if(res.state==='no-target')return {tip:named+' · no sheet recorded',aria:named+', no sheet recorded'};
27136
+ if(res.state==='view'){const v=res.views.find(x=>x.viewId===res.viewId)||res.views[0];
27137
+ return {tip:named+' → '+res.sheet+(v.viewKind==='plan'?'':' · opens its picture'),aria:named+', points to '+res.sheet};}
27138
+ if(res.state==='choose')return {tip:named+' → '+res.sheet+' · pick one',aria:named+', points to '+res.sheet+', more than one view to choose from'};
27139
+ const pic=!!previewFor(coPreviewKey(res,co));
27140
+ return {tip:named+' → '+res.sheet+(pic?' · opens its picture':' · not in this model'),aria:named+', points to '+res.sheet+(pic?'':', which is not in this model')};
27141
+ }
27142
+ /** The bubbles for the active plan, plus the draft bubble while a new callout is being placed. */
27143
+ function calloutBubblesSvg(){
27144
+ let s='';
27145
+ const one=(list,i,co)=>{
27146
+ if(!co||typeof co!=='object'||!coFinite(co.disp))return;
27147
+ const kind=coKindOf(co,list),res=MarksCore.resolveCalloutTarget(C,co),w=coWords(co,list,res),mark=coMarkOf(co,list);
27148
+ const kc=list==='details'?'detail':(kind==='section'?'section':kind==='elevation'?'elev':'detailref');
27149
+ const x=+co.disp[0],y=+co.disp[1];
27150
+ s+=`<g class=cohot data-co-list="${list}" data-co-i="${i}" tabindex=0 role=button aria-label="${esc(w.aria)}" data-tip="${esc(w.tip)}"><circle class="cobub k-${kc}" cx="${x}" cy="${y}" r="11"/><text class=cotx x="${x}" y="${y}">${esc(mark.slice(0,3))}</text></g>`;
27151
+ };
27152
+ (P.details||[]).forEach((d,i)=>one('details',i,d));
27153
+ (P.callouts||[]).forEach((c,i)=>one('callouts',i,c));
27154
+ if(calloutDraft&&calloutDraft.index==null&&coFinite(calloutDraft.at)){
27155
+ const k=calloutDraft.kind,kc=k==='section'?'section':k==='elevation'?'elev':'detailref';
27156
+ s+=`<g id=coDraft aria-hidden=true><circle class="cobub k-${kc} draft" cx="${calloutDraft.at[0]}" cy="${calloutDraft.at[1]}" r="11"/><text class=cotx style="opacity:1" x="${calloutDraft.at[0]}" y="${calloutDraft.at[1]}">${esc(String(calloutDraft.mark||'').slice(0,3))}</text></g>`;
27157
+ }
27158
+ return s;
27159
+ }
27160
+ function paintCalloutDraft(){ // the draft bubble follows the form live, without repainting the whole plan on a keystroke
27161
+ const g=svg.querySelector('#coDraft');if(!g||!calloutDraft)return;
27162
+ const k=calloutDraft.kind,kc=k==='section'?'section':k==='elevation'?'elev':'detailref';
27163
+ g.querySelector('circle').setAttribute('class','cobub k-'+kc+' draft');
27164
+ g.querySelector('text').textContent=String(calloutDraft.mark||'').slice(0,3);
27165
+ }
27166
+
27167
+ // ── following a callout ────────────────────────────────────────────────────────────────────────────────────
27168
+ function followCallout(g){
27169
+ const list=g.dataset.coList,i=+g.dataset.coI,co=(P[list]||[])[i];if(!co||!MarksCore)return;
27170
+ const res=MarksCore.resolveCalloutTarget(C,co);
27171
+ if(res.state==='no-target'){toast('This callout doesn’t say which sheet it points to. Turn on Add a callout and click it to fill that in.');return;}
27172
+ if(res.state==='view'){openCalloutView(res.views.find(x=>x.viewId===res.viewId)||res.views[0],g);return;}
27173
+ if(res.state==='choose'){openViewFly(g,res);return;}
27174
+ openMissingTarget(co,res,g);
27175
+ }
27176
+ function openCalloutView(v,from){
27177
+ const idx=C.plans.findIndex(p=>viewIdOf(p)===v.viewId);if(idx<0)return;
27178
+ const plan=C.plans[idx];
27179
+ if(plan.viewKind==='plan'){if(idx!==C.active)setPlan(idx);else fitToWindow();return;} // already here → just re-frame it
27180
+ openViewPicture(plan,from);
27181
+ }
27182
+ /** An elevation or a section is not editable in 2D yet, but its own picture can be looked at, so a callout that points
27183
+ * there lands somewhere instead of toasting "not editable". Hotspots on that picture are a follow-up. */
27184
+ function openNoPictureCard(plan,from){
27185
+ const label=viewLabel(plan)||plan.sheet||'this view';
27186
+ const what=plan.viewKind==='elevation'?'an elevation view':plan.viewKind==='section'?'a section view':'not a plan view';
27187
+ openCalloutCard({title:'No picture for '+label,from,
27188
+ html:`<p>${esc(label)} is ${what} and the editor can’t show it yet. The drawing read didn’t save a picture of it.</p>`,
27189
+ actions:[
27190
+ {label:'Ask your AI to add its picture',cmd:'steel.callout-ask-ai',primary:true,run:b=>coAskAi('The sheet picture for '+label+' is missing from the model. Please read it into the model so its callouts can be followed, or tell me why it can’t be done.',b)},
27191
+ {label:'Carry on',cmd:'steel.dialog-cancel#the callout notice',ghost:true,run:closeCalloutCard}]});
27192
+ }
27193
+ function openViewPicture(plan,from){
27194
+ const label=viewLabel(plan)||plan.sheet||'this view';
27195
+ if(!plan.raster_b64){openNoPictureCard(plan,from);return;}
27196
+ const li=document.getElementById('lbImg'),lb=document.getElementById('lightbox'),cl=document.getElementById('lbClose');
27197
+ // A picture the browser cannot decode must not leave a blank dialog behind: it becomes the same plain card as no picture.
27198
+ li.onerror=()=>{li.onerror=null;li.onload=null;closeLightbox();openNoPictureCard(plan,from);};
27199
+ li.onload=()=>{li.onload=null;li.onerror=null;lbReset();};li.src='data:image/jpeg;base64,'+plan.raster_b64;li.alt=label+' picture';
27200
+ document.getElementById('lbCap').textContent=label+' · picture only';
27201
+ lb.setAttribute('role','dialog');lb.setAttribute('aria-modal','true');lb.setAttribute('aria-labelledby','lbCap');cl.setAttribute('aria-label','Close the picture');
27202
+ lb._pictureReturn=(from&&from.isConnected)?from:stage;
27203
+ lb.style.display='flex';if(li.complete)lbReset();cl.focus();
27204
+ }
27205
+ function openMissingTarget(co,res,from){
27206
+ const prev=coPreviewKey(res,co);
27207
+ if(prev&&previewFor(prev)){openPreview(prev);return;} // a stored picture of that sheet: show it, as before
27208
+ tryDetailVector(res.sheet,prev,()=>openMissingSheetCard(co,res,from));
27209
+ }
27210
+ /** Is there already an open question about this sheet? (The read raises a missing-sheet one for a marker it could not resolve.) */
27211
+ function coSheetQuestion(sheet,co){
27212
+ const want=String(sheet||'').trim();if(!want)return null;
27213
+ const open=((rfiState&&rfiState.records)||[]).filter(r=>r&&r.kind==='missing-sheet'&&r.status!=='closed');
27214
+ // The structured link first: the question the read raised about THIS marker names the marker's own element.
27215
+ const el=co&&typeof co.elementId==='string'?co.elementId:'';
27216
+ const aboutMarker=r=>[...(Array.isArray(r.subjects)?r.subjects:[]),...(Array.isArray(r.occurrences)?r.occurrences.flatMap(o=>Array.isArray(o&&o.subjects)?o.subjects:[]):[])].some(x=>x&&x.elementId===el);
27217
+ if(el){const hit=open.find(aboutMarker);if(hit)return hit;}
27218
+ // Otherwise the sheet NAMED AS A WHOLE WORD in the question ("S-1" is not "S-10"); never a substring of the record.
27219
+ const token=new RegExp('(?<![A-Z0-9])'+want.replace(/[.*+?^${}()|[\]\\]/g,'\\$&').replace(/\s+/g,'\\s*')+'(?![A-Z0-9]|-[A-Z0-9])','i');
27220
+ return open.find(r=>token.test(String(r.question||'')))||null;
27221
+ }
27222
+ function openMissingSheetCard(co,res,from){
27223
+ const question=coSheetQuestion(res.sheet,co);
27224
+ const where=viewLabel(P)||P.sheet||'this sheet',text=co.text||coMarkOf(co,'callouts')||'this callout';
27225
+ const instruction='Sheet '+res.sheet+' is referenced by callout '+text+' on '+where+' but isn’t in this model. Please read it into the model, or tell me why it’s missing.';
27226
+ openCalloutCard({title:'Sheet '+res.sheet+' isn’t in this model',from,
27227
+ html:`<p>Callout ${esc(text)} on ${esc(where)} points to it, so there is nowhere to jump to.</p>`
27228
+ +(res.outsideSet?'<p class=cocard-note>The drawing read noted that this sheet isn’t in the drawing set.</p>':''),
27229
+ actions:[
27230
+ {label:'Ask your AI to get the sheet',cmd:'steel.callout-ask-ai',primary:true,run:b=>coAskAi(instruction,b,res.sheet)},
27231
+ ...(question?[{label:'See the question',cmd:'steel.callout-see-question',run:()=>{closeCalloutCard();openRFI(null,from,question.id);}}]:[]),
27232
+ {label:'Carry on',cmd:'steel.dialog-cancel#the callout notice',ghost:true,run:closeCalloutCard}]});
27233
+ }
27234
+ async function coAskAi(instruction,btn,sheet){
27235
+ const status=document.getElementById('coCardStatus');btn.disabled=true;status.textContent='Sending to your AI…';
27236
+ // The request must never be queued against an older server document, so the model is saved FIRST and the save must
27237
+ // have produced an ETag (the same rule as the detail requests). A failed save says so and queues nothing.
27238
+ try{persist();}catch(_){}
27239
+ let flushed=null;
27240
+ try{flushed=await window.flushContract();if(!flushed||typeof flushed.etag!=='string'||!flushed.etag)throw new Error('saved contract has no ETag');}
27241
+ catch(_){coAskAiFailed(btn,instruction,'Not queued — the model could not be saved, so nothing was sent to your AI. Try again, or copy the request.');return;}
27242
+ let why='';
27243
+ try{
27244
+ const res=await fetch('/api/contract-request',{method:'POST',headers:{'content-type':'application/json'},
27245
+ body:JSON.stringify({appId:APP_ID,project:PROJECT||undefined,instruction,intent:'modify',mode:'modify',target:{sheet:(P&&P.sheet)||undefined,items:[],baseEtag:flushed.etag}})});
27246
+ if(res.ok){closeCalloutCard();toast('Request queued for your terminal AI session');return;}
27247
+ try{const body=await res.json();if(body&&typeof body.error==='string')why=body.error;}catch(_){}
27248
+ coAskAiFailed(btn,instruction,'Couldn’t send that to your AI'+(why?': '+why.replace(/[.!?\s]+$/,'')+'.':'.')+' Try again, or copy the request.');return;
27249
+ }catch(_){}
27250
+ coAskAiFailed(btn,instruction,'Couldn’t reach FloLess to send that to your AI. Try again, or copy the request.');
27251
+ }
27252
+ function coAskAiFailed(btn,instruction,text){
27253
+ const status=document.getElementById('coCardStatus');
27254
+ btn.disabled=false;status.textContent=text;
27255
+ const acts=document.getElementById('coCardActions');
27256
+ if(!acts.querySelector('[data-co-copy]')){const c=document.createElement('button');c.type='button';c.className='ghost';c.dataset.coCopy='1';c.textContent='Copy request';c.setAttribute('data-command-id','steel.callout-copy-request');
27257
+ c.onclick=async()=>{try{await navigator.clipboard.writeText(instruction);status.textContent='Request copied. Paste it into your AI session.';}catch(_){status.textContent='Couldn’t copy. Select the text and copy it yourself: '+instruction;}};
27258
+ acts.insertBefore(c,acts.firstChild);}
27259
+ }
27260
+ // A neutral notice card, built on demand. `from` is where focus returns to.
27261
+ let coCardReturn=null;
27262
+ function openCalloutCard(o){
27263
+ const m=document.getElementById('coCardModal'),acts=document.getElementById('coCardActions');
27264
+ document.getElementById('coCardTitle').textContent=o.title;
27265
+ document.getElementById('coCardBody').innerHTML=o.html;
27266
+ document.getElementById('coCardStatus').textContent='';
27267
+ acts.replaceChildren();
27268
+ for(const a of o.actions){const b=document.createElement('button');b.type='button';b.textContent=a.label;b.setAttribute('data-command-id',a.cmd);
27269
+ if(a.primary)b.className='copPrimary';else if(a.ghost)b.className='ghost';b.onclick=()=>a.run(b);acts.appendChild(b);}
27270
+ coCardReturn=(o.from&&o.from.isConnected)?o.from:document.activeElement;
27271
+ m.style.display='flex';
27272
+ const first=acts.querySelector('button.copPrimary')||acts.querySelector('button');if(first)first.focus();
27273
+ }
27274
+ function closeCalloutCard(){
27275
+ const m=document.getElementById('coCardModal');if(m.style.display!=='flex')return;
27276
+ m.style.display='none';
27277
+ const back=coCardReturn;coCardReturn=null;if(back&&back.isConnected&&back.focus)try{back.focus({preventScroll:true});}catch(_){}
27278
+ }
27279
+ function coCardOpen(){return document.getElementById('coCardModal').style.display==='flex';}
27280
+ document.getElementById('coCardClose').onclick=closeCalloutCard;
27281
+ document.getElementById('coCardBackdrop').onclick=closeCalloutCard;
27282
+ document.getElementById('coCardModal').addEventListener('keydown',e=>{
27283
+ e.stopPropagation();
27284
+ if(e.key==='Escape'){e.preventDefault();if(window.OverlayEscape)window.OverlayEscape.markUsed(e);closeCalloutCard();return;}
27285
+ if(e.key!=='Tab')return;
27286
+ const f=[...document.querySelectorAll('#coCardModal button')].filter(n=>!n.disabled&&n.offsetParent!==null);if(!f.length)return;
27287
+ const first=f[0],last=f[f.length-1];
27288
+ if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}
27289
+ else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}
27290
+ });
27291
+
27292
+ // ── choosing among several views of one sheet ─────────────────────────────────────────────────────────────
27293
+ let viewFlyAway=null,viewFlyReturn=null;
27294
+ function closeViewFly(){
27295
+ const fly=document.getElementById('viewFly');if(!fly)return;
27296
+ fly.remove();
27297
+ if(viewFlyAway){document.removeEventListener('pointerdown',viewFlyAway,true);viewFlyAway=null;}
27298
+ const back=viewFlyReturn;viewFlyReturn=null;if(back&&back.isConnected&&back.focus)try{back.focus({preventScroll:true});}catch(_){}
27299
+ }
27300
+ function openViewFly(g,res){
27301
+ closeViewFly();
27302
+ const fly=document.createElement('div');fly.id='viewFly';fly.className='open';fly.setAttribute('role','menu');
27303
+ fly.setAttribute('aria-label',res.sheet+' has '+res.views.length+' views');
27304
+ const kindWord={plan:'Plan',section:'Section',elevation:'Elevation'};
27305
+ const rows=res.views.map(v=>{
27306
+ const plan=C.plans.find(p=>viewIdOf(p)===v.viewId)||{sheet:v.sheet},label=viewLabel(plan)||v.title||v.sheet;
27307
+ const sub=(kindWord[v.viewKind]||'View')+(v.viewKind==='plan'?'':' · picture only');
27308
+ return `<button type=button role=menuitem class=frow data-v="${esc(v.viewId)}" data-command-id="steel.callout-pick-view#${esc(label)}" data-command-instance-label="${esc(label)}"><span class=nm>${esc(label)}</span><span class=sub>${esc(sub)}</span></button>`;}).join('');
27309
+ fly.innerHTML=`<div class=fhdr>${esc(res.sheet)} has ${res.views.length} views</div>${rows}<div class=ffoot>Pick the one this callout points to.</div>`;
27310
+ document.body.appendChild(fly);
27311
+ const r=g.getBoundingClientRect();
27312
+ fly.style.left=Math.max(8,Math.min(Math.round(r.left),window.innerWidth-fly.offsetWidth-8))+'px';
27313
+ fly.style.top=Math.max(8,Math.min(Math.round(r.bottom+6),window.innerHeight-fly.offsetHeight-8))+'px';
27314
+ viewFlyReturn=g;
27315
+ const btns=[...fly.querySelectorAll('.frow')];
27316
+ btns.forEach(b=>b.onclick=()=>{const v=res.views.find(x=>x.viewId===b.dataset.v);const from=viewFlyReturn;
27317
+ fly.remove();if(viewFlyAway){document.removeEventListener('pointerdown',viewFlyAway,true);viewFlyAway=null;}viewFlyReturn=null;
27318
+ if(v)openCalloutView(v,from);});
27319
+ fly.addEventListener('keydown',e=>{
27320
+ e.stopPropagation();
27321
+ const i=btns.indexOf(document.activeElement);
27322
+ if(e.key==='Escape'){e.preventDefault();if(window.OverlayEscape)window.OverlayEscape.markUsed(e);closeViewFly();}
27323
+ else if(e.key==='ArrowDown'){e.preventDefault();btns[(i+1)%btns.length].focus();}
27324
+ else if(e.key==='ArrowUp'){e.preventDefault();btns[(i-1+btns.length)%btns.length].focus();}
27325
+ else if(e.key==='Tab'){e.preventDefault();closeViewFly();}
27326
+ });
27327
+ viewFlyAway=ev=>{const f=document.getElementById('viewFly');if(f&&!f.contains(ev.target))closeViewFly();};
27328
+ setTimeout(()=>{if(document.getElementById('viewFly'))document.addEventListener('pointerdown',viewFlyAway,true);},0); // deferred so the click that opened it does not close it
27329
+ if(btns[0])btns[0].focus();
27330
+ }
27331
+
27332
+ // ── adding and fixing a callout by hand ───────────────────────────────────────────────────────────────────
27333
+ function syncCalloutButton(){
27334
+ const b=document.getElementById('calloutB');if(!b)return;
27335
+ const blocked=!!NO_PLAN_VIEW;
27336
+ b.classList.toggle('on',!!calloutEditMode);b.setAttribute('aria-pressed',String(!!calloutEditMode)); // an armable mode must SAY whether it is armed (the class alone is invisible to a screen reader and to the Instructor)
27337
+ b.disabled=blocked;
27338
+ if(blocked){b.setAttribute('data-blocked-reason','Callouts can be added on plan views. Open a plan to add one.');b.dataset.tip='Callouts can be added on plan views. Open a plan to add one.';}
27339
+ else{b.removeAttribute('data-blocked-reason');b.dataset.tip=COALLOUT_TIP;}
27340
+ updCalloutToggle();
27341
+ }
27342
+ function setCalloutMode(on){
27343
+ on=!!on;
27344
+ if(on&&(view3d||NO_PLAN_VIEW)){toast('Callouts can be added on plan views. Open a plan to add one.');on=false;}
27345
+ if(on&&(memberEndReview||memberEndScan)&&!memberEndYieldPanel('Add a callout',()=>{setCalloutMode(true);},'calloutB'))return; // like every other armable tool (#1412)
27346
+ calloutEditMode=on;document.body.classList.toggle('calloutedit',on);
27347
+ if(on){ // arming ends the tools it would fight with
27348
+ if(mode==='add'){mode='sel';setMode();}
27349
+ if(dimMode){dimMode=false;setDimMode();}
27350
+ if(csaxisMode){csaxisMode=false;setCsMode();}
27351
+ if(gridMode)setGridMode(false);
27352
+ if(dimStyleMode)setDimStyleMode(false);
27353
+ if(cmTool)disarmCm();
27354
+ picking=false;pickKind='profile';pickEnd=null;geoMode=null;setGeo();qdPick=null;setQdPickCls();dimSplitMode=false;
27355
+ modelSelection.clearMembers();selDimIds.clear();snapOnlyClear2d();
27356
+ }else closeCalloutForm();
27357
+ render();
27358
+ }
27359
+ function closeCalloutForm(){
27360
+ const pop=document.getElementById('calloutPop');
27361
+ if(!pop)return;
27362
+ const hadFocus=pop.contains(document.activeElement);
27363
+ if(comboInput&&pop.contains(comboInput))hideCombo();
27364
+ pop.classList.remove('open');
27365
+ const had=!!calloutDraft;calloutDraft=null;
27366
+ if(had&&hadFocus&&calloutEditMode){try{stage.focus({preventScroll:true});}catch(_){}}
27367
+ }
27368
+ function calloutDisarmByKey(){
27369
+ if(calloutDraft){closeCalloutForm();render();return;}
27370
+ setCalloutMode(false);
27371
+ try{document.getElementById('calloutB').focus({preventScroll:true});}catch(_){}
27372
+ }
27373
+ function coId(){return 'mk-hand-'+Date.now().toString(36)+Math.random().toString(36).slice(2,7);} // a hand-added mark's id: only ever minted in the browser, so unlike a read's ids it may be random
27374
+ function calloutForm(){
27375
+ let pop=document.getElementById('calloutPop');if(pop)return pop;
27376
+ pop=document.createElement('div');pop.id='calloutPop';pop.setAttribute('role','dialog');pop.setAttribute('aria-modal','false');pop.setAttribute('aria-labelledby','coPopTitle');
27377
+ const kinds=['detail','section','elevation'].map(k=>`<button type=button role=radio data-kind="${k}" data-command-id="steel.callout-kind#${esc(CALLOUT_WORD[k].toLowerCase())}" data-command-instance-label="${esc(CALLOUT_WORD[k].toLowerCase())}" aria-checked=false tabindex=-1>${CALLOUT_WORD[k]}</button>`).join('');
27378
+ pop.innerHTML=`<form novalidate>
27379
+ <div class=copTitle id=coPopTitle></div>
27380
+ <label class=elab for=coText>Mark as printed</label>
27381
+ <input data-command-id="steel.callout-mark" type=text id=coText placeholder="7/S-402" autocomplete=off spellcheck=false aria-describedby=coTextErr>
27382
+ <div class=gerr id=coTextErr hidden></div>
27383
+ <label class=elab for=coSheet>Points to sheet</label>
27384
+ <input data-command-id="steel.callout-sheet" type=text id=coSheet class=combo data-src=sheets placeholder="S-402" autocomplete=off spellcheck=false aria-describedby="coSheetErr coSheetNote">
27385
+ <div class=gerr id=coSheetErr hidden></div><div class=hint id=coSheetNote hidden></div>
27386
+ <label class=elab for=coNum>Number or letter</label>
27387
+ <input data-command-id="steel.callout-number" type=text id=coNum placeholder="7 or A" autocomplete=off spellcheck=false aria-describedby=coNumErr>
27388
+ <div class=gerr id=coNumErr hidden></div>
27389
+ <div class=elab id=coKindLbl>It points to a</div>
27390
+ <div class=seg2 id=coKind role=radiogroup aria-labelledby=coKindLbl>${kinds}</div>
27391
+ <div class=hint id=coOrigin hidden>From the drawing read. Your changes are kept if the drawing is read again. If you delete it, a new drawing read may suggest it again.</div>
27392
+ <div class=gerr id=coFormErr role=alert hidden></div>
27393
+ <div class=copFoot><button type=button class=copDelete data-command-id="steel.callout-delete" id=coDelete>Delete</button><span class=copSpacer></span><button type=button data-command-id="steel.dialog-cancel#the callout" id=coCancel>Cancel</button><button type=submit class=copPrimary data-command-id="steel.callout-save" id=coSave>Save callout</button></div>
27394
+ </form>`;
27395
+ document.body.appendChild(pop);
27396
+ const $=id=>pop.querySelector('#'+id);
27397
+ const touched=new Set();
27398
+ pop.addEventListener('keydown',e=>{
27399
+ e.stopPropagation(); // the form owns its keys: the editor's shortcuts (and Ctrl+Z on the canvas) never see them
27400
+ if(e.key==='Escape'){e.preventDefault();if(window.OverlayEscape)window.OverlayEscape.markUsed(e);closeCalloutForm();render();return;}
27401
+ const rb=e.target.closest&&e.target.closest('[role=radio]');
27402
+ if(rb&&(e.key==='ArrowRight'||e.key==='ArrowDown'||e.key==='ArrowLeft'||e.key==='ArrowUp')){
27403
+ e.preventDefault();const all=[...pop.querySelectorAll('[role=radio]')],i=all.indexOf(rb),n=all.length;
27404
+ const to=all[(i+((e.key==='ArrowRight'||e.key==='ArrowDown')?1:n-1))%n];coSetKind(to.dataset.kind);to.focus();
27405
+ }
27406
+ });
27407
+ pop.addEventListener('submit',e=>{e.preventDefault();calloutSave();});
27408
+ pop.querySelectorAll('[role=radio]').forEach(b=>b.onclick=()=>coSetKind(b.dataset.kind));
27409
+ $('coCancel').onclick=()=>{closeCalloutForm();render();};
27410
+ $('coDelete').onclick=()=>calloutDelete();
27411
+ // Typing the mark as printed fills the next two fields from it, until the person types in them themselves.
27412
+ $('coText').addEventListener('input',()=>{
27413
+ const t=$('coText').value;if(calloutDraft)calloutDraft.mark=numOf(t)||t.trim();
27414
+ if(!touched.has('coSheet')){const sh=sheetOf(t);if(sh)$('coSheet').value=sh;coSheetNote();}
27415
+ if(!touched.has('coNum')){const nu=numOf(t);if(nu)$('coNum').value=nu;}
27416
+ clearCoErr('coText');paintCalloutDraft();
27417
+ });
27418
+ $('coSheet').addEventListener('input',()=>{touched.add('coSheet');coSheetNote();clearCoErr('coSheet');});
27419
+ $('coSheet').addEventListener('change',()=>{touched.add('coSheet');coSheetNote();});
27420
+ $('coNum').addEventListener('input',()=>{touched.add('coNum');if(calloutDraft&&!$('coText').value.trim())calloutDraft.mark=$('coNum').value.trim();clearCoErr('coNum');paintCalloutDraft();});
27421
+ pop._touched=touched;
27422
+ return pop;
27423
+ }
27424
+ function coEl(id){return document.getElementById(id);}
27425
+ function clearCoErr(field){const input=coEl(field),err=coEl(field+'Err');if(input)input.removeAttribute('aria-invalid');if(err){err.hidden=true;err.textContent='';}const f=coEl('coFormErr');if(f){f.hidden=true;f.textContent='';}}
27426
+ function setCoErr(field,text){const input=coEl(field),err=coEl(field+'Err');if(input)input.setAttribute('aria-invalid','true');if(err){err.textContent=text;err.hidden=false;}}
27427
+ /** A muted note, not an error: a callout may legitimately name a sheet the model does not have yet. */
27428
+ function coSheetNote(){
27429
+ const note=coEl('coSheetNote'),v=coEl('coSheet').value.trim();if(!note)return;
27430
+ const known=(C.plans||[]).some(p=>p&&MarksCore.normSheet(p.sheet)===MarksCore.normSheet(v));
27431
+ if(v&&!known){note.textContent=v+' isn’t in this model yet. You can still save this.';note.hidden=false;}else{note.textContent='';note.hidden=true;}
27432
+ }
27433
+ function coSetKind(kind){
27434
+ if(!calloutDraft)return;calloutDraft.kind=kind;
27435
+ coEl('calloutPop').querySelectorAll('[role=radio]').forEach(b=>{const on=b.dataset.kind===kind;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));b.tabIndex=on?0:-1;});
27436
+ paintCalloutDraft();
27437
+ }
27438
+ /** Open the form for a NEW callout at `at` (sheet px), or for the existing callout `index`. `client` is where to put it on screen. */
27439
+ function openCalloutForm(o){
27440
+ const canon=C.plans[C.active];if(!canon||canon.viewKind!=='plan')return;
27441
+ const pop=calloutForm(),existing=o.index!=null?(canon.callouts||[])[o.index]:null;
27442
+ const keep=!existing&&calloutDraft&&calloutDraft.index==null; // clicking another empty spot MOVES the form and keeps what was typed
27443
+ const typed=keep?{text:coEl('coText').value,sheet:coEl('coSheet').value,num:coEl('coNum').value,touched:new Set(pop._touched)}:null;
27444
+ pop._touched.clear();
27445
+ ['coText','coSheet','coNum'].forEach(clearCoErr);coEl('coFormErr').hidden=true;
27446
+ calloutDraft={at:existing?[+existing.disp[0],+existing.disp[1]]:o.at.slice(),index:o.index==null?null:o.index,kind:existing?coKindOf(existing,'callouts'):(typed&&calloutDraft?calloutDraft.kind:'detail'),mark:''};
27447
+ coEl('coPopTitle').textContent=existing?'Edit callout':'Add a callout';
27448
+ coEl('coSave').textContent=existing?'Save changes':'Save callout';
27449
+ coEl('coDelete').hidden=!existing;
27450
+ const origin=coEl('coOrigin');origin.hidden=!(existing&&existing.origin==='read');
27451
+ if(existing){
27452
+ const t=MarksCore.calloutTargetOf(existing);
27453
+ coEl('coText').value=existing.text||'';coEl('coSheet').value=t.sheet||'';coEl('coNum').value=t.number||'';
27454
+ ['coSheet','coNum'].forEach(id=>pop._touched.add(id));
27455
+ calloutDraft.mark=t.number||numOf(existing.text)||existing.text||'';
27456
+ }else if(typed){
27457
+ coEl('coText').value=typed.text;coEl('coSheet').value=typed.sheet;coEl('coNum').value=typed.num;typed.touched.forEach(id=>pop._touched.add(id));
27458
+ calloutDraft.mark=numOf(typed.text)||typed.text.trim();
27459
+ }else{coEl('coText').value='';coEl('coSheet').value='';coEl('coNum').value='';}
27460
+ coSetKind(calloutDraft.kind);coSheetNote();
27461
+ pop.classList.add('open');
27462
+ // Put it beside the click, then keep it inside the plan pane using its real size.
27463
+ const sr=stage.getBoundingClientRect(),w=pop.offsetWidth,h=pop.offsetHeight;
27464
+ const cx=o.client?o.client[0]:sr.left+sr.width/2,cy=o.client?o.client[1]:sr.top+sr.height/2;
27465
+ pop.style.left=Math.max(sr.left+8,Math.min(Math.round(cx+16),sr.right-w-8))+'px';
27466
+ pop.style.top=Math.max(sr.top+8,Math.min(Math.round(cy+16),sr.bottom-h-8))+'px';
27467
+ render(); // draws the draft bubble
27468
+ coEl('coText').focus();coEl('coText').select();
27469
+ }
27470
+ function calloutClick(e){
27471
+ const g=e.target.closest&&e.target.closest('g.cohot');
27472
+ if(g){calloutOpenForMark(g,e);return;}
27473
+ const q=toSvg(e);
27474
+ openCalloutForm({at:[Math.round(q.x*100)/100,Math.round(q.y*100)/100],client:[e.clientX,e.clientY],index:null});
27475
+ }
27476
+ function calloutOpenForMark(g,e){
27477
+ if(g.dataset.coList!=='callouts'){toast('That mark came from an older drawing read and can’t be edited here. Add a callout next to it to change where it points.');return;}
27478
+ const r=g.getBoundingClientRect();
27479
+ openCalloutForm({index:+g.dataset.coI,client:e&&e.clientX!=null?[e.clientX,e.clientY]:[r.left+r.width/2,r.top+r.height/2]});
27480
+ }
27481
+ function calloutSave(){
27482
+ if(!calloutDraft||!MarksCore)return;
27483
+ const canon=C.plans[C.active];if(!canon)return;
27484
+ const text=coEl('coText').value.trim(),sheet=coEl('coSheet').value.trim(),number=coEl('coNum').value.trim(),kind=calloutDraft.kind;
27485
+ const base=Array.isArray(canon.callouts)?canon.callouts:[],idx=calloutDraft.index,existing=idx!=null?base[idx]:null;
27486
+ if(idx!=null&&!existing){closeCalloutForm();render();toast('That callout is no longer there.');return;}
27487
+ const at=existing?[+existing.disp[0],+existing.disp[1]]:calloutDraft.at;
27488
+ const r=MarksCore.cleanCallout({kind,text,disp:at,target:{sheet,...(number?{number}:{})}});
27489
+ ['coText','coSheet','coNum'].forEach(clearCoErr);
27490
+ if(!r.ok){
27491
+ const first=[];
27492
+ for(const p of r.problems){
27493
+ if(p.code==='text'&&!first.includes('coText')){setCoErr('coText',text?'Keep the mark under '+MarksCore.MARK_TEXT_MAX+' characters.':'Type what the mark says on the drawing, e.g. 7/S-402.');first.push('coText');}
27494
+ else if(p.code==='target-sheet'&&!first.includes('coSheet')){setCoErr('coSheet',sheet?'Keep the sheet name under '+MarksCore.MARK_SHEET_MAX+' characters.':'Say which sheet it points to, e.g. S-402.');first.push('coSheet');}
27495
+ else if(p.code==='target-number'&&!first.includes('coNum')){setCoErr('coNum','Keep the number or letter under '+MarksCore.MARK_NUMBER_MAX+' characters.');first.push('coNum');}
27496
+ else if(!first.length){const f=coEl('coFormErr');f.textContent='Couldn’t place that callout. Click the plan again where the mark is drawn.';f.hidden=false;first.push('coText');}
27497
+ }
27498
+ const el=coEl(first[0]);if(el)el.focus();
27499
+ return;
27500
+ }
27501
+ let entry,msg;
27502
+ if(existing){
27503
+ const target={...r.entry.target};
27504
+ if(existing.target&&existing.target.outsideSet===true&&MarksCore.normSheet(existing.target.sheet)===MarksCore.normSheet(sheet))target.outsideSet=true; // still the same sheet the read said was missing
27505
+ entry={...existing,kind:r.entry.kind,text:r.entry.text,target};
27506
+ if(JSON.stringify(entry)===JSON.stringify(existing)){closeCalloutForm();render();return;} // nothing changed: no undo step for it
27507
+ msg='Callout '+r.entry.text+' saved. Ctrl+Z undoes it.';
27508
+ }else{
27509
+ entry={id:coId(),...r.entry,origin:'manual'};
27510
+ msg='Callout '+r.entry.text+' added. Ctrl+Z undoes it.';
27511
+ }
27512
+ const next=existing?base.map((c,i)=>i===idx?entry:c):[...base,entry];
27513
+ const ok=edit(()=>{V2_SESSION.patchPlan(viewIdOf(canon),{callouts:next});});
27514
+ if(!ok){const f=coEl('coFormErr');if(f){f.textContent='Couldn’t save that callout. Nothing was changed.';f.hidden=false;}return;}
27515
+ closeCalloutForm();render();toast(msg);
27516
+ }
27517
+ function calloutDelete(){
27518
+ if(!calloutDraft||calloutDraft.index==null)return;
27519
+ const canon=C.plans[C.active],base=Array.isArray(canon&&canon.callouts)?canon.callouts:[],idx=calloutDraft.index,existing=base[idx];
27520
+ if(!existing){closeCalloutForm();render();return;}
27521
+ const next=base.filter((_,i)=>i!==idx),label=existing.text||'callout';
27522
+ const ok=edit(()=>{V2_SESSION.patchPlan(viewIdOf(canon),{callouts:next});});
27523
+ if(!ok){const f=coEl('coFormErr');if(f){f.textContent='Couldn’t delete that callout. Nothing was changed.';f.hidden=false;}return;}
27524
+ closeCalloutForm();render();toast('Callout '+label+' deleted. Ctrl+Z brings it back.'+(existing.origin==='read'?' A new drawing read may suggest it again.':''));
27525
+ }
27526
+ document.getElementById('calloutB').onclick=()=>{
27527
+ setCalloutMode(!calloutEditMode);
27528
+ setLastCmd('Add a callout',()=>{if(!calloutEditMode)setCalloutMode(true);});
27529
+ };
25183
27530
  // --- custom dark combobox (replaces the native white datalist dropdown) ---
25184
27531
  const COMBO_SRC={
25185
27532
  profiles:()=>profs,
@@ -25187,8 +27534,10 @@ const COMBO_SRC={
25187
27534
  membertypes:()=>memberTypeRecords().map(t=>t.label),
25188
27535
  conntypes:()=>['moment','drag','shear','braced','pinned','fixed'],
25189
27536
  details:()=>detTexts(), // the SAME list the Details modal shows — see detTexts (#397)
27537
+ sheets:()=>[...new Set((C.plans||[]).map(p=>p&&p.sheet).filter(Boolean))], // the sheets this model has, for a callout's "Points to sheet" (free text is still allowed)
25190
27538
  favcats:()=>FAV_CAT_SUGGEST[favCatKind]||[],
25191
- connrows:()=>['— none —',...(C.connections||[]).map(r=>connLabel(r))]
27539
+ connrows:()=>['— none —',...(C.connections||[]).map(r=>connLabel(r))],
27540
+ framelevels:()=>['Not set',...(FramesCore?FramesCore.levelsOf(C.moment_frames).map(l=>l.name):[])] // the Frames dialog's "which level is this sheet?" picker (#2210): pick only
25192
27541
  };
25193
27542
  // A connection-library row's one-line label for the per-end picker. The id is the prefix (parsed
25194
27543
  // back on select); type/detail follow for the human. Kept here so COMBO_SRC + cFld + wireConn agree.
@@ -25196,11 +27545,7 @@ function connLabel(r){return r.id+' · '+(r.type||'?')+(r.detail?' · '+r.detail
25196
27545
  function connRowById(id){return (C.connections||[]).find(r=>r&&r.id===id)||null;}
25197
27546
  // How many member ends reference this library row — model-wide (a column base counts as one end). Used to
25198
27547
  // tell the user what a row deletion would cut loose before it happens.
25199
- function connEndUsage(id){let n=0;
25200
- for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(!m)continue;
25201
- if(m.col&&m.col.conn===id)n++;
25202
- for(const en of (m.ends||[]))if(en&&en.conn===id)n++;}
25203
- return n;}
27548
+ function connEndUsage(id){return endsCitingRow(id).length;} // canonical members, not C.plans (which carries no members on v2) — see endsCitingRow
25204
27549
 
25205
27550
  // ── detail → connection recipe ──────────────────────────────────────────────────────────────────
25206
27551
  // >>> BEGIN detail-recipes mirror >>> (the markers are load-bearing: detail-recipes-parity.test.ts
@@ -25317,10 +27662,62 @@ function resolveDetail(m,which){
25317
27662
  // <<< END detail-recipes mirror <<<
25318
27663
 
25319
27664
  // ── building a connection FROM a detail ─────────────────────────────────────────────────────────
27665
+ // >>> BEGIN detail-apply engine >>> (load-bearing, like the mirror's markers above: detail-apply-engine.test.ts
27666
+ // slices this block — through the end of applyAllDetails — out of the page and RUNS it against a fixture model,
27667
+ // so what "rebuild" and "protected" mean is pinned by a driven test, not by a comment. Move a marker and that
27668
+ // test fails by name.)
25320
27669
  // The apply engine, kept free of DOM so the single-end button, the bulk action and any future caller
25321
27670
  // all go through one set of rules. Joint shape matches every other authoring path (auto-detail, the
25322
27671
  // Favourites apply at onInsertPlace, the IFC import): {id,kind,main,at,params,source} + conn.
25323
27672
 
27673
+ /**
27674
+ * WHO MADE THE JOINT SITTING AT A DETAIL-BOUND END — the one place this action decides what it may rebuild
27675
+ * and what it must leave alone. Everything else (the blocker, the toolbar's Clear, the inspector's intro)
27676
+ * asks this function; none of them reads `source` on its own.
27677
+ *
27678
+ * 'built' source 'auto' + a `conn` row id. This action's own work, and nobody has edited it: every hand
27679
+ * edit of a joint's parameters (the base-plate and shear-plate inspector, the web-side, weld-side,
27680
+ * grade and stiffener switches) goes through markJointTuned, which ends this state. Rebuilt
27681
+ * whenever the detail's meaning changed. NOT the toolbar's own auto plate.
27682
+ * 'earlier' source 'user' + a `conn`. How an older version of this action saved its own work — and also what
27683
+ * "Remember as…" leaves on a hand-made joint. "Built and never touched" cannot be told from
27684
+ * "built, then tuned", so it is PROTECTED, but listed as what it is: never as "tuned by hand",
27685
+ * which may be untrue. "Replace the protected ones" brings one up to date, and rebuilds it as
27686
+ * 'built' from then on. (A joint tuned by hand under THIS version is not 'earlier': markJointTuned
27687
+ * let go of its `conn`, which is exactly what keeps the two apart.)
27688
+ * 'hand' source 'user', no `conn`. A person (or the AI) placed it, or tuned a built one.
27689
+ * 'plain' source 'auto', no `conn`. The toolbar's Shear plates / Base plates auto-detail.
27690
+ * 'other' no source at all (nothing the editor writes) — treated as before: not protected, not cleared.
27691
+ */
27692
+ function detailJointOrigin(j){
27693
+ if(!j)return null;
27694
+ const linked=typeof j.conn==='string'&&j.conn!=='';
27695
+ if(j.source==='auto')return linked?'built':'plain';
27696
+ if(j.source==='user')return linked?'earlier':'hand';
27697
+ return 'other';}
27698
+ /**
27699
+ * A person edited this joint's parameters: it is theirs from now on. Every hand-edit path calls this, and none
27700
+ * writes `source` itself. It also lets go of the row the joint cites — otherwise a connection tuned today would
27701
+ * be indistinguishable from one an older version of this action saved as 'user' ('earlier'), and the report
27702
+ * could only say "linked earlier, possibly changed" about a change we KNOW happened. The end still cites the
27703
+ * row, so nothing about the detail binding is lost. Call it inside edit(), like the edit itself.
27704
+ */
27705
+ function markJointTuned(j){if(!j)return;delete j.conn;j.source='user';}
27706
+ /** The toolbar's own auto-added plate — the only kind "Clear base plates / Clear shear plates" may delete. */
27707
+ function isPlainAutoJoint(j){return detailJointOrigin(j)==='plain';}
27708
+ /** A connection this action built and no one has edited. */
27709
+ function isDetailBuiltJoint(j){return detailJointOrigin(j)==='built';}
27710
+ // Named once so the report, the single-end toast and the tests all say the same thing. Deliberately does not
27711
+ // claim a person tuned it, because for a connection saved before this action marked its own work nobody can know.
27712
+ const DETAIL_EARLIER_TEXT='it was linked to a detail earlier and may have been changed by hand since';
27713
+ // A brace is listed, never built: the engine refuses a shear plate or base plate on one. Used when the
27714
+ // callout itself did not resolve far enough to name the kind (resolveDetail names it when it can).
27715
+ const DETAIL_BRACE_TEXT='A brace can’t carry a connection built from a detail — building it would produce nothing.';
27716
+ // Callouts the sweep can see but nothing can be built from. Listed so none of them vanishes from the report.
27717
+ const DETAIL_NOT_DRAWN_TEXT='not drawn on any sheet the editor can place, so nothing can be built from here';
27718
+ const DETAIL_COLUMN_BOTTOM_TEXT='Nothing is built from a column’s bottom callout — a column’s base plate comes from its top-end callout.';
27719
+ const DETAIL_REFUSED_TEXT='the model refused the change, so nothing was built';
27720
+
25324
27721
  // Unique vs ANY existing joint id, the same way bpJointId/spJointId are — NOT the single-shot
25325
27722
  // Date.now()+random() the favourite/import paths use. Those mint one id per user click; this one runs in a
25326
27723
  // synchronous sweep where Date.now() is constant for every end, leaving a 10k random space: a 200-end
@@ -25336,23 +27733,63 @@ function detailJointId(){const ids=new Set((C.joints||[]).map(j=>j&&j.id));
25336
27733
  // top of imported geometry. Matched by member alone, deliberately: without an `at` we cannot tell WHERE on
25337
27734
  // the member it sits, and refusing a whole member is the honest side of that ignorance.
25338
27735
  function customJointOn(memberId){return (C.joints||[]).find(j=>j&&j.kind==='custom'&&j.main===memberId)||null;}
25339
- // Defensive detection for malformed input that repeats a member id across projected sheets. Anything
25340
- // that matches joints by `main` alone cannot tell repeated ids apart.
27736
+ // Defensive detection for malformed input that repeats a member id. Anything that matches joints by `main`
27737
+ // alone cannot tell repeated ids apart. Walks the canonical members at the document root: on steel.model/v2
27738
+ // `C.plans[].members` does not exist, so the old walk answered "no duplicates" for every model, silently.
25341
27739
  function duplicateMemberIds(){const seen={},dup=new Set();
25342
- for(const pl of (C.plans||[]))for(const m of (pl.members||[])){if(!m||!m.id)continue;
27740
+ for(const m of (C.members||[])){if(!m||!m.id)continue;
25343
27741
  if(seen[m.id])dup.add(m.id);else seen[m.id]=1;}
25344
27742
  return dup;}
27743
+ // The member ends that cite a library row, read from the CANONICAL members (so a member drawn on no sheet
27744
+ // counts too). `index` is the canonical end: 0/1, a column's top being ends[1]. Never walks C.plans — see
27745
+ // duplicateMemberIds.
27746
+ function endsCitingRow(rowId){const out=[];
27747
+ for(const m of (C.members||[])){if(!m||!m.id)continue;
27748
+ (Array.isArray(m.ends)?m.ends:[]).forEach((e,i)=>{if(e&&e.conn===rowId)out.push({id:m.id,index:i});});}
27749
+ return out;}
27750
+ /**
27751
+ * Let go of every citation of a library row ahead of deleting it: the joints that cite it keep standing (an
27752
+ * 'auto' one becomes the person's, or it would read as the toolbar's own plate and "Clear shear plates" would
27753
+ * delete work the dialog promised to keep), then every member end that cites it is cleared THROUGH THE MODEL
27754
+ * COMMAND PATH. A member end handed out by the projection is a clone: writing `end.conn=''` on it is lost, the
27755
+ * saved model still cites a row that is gone, and the server then refuses every save ("does not name a
27756
+ * connections[] row"). The ends go last, while the row still exists, because each command re-validates the
27757
+ * whole model. Call it inside edit(), and delete the row from C.connections AFTER it (patchEnd re-seats C).
27758
+ */
27759
+ function releaseRowCitations(rowId){
27760
+ const cited=endsCitingRow(rowId); // collected first: every patchEnd below re-seats the document under a live walk
27761
+ for(const j of (C.joints||[]))if(j&&j.conn===rowId){delete j.conn;if(j.source==='auto')j.source='user';}
27762
+ for(const c of cited){
27763
+ const shown=byId(c.id),end=shown&&(shown.ends||[])[c.index];
27764
+ if(end)ModelCmd.patchEnd(end,{conn:''});
27765
+ else V2_SESSION.patchEnd(c.id,c.index,{conn:undefined});} // drawn on no sheet: there is no projection to hand the command
27766
+ return cited.length;}
27767
+ /** Delete a library row and everything that cites it, as ONE undo step. True when the model took it. */
27768
+ function removeConnectionRow(rowId){
27769
+ return edit(()=>{releaseRowCitations(rowId);C.connections=(C.connections||[]).filter(x=>x&&x.id!==rowId);})!==false;}
27770
+ /** Point one end at a library row (the "Pick one…" chooser). True when the model took it. */
27771
+ function citeDetailRow(m,which,rowId){
27772
+ const end=endObjFor(m,which);if(!end)return false;
27773
+ return edit(()=>{ModelCmd.patchEnd(end,{conn:rowId});})!==false;}
25345
27774
  // The joint already sitting at this end, if any — one connection per end, same rule the favourite/import
25346
27775
  // paths use (two overlapping joints would also make "edit on member" target the older one).
25347
27776
  function jointAtEnd(memberId,which){const at=jointAtFor(which);
25348
27777
  return (C.joints||[]).find(j=>j&&j.main===memberId&&(j.at===at||(which==='col'&&j.kind==='base-plate'&&!j.at)))||null;}
25349
27778
  // Every (member, end) in the MODEL that carries a callout or a library reference — the population the
25350
27779
  // bulk action walks. Model-wide, like joints and the selection.
25351
- function detailEndTargets(){const out=[];
27780
+ // A brace carries neither a shear plate nor a base plate — the engine skips the joint, so nothing is ever
27781
+ // built for one and we must not claim to have applied one; a column's BOTTOM end is no target either (its base
27782
+ // plate is built from the top-end callout). By default both are left out (the capture dialog counts the ends a
27783
+ // rule would BUILD on). The bulk action passes `withUnbuildable` so a callout on one of them is still listed,
27784
+ // tagged `brace:true` / `colBottom:true`, instead of vanishing from the report.
27785
+ function detailEndTargets(withUnbuildable){const out=[];
25352
27786
  for(const m of projectedAllMembers()){if(!m)continue;
25353
- if(m.role==='column'){if(m.col&&(m.col.detail||m.col.conn))out.push({m,which:'col'});continue;}
25354
- if(isBrace(m))continue; // a brace carries neither a shear plate nor a base plate — the engine skips the joint, so we must not claim to have applied one
25355
- for(const w of [0,1]){const e=(m.ends||[])[w];if(e&&(e.detail||e.conn))out.push({m,which:w});}}
27787
+ if(m.role==='column'){
27788
+ if(withUnbuildable){const b=(m.ends||[])[0];if(b&&(b.detail||b.conn))out.push({m,which:0,colBottom:true});}
27789
+ if(m.col&&(m.col.detail||m.col.conn))out.push({m,which:'col'});continue;}
27790
+ const brace=isBrace(m);
27791
+ if(brace&&!withUnbuildable)continue;
27792
+ for(const w of [0,1]){const e=(m.ends||[])[w];if(e&&(e.detail||e.conn))out.push(brace?{m,which:w,brace:true}:{m,which:w});}}
25356
27793
  return out;}
25357
27794
  /**
25358
27795
  * Why applying to this end would be REFUSED even though its detail resolves — the protection for work
@@ -25367,9 +27804,32 @@ function detailApplyBlocker(m,which,res,force){
25367
27804
  if(end.connVerified===true)return {reason:'verified',text:'someone confirmed this end'};
25368
27805
  if(j&&j.verified===true)return {reason:'verified',text:'someone confirmed this connection'};
25369
27806
  if((j&&j.kind==='custom')||customJointOn(m.id))return {reason:'custom',text:'an imported connection is on this member — it cannot be rebuilt if replaced'};
25370
- if(j&&j.source==='user'&&recipeParamsDiffer(j.params,res.params))return {reason:'tuned',text:'this one was tuned by hand'};
27807
+ // An 'auto' joint that cites a detail row is this action's own untouched work (see detailJointOrigin), so
27808
+ // it falls through and is rebuilt when the recipe changed. Only a person's joints are protected here, and
27809
+ // a 'user' joint that cites a row is the ambiguous legacy case — protected, but not called "tuned".
27810
+ const own=detailJointOrigin(j);
27811
+ if(own==='earlier'&&recipeParamsDiffer(j.params,res.params))return {reason:'built-earlier',text:DETAIL_EARLIER_TEXT};
27812
+ if(own==='hand'&&recipeParamsDiffer(j.params,res.params))return {reason:'tuned',text:'this one was tuned by hand'};
25371
27813
  }
25372
27814
  return null;}
27815
+ /**
27816
+ * What the bulk action AND the single-end button do at one end whose detail resolves — one decision, so the two
27817
+ * cannot drift (the single-end button once turned a person's matching connection into the action's own work, which a
27818
+ * later change to the detail then overwrote unasked).
27819
+ * {kind:'skip', reason, text} protected: leave it, say why
27820
+ * {kind:'already', own} it already says what the detail says. A PERSON's joint ('hand' / 'earlier') stays
27821
+ * theirs — rebuilding it would hand it to this action. Our own work counts as
27822
+ * right only when the joint AND the end cite the row; otherwise a rebuild relinks.
27823
+ * {kind:'build'} build (or rebuild) it
27824
+ */
27825
+ function detailEndDecision(m,which,res,force){
27826
+ const blk=detailApplyBlocker(m,which,res,force);
27827
+ if(blk)return {kind:'skip',reason:blk.reason,text:blk.text};
27828
+ const j=jointAtEnd(m.id,which),own=detailJointOrigin(j);
27829
+ const exact=!!j&&j.kind===res.kind&&!recipeParamsDiffer(j.params,res.params);
27830
+ if(exact&&(detailPersonOwned(own)||(j.conn===res.rowId&&endObjFor(m,which).conn===res.rowId)))return {kind:'already',own};
27831
+ return {kind:'build'};}
27832
+ function detailPersonOwned(own){return own==='hand'||own==='earlier';}
25373
27833
  /**
25374
27834
  * Build the connection this end's detail describes. Caller owns the edit() wrapper so a bulk run is ONE
25375
27835
  * undo step; pass the resolution in so the caller can report without resolving twice.
@@ -25377,7 +27837,12 @@ function detailApplyBlocker(m,which,res,force){
25377
27837
  */
25378
27838
  function buildJointFromDetail(m,which,res){
25379
27839
  const at=jointAtFor(which),id=detailJointId();
25380
- const joint={id,kind:res.kind,main:m.id,at,params:Object.assign({},res.params),source:'user',conn:res.rowId};
27840
+ // source 'auto' + conn marks this as the action's OWN, untouched work (detailJointOrigin 'built'): the next
27841
+ // run rebuilds it when the detail changes. It used to be 'user', which made every connection this button
27842
+ // built read as hand-tuned the moment the recipe moved. The schema's source is a closed enum
27843
+ // ["auto","user"], so provenance rides on the row id the joint already cites. Editing any parameter flips
27844
+ // it to 'user' (the inspector wiring), which is what protects a person's tuning from a later run.
27845
+ const joint={id,kind:res.kind,main:m.id,at,params:Object.assign({},res.params),source:'auto',conn:res.rowId};
25381
27846
  // A fin plate wants its support recorded the same way auto-detail records it (geometry-inferred, and
25382
27847
  // optional — the engine places the plate off the beam end + axis either way).
25383
27848
  if(res.kind==='shear-plate'&&which!=='col'){const sup=spInferSupport(m,which);joint.secondaries=sup?[sup.id]:[];}
@@ -25385,15 +27850,18 @@ function buildJointFromDetail(m,which,res){
25385
27850
  C.joints=C.joints.filter(j=>!(j&&j.main===m.id&&(j.at===at||(which==='col'&&j.kind==='base-plate'&&!j.at))));
25386
27851
  C.joints.push(joint);
25387
27852
  // Point the end at the row it was built from, on BOTH sides: the end and the joint cite the same row,
25388
- // so type/detail identity and the "unassigned" state cannot disagree between them.
25389
- const end=endObjFor(m,which);if(end)end.conn=res.rowId;
27853
+ // so type/detail identity and the "unassigned" state cannot disagree between them. Through the command path,
27854
+ // and AFTER the joint is in C.joints: the end handed out by the projection is a clone, so `end.conn=…` was
27855
+ // silently lost (the next run, or any reload, then saw an end citing nothing and rebuilt every connection under
27856
+ // a new id), while patchEnd re-seats the document, so a joint written after it would be lost the same way.
27857
+ const end=endObjFor(m,which);if(end&&end.conn!==res.rowId)ModelCmd.patchEnd(end,{conn:res.rowId});
25390
27858
  return id;}
25391
27859
  /**
25392
27860
  * Resolve + build every end whose detail resolves. One edit() → one undo step for the whole sweep.
25393
27861
  * Returns {applied, already, skipped:[{m,which,reason,text}]} — the caller reports it; nothing is silent.
25394
27862
  */
25395
27863
  function applyAllDetails(opts){const force=!!(opts&&opts.force),only=opts&&opts.onlyRowId;
25396
- const targets=detailEndTargets(),skipped=[];let applied=0,already=0,lastId=null;
27864
+ const targets=detailEndTargets(true),skipped=[];let applied=0,already=0,lastId=null;
25397
27865
  // If malformed input repeats an id, model-wide main+at matching could let the second build replace the
25398
27866
  // first connection. This action sweeps every sheet in one click, so refuse those ends by name rather
25399
27867
  // than quietly losing a connection.
@@ -25401,18 +27869,53 @@ function applyAllDetails(opts){const force=!!(opts&&opts.force),only=opts&&opts.
25401
27869
  const work=[];
25402
27870
  for(const t of targets){
25403
27871
  if(dupIds.has(t.m.id)){skipped.push({m:t.m,which:t.which,reason:'duplicate-id',text:'more than one member is called '+t.m.id});continue;}
27872
+ if(t.colBottom){if(!only)skipped.push({m:t.m,which:t.which,reason:'column-bottom',text:DETAIL_COLUMN_BOTTOM_TEXT});continue;} // listed, never built
25404
27873
  const res=resolveDetail(t.m,t.which);
27874
+ if(t.brace){ // listed, NEVER built — whatever its callout resolves to. resolveDetail names the kind when it can; otherwise the generic sentence.
27875
+ if(!only)skipped.push({m:t.m,which:t.which,reason:'brace-unsupported',text:res.reason==='brace-unsupported'?res.message:DETAIL_BRACE_TEXT});
27876
+ continue;}
25405
27877
  if(!res.ok){skipped.push({m:t.m,which:t.which,reason:res.reason,text:res.message});continue;}
25406
27878
  if(only&&res.rowId!==only)continue;
25407
- const blk=detailApplyBlocker(t.m,t.which,res,force);
25408
- if(blk){skipped.push({m:t.m,which:t.which,reason:blk.reason,text:blk.text});continue;}
27879
+ const d=detailEndDecision(t.m,t.which,res,force);
27880
+ if(d.kind==='skip'){skipped.push({m:t.m,which:t.which,reason:d.reason,text:d.text});continue;}
25409
27881
  // Already exactly what the detail says → not work, and not a failure either. Counted separately so
25410
27882
  // "applied 0" never reads as "nothing happened" when the model is simply already correct.
25411
- const j=jointAtEnd(t.m.id,t.which);
25412
- if(j&&j.kind===res.kind&&!recipeParamsDiffer(j.params,res.params)&&j.conn===res.rowId&&endObjFor(t.m,t.which).conn===res.rowId){already++;continue;}
27883
+ if(d.kind==='already'){already++;continue;}
25413
27884
  work.push({t,res});}
25414
- if(work.length)edit(()=>{for(const w of work){lastId=buildJointFromDetail(w.t.m,w.t.which,w.res);applied++;}});
27885
+ // A callout on a member the editor cannot place on any sheet (elevation-only, a refused sheet) never reaches
27886
+ // the walk above, which goes through the projection. Read the canonical members so it is listed, not lost.
27887
+ if(!only){const drawn=new Set(projectedAllMembers().map(pm=>pm&&pm.id));
27888
+ for(const cm of (C.members||[])){if(!cm||!cm.id||drawn.has(cm.id))continue;
27889
+ (Array.isArray(cm.ends)?cm.ends:[]).forEach((e,i)=>{if(e&&(e.detail||e.conn))
27890
+ skipped.push({m:{id:cm.id},which:(cm.role==='column'&&i===1)?'col':i,reason:'not-drawn',text:DETAIL_NOT_DRAWN_TEXT});});}}
27891
+ // One edit() → one undo step. edit() answers false when the model refused the change and rolled it back: then
27892
+ // nothing was built, and the report must not say it was.
27893
+ if(work.length){
27894
+ const ok=edit(()=>{for(const w of work)lastId=buildJointFromDetail(w.t.m,w.t.which,w.res);});
27895
+ if(ok===false){lastId=null;for(const w of work)skipped.push({m:w.t.m,which:w.t.which,reason:'build-failed',text:DETAIL_REFUSED_TEXT});}
27896
+ else applied=work.length;}
25415
27897
  return {applied,already,skipped,lastId};}
27898
+ /**
27899
+ * The single-end button's whole action. It decides with detailEndDecision, exactly like the sweep, and says
27900
+ * what happened as an outcome the click handler turns into words:
27901
+ * unresolved {message} the callout does not resolve (re-resolved at click time: the model can move under an open panel)
27902
+ * duplicate-id more than one member carries this id, so a joint could land on the wrong one
27903
+ * blocked {reason,text} protected work is there — not changed
27904
+ * kept {own} a PERSON's connection already says what the detail says — left as theirs
27905
+ * refused the model rejected the change (edit() has already said so) — nothing was built
27906
+ * built {id,res} built, or rebuilt
27907
+ */
27908
+ function applySingleDetail(m,which){
27909
+ const res=resolveDetail(m,which);
27910
+ if(!res.ok)return {outcome:'unresolved',message:res.message};
27911
+ if(duplicateMemberIds().has(m.id))return {outcome:'duplicate-id'};
27912
+ const d=detailEndDecision(m,which,res,false);
27913
+ if(d.kind==='skip')return {outcome:'blocked',reason:d.reason,text:d.text};
27914
+ if(d.kind==='already'&&detailPersonOwned(d.own))return {outcome:'kept',own:d.own};
27915
+ let id=null;
27916
+ if(edit(()=>{id=buildJointFromDetail(m,which,res);})===false)return {outcome:'refused'};
27917
+ return {outcome:'built',id,res};}
27918
+ // <<< END detail-apply engine <<<
25416
27919
 
25417
27920
  // ── the two detail modals ───────────────────────────────────────────────────────────────────────
25418
27921
  // Both are built with createElement rather than an HTML string: every value shown here is MODEL data
@@ -25520,8 +28023,9 @@ function openDetailPick(m,which){
25520
28023
  cancel.className='ghost';cancel.onclick=close;
25521
28024
  use.onclick=()=>{const id=(group.querySelector('input[name=dpick]:checked')||{}).value;close();
25522
28025
  if(!id)return;
25523
- const end=endObjFor(m,which);edit(()=>{end.conn=id;});
25524
- toast('This '+whichLabel(which)+' now uses '+((connRowById(id)||{}).detail||id));};
28026
+ // Through the command path (citeDetailRow): the end is a projected clone, so writing it directly was lost
28027
+ // while this toast still claimed the choice had been made.
28028
+ if(citeDetailRow(m,which,id))toast('This '+whichLabel(which)+' now uses '+((connRowById(id)||{}).detail||id));};
25525
28029
  foot.append(cancel,use);use.focus();}
25526
28030
 
25527
28031
  // ── plain-English labels for the detail UI ──────────────────────────────────────────────────────
@@ -25603,7 +28107,17 @@ function captureDetailRecipe(m,which,opt,type){
25603
28107
  // so this is for the reader, not for correctness.
25604
28108
  sched.sort((a,b)=>schedRank(a&&a.match)-schedRank(b&&b.match));
25605
28109
  rec.schedule=sched;}
25606
- ModelCmd.patchEnd(e,{conn:rowId});j.conn=rowId; // the end and the joint both cite the row, so neither can read as unassigned while the other is built
28110
+ // The end and the joint both cite the row, so neither can read as unassigned while the other is built.
28111
+ // The joint is written BEFORE patchEnd on purpose: patchEnd re-seats the document, so `j` (fetched above) is a
28112
+ // stale copy afterwards and a write to it is silently lost — which is what the old order did, leaving the
28113
+ // joint citing nothing. A joint that cites a row while still 'auto' would read as THIS ACTION's own work
28114
+ // (detailJointOrigin 'built'), which Build from details would then rewrite. One that was the toolbar's own
28115
+ // plate (auto, no row) was not made by that button, so it becomes the person's: protected, and no longer the
28116
+ // toolbar's to clear. One Build from details made and nobody touched ('built') stays 'auto': it keeps
28117
+ // following the detail, and its `conn` now simply names the row it was remembered under (owner ruling, #2207).
28118
+ const wasPlain=isPlainAutoJoint(j);
28119
+ j.conn=rowId;if(wasPlain)j.source='user';
28120
+ ModelCmd.patchEnd(e,{conn:rowId});
25607
28121
  });
25608
28122
  return {rowId:rowId,droppedSchedule:droppedSchedule};}
25609
28123
  const comboPop=document.createElement('div');comboPop.id='comboPop';document.body.appendChild(comboPop);
@@ -25611,10 +28125,11 @@ let comboInput=null,comboIdx=-1;
25611
28125
  function showCombo(inp){if(inp&&inp.getAttribute&&inp.getAttribute('aria-disabled')==='true'){hideCombo();return;}const src=COMBO_SRC[inp.dataset.src];if(!src)return;comboInput=inp;
25612
28126
  // connrows is a row PICKER (readonly), not a type-to-filter field — always offer every row.
25613
28127
  const isType=inp.dataset.src==='membertypes';
25614
- const q=(inp.dataset.src==='connrows'||isType)?'':(inp.value||'').trim().toUpperCase();const opts=src().filter(o=>String(o).toUpperCase().includes(q));
28128
+ const q=(inp.dataset.src==='connrows'||inp.dataset.src==='framelevels'||isType)?'':(inp.value||'').trim().toUpperCase();const opts=src().filter(o=>String(o).toUpperCase().includes(q));
25615
28129
  const typed=isType?cleanMemberTypeLabel(inp.value):'',canAdd=!!(isType&&typed&&!memberTypeKnownLabel(typed));
25616
28130
  if(!opts.length&&!canAdd){comboPop.style.display='none';return;}
25617
28131
  comboPop.classList.toggle('membertypes',isType);
28132
+ comboPop.classList.toggle('on-stage',!!(inp.closest&&inp.closest('#calloutPop'))); comboPop.classList.toggle('over-modal',!!(inp.closest&&inp.closest('#framesModal'))); // a list opened inside the Frames dialog must sit above it // a list opened from a form that floats on the drawing wears the drawing's dark palette in both themes
25618
28133
  comboPop.innerHTML=opts.map(o=>`<div class=opt data-v="${esc(o)}"${String(o).length>24?` data-tip="${esc(o)}"`:''}>${esc(o)}</div>`).join('')+(canAdd?`<div class="opt add" data-v="${esc(typed)}">+ Add "${esc(typed)}"</div>`:'');
25619
28134
  const r=inp.getBoundingClientRect();comboPop.style.left=Math.round(r.left)+'px';comboPop.style.top=Math.round(r.bottom+2)+'px';comboPop.style.minWidth=Math.round(r.width)+'px';
25620
28135
  comboPop.style.display='block';comboIdx=-1;}
@@ -25710,6 +28225,7 @@ function resetPlanViewState(i){
25710
28225
  setMode();
25711
28226
  if(gridMode||gridPick||gridLinePick){if(gridLinePick&&gridLinePick.line)gridLinePick.line.remove();gridMode=false;gridPick=false;gridLinePick=null;gridSetPickClass();}
25712
28227
  dimStyleMode=false;csaxisMode=false;setCsMode();snapOnlyClear2d();closeSnapMenu();disarmCm();
28228
+ calloutEditMode=false;document.body.classList.remove('calloutedit');closeCalloutForm();closeViewFly(); // the + Callout tool and its form belong to the sheet they were opened on
25713
28229
  render();fitToWindow();
25714
28230
  refresh3DGrid();
25715
28231
  syncPlanSwitcher(i);}
@@ -25763,6 +28279,7 @@ function setPlan(i){
25763
28279
  if(gridMode||gridPick||gridLinePick){if(gridLinePick&&gridLinePick.line)gridLinePick.line.remove();gridMode=false;gridPick=false;gridLinePick=null;gridSetPickClass();} // grid panel/pick disarms per plan like the other takeover tools (a leaked pick would set geometry in the WRONG sheet's display space)
25764
28280
  dimStyleMode=false; // the style pane's override count is per-sheet → close it on a plan switch rather than show a stale one
25765
28281
  csaxisMode=false;setCsMode(); // set-axes tool resets per plan; P.frame itself is per-plan data (persisted), so it stays
28282
+ calloutEditMode=false;document.body.classList.remove('calloutedit');closeCalloutForm();closeViewFly(); // …and the + Callout tool + form likewise: a mark placed in the wrong sheet's display space is the failure this prevents
25766
28283
  snapOnlyClear2d();closeSnapMenu(); // a snap override never outlives its plan (different geometry)
25767
28284
  disarmCm(); // Move/Copy resets per plan too (its counts persist — they're session prefs, not plan data)
25768
28285
  document.getElementById('detailsBtn').textContent='Details ('+detTexts().length+')…'; // counts what the modal LISTS — openDetails() sets the same label from the same list, and the two disagreed on a callouts-only sheet (#397)
@@ -25926,7 +28443,7 @@ function openPlans(){
25926
28443
  planTrigger.setAttribute('aria-expanded','true');
25927
28444
  tipClippedRows(); // now that the rows have layout, tooltip only the ones that actually lost their tail
25928
28445
  // Open ON the current plan, so ↓ steps to the next one rather than to the top — and take "current" from
25929
- // the row the control is SHOWING, not from C.active. The two can disagree: "View my edits instead"
28446
+ // the row the control is SHOWING, not from C.active. The two can disagree: "Show my earlier edits"
25930
28447
  // (showStaleDraftBanner) calls applyDraftFields, which writes C.active and then only render()s — it never
25931
28448
  // reaches setPlan, so P, the canvas and this control all stay on the old plan while C.active moves. That
25932
28449
  // desync predates this control and is not ours to fix here, but reading C.active would make this the
@@ -26957,12 +29474,27 @@ function askAiMoveKey(e){
26957
29474
  const palette=e.currentTarget.closest('.mpanel'),r=palette.getBoundingClientRect(),step=e.shiftKey?48:16;
26958
29475
  askAiManualPosition={left:r.left+(e.key==='ArrowLeft'?-step:e.key==='ArrowRight'?step:0),top:r.top+(e.key==='ArrowUp'?-step:e.key==='ArrowDown'?step:0)};askAiPosition();
26959
29476
  }
26960
- function askAiOpen() {
29477
+ // `opts` is optional: `{mode:'modify'|'query', text}` opens Ask AI in that mode with that request filled in. A bare call (the button)
29478
+ // opens a question, as it always did. Text a person had typed and not sent is KEPT: a prefilled request is added BELOW it, with a
29479
+ // toast saying so, never written over it. EVERY open starts as a Question (a drafted Change must not stay armed across a close and a reopen),
29480
+ // and a caller that prefilled a change request asks for Change explicitly AFTER that reset, here, so it cannot be lost the way a mode set
29481
+ // before the call was.
29482
+ function askAiOpen(opts) {
29483
+ const o=(opts&&typeof opts==='object'&&!opts.nodeType&&!('target' in opts))?opts:{};
26961
29484
  askAiSetMode('query');
29485
+ if(o.mode==='modify')askAiSetMode('modify');
29486
+ const field=document.getElementById('askAiText');
29487
+ if(typeof o.text==='string'&&o.text.trim()){
29488
+ const have=String(field.value||'').trim(),want=o.text.trim();
29489
+ if(!have)field.value=want;
29490
+ else if(!have.includes(want)){field.value=have+'\n\n'+want;toast('Kept your unsent Ask AI text and added this request below it. Check it before you send.');} // already there (asked twice): leave it, do not stack it
29491
+ askAiTouchDraft();
29492
+ }
26962
29493
  askAiTarget=canonicalTargetItems(selIds);askAiTargetSheet=(P&&P.sheet)||null;askAiRenderSelection();
26963
29494
  askAiLastRequest=null;document.getElementById('askAiCopyRetry').hidden=true;
26964
29495
  askAiSetStatus('');document.getElementById('askAiModal').style.display = 'block';document.getElementById('askAiBtn').setAttribute('aria-expanded','true');askAiPosition();
26965
- document.getElementById('askAiText').focus();
29496
+ askAiSyncSend();
29497
+ field.focus();
26966
29498
  void askAiRefreshRuntimes();
26967
29499
  }
26968
29500
  function askAiClose(returnFocus=true) {