@floless/app 0.112.0 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -532,7 +532,57 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
532
532
  text.numtx{fill:#fff;font:bold 12px system-ui;text-anchor:middle;dominant-baseline:central;pointer-events:none}
533
533
  #dupStat.has b{color:#fca5a5} #dupB.alert{background:#7f1d1d;border-color:#991b1b} #dupB.alert:hover{background:#991b1b}
534
534
  #dupB.ok,#revB.ok{background:#166534;border-color:#16a34a;color:#dcfce7}
535
- header select#planSel{width:auto;min-width:210px;padding:5px 8px;font-weight:600}
535
+ /* Plan switcher — a themed combobox, NOT a native <select>.
536
+ A <select>'s CLOSED state takes styling fine; its arrow and its option list do not. Those are drawn
537
+ by the OS, so they come up as a light panel against this dark theme no matter what the rule says —
538
+ the browser default the "style every control" rule exists to stop. Same defect, same fix, as
539
+ web/steel-filter.html's sheet switcher; the control's vocabulary (trigger + popover + option rows)
540
+ is the app-wide .wf-combo's (web/index.html + web/app.css).
541
+ Re-expressed in THIS page's dropdown idiom rather than copied from the sibling page, because the
542
+ editor already HAS a header-dropdown family (#moreMenu, .cmmenu, .m3dmenu, #comboPop) and a fifth
543
+ dropdown that read differently from the other four would be the drift this comment exists to stop:
544
+ #475569 border (not --line), top:calc(100% + 6px), z-index:30, 240px of list. Deliberately with NO
545
+ entry animation — the sibling page fades its panel in; this page's four dropdowns appear instantly
546
+ and it carries exactly one @keyframes (a spinner), so a fade here would be a new micro-aesthetic
547
+ rather than fidelity to the locked baseline. */
548
+ .plan-combo{position:relative;display:inline-flex;flex:none}
549
+ /* min-width is the OLD select's 210px floor, kept so the header's spacing does not move. The 320px cap
550
+ is new: `width:auto` let the native control grow without limit, and a long "S-202 · Second Floor
551
+ Framing At El 118'-6"" pushed the stat readouts along the dense header. What the cap clips, the
552
+ data-tip below restores on hover.
553
+ appearance:none is inert on a <button> — the background/border rules here already de-nativize it —
554
+ but it is stated rather than assumed: `appearance: auto` on this control is the exact signature the
555
+ QA pass matched on when it caught the <select>, and leaving it reading `auto` would have the next
556
+ such pass re-raise a defect that is gone. */
557
+ .plan-trigger{display:inline-flex;align-items:center;gap:6px;min-width:210px;max-width:320px;-webkit-appearance:none;appearance:none;background:var(--bg);border:1px solid #475569;border-radius:6px;padding:5px 8px;font:600 13px system-ui}
558
+ /* Load-bearing, not decorative: the page's generic `button:hover{background:#475569}` would otherwise
559
+ win on hover and flash the grey ACTION-button chrome onto a control that is a field you pick from.
560
+ (Class beats tag, so this rule wins wherever it is declared.) */
561
+ .plan-trigger:hover,.plan-trigger.open{background:var(--bg);border-color:var(--brand)}
562
+ .plan-trigger-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}
563
+ .plan-caret{color:var(--mut);flex:none;transition:transform .15s}
564
+ .plan-trigger.open .plan-caret{transform:rotate(180deg)}
565
+ /* Panel matched to #moreMenu/.cmmenu — the other dropdowns hanging off this same header row. */
566
+ .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 #475569;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);padding:4px 0;z-index:30}
567
+ /* This page has no global [hidden] rule, so an author `display` on a hidden element wins by ORIGIN over
568
+ the UA's own [hidden] and `planPopover.hidden = true` would quietly do nothing. .plan-popover declares
569
+ no `display` TODAY, so this is redundant right now — it stays as insurance, because the moment anyone
570
+ gives this panel a `display` its absence becomes exactly that silent-inert-`hidden` bug. */
571
+ .plan-popover[hidden]{display:none}
572
+ .plan-list{overflow-y:auto;max-height:240px} /* a scroll container — themed by the global * scrollbar rules at the top of this file */
573
+ /* A <div role=option>, NOT a <button>: focus must stay on the trigger for aria-activedescendant to mean
574
+ anything, and a focusable row also leaves focus on <body> when the row is clicked and then hidden. So
575
+ it needs its own cursor/font rather than inheriting the page's button rules. The transparent
576
+ border-left is what stops the selected row's accent shifting its text by 2px. */
577
+ .plan-option{display:block;width:100%;cursor:pointer;background:transparent;border:none;border-left:2px solid transparent;padding:7px 12px;text-align:left;font:13px system-ui;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
578
+ .plan-option:hover,.plan-option.active{background:#334155} /* .active = the keyboard highlight, the name #comboPop already uses for it on this page */
579
+ /* Left-border accent for the current plan — the shared .wf-option.selected convention, not a tick glyph:
580
+ this page already spends ✓ on .m3dmenu's mode toggles, and blurring "pick one value" with "toggle a
581
+ mode" is worse than keeping the two apart. */
582
+ .plan-option.selected{border-left-color:var(--brand);color:var(--brand)}
583
+ /* Mirrors app.css's .sr-only. Needed because this page does not load app.css, and the plan switcher has
584
+ no visible label beside it the way the workflow/project pickers do. */
585
+ .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
536
586
  /* 2D|3D view toggle — segmented, far-left; active segment filled (--panel) with a --brand underline */
537
587
  #viewToggle{display:inline-flex;border:1px solid var(--line);border-radius:6px;overflow:hidden;flex:none}
538
588
  #viewToggle .seg{padding:5px 11px;margin:0;border:0;border-radius:0;background:transparent;color:var(--mut);font:600 12px system-ui;cursor:pointer}
@@ -819,7 +869,35 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
819
869
  <header>
820
870
  <b>Steel Model</b>
821
871
  <div id=viewToggle role=group aria-label="Canvas view"><button id=vt2d class="seg on" aria-pressed=true data-tip="Plan view (2D overlay)">2D</button><button id=vt3d class=seg aria-pressed=false data-tip="3D model view">3D</button></div>
822
- <select id=planSel data-tip="Switch plan view"></select>
872
+ <!-- Plan switcher. See the .plan-* rules for why this is not a <select>. Unlike the sibling page's sheet
873
+ switcher it is NOT hidden for a single plan: this control is the ONLY place the current sheet name
874
+ appears in this editor, so hiding it for a one-plan model would delete information rather than a
875
+ dead control. (An earlier version of this comment justified that by claiming the sibling can hide
876
+ because the sheet is also named on its #src readout. That is false — #src renders `C.source.name`,
877
+ the source FILE's name — and the sibling really does leave a lone sheet unnamed on screen. The
878
+ decision here stands on its own; it does not need a claim about the other page.) -->
879
+ <div class="plan-combo" id=planCombo>
880
+ <!-- aria-labelledby (label + VALUE), never aria-label: aria-label would OVERRIDE the button's own text,
881
+ so a screen reader would announce the control's purpose and never say which plan is open — a
882
+ regression against the <select>, which announced its selected option for free. data-tip is a
883
+ tooltip, not an accessible name, so it cannot carry this on its own. The label span is visually
884
+ hidden only because this header has no room for a visible one. -->
885
+ <span id=planComboLabel class=sr-only>Plan view</span>
886
+ <button id=planTrigger class=plan-trigger type=button role=combobox aria-haspopup=listbox aria-expanded=false aria-controls=planPopover aria-labelledby="planComboLabel planTriggerLabel" data-tip="Switch plan view">
887
+ <span class=plan-trigger-label id=planTriggerLabel></span>
888
+ <svg class=plan-caret width=10 height=6 viewBox="0 0 10 6" aria-hidden=true><path fill=currentColor d="M0 0l5 6 5-6z"/></svg>
889
+ </button>
890
+ <!-- role=listbox sits on the element aria-controls POINTS AT. With the role on the inner scroller
891
+ instead, the trigger would carry aria-activedescendant naming an option inside a listbox it never
892
+ declared it controlled — the APG relationship, broken. -->
893
+ <div id=planPopover class=plan-popover role=listbox aria-labelledby=planComboLabel hidden>
894
+ <!-- role=none on the scroller: it exists only to carry overflow, and without this the listbox owns no
895
+ options directly — every role=option would sit one generic group below it, which is not the
896
+ listbox→option relationship aria-activedescendant is read against. (Code review; the sibling page
897
+ has the same gap, so this is a fix, not a divergence to copy back blindly.) -->
898
+ <div class=plan-list id=planList role=none></div>
899
+ </div>
900
+ </div>
823
901
  <!-- These four are per-SHEET counts (see stats()). A model in the canonical format has no per-sheet
824
902
  members, so for it they are HIDDEN rather than dimmed — a readout that is wrong is worse than one
825
903
  that is absent, and "Members 0" beside a populated 3D scene is wrong (unit 5, P7d §8.5). -->
@@ -1322,6 +1400,23 @@ function restampDraftBase(prev, next) {
1322
1400
  localStorage.setItem(draftKey(), JSON.stringify(d));
1323
1401
  } catch (_) { /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
1324
1402
  }
1403
+ /**
1404
+ * Write a PENDING in-memory edit into this browser's draft row, right now. Assigned by main().
1405
+ *
1406
+ * WHY IT IS A SEAM AND NOT A CALL. `persist()` and the debounce handle `saveT` live inside main()'s
1407
+ * closure; the SSE handler below lives in boot()'s. Two scopes, one document — the same reason
1408
+ * `serverEtag` is declared out here rather than in there.
1409
+ *
1410
+ * WHY IT EXISTS AT ALL. `scheduleSave` debounces 500 ms, and it is the only AUTOSAVE caller of
1411
+ * `persist()` — Ctrl+S, connModifyRequest and detailRequest call it too, from explicit user actions, and
1412
+ * an earlier version of this comment wrongly called scheduleSave the only caller at all. For
1413
+ * that window an edit exists ONLY in memory: the pill already says "Saving…", the SSE handler already
1414
+ * counts it as unsaved and correctly banners instead of reloading — but the Reload it then offers would
1415
+ * destroy the very edit the banner is protecting, because there is nothing in storage to park or offer
1416
+ * back. Null until main() runs, and called defensively, so an event arriving mid-boot cannot throw the
1417
+ * handler (an exception there means the tab goes deaf to external writes entirely).
1418
+ */
1419
+ let flushLocalDraft = null;
1325
1420
  // ── Own-write identity, replacing the 2.5 s SSE echo clock (unit 5, P1c-3) ──
1326
1421
  // Every PUT names itself; the server echoes that name in the contract-changed broadcast. A clock could not
1327
1422
  // tell "my echo" from "someone else's write inside the window", so a genuine external write landing in
@@ -1461,6 +1556,32 @@ function armEarlyViewToggle() {
1461
1556
  arm(t2, false); arm(t3, true);
1462
1557
  }
1463
1558
 
1559
+ /**
1560
+ * The `code` on an error response, or null when there isn't one to be had.
1561
+ *
1562
+ * GUARDED, because this reads a body that is not guaranteed to be ours. A 404 can come from a proxy,
1563
+ * a dev-server error page, or any body-less error response — `res.json()` rejects on every one of
1564
+ * those, and an unhandled rejection here would replace a styled empty state with a raw `boot().catch`
1565
+ * message. Any failure means "no code", which lands the caller on the generic copy that was correct
1566
+ * before this field existed.
1567
+ *
1568
+ * The FALLBACK is silent-by-design; the DIAGNOSIS is not. Returning null for an unparseable body and
1569
+ * returning null for our own ordinary "no contract yet" body are the same value and very different
1570
+ * events, and without a line here the first leaves no trace anywhere. So the unparseable case warns
1571
+ * and the ordinary one does not — `body.code` simply being absent is the normal `none` answer.
1572
+ */
1573
+ async function errorCodeOf(res) {
1574
+ try {
1575
+ const body = await res.json();
1576
+ return body && typeof body.code === 'string' ? body.code : null;
1577
+ } catch (_) {
1578
+ // Not JSON, empty, or already consumed. The generic state is the safe answer, but this is a
1579
+ // response that did not come from us at all — say so rather than letting it look ordinary.
1580
+ console.warn('errorCodeOf: ' + res.status + ' body was not readable JSON — falling back to the generic empty state');
1581
+ return null;
1582
+ }
1583
+ }
1584
+
1464
1585
  async function boot() {
1465
1586
  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; }
1466
1587
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
@@ -1468,7 +1589,39 @@ async function boot() {
1468
1589
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1469
1590
  if (!res.ok) {
1470
1591
  if (res.status === 404) {
1471
- showEmpty('⊞', 'No model for', 'Read a structural drawing first — ask your terminal AI to run the workflow, then open this editor again.', APP_ID);
1592
+ // TWO different 404s, and telling them apart is the whole point of this branch.
1593
+ //
1594
+ // Approving a migrated project publishes that project's model into the WORKFLOW's shared .flo, so
1595
+ // an app-keyed read then finds a document that is real but is not this workflow's own — the server
1596
+ // answers `project-publication` for it. Until that code existed both cases said "No model for …
1597
+ // read a structural drawing first", which for a migrated project is false twice over: the model
1598
+ // exists, and reading another drawing is not what gets the user to it.
1599
+ //
1600
+ // The CODE, never the sentence — the sentence is copy and copy gets edited.
1601
+ const code = await errorCodeOf(res);
1602
+ if (code === 'project-publication') {
1603
+ // NO `appIdText` HERE, and that is the fix for a real defect rather than a style choice.
1604
+ //
1605
+ // `showEmpty` BOLDS its 4th argument and appends it after the headline, so the sibling states
1606
+ // read "No model for **steel-model**" — true, because the id is the grammatical object of the
1607
+ // claim. This headline's only true claim is about the PROJECT, which we are barred from naming
1608
+ // (the baked bytes carry no owner marker — see contract-gateway.ts). Passing APP_ID here put a
1609
+ // bolded **steel-model** immediately after an em dash, where it reads as an appositive naming
1610
+ // the owning project — so the one screen that exists BECAUSE the old copy was untrue shipped a
1611
+ // headline that appeared to name the project and named the workflow instead.
1612
+ //
1613
+ // The workflow id is low-information here anyway: the user opened this editor from that very
1614
+ // workflow. The body says what is true about it in prose instead.
1615
+ showEmpty('⊞', 'This model belongs to a project',
1616
+ 'It was approved inside that project, and this workflow doesn’t hold its own copy of it. Open Workspaces and look for the project it came from to see the model there.',
1617
+ null);
1618
+ } else {
1619
+ // A code this build has never heard of falls here on purpose — inventing copy for it would be
1620
+ // worse than the generic state. But an UNRECOGNISED code and NO code are different events
1621
+ // landing on the same sentence, and only the second is ordinary, so name the first.
1622
+ if (code != null) console.warn('boot: unrecognised contract 404 code "' + code + '" — using the generic empty state');
1623
+ showEmpty('⊞', 'No model for', 'Read a structural drawing first — ask your terminal AI to run the workflow, then open this editor again.', APP_ID);
1624
+ }
1472
1625
  } else {
1473
1626
  showEmpty('⚠', 'Couldn’t load the contract', 'The server returned an error. Check that the FloLess server is running, then reopen the editor.');
1474
1627
  }
@@ -1591,8 +1744,40 @@ async function boot() {
1591
1744
  // bearing on its own merits and stays.)
1592
1745
  const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err')
1593
1746
  || sv.classList.contains('conflict'));
1594
- if (hasUnsaved) showAiUpdateBanner('The AI updated this model — reload to see it (you have unsaved edits).');
1595
- else location.reload();
1747
+ if (hasUnsaved) {
1748
+ // GET THE EDIT ONTO DISK FIRST. 'dirty' also covers the 500 ms debounce window, where
1749
+ // `persist()` has not run yet and the edit lives only in `C` — so the Reload this banner is
1750
+ // about to offer would discard it, with no draft to park and nothing to offer back. That is
1751
+ // the same loss the stale-draft flow exists to prevent, arriving 500 ms earlier.
1752
+ //
1753
+ // The LOCAL half only. The server write stays on its debounce: the store has just moved, so a
1754
+ // PUT fired from here would be refused anyway, and racing one against the write we are
1755
+ // reacting to buys nothing. `persist()` is idempotent and does not disarm the timer, so the
1756
+ // pending tick rewriting the same row a moment later changes nothing.
1757
+ // The RESULT matters: quota exceeded, private mode, storage disabled by policy — persist()
1758
+ // swallows each into a red pill, and offering "↻ Reload" over an edit that reached no storage
1759
+ // is offering the very loss this flush exists to prevent, with a button on it.
1760
+ const parked = flushLocalDraft ? flushLocalDraft() : false;
1761
+ if (!parked) console.warn('steel-editor: the pending edit could not be written to this browser — a reload would lose it');
1762
+ // WHAT happened, not a guess at who. Absent or unrecognised → today's wording byte for byte.
1763
+ // The contract PUT — the one writer that usually IS the terminal AI — deliberately sends no
1764
+ // reason, so the generic sentence stays correct for it; and a tab left open across an
1765
+ // auto-update can outlive its server, so a token from a NEWER build has to degrade quietly
1766
+ // rather than reach the bar.
1767
+ //
1768
+ // Read INSIDE this branch on purpose. Computed above the `if`, a `CHANGE_LEAD` that ever
1769
+ // became unreachable (P3 is actively refactoring `main()`'s closure) would throw here — and
1770
+ // an exception at this point means the tab neither banners NOR reloads, silently going deaf
1771
+ // to external writes with the error swallowed by the event loop. The reload path must not be
1772
+ // able to fail for a reason that only the banner path cares about.
1773
+ const lead = (typeof m.reason === 'string' && CHANGE_LEAD[m.reason]) || 'The AI updated this model';
1774
+ showAiUpdateBanner(parked
1775
+ ? lead + ' — reload to see it (you have unsaved edits).'
1776
+ // No Reload offered here, deliberately: with nothing in storage it is a button that destroys
1777
+ // their work, and there is no second copy to offer back afterwards.
1778
+ : lead + ' — but this browser could not save your unsaved edits, so reloading would lose them. Copy them out first.',
1779
+ parked ? undefined : { noReload: true });
1780
+ } else location.reload();
1596
1781
  };
1597
1782
  es.onerror = () => {
1598
1783
  // Transient drops (readyState CONNECTING) auto-reconnect — ignore. A CLOSED channel is
@@ -1613,6 +1798,76 @@ async function boot() {
1613
1798
  }
1614
1799
  }
1615
1800
 
1801
+ /**
1802
+ * What to CALL the change that arrived, keyed by the server's `reason` token (server/mutation-id.ts,
1803
+ * `ContractChangeReason`).
1804
+ *
1805
+ * THE TOKEN IS THE SERVER'S; THE SENTENCE IS OURS. Nothing from the frame is ever rendered — the frame
1806
+ * only SELECTS a row from this table — so no value arriving over the wire can become copy on screen.
1807
+ * That is also why the wire tokens can stay terse and internal while these stay plain English.
1808
+ *
1809
+ * Each string matches the vocabulary of the control the user actually operated, because closing the loop
1810
+ * between what they clicked and what this bar says is the whole job here: History's button reads
1811
+ * "↺ Rollback" (workspaces.js), the conversion's reads "Convert to the 3D model →", and the History pane
1812
+ * already describes a re-read as "The AI read a revised drawing set". Copy that drifts from the control
1813
+ * it describes sends the user looking for a second, non-existent event.
1814
+ *
1815
+ * The two READ tokens name an actor — `revision-read` and `pre-read`, the two phases of one attach —
1816
+ * and that asymmetry is deliberate rather than sloppy: a read genuinely IS AI-authored (`author: 'AI'`,
1817
+ * the History badge reads "AI read"), while a rollback and a conversion are the user's own doing, so
1818
+ * saying "the AI" there is the untruth this table exists to fix. None of them says "you", because this
1819
+ * frame does not carry WHO, and a sentence asserting the reader did it would be guessing at the one
1820
+ * fact the wire withheld.
1821
+ *
1822
+ * (This paragraph said "only `revision-read`" until `pre-read` joined it, which is the kind of sentence
1823
+ * that goes quietly false when a fourth token lands. `verify-change-reasons.mjs` pins that every token
1824
+ * HAS a sentence; nothing can pin that the prose about them still counts them correctly.)
1825
+ *
1826
+ * The staged confirm (`revision-routes.ts`, the second site) shares `revision-read` even though a human
1827
+ * picked which proposals to apply. Deliberate: the AI still authored the read, and the ledger records
1828
+ * both the same way (`author: 'AI'`, `kind: 'revision-read'`). That is unlike rollback, where blaming
1829
+ * the AI was flatly false rather than merely coarse. Split the token if the two ever want different
1830
+ * sentences — nothing here assumes they cannot.
1831
+ *
1832
+ * NULL PROTOTYPE, deliberately. A plain object literal answers `CHANGE_LEAD['constructor']` with a
1833
+ * FUNCTION, so a frame carrying `reason:"constructor"` would concatenate "function Object() { [native
1834
+ * code] }" into the banner. With no prototype there is nothing to inherit, and every unknown token —
1835
+ * malformed, hostile, or simply from a newer server — falls through to the generic sentence.
1836
+ */
1837
+ const CHANGE_LEAD = Object.assign(Object.create(null), {
1838
+ 'rollback': 'This model was rolled back',
1839
+ // A DELIBERATE VISIBLE PAIR with the row below it, two words apart, and they must be edited together.
1840
+ // These are phase one and phase two of a single user action (attach a revised set / re-read & re-bake):
1841
+ // the pre-read writes the filter and registration and STOPS for the user to review and Save, then the
1842
+ // committed read brings in the members. This bar is a single slot — `showAiUpdateBanner` removes any
1843
+ // existing `#aiUpdateBanner` before appending — so the second sentence REPLACES the first in the same
1844
+ // pixels. "started reading" → "read" therefore reads as progress; two differently-worded sentences
1845
+ // would read as a contradiction. `verify-change-reasons.mjs` pins that both tokens have sentences, but
1846
+ // nothing can check that they still rhyme, so: reword one, reword the other.
1847
+ //
1848
+ // It claims no CONTENT, on purpose. The pre-read writes a different set per schema version — on v2 a
1849
+ // `grid` or root `datum` write is refused by name — so a lead naming the grid would be false on a v2
1850
+ // model. "started reading" is true on both.
1851
+ //
1852
+ // AND IT DOES NOT SAY "REVISED", which is where it parts company with the row below. That row's
1853
+ // comment calls "a revised" a default and an initial read merely reachable "in principle"; for the
1854
+ // PRE-READ it is not in principle at all — `web/aware.js` has a first-class `isInitialRead` branch
1855
+ // that sends the AI through this same two-phase gate, and on a seeded project (which holds a contract
1856
+ // before it holds a v1) that initial pass writes through the verb. So the phase-one sentence would be
1857
+ // wrong on a documented path, not a rare one. Two words apart from phase two instead of one; still
1858
+ // "started reading" → "read", which is what carries the progress.
1859
+ 'pre-read': 'The AI started reading a drawing set into this model',
1860
+ // "a revised" is a DEFAULT, not a proof. An initial read can reach this in principle — "initial" is
1861
+ // decided by the version ledger, not by the contract, and a seeded project has a contract before it
1862
+ // has a v1 (`workspaces.js` renders exactly that empty state). It is rare, and the frame carries no
1863
+ // base version to tell the two apart, so the common case wins. `workspaces.js` distinguishes them
1864
+ // ("the initial" vs "a revised") only because it has the ledger to hand; here we do not.
1865
+ //
1866
+ // The row above inherits this trade rather than re-deciding it: same phrase, one decision.
1867
+ 'revision-read': 'The AI read a revised drawing set into this model',
1868
+ 'migration': 'This project was converted to the 3D model',
1869
+ });
1870
+
1616
1871
  /**
1617
1872
  * The bottom bar for "this model changed underneath you".
1618
1873
  *
@@ -1628,6 +1883,12 @@ function showAiUpdateBanner(message, opts) {
1628
1883
 
1629
1884
  const bar = document.createElement('div');
1630
1885
  bar.id = 'aiUpdateBanner';
1886
+ // A POLITE live region, matching #gZwarn's role=status rather than inventing a pattern. This bar appears
1887
+ // without the user doing anything and is the only notice that the model moved underneath them, so a
1888
+ // sighted user sees it and a screen-reader user previously got nothing at all. Deliberately `status`,
1889
+ // not `alert`: it is non-blocking, it can land mid-drag, and interrupting for it would be wrong.
1890
+ // Focus is NOT moved here for the same reason — see confirmDanger for the case where that IS right.
1891
+ bar.setAttribute('role', 'status');
1631
1892
  // Which cause raised this bar. Only the stale-draft caller sets it, so that one can be auto-dismissed
1632
1893
  // when it stops being true (see edit()) without touching the AI-update and conflict banners, which must
1633
1894
  // survive edits — persisting through them is the whole point of the conflict banner.
@@ -1643,25 +1904,45 @@ function showAiUpdateBanner(message, opts) {
1643
1904
 
1644
1905
  const msg = document.createElement('span');
1645
1906
  msg.style.cssText = 'flex:1';
1646
- msg.textContent = message || 'The AI updated this model — reload to see the latest version.';
1907
+ // The fallback is deliberately CAUSE-FREE. All five callers pass a message, so this is unreachable
1908
+ // today — but it was the last place in the file still asserting "the AI" about a change nobody has
1909
+ // established the AI made, which is the claim this bar stopped making. A caller that forgets its
1910
+ // message should say nothing it cannot support.
1911
+ //
1912
+ // The text is written AFTER the bar is in the document (see the end of this function), not here.
1913
+ // A live region that is inserted ALREADY POPULATED is announced inconsistently across screen
1914
+ // readers — the announcement hangs off a mutation INSIDE an existing region — so setting it up
1915
+ // front made role=status decorative. Review caught that; `sentence` carries it to the append.
1916
+ const sentence = message || 'This model changed — reload to see the latest version.';
1647
1917
 
1648
- const reloadBtn = document.createElement('button');
1649
- reloadBtn.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
1650
- // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1651
- // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1652
- // would have named an action it does not perform.
1653
- reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1654
- if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1655
- reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1918
+ // `noReload` — the one caller that must NOT offer it: an unsaved edit that reached no storage.
1919
+ // Suppressing the button beats disabling it; a dead control invites a hunt for why.
1920
+ const reloadBtn = (opts && opts.noReload) ? null : document.createElement('button');
1921
+ if (reloadBtn) {
1922
+ reloadBtn.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
1923
+ // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1924
+ // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1925
+ // would have named an action it does not perform.
1926
+ reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1927
+ if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1928
+ reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1929
+ }
1656
1930
 
1657
1931
  const dismissBtn = document.createElement('button');
1658
1932
  dismissBtn.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
1659
1933
  dismissBtn.textContent = '✕';
1660
1934
  dismissBtn.dataset.tip = 'Dismiss';
1935
+ // The glyph is the button's only content, and data-tip is hover-driven — it reaches neither a keyboard
1936
+ // nor a screen-reader user (the same argument this file makes for aria-describedby on the disabled grid
1937
+ // controls). An earlier version of this comment claimed every other icon-only control here already has
1938
+ // one — review measured that as false (several panel ✕ buttons lack it). It is still the right thing to
1939
+ // add HERE, because this bar appears unbidden and is the only notice that the model moved; the others
1940
+ // are a separate sweep, not a claim to make in passing.
1941
+ dismissBtn.setAttribute('aria-label', 'Dismiss');
1661
1942
  dismissBtn.onclick = () => bar.remove();
1662
1943
 
1663
1944
  bar.appendChild(msg);
1664
- bar.appendChild(reloadBtn);
1945
+ if (reloadBtn) bar.appendChild(reloadBtn);
1665
1946
  if (opts && opts.onOverwrite) {
1666
1947
  // Visually subordinate to Reload — it is the destructive option, and it still has to pass a confirm.
1667
1948
  const over = document.createElement('button');
@@ -1673,6 +1954,10 @@ function showAiUpdateBanner(message, opts) {
1673
1954
  }
1674
1955
  bar.appendChild(dismissBtn);
1675
1956
  document.body.appendChild(bar);
1957
+ // NOW fill the live region, with the bar already in the document — that mutation is what a screen
1958
+ // reader announces. Synchronous, so nothing can see an empty bar paint: the browser has not yielded
1959
+ // between the append and this line, and every DOM probe in the tests reads the sentence as before.
1960
+ msg.textContent = sentence;
1676
1961
  }
1677
1962
 
1678
1963
  function main() {
@@ -1984,7 +2269,14 @@ function snapshot(){return JSON.stringify(Object.assign(MODEL_RO?{modelGrid:C.gr
1984
2269
  function snapshotLike(){return snapshot();}
1985
2270
  function refreshDims3d(){if(window.Steel3DView&&window.Steel3DView.refreshDims)window.Steel3DView.refreshDims();} // repaint the 3D dim lines/labels from C.dims3d
1986
2271
  function refreshOverlayDims3d(){if(window.Steel3DView&&window.Steel3DView.refreshOverlayDims)window.Steel3DView.refreshOverlayDims();} // re-derive the legend DIMENSIONS overlays from C.dim_overlays
1987
- function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();}
2272
+ // updUR() here, at the one place that GROWS the undo stack, because not every pusher ends in a render().
2273
+ // The 3D clip / work-area manipulations are the live example: beginClipEdit is literally
2274
+ // `()=>pushUndo(snapshot())`, and the callbacks that follow it (onClipsChange, onWorkAreaChange) rebuild
2275
+ // the legend and the work-area button, never the header — so the entry existed while Undo still looked
2276
+ // dead until some later, unrelated repaint happened to fix it. That was already true on v1; it became
2277
+ // visible on v2 once the read-only branch started syncing these buttons at all, since render() is then
2278
+ // the ONLY other caller. Syncing at the writer covers both formats and every future pusher.
2279
+ function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();updUR();}
1988
2280
  function apply(json){
1989
2281
  // The undo stack's restore is the third write primitive (unit 5, P7d). Nothing pushes onto that stack while
1990
2282
  // the document is read-only — edit() refuses before pushUndo — so this is unreachable rather than merely
@@ -2121,9 +2413,18 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
2121
2413
  // AI revision changes members, not segments) compared EQUAL, and restoreSaved silently overlaid a stale
2122
2414
  // draft on top of it, masking the other write. See restampDraftBase() for why reading the CURRENT
2123
2415
  // serverEtag here is right, and why it must be re-stamped when a write lands.
2416
+ // `grid` — the ROOT one, which is v2's (v1's grid is per-plan and rides in `plans` below). P7d made it writable on a
2417
+ // read-only document (editGrid), and leaving it out meant a v2 grid edit was never stored at all. NOT
2418
+ // "the only field a v2 document can have unsaved edits in", which is what this said first and what review
2419
+ // disproved: `dim_overlays`, `target_confidence` and `profile_colors` are ungated too (see
2420
+ // RO_DRAFT_KEYS). The narrower true statement is that the grid was the only such field persist() was not
2421
+ // ALREADY storing — and a reload
2422
+ // after an external write discarded it with no offer and no warning. See applyDraftReadOnlyFields for
2423
+ // restore half. Undefined on v1, where JSON.stringify simply drops it.
2124
2424
  function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
2425
+ grid:C.grid,
2125
2426
  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,
2126
- plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,callouts:p.callouts,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));}catch(e){setSaved('err');console.error('local autosave failed',e);}}
2427
+ plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,callouts:p.callouts,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));return true;}catch(e){setSaved('err');console.error('local autosave failed',e);return false;}}
2127
2428
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
2128
2429
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
2129
2430
  // fetch does NOT reject on HTTP 400 (schema rejection), so treat !res.ok as 'err' (not a false 'Saved ✓'). ---
@@ -2294,6 +2595,18 @@ async function persistServer(force){const seq=saveSeq;
2294
2595
  }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}
2295
2596
  });}
2296
2597
  function scheduleSave(){setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{saveT=null;persist();persistServer();},500);} // clear the handle as it fires: `saveT !== null` is read as "a write is still pending" (the project send refuses on it), and a spent timer id would read as pending forever // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
2598
+ // The boot-scope SSE handler's seam into that debounce — see `flushLocalDraft` for why the handler
2599
+ // cannot reach `persist()` itself.
2600
+ //
2601
+ // UNCONDITIONAL, and the first cut of this was not. It guarded on `saveT !== null` ("only write when a
2602
+ // save is actually pending"), described as hygiene — and Codex's review found the state that makes that
2603
+ // guard the bug rather than the tidiness: `flushContract()` CANCELS the debounce (`saveT = null`)
2604
+ // without persisting first, and on a refused flush leaves the pill 'err'/'conflict'. So a grid edit
2605
+ // followed inside 500 ms by Ask AI Send, the History revert or the shell's Approve reaches this handler
2606
+ // with the pill unsaved, no timer pending, and nothing on disk — precisely the case the flush exists
2607
+ // for, skipped. There is no state where writing is wrong: `persist()` records `C` as it stands against
2608
+ // the tag this tab believes it is editing, which is what a reload needs to park and offer back.
2609
+ flushLocalDraft = () => persist(); // the RESULT is load-bearing at the call site — a block body returns undefined, i.e. "it failed", and the banner would drop its Reload on every event
2297
2610
  // Flush: cancel the pending debounce and PUT the current in-memory contract to the
2298
2611
  // server right now. The parent (aware.js #contract-editor-approve) awaits this before
2299
2612
  // POSTing approve, so Approve always bakes the latest edits — not a stale debounce
@@ -2350,15 +2663,27 @@ window.flushContract = async () => {
2350
2663
  * Extracted from restoreSaved() (unit 5, P1c-3) so the AUTOMATIC restore and the user-initiated "View my
2351
2664
  * edits instead" apply exactly the same fields. Two copies of this list would drift, and the failure would
2352
2665
  * be silent: a field the button forgot would simply not come back, looking like it was never saved.
2666
+ *
2667
+ * RETURNS whether anything was applied, so the save pill cannot say "Restored ✓" over a document with no
2668
+ * restored edits in it. Be exact about how much that does today: the automatic caller has already passed
2669
+ * `draftFits`, which on a read-only document IS `v2DraftFits`, so the refusal arm is unreachable from
2670
+ * there. It IS reachable from showStaleDraftBanner's handler, where the user can move the document to
2671
+ * match the draft while the bar is up (the three model-global writers are ungated) — and beyond that it
2672
+ * is defence-in-depth against a future caller that skips the gate.
2353
2673
  */
2354
2674
  function applyDraftFields(d){
2355
- // The draft is V1-SHAPED, and overlaying it onto a read-only v2 document is one of the three leaks §8.4
2356
- // names: the per-plan pass below writes `members`, `default_tos` and `grid`, all three of which v2's
2357
- // plan schema forbids. Refused at the primitive rather than at each caller, so the automatic restore and
2358
- // the "View my edits instead" button are covered by one guard. (When the model grid becomes writable it
2359
- // needs a v2-shaped draft of its own — a ROOT `grid`, not a per-plan one; there is nothing to restore
2360
- // until then, because every write is refused.)
2361
- if(!canWriteModel()){console.warn('steel-editor: a local draft was not applied — this document is open read-only');return;}
2675
+ // The per-plan pass below is V1-SHAPED, and overlaying it onto a read-only v2 document is one of the
2676
+ // three leaks §8.4 names: it writes `members`, `default_tos` and `grid`, all three of which v2's plan
2677
+ // schema forbids. Refused at the primitive rather than at each caller, so the automatic restore and the
2678
+ // "View my edits instead" button are covered by one guard.
2679
+ //
2680
+ // CORRECTING WHAT THIS USED TO SAY. It read "there is nothing to restore until then, because every write
2681
+ // is refused" — true when P7d was written, false the moment P7d shipped: that same unit made the MODEL
2682
+ // grid writable on a v2 document (`editGrid` / `GRID_EDIT`, the one exemption `edit()`'s gate carries).
2683
+ // So a v2 document CAN hold an unsaved edit, and it is exactly the one this refusal covered — which made
2684
+ // the sentence not merely stale but load-bearing in the wrong direction. The v2-shaped draft it predicted
2685
+ // is now real (a ROOT `grid`, see persist), and this is where it lands.
2686
+ if(!canWriteModel())return applyDraftReadOnlyFields(d);
2362
2687
  const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p);
2363
2688
  if(d.custom_details)C.custom_details=d.custom_details;
2364
2689
  if(d.profile_colors)C.profile_colors=d.profile_colors;
@@ -2377,7 +2702,179 @@ function applyDraftFields(d){
2377
2702
  if('prop_labels' in d)C.prop_labels=sanitizePropLabels(d.prop_labels); // restore canvas property-label display state (sanitised to known keys/placement)
2378
2703
  if(Array.isArray(d.joints))C.joints=d.joints; // restore model-global connection joints (base plates) from the local draft
2379
2704
  if(Array.isArray(d.views))C.views=sanitizeViews(d.views); // restore the unlimited saved-view library from the local draft; malformed generated provenance is dropped
2380
- if(d.active!=null)C.active=d.active;}
2705
+ if(d.active!=null)C.active=d.active;
2706
+ return true;}
2707
+ /**
2708
+ * Does a draft's grid describe the SAME grid lines as the document now holds?
2709
+ *
2710
+ * The v2 counterpart of dataSig(), and needed for the same reason: `labels_z` is positional against the
2711
+ * authored Z entries and `hidden_z` names elevations, so overlaying either onto a re-spaced grid relabels
2712
+ * or re-hides the wrong levels. Axes are compared as a NORMALISED PROJECTION rather than by stringifying
2713
+ * the objects: `JSON.stringify` is key-order sensitive, so a producer emitting `{dir,id,label}` instead of
2714
+ * `{id,dir,label}` would make an unchanged grid read as re-spaced and refuse the draft with a warning
2715
+ * that names the wrong cause (review).
2716
+ */
2717
+ function gridTopoSig(g){return (g&&typeof g==='object'&&!Array.isArray(g))?JSON.stringify({x:g.x||'',y:g.y||'',z:g.z||'',axes:(Array.isArray(g.axes)?g.axes:[]).map(a=>[(a&&a.id)||'',(a&&a.dir)||'',(a&&a.label)||''])}):'';}
2718
+ /**
2719
+ * WILL the draft's grid land? Topology must match (gridTopoSig), and there must be something to land.
2720
+ *
2721
+ * The second half is not pedantry — though the reason an earlier draft of this comment gave was wrong.
2722
+ * It claimed `boot()` writes a grid into every document; it does not (v2 declares `grid` nullable, and
2723
+ * boot defaults nine other keys but never this one). The real reason survives the correction: a draft is
2724
+ * a snapshot of `C`, so a document that HAS a grid produces a draft with a grid whether or not the user
2725
+ * touched it. "It has a grid" is not "the user changed one". Callers that need "is this worth offering" must ask this, not `d.grid`.
2726
+ */
2727
+ function v2GridFits(d){
2728
+ const dg=d&&d.grid,live=C&&C.grid;
2729
+ if(!dg||typeof dg!=='object'||Array.isArray(dg)||!live)return false;
2730
+ return gridTopoSig(dg)===gridTopoSig(live)&&JSON.stringify(dg)!==JSON.stringify(live);
2731
+ }
2732
+ /**
2733
+ * Is there anything in this draft that a READ-ONLY document can put back?
2734
+ *
2735
+ * Asked before the draft is offered, not only when it is applied: `showStaleDraftBanner` promises the
2736
+ * user their edits are still here and can be switched to, and offering a draft the overlay would then
2737
+ * refuse turns that promise into a button that does nothing.
2738
+ *
2739
+ * TWO WAYS TO QUALIFY — a grid that will land, or a model-global key whose value DIFFERS from the
2740
+ * document's. Both halves have now been wrong once, in opposite directions, and both errors produced
2741
+ * the same symptom:
2742
+ * - grid only: a draft whose one edit was a confidence target was dropped with no offer;
2743
+ * - `k in d`: `boot()` defaults `profile_colors` and `dim_overlays` onto EVERY contract before
2744
+ * `persist()` ever runs, so key presence is universally true. That made this function a constant
2745
+ * `true`, retired the topology gate entirely, and offered a re-spaced draft back under a promise
2746
+ * about a grid that the overlay would then silently skip. Both reviewers reproduced it.
2747
+ * So the test is a DELTA against the live document, which is the only thing "worth offering" can mean.
2748
+ */
2749
+ function v2DraftFits(d){
2750
+ if(!d||typeof d!=='object')return false;
2751
+ if(v2GridFits(d))return true;
2752
+ // JSON compare: both sides descend from the same object graph (C → persist → JSON.parse), so key
2753
+ // order matches whenever the values do. A false "differs" would only cost a no-op offer; a false
2754
+ // "same" would drop the user's edit, so the comparison errs in the safe direction by construction.
2755
+ return RO_DRAFT_KEYS.some(k=>k in d&&JSON.stringify(d[k])!==JSON.stringify(C&&C[k]));
2756
+ }
2757
+ /**
2758
+ * The MODEL-GLOBAL keys a read-only v2 document can still hold unsaved edits in, besides the grid.
2759
+ *
2760
+ * NOT a design statement — an OBSERVATION, and review is what turned it up. `edit()` refuses every
2761
+ * model write on a read-only document, but these three writers never went through `edit()`: the 3D
2762
+ * legend's dimension-overlay swatches (`C.dim_overlays[cat] = …`), the confidence target
2763
+ * (`C.target_confidence = …`) and the palette (`C.profile_colors`). Each ends in `scheduleSave()`,
2764
+ * each key is legal at a v2 root, so each reaches the server today and each lands in the draft.
2765
+ *
2766
+ * Which means they had exactly the same data-loss path this change exists to close, and an earlier cut
2767
+ * of it made them WORSE: the pill said "Grid restored ✓" and the bar promised "your grid changes" over
2768
+ * a draft whose real content was a confidence target that nothing put back. Restoring them is the
2769
+ * conservative reading — the edit already persists to the server, so bringing it back from the draft is
2770
+ * consistency, not new behaviour.
2771
+ *
2772
+ * Whether those three SHOULD be writable on a read-only document is a separate question (a P7d gate
2773
+ * gap) and deliberately not answered here — answering it by dropping the user's edit would be the
2774
+ * wrong way round.
2775
+ */
2776
+ const RO_DRAFT_KEYS=['dim_overlays','target_confidence','profile_colors'];
2777
+ /**
2778
+ * Overlay the parts of a stored draft that a READ-ONLY (v2) document can take back.
2779
+ *
2780
+ * THE GRID, plus RO_DRAFT_KEYS above. The grid's half is the one renderGridPanel leaves enabled: the
2781
+ * visibility switch, the typed origin, the X/Y label overrides, the per-level labels, which levels show,
2782
+ * and the extension. Its complement — the spacings, the levels and the axis ids they mint — belongs to
2783
+ * editGridTopology and is refused for the human as well as the AI, so a restore keeps the DOCUMENT's
2784
+ * topology: no draft, however old or hand-edited, can rebind an axis id or re-space a grid that
2785
+ * dimensions and generated views are anchored to. Keys outside both sets (`axes`, `ends`, `lines`) stay
2786
+ * the document's, which is also what keeps the result schema-valid — v2's `modelGrid` is
2787
+ * `additionalProperties:false`, so a stray key would mean "Save failed" for edits the user never made.
2788
+ * The prose above names those seven, and the single `patchGrid` literal below is what executes — read the
2789
+ * literal as the authority if the two ever disagree. (`x`, `y`, `z` and `axes` are the topology half and
2790
+ * stay the document's; `ends` and `lines` sit outside both sets and stay the document's too.)
2791
+ *
2792
+ * SANITISED FIELD BY FIELD, because localStorage is unvalidated input (the same treatment `member_styles`,
2793
+ * `dims3d`, `views` and `connections` get on the v1 arm) and because this document is bound for a
2794
+ * schema-checked PUT. The draft is AUTHORITATIVE for those keys: one it does not carry comes out as
2795
+ * `undefined`, which `patchGrid` DELETES rather than leaving standing — so "I unhid every level" restores
2796
+ * as an absent `hidden_z` instead of silently keeping the levels hidden.
2797
+ *
2798
+ * TWO EXCEPTIONS, for one reason: `origin` and `ext` are POSITIONS, not flags, so dropping them does not
2799
+ * reset something — it moves or resizes the drawn grid. A missing or unusable value there falls back to
2800
+ * the document's, never to a guess (a [0,0] origin fallback would relocate the whole grid, silently, on a
2801
+ * document bound for an IFC/Tekla bake). `Number.isFinite`, NOT the global `isFinite`, because the global
2802
+ * COERCES: `isFinite(null)` and `isFinite('')` are both true, so `origin:[null,null]` used to sail through
2803
+ * this guard and land as `[0,0]` — the exact outcome the paragraph above says cannot happen (review).
2804
+ *
2805
+ * THROUGH `ModelCmd.patchGrid`, and not by assigning `C.grid` — which the model-boundary guard
2806
+ * (`server/build/verify-model-boundary.mjs`) tracks and refuses. (The undo `apply` path does assign it
2807
+ * directly; that is an explicit, named entry in the guard's allowlist, not a precedent to follow.) The
2808
+ * guard was right to refuse the first cut of this: a restore is a model edit like any other, and
2809
+ * routing it means the ONE place that mutates a grid stays the one place. It also lands the edit in the
2810
+ * live object rather than swapping in a new one, so nothing holding a reference to `C.grid` goes stale.
2811
+ */
2812
+ function applyDraftReadOnlyFields(d){
2813
+ if(!v2DraftFits(d)){
2814
+ // NAMED PRECISELY, because review found this line claiming a re-space for any refused draft that
2815
+ // merely had a grid on both sides — including one with nothing to restore at all, where no re-space
2816
+ // happened. A grid that DIFFERS but does not fit is the re-space; a grid that matches is a draft
2817
+ // with nothing in it.
2818
+ const dg0=d&&d.grid,live0=C&&C.grid;
2819
+ if(dg0&&live0&&JSON.stringify(dg0)!==JSON.stringify(live0))
2820
+ console.warn('steel-editor: a stored grid edit was not applied — the grid was re-spaced elsewhere since those edits were made');
2821
+ else console.warn('steel-editor: a stored draft held nothing this read-only document could put back');
2822
+ return false;}
2823
+ const num=v=>typeof v==='number'&&Number.isFinite(v);
2824
+ const dg=d.grid,live=C&&C.grid,gc=GC();
2825
+ // THE MIXED CASE, and it is the one review called the remaining silent loss: this draft qualified on
2826
+ // one of the model-global keys, so the refusal above did not fire, and the grid is about to be skipped
2827
+ // because it no longer fits. Saying nothing here means a toast that claims the user's edits are on
2828
+ // screen over a grid edit that is not — and the next `persist()` then overwrites the stored grid with
2829
+ // the document's, so the copy goes too. Both channels: the console for the triage, the toast for the
2830
+ // person who lost the work.
2831
+ if(dg&&live&&!v2GridFits(d)&&JSON.stringify(dg)!==JSON.stringify(live)){
2832
+ console.warn('steel-editor: a stored grid edit was not applied — the grid was re-spaced elsewhere since those edits were made');
2833
+ toast('Your earlier grid changes could not be put back — the grid was re-spaced since you made them.');}
2834
+ // The SAME predicate the offer was made on — two spellings of "will the grid land" is exactly how the
2835
+ // banner came to promise a grid the overlay then skipped.
2836
+ if(v2GridFits(d)){
2837
+ const o=dg.origin,originV=(Array.isArray(o)&&o.length>=2&&num(o[0])&&num(o[1]))?[o[0],o[1]]:(Array.isArray(live.origin)?live.origin:undefined);
2838
+ const extV=(num(dg.ext)&&dg.ext>=0)?dg.ext:(num(live.ext)?live.ext:undefined);
2839
+ const zLabels=('labels_z' in dg)?(Array.isArray(dg.labels_z)?dg.labels_z.map(gridLabelText):[]):undefined; // gridLabelText clamps to the schema's 40 chars, exactly as sanitizeGridLines does for v1
2840
+ let hiddenV;
2841
+ if('hidden_z' in dg){
2842
+ const parsed=(gc&&gc.parseLevels)?gc.parseLevels(live.z,zLabels||live.labels_z):null; // against the DOCUMENT's levels (topology is the document's), with the draft's labels — the pair the panel itself renders
2843
+ const hidden=(gc&&gc.normalizeHiddenLevels&&parsed&&!parsed.err)?gc.normalizeHiddenLevels(dg.hidden_z,parsed.levels)
2844
+ :[...new Set((Array.isArray(dg.hidden_z)?dg.hidden_z:[]).filter(num))].sort((a,b)=>a-b);
2845
+ hiddenV=hidden.length?hidden:undefined;}
2846
+ ModelCmd.patchGrid(live,{
2847
+ on:('on' in dg)?!!dg.on:undefined,
2848
+ origin:originV,
2849
+ labels_x:('labels_x' in dg)?String(dg.labels_x==null?'':dg.labels_x):undefined,
2850
+ labels_y:('labels_y' in dg)?String(dg.labels_y==null?'':dg.labels_y):undefined,
2851
+ labels_z:zLabels,
2852
+ hidden_z:hiddenV,
2853
+ ext:extV,
2854
+ });
2855
+ // Mirror the undo path (`apply`, the `modelGrid` branch): the 3D grid is rebuilt from C.grid rather
2856
+ // than re-read on render, and the header toggle's on/off state comes from the same object.
2857
+ refresh3DGrid();updGridToggle();
2858
+ }
2859
+ // The ungated model-global three. `dim_overlays` is sanitised exactly as the v1 arm sanitises it — one
2860
+ // treatment, not two that can drift. The other two are deliberately STRICTER than v1, which takes any
2861
+ // non-null value and any object; see the clamp note below for why a read-only document cannot afford
2862
+ // that laxity.
2863
+ if(d.dim_overlays&&typeof d.dim_overlays==='object'&&!Array.isArray(d.dim_overlays)){const o=d.dim_overlays;C.dim_overlays={bolt_pitch:o.bolt_pitch!==false,edge_clearance:o.edge_clearance!==false,cope_size:o.cope_size!==false,base_plate:o.base_plate!==false,anchor_depth:o.anchor_depth!==false};}
2864
+ // CLAMPED to what v2 declares, not merely type-checked. Review reproduced both escapes from a
2865
+ // hand-edited row: `target_confidence: 999` (the schema caps it at 100) and a `profile_colors` value
2866
+ // that is not a string (the schema's additionalProperties is `{type:'string'}`) each produced a
2867
+ // document the server refuses — "Save failed" on edits the user never made, from a restore.
2868
+ if(num(d.target_confidence))C.target_confidence=Math.max(0,Math.min(100,d.target_confidence));
2869
+ if(d.profile_colors&&typeof d.profile_colors==='object'&&!Array.isArray(d.profile_colors)){
2870
+ const out={};for(const [k,v] of Object.entries(d.profile_colors))if(typeof v==='string')out[k]=v;
2871
+ C.profile_colors=out;}
2872
+ // TRUE means "the draft is the live document again", which is what the caller needs to know — not
2873
+ // "every byte of it landed". Those differ reachably: a grid delta confined to `lines` or `ends` passes
2874
+ // v2GridFits and is then skipped by the patch literal, which takes neither. The v1 arm above answers
2875
+ // the same question the same way. (A draft IDENTICAL to the document cannot reach here at all —
2876
+ // v2DraftFits requires a delta — so it is not the example to reason from.)
2877
+ return true;}
2381
2878
  /**
2382
2879
  * The bar for "your unsaved edits are older than what the server now holds".
2383
2880
  *
@@ -2388,14 +2885,35 @@ function applyDraftFields(d){
2388
2885
  *
2389
2886
  * One click, no confirm: nothing server-side changes when they look. What DOES need care is what happens
2390
2887
  * on the next autosave — see the handler.
2888
+ *
2889
+ * ONE SENTENCE FOR BOTH MODES, and an earlier cut of this had two. The read-only variant said "This
2890
+ * model's GRID has changed … you're viewing the current grid", on the reasoning that a v2 draft can only
2891
+ * hold a grid edit. Review killed it, correctly, on two counts. The trigger is a base-etag mismatch —
2892
+ * ANY external write, most often members or a rollback. Where the draft qualified on its GRID, the gate
2893
+ * has just established that the grid's topology is IDENTICAL, so the sentence asserted the one thing
2894
+ * ruled out immediately above it; where it qualified on a RO_DRAFT_KEYS delta instead, the grid may well
2895
+ * have moved, but then it is not what is coming back. Either way the first half cannot name a cause, and
2896
+ * it sent the user hunting for a grid change that did not happen. The premise was wrong besides:
2897
+ * RO_DRAFT_KEYS are not the grid. What the offer can honestly narrow is the second half — what is being
2898
+ * offered BACK — so only that half names the grid, and only when a grid is what came back.
2391
2899
  */
2392
2900
  function showStaleDraftBanner(d){
2393
- 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.',{
2901
+ // v2GridFits, NOT `d.grid`: every v2 draft HAS a grid (boot writes one), and a draft whose grid no
2902
+ // longer fits is still offerable for its other keys — so keying on presence promised grid changes
2903
+ // the overlay would then skip. Both reviewers reproduced exactly that.
2904
+ const mine=(!canWriteModel()&&v2GridFits(d))?'Your grid changes':'Your edits';
2905
+ showAiUpdateBanner('This model has changed since you last edited it here — you’re viewing the current version. '+mine+' from before are still saved on this computer.',{
2394
2906
  kind:'staleBase',
2395
2907
  reloadLabel:'View my edits instead',
2396
2908
  reloadTip:'Switch to the changes you made before. The version on the server won’t change unless you edit and save again.',
2397
2909
  onReload:()=>{
2398
- applyDraftFields(d);
2910
+ // The RETURN VALUE, which this caller used to drop on the floor. The three model-global writers are
2911
+ // ungated, so the user can move the document to match the draft while the bar is still up — and
2912
+ // rewinding `serverEtag` then arms a 412 for a restore that put nothing back.
2913
+ if(!applyDraftFields(d)){
2914
+ toast('Those earlier edits no longer apply to this model — nothing was changed.');
2915
+ const b0=document.getElementById('aiUpdateBanner'); if(b0)b0.remove();
2916
+ return;}
2399
2917
  // REWIND the tag to the one those edits were built on. Without this the next autosave would carry
2400
2918
  // the CURRENT server tag, satisfy the precondition, and silently replace the newer version with
2401
2919
  // these older edits — no 412, no banner, no warning. With it, the next save is correctly refused
@@ -2438,8 +2956,11 @@ function restoreSaved(){
2438
2956
  // The SAME structural gate the live row gets, which review found this path had skipped.
2439
2957
  // applyDraftFields overlays per SHEET, so offering a draft built against a different dataset
2440
2958
  // would let the user apply edits that cannot fit — the very masking the live gate prevents,
2441
- // reachable through the parked copy instead.
2442
- if(od&&typeof od==='object'&&od.sig===dataSig())showStaleDraftBanner(od);
2959
+ // reachable through the parked copy instead. (On a read-only v2 document `draftFits` asks the
2960
+ // v2 question as well — is there anything in here such a document can take back, and does a
2961
+ // grid in it still fit this grid — since dataSig alone would wave through a row with nothing
2962
+ // offerable in it.)
2963
+ if(draftFits(od))showStaleDraftBanner(od);
2443
2964
  // Deliberately NOT deleted when it does not fit. dataSig() is derived from the server document,
2444
2965
  // and a rollback can restore the dataset these edits were built against — at which point they
2445
2966
  // become offerable again. An unofferable row is one small row per store; discarding the user's
@@ -2454,14 +2975,42 @@ function restoreSaved(){
2454
2975
  }
2455
2976
  return applied;
2456
2977
  }
2978
+ /**
2979
+ * Can this draft be put back onto the document as it now stands?
2980
+ *
2981
+ * v1: the overlay is per-SHEET, so it is meaningless if the sheets moved — dataSig() is that check.
2982
+ *
2983
+ * v2: dataSig() still has to hold, but it is no longer sufficient, and on its own it is barely relevant —
2984
+ * what a read-only document's draft can carry (the MODEL grid, and the ungated keys in RO_DRAFT_KEYS) is
2985
+ * model-global, and dataSig knows only sheet names and segment counts. So the v2 arm asks `v2DraftFits`:
2986
+ * is there a grid edit that will actually land, or a model-global value that differs? Asked in ONE place
2987
+ * because both the live row and the parked offer must answer it identically — the parked path having
2988
+ * skipped the live path's gate is a bug review already found here once.
2989
+ *
2990
+ * KNOWN SHARP EDGE, logged rather than silently widened (see restoreSavedInner): dataSig is per-SHEET,
2991
+ * so an AI read that adds or drops a sheet refuses a model-global draft that would have applied.
2992
+ */
2993
+ function draftFits(d){return !!(d&&typeof d==='object'&&d.sig===dataSig()&&(canWriteModel()||v2DraftFits(d)));}
2457
2994
  function restoreSavedInner(){
2458
- // Nothing to restore onto a read-only document, and applyDraftFields would refuse anyway — but returning
2459
- // early keeps the SAVE PILL honest. Falling through would reach `return true` having applied nothing, and
2460
- // the pill would say "Restored ✓" over a document with no restored edits in it.
2461
- if(!canWriteModel())return false;
2995
+ // A read-only v2 document is NOT excluded here any more. It was, on the reasoning that "every write is
2996
+ // refused so there is nothing to restore" — which stopped being true when P7d made the model grid
2997
+ // writable in this very mode, and the exclusion then guaranteed the loss it was written to prevent:
2998
+ // the one edit a v2 document can hold was the one edit that could never come back. draftFits() below
2999
+ // asks the v2 question instead of refusing the whole format, and applyDraftFields' return value keeps
3000
+ // the SAVE PILL honest — a refused draft must not leave it saying "Restored ✓" over a document with no
3001
+ // restored edits in it, which is what the early return was really protecting.
2462
3002
  try{const raw=localStorage.getItem(LSKEY);if(!raw)return false;const d=JSON.parse(raw);
2463
- // Structural first: the overlay below is per-sheet, so it is meaningless if the sheets moved.
2464
- if(d.sig!==dataSig())return false;
3003
+ // Structural first: the overlay is per-sheet on v1 and per-grid-topology on v2, so it is meaningless if
3004
+ // either moved.
3005
+ if(!draftFits(d)){
3006
+ // NOT SILENT any more (review). Two different refusals reach here and a triage needs to tell them
3007
+ // apart — and the second is a known sharp edge: `dataSig()` is per-SHEET, while a v2 draft's grid is
3008
+ // model-global, so an AI read that adds or drops a sheet refuses a grid draft that would have
3009
+ // applied perfectly. Logged rather than quietly widened: relaxing the gate for v2 changes what "the
3010
+ // same drawing set" means, which is not this fix's call to make.
3011
+ if(d&&d.sig!==dataSig())console.warn('steel-editor: stored edits were not restored — the drawing set changed (sheets added or removed) since they were made');
3012
+ else console.warn('steel-editor: stored edits were not restored — nothing in them fits this document as it now stands');
3013
+ return false;}
2465
3014
  // Then the real base check. `serverEtag` is the tag boot() just read — main() is called synchronously
2466
3015
  // from boot() and nothing writes before this point, so it has not been advanced by a save yet. (If a
2467
3016
  // future change schedules a write earlier, this comparison silently starts meaning something else.)
@@ -2486,7 +3035,7 @@ function restoreSavedInner(){
2486
3035
  showStaleDraftBanner(d);
2487
3036
  return false;
2488
3037
  }
2489
- applyDraftFields(d);return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
3038
+ return applyDraftFields(d);}catch(e){console.warn('steel-editor: a stored draft could not be read or applied — leaving it in place',e);return false;}}
2490
3039
  function updUR(){document.getElementById('undoB').disabled=!undo.length;document.getElementById('redoB').disabled=!redo.length;}
2491
3040
  // Canonical, model-global palette rank (B2): EVERY plan's non-blank member profiles ∪ weight-table keys,
2492
3041
  // uppercased + sorted — the SAME basis contract-to-scene.ts uses, so a profile gets ONE hue in the 2D legend
@@ -3442,7 +3991,29 @@ function render(){
3442
3991
  // never persisted — the adapter's own sheetFrame() refuses to fabricate one. So the canvas stays empty
3443
3992
  // rather than drawing a plausible plan in the wrong place, which is the worst defect class this epic has.
3444
3993
  // The inspector still repaints: the read-only panel is what the user actually has here.
3445
- if(MODEL_RO){svg.replaceChildren();stats();panel();return;} // stats() here only RETIRES the per-sheet readouts — see its v2 branch
3994
+ // …and the header state, which this return used to skip entirely. The ⋯ → Display rows are the one
3995
+ // group of STATE-REPORTING rows read-only leaves usable (RO_LOCKED_SECS locks detailing/checks/snap;
3996
+ // coords and session are left live too, but carry actions rather than state). Their sync sits in
3997
+ // render()'s trailing upd*() batch, which this return never reaches — so every one of them showed its
3998
+ // static markup instead, and the static markup carries NO `on` class at all, so the slider switch
3999
+ // painted OFF on all six however their flags actually stood. Grid lines lied loudest: OFF over a grid
4000
+ // that is on and drawn in 3D, and enabled on a document with no grid. (Grid lines alone could recover,
4001
+ // since gridSetVisible and the undo restore call its updater directly; the other five could not.)
4002
+ // syncDisplayRows() is deliberately a NAMED function called from both exits rather than a second list
4003
+ // spelled out here — a hand-maintained copy of "the Display rows" is how these came to be skipped, and
4004
+ // verify:display-sync fails the build if the two ever disagree.
4005
+ // updUR joins them: apply() does not sync the buttons either, so on a v2 document Undo/Redo NEVER track
4006
+ // the stack — enabled from boot, still enabled after the one grid edit this mode allows has been undone
4007
+ // and there is nothing left to undo. An earlier revision of this repair left it out on the grounds that
4008
+ // an empty stack at boot is harmless; that was wrong, because the desync is permanent, not initial.
4009
+ // The REST of the batch is deliberately NOT called here; each was checked rather than assumed:
4010
+ // updDup THROWS on v2 (redundantDups reads P.members, which a v2 plan does not have — measured, and on
4011
+ // its own reason enough not to call the batch wholesale; pinned by a characterisation test);
4012
+ // updConnBtn/updBpBtn/updSpBtn label rows inside the Detailing section, which read-only disables AND
4013
+ // force-closes, so they are unreachable; updConf yields an empty report that leaves #confStat at the
4014
+ // display:none its markup already carries; and updCS is already called from every path that can change
4015
+ // the axes on a v2 document (csArm3dB, onFrame3dChange, the view switch), so it would add nothing.
4016
+ if(MODEL_RO){svg.replaceChildren();stats();panel();updUR();syncDisplayRows();return;} // stats() here only RETIRES the per-sheet readouts — see its v2 branch
3446
4017
  document.body.classList.remove('snapping'); // a wholesale svg rebuild drops any #snapMark → clear the cursor-hide flag too (the next pointermove re-adds it if still snapping)
3447
4018
  buildColorRank(); // refresh the model-global colour rank before any colorFor() call below (B2 — keeps 2D hues stable across plans + matched to 3D)
3448
4019
  reanchorAllPlans(); // F9: glue magnetic dims to their members BEFORE anything reads P.dims — covers every mutation path that ends in a render()
@@ -3497,7 +4068,7 @@ function render(){
3497
4068
  if(P.frame)s+=axisGlyphSvg(P.frame.o,P.frame.u,false); // local-axes glyph at the origin (only when a frame is set; removed on reset)
3498
4069
  // the detail datalist shows the SAME list as the combobox and the Details modal (#397), built as DOM
3499
4070
  // nodes rather than markup so a detail name coming off the drawing is never parsed as HTML
3500
- svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); {const dl=document.getElementById('details');dl.replaceChildren(...detTexts().map(t=>{const o=document.createElement('option');o.value=t;return o;}));} stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); updGridToggle(); updLenToggle(); updDimToggle(); updCalloutToggle(); updPlToggle(); updRefToggle();
4071
+ svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); {const dl=document.getElementById('details');dl.replaceChildren(...detTexts().map(t=>{const o=document.createElement('option');o.value=t;return o;}));} stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
3501
4072
  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()).
3502
4073
  if(view3d&&window.Steel3DView){window.Steel3DView.setSelection(selIds);if(window.Steel3DView.setGridSelection)window.Steel3DView.setGridSelection(selGridIds);updateIsolateBtn();if((selIds.size||selGridIds.size)&&window.Steel3DView.selectedClips&&window.Steel3DView.selectedClips().length)window.Steel3DView.setSelectedClips([]);refreshLegendSel();} // keep the 3D member + grid highlight in sync; selecting geometry clears any clip selection (exclusive)
3503
4074
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -5336,7 +5907,7 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
5336
5907
  let pick=-1;const rows=[];
5337
5908
  const go=document.createElement('button');go.className='primary';go.disabled=true;go.textContent=tool==='move'?'Move here':'Copy here';
5338
5909
  C.plans.forEach((pl,i)=>{const row=document.createElement('div');row.className='lvrow'+(pl===P?' cur':'');
5339
- const nm=document.createElement('span');nm.textContent=pl.sheet+(pl.title?' · '+pl.title:'')+(pl===P?' (current)':'');
5910
+ const nm=document.createElement('span');nm.textContent=planLabel(pl,i)+(pl===P?' (current)':''); // the page's ONE plan-label rule — this modal and the header switcher must not disagree about what a plan is called
5340
5911
  const ts=document.createElement('span');ts.className='lvtos';const nM=(pl.members||[]).length;ts.textContent=nM+' member'+(nM===1?'':'s')+' · TOS '+fmtFtIn(pl.default_tos!=null?pl.default_tos:198);
5341
5912
  row.append(nm,ts);
5342
5913
  if(pl!==P){row.onclick=()=>{pick=i;rows.forEach(r=>r.classList.remove('pick'));row.classList.add('pick');go.disabled=false;};
@@ -5713,16 +6284,66 @@ document.getElementById('csArm3dB').onclick=()=>{const d3=window.Steel3DView;if(
5713
6284
  const fi=d3.frameInfo(),o=fi.origin?[...fi.origin]:[0,0,0],x=parseFloat(document.getElementById('csF3dX').value)*FT,y=parseFloat(document.getElementById('csF3dY').value)*FT,z=parseFloat(document.getElementById('csF3dZ').value)*FT;
5714
6285
  d3.setFrameOrigin([isNaN(x)?o[0]:x,isNaN(y)?o[1]:y,isNaN(z)?o[2]:z]);
5715
6286
  updCS();});});
5716
- function updDimToggle(){const b=document.getElementById('dimToggleB');if(b){b.classList.toggle('on',dimsVisible);b.setAttribute('aria-checked',String(dimsVisible));}}
5717
- document.getElementById('dimToggleB').onclick=e=>{e.stopPropagation();dimsVisible=!dimsVisible;updDimToggle();render();};
5718
- function updLenToggle(){const b=document.getElementById('lenToggleB');if(b){b.classList.toggle('on',showSelLen);b.setAttribute('aria-checked',String(showSelLen));}}
5719
- document.getElementById('lenToggleB').onclick=e=>{e.stopPropagation();showSelLen=!showSelLen;try{localStorage.setItem('steel:selLen:v1',showSelLen?'1':'0');}catch(_){}updLenToggle();render();}; // render() repaints the 2D chips + pushes labels to 3D
5720
- function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(b){b.classList.toggle('on',calloutsVisible);b.setAttribute('aria-checked',String(calloutsVisible));}}
5721
- document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
6287
+ /**
6288
+ * The ⋯ → Display TOGGLE ROWS — the `.dtog` buttons, synced in ONE place.
6289
+ *
6290
+ * Named once and called from both of render()'s exits (the MODEL_RO branch and the trailing sync), so
6291
+ * "the Display rows" cannot mean two different lists. Adding a seventh `.dtog` row means adding its
6292
+ * updater here and nowhere else; `npm run verify:display-sync` fails the build if a `.dtog` id in the
6293
+ * markup has no updater in this function, because a hand-maintained second copy is exactly how the v2
6294
+ * rows came to be skipped in the first place.
6295
+ *
6296
+ * WHAT A ROW ON A READ-ONLY DOCUMENT REPORTS. Each of these paints one surface and one only: Dimensions
6297
+ * and Callouts draw onto the 2D plan, Reference sheet draws the traced sheet under it, Member length
6298
+ * needs a length v2 cannot yet produce (below). A v2 document has no 2D plan — render() returns before
6299
+ * drawing one and the 2D tab is permanently the #ro2d empty state — so on v2 all four are OFF, and they
6300
+ * say so: `!MODEL_RO && flag` rather than the raw flag. Reporting the raw flag is what the first version
6301
+ * of this repair did, and it shipped `aria-checked=true` on a DISABLED row — "on, and you cannot turn it
6302
+ * off", which is the very defect this repair exists to remove, just moved to different rows.
6303
+ *
6304
+ * (The equivalent v1 case — Reference sheet checked-and-disabled on a plan with no traced sheet — is
6305
+ * pre-existing and deliberately untouched here; this change is scoped to the read-only regression.)
6306
+ *
6307
+ * DISABLED BARE, with no aria-describedby: the self-disable updGridToggle (no grid) and updRefToggle (no
6308
+ * reference sheet) already use. #roRibbon would state the wrong reason — its copy is about REFUSED
6309
+ * EDITS, and these are not refused writes. `dimsVisible` flips perfectly well; there is no canvas for it
6310
+ * to reach. (Known gap: a disabled button fires no pointer events, so its data-tip cannot explain the
6311
+ * greying either. Shared with the two pre-existing self-disabling rows — see the follow-up.)
6312
+ */
6313
+ function syncDisplayRows(){updGridToggle();updLenToggle();updDimToggle();updCalloutToggle();updPlToggle();updRefToggle();}
6314
+ function updDimToggle(){const b=document.getElementById('dimToggleB');if(!b)return;const on=!MODEL_RO&&dimsVisible;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}
6315
+ document.getElementById('dimToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;dimsVisible=!dimsVisible;updDimToggle();render();}; // the guard is the enforcement, the disable is only the UX — same split canWriteViews makes
6316
+ // Member length is OFF on v2 for a DIFFERENT reason than its plan-only neighbours, and the difference
6317
+ // matters to whoever re-enables it. This one is not conceptually 2D — it pushes labels to 3D too
6318
+ // (refreshSelLen3d), and 3D is the view a v2 document opens in, so it OUGHT to apply here. It cannot
6319
+ // produce a label at all today, twice over: refreshSelLen3d is reached only via
6320
+ // syncPropLabelsAfterRender(), whose two callers (render()'s trailing sync and reflect2dGridSelection)
6321
+ // are both skipped or unreachable on v2; and _len3dFt measures `m.wp`, which a v2 member does not have
6322
+ // (it carries from/to), so every length comes back 0 and is dropped as degenerate. Wiring the call alone
6323
+ // would therefore NOT fix it. Delete this disable when v2 gets a real length — it describes a gap, it
6324
+ // does not declare the row inapplicable.
6325
+ function updLenToggle(){const b=document.getElementById('lenToggleB');if(!b)return;const on=!MODEL_RO&&showSelLen;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}
6326
+ document.getElementById('lenToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;showSelLen=!showSelLen;try{localStorage.setItem('steel:selLen:v1',showSelLen?'1':'0');}catch(_){}updLenToggle();render();}; // render() repaints the 2D chips + pushes labels to 3D
6327
+ function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(!b)return;const on=!MODEL_RO&&calloutsVisible;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));} // plan-only, like Dimensions
6328
+ document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
6329
+ // NOTE FOR THE NEXT EDITOR: do NOT add `b.disabled=MODEL_RO` here to match the five rows around it.
6330
+ // This row's disable is owned by roDisablePropLabelToggles(), which runs ONCE at boot and also sets the
6331
+ // aria-describedby; updPlToggle runs on EVERY render, so an assignment here would clobber both on the
6332
+ // first repaint after boot — the row would silently go live and lose its screen-reader reason. A
6333
+ // mutation run proved the shape passes the suite unless it is asserted after an op, which is why
6334
+ // steel-editor-v2.test.ts re-asserts this row's whole state following a render.
6335
+ // Its OFF-on-v2 reading needs no MODEL_RO term: plVis() already short-circuits to false under it — and
6336
+ // that short-circuit is also what keeps this line safe, because C.prop_labels is left UNNORMALISED on a
6337
+ // read-only document (sanitizePropLabels runs inside a canWriteModel() guard).
5722
6338
  function updPlToggle(){const b=document.getElementById('plToggleB');if(b){const on=!!(C.prop_labels&&plVis(false));b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}} // B1: 2D property-label visibility (independent of 3D)
5723
6339
  document.getElementById('plToggleB').onclick=e=>{e.stopPropagation();if(!canWritePropLabelVis())return;C.prop_labels.vis2d=!C.prop_labels.vis2d;updPlToggle();refreshPropLabels();}; // refreshPropLabels → scheduleSave()+render(): repaints the 2D chips (gated by vis2d) and persists the choice
5724
- function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;b.disabled=!hasOverlay();b.classList.toggle('on',refSheetOn);b.setAttribute('aria-checked',String(refSheetOn));} // F13: grey the row out on a plan with no reference sheet (mirrors updGridToggle's no-grid disable)
5725
- document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v1',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();}; // render() rebuilds the SVG (overlaySvg gone/back) and buildSnap re-reads overlaySnapGeom (snap candidates gone/back)
6340
+ // MODEL_RO is a term here in its own right, NOT covered by !hasOverlay(): `filter` is a legal v2 root key
6341
+ // and the migration copies it verbatim, so a project migrated from drawings arrives WITH one and
6342
+ // hasOverlay() answers true — leaving this row live over a canvas that draws nothing. Worse than inert:
6343
+ // the handler persists to `steel:refSheet:v1`, which is not project-scoped, so a click here would follow
6344
+ // the user into their next v1 project and hide the traced sheet there.
6345
+ function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;const on=!MODEL_RO&&refSheetOn;b.disabled=MODEL_RO||!hasOverlay();b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));} // F13: grey the row out on a plan with no reference sheet (mirrors updGridToggle's no-grid disable)
6346
+ document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v1',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();}; // render() rebuilds the SVG (overlaySvg gone/back) and buildSnap re-reads overlaySnapGeom (snap candidates gone/back)
5726
6347
  document.getElementById('gridEditB').onclick=()=>{setGridMode(!gridMode);render();};
5727
6348
  {const ghb=document.getElementById('gridHdrB');if(ghb)ghb.onclick=()=>{setGridMode(!gridMode);render();};} // the header twin (read-only mode only) — same one action, not a second implementation
5728
6349
  /**
@@ -5844,7 +6465,14 @@ document.getElementById('redoB').onclick=doRedo;
5844
6465
  document.getElementById('dragMoveB').onclick=()=>{setDragMove(!dragMoveOn);toast(dragMoveOn?'Drag to move/copy: ON — drag moves, Ctrl+drag copies':'Drag to move/copy: OFF — a click only selects');};
5845
6466
  setDragMove(dragMoveOn); // reflect the persisted state on load (body class + pill)
5846
6467
  addEventListener('keydown',e=>{
5847
- const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test((document.activeElement||{}).tagName);
6468
+ // #planTrigger is named explicitly because it USED to be covered for free: the plan switcher was a
6469
+ // <select>, so focusing it matched the tag test and suppressed every !inForm shortcut below. It is now a
6470
+ // themed combobox on a <button> (see the .plan-* CSS for why), and without this line focusing it would
6471
+ // start letting Delete, Alt+Z and the rest fire against the canvas underneath — a regression the theming
6472
+ // fix would otherwise have smuggled in. The keys the combobox itself handles never reach here at all;
6473
+ // its own keydown stops them.
6474
+ const _ae=document.activeElement||{};
6475
+ const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test(_ae.tagName)||_ae.id==='planTrigger';
5848
6476
  if(dimEdit){if(e.key==='Escape'){e.preventDefault();closeDimEdit();}return;} // F8 popup is modal — suppress every editor/tool shortcut (incl. Ctrl+Z under the popup). Its own input/buttons handle their keys and stopPropagation, so they never reach here (Codex R2 #8).
5849
6477
  // A live drag-out to Tekla owns Escape: the 3D view cancels the gesture on its own handler (this one
5850
6478
  // runs first). Without this, Escape would fall through to the deselect below and clear the very
@@ -6316,10 +6944,16 @@ const view3dApi={
6316
6944
  // The bake reports everything it could NOT emit in `skipped[]`, and we used to discard it entirely — so a
6317
6945
  // connection the engine refused (e.g. a shear plate whose main became a brace) vanished from 3D silently.
6318
6946
  // Always log the full list. TOAST only for `joint:<id>` entries: a refused connection is unambiguous and
6319
- // always surprising. Member skips are NOT toasted — the bake legitimately drops RFI members (no size) and
6320
- // zero-height foundation columns, so the count is dominated by expected drops and a toast would nag on
6321
- // every 3D open. Telling a degenerate brace apart from those needs skip REASONS from the server; until
6322
- // contract-to-scene returns them, the console is the honest channel. (silent-failure review)
6947
+ // always surprising. Member skips are NOT toasted — the bake legitimately drops RFI members (no size),
6948
+ // so the count is dominated by expected drops and a toast would nag on every 3D open. Telling a
6949
+ // degenerate member apart from those needs skip REASONS from the server; until contract-to-scene
6950
+ // returns them, the console is the honest channel. (silent-failure review)
6951
+ //
6952
+ // "and zero-height foundation columns" USED TO BE IN THAT LIST and no longer belongs: on v2 migration
6953
+ // keeps every footprint marker out of `members[]` entirely, and the bake's height-only rule is gone, so
6954
+ // v2 drops no foundation columns at all. What remains on v2 is (a) no resolvable section and (b) a
6955
+ // genuinely zero-LENGTH member — and (b) is never expected, so the "would nag" argument no longer
6956
+ // covers it. Widening `skipped` to carry reasons is the fix; it is not this change.
6323
6957
  {const sk=Array.isArray(j.skipped)?j.skipped:[];
6324
6958
  if(sk.length){
6325
6959
  const jn=sk.filter(s=>String(s).startsWith('joint:')).length;
@@ -7759,7 +8393,12 @@ function applyViewState(on){ // flip the toggle + swap the canvases (
7759
8393
  document.getElementById('stage').style.display=on?'none':'';
7760
8394
  document.getElementById('stage3d').style.display=on?'block':'none';
7761
8395
  document.getElementById('zoombar').style.display=on?'none':''; // zoom slider is 2D-only
7762
- document.getElementById('planSel').style.display=on?'none':''; // plan selector is 2D-only (3D shows the whole model)
8396
+ // Plan switcher is 2D-only (3D shows the whole model). Hidden by `display`, not the `hidden` attribute:
8397
+ // .plan-combo carries an author `display:inline-flex`, which beats the UA's [hidden] rule by ORIGIN, so
8398
+ // `hidden = true` would quietly do nothing here. closePlans() first — a popover left open across the
8399
+ // switch is hidden with its wrapper, but would strand `aria-expanded=true` and the .open caret behind it.
8400
+ if(on)closePlans(false);
8401
+ document.getElementById('planCombo').style.display=on?'none':'';
7763
8402
  document.getElementById('m3dBar').style.display=on?'flex':'none';
7764
8403
  document.body.classList.toggle('v3d',on); // 3D-only chrome (e.g. ⋯ → Detailing → Insert detail) keys off this
7765
8404
  document.getElementById('dimB').style.display=on?'none':''; // 2D Dimension button — 2D only
@@ -8924,7 +9563,7 @@ function setPlanV2(i){
8924
9563
  dimStyleMode=false;csaxisMode=false;setCsMode();snapOnlyClear2d();closeSnapMenu();disarmCm();
8925
9564
  render();fitToWindow();
8926
9565
  refresh3DGrid();
8927
- const ps=document.getElementById('planSel');if(ps)ps.value=String(i);}
9566
+ syncPlanSwitcher(i);}
8928
9567
  // --- multi-plan: switch between all steel plan views ---
8929
9568
  function setPlan(i){C.active=i;P=C.plans[i];
8930
9569
  if(MODEL_RO){setPlanV2(i);return;} // v2: no 2D setup at all — see setPlanV2 for why that is the whole branch
@@ -8968,11 +9607,264 @@ function setPlan(i){C.active=i;P=C.plans[i];
8968
9607
  if(!P.autofilled){autofillTOS();P.autofilled=true;}
8969
9608
  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)
8970
9609
  setMode();render();fitToWindow();
8971
- refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan <select> is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
8972
- const ps=document.getElementById('planSel');if(ps)ps.value=String(i);}
8973
- const planSel=document.getElementById('planSel');
8974
- planSel.innerHTML=C.plans.map((p,i)=>`<option value="${i}">${esc(p.sheet)} · ${esc(p.title)}</option>`).join('');
8975
- planSel.onchange=e=>setPlan(+e.target.value);
9610
+ refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan switcher is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
9611
+ syncPlanSwitcher(i);}
9612
+ // ── plan switcher ───────────────────────────────────────────────────────────────────────────────
9613
+ //
9614
+ // A themed combobox rather than a <select>: see the .plan-* CSS for why the native control cannot be made
9615
+ // to obey the dark baseline. Same control, and the same reasoning, as web/steel-filter.html's sheet
9616
+ // switcher; both descend from the app-wide .wf-combo (web/index.html + web/aware.js).
9617
+ //
9618
+ // Not ported from that shared control (a closed list, so the divergences are worth naming):
9619
+ // · no SEARCH field — the workflow and project pickers face dozens of rows, a plan set faces a handful,
9620
+ // and an input that grabs focus on open would put a control with nothing to do between the user and
9621
+ // the list. With no input to host them, focus stays on the trigger and the TRIGGER carries
9622
+ // aria-activedescendant — the WAI-ARIA select-only shape, hence role=combobox on a <button>.
9623
+ // · no per-row action or dirty-dot chrome — a plan is a place to look, not an entity you own.
9624
+ // · opens ON the current row, where the shared control opens with no highlight and merely scrolls the
9625
+ // selection into view. A short list has somewhere obvious to start.
9626
+ const planCombo=document.getElementById('planCombo');
9627
+ const planTrigger=document.getElementById('planTrigger');
9628
+ const planTriggerLabel=document.getElementById('planTriggerLabel');
9629
+ const planPopover=document.getElementById('planPopover');
9630
+ // planListEl, not planList: `planList` is already taken further up (modelReadsV1's per-plan DATA getter,
9631
+ // which returns members/scale/TOS). Two same-named consts meaning entirely different things in one file is
9632
+ // a trap even though the scopes don't collide today. (Code review.)
9633
+ const planListEl=document.getElementById('planList');
9634
+ let planHi=-1; // index of the keyboard-highlighted row while open; -1 = none
9635
+ let planType=''; // typeahead buffer, reset on open and after a pause
9636
+ let planTypeAt=0; // …and when the last key of it arrived
9637
+
9638
+ /** One plan's one-line label — "S-201 · Second Floor Framing".
9639
+ *
9640
+ * ONE rule, because the page needs this string in three places now (the closed trigger, the open option
9641
+ * row, the Move/Copy level modal) and it already held two that DISAGREED: the modal has always written
9642
+ * `sheet + (title ? ' · ' + title : '')`, while the <select> this replaced wrote an unconditional
9643
+ * `sheet · title` — so a plan with no title read "S-201 · undefined" in the header and "S-201" in the
9644
+ * modal. Both now call here.
9645
+ *
9646
+ * Deliberately NOT steel-filter-core.js's sheetLabel(), which is the same rule for the sibling page: the
9647
+ * editor does not otherwise depend on the filter pre-stage, and importing its pure core for one string
9648
+ * would couple the model editor to that pipeline while STILL leaving this page holding two rules unless
9649
+ * the modal changed too. Converging in-page is the win; the two are siblings, and a change to what a
9650
+ * sheet is called belongs in both.
9651
+ *
9652
+ * Every part of a plan's identity is drawing-derived, so nothing here may assume a string: an object
9653
+ * reaching String() paints the literal "[object Object]" into the header, which is why null/undefined
9654
+ * and anything typeof 'object' drop to the "Plan N" fallback rather than being coerced. */
9655
+ function planLabel(pl,i){
9656
+ const p=(pl&&typeof pl==='object')?pl:{};
9657
+ const text=v=>(v==null||typeof v==='object')?'':String(v).trim();
9658
+ const n=Number.isFinite(Number(i))?Math.max(0,Math.trunc(Number(i))):0; // 1-based for humans; the floor keeps "Plan 0" out
9659
+ const name=text(p.sheet)||('Plan '+(n+1));
9660
+ const title=text(p.title);
9661
+ return title?(name+' · '+title):name;
9662
+ }
9663
+
9664
+ const planOptions=()=>[...planListEl.children];
9665
+
9666
+ function buildPlanSwitcher(){
9667
+ // Rebuilding under an open popover would strand planHi and aria-activedescendant on rows that no longer
9668
+ // exist. Unreachable today (this runs once, from main()) — but it is one call, and it stops the trap the
9669
+ // day the plan list re-renders in place.
9670
+ closePlans(false);
9671
+ planListEl.replaceChildren();
9672
+ (C.plans||[]).forEach((pl,i)=>{
9673
+ // A <div role=option>, NOT a <button> — see the .plan-option rule for why focus has to stay on the trigger.
9674
+ const o=document.createElement('div');
9675
+ o.className='plan-option';
9676
+ o.id='plan-opt-'+i; // the target aria-activedescendant points at
9677
+ o.setAttribute('role','option');
9678
+ o.setAttribute('aria-selected','false');
9679
+ o.dataset.i=String(i);
9680
+ o.textContent=planLabel(pl,i); // textContent, never innerHTML: a sheet name and title are read off the drawing, so they are data
9681
+ // The tooltip is attached at OPEN time, not here — see tipClippedRows().
9682
+ o.addEventListener('click',()=>pickPlan(i));
9683
+ planListEl.appendChild(o);
9684
+ });
9685
+ }
9686
+
9687
+ /** Point the control at whatever plan is now active — called from BOTH setPlan and setPlanV2, so a
9688
+ * programmatic switch (the Confidence report's Locate buttons, a restored C.active) moves the label and
9689
+ * the selected-row accent exactly as a click does. Replaces the two `planSel.value = String(i)` writebacks. */
9690
+ function syncPlanSwitcher(i){
9691
+ // An ABSENT plan gets an empty label, not planLabel's fallback. The fallback exists for a plan that is
9692
+ // THERE but whose sheet/title is junk — "Plan 3" is the honest name for it. With no plan at all it would
9693
+ // instead assert a plan that does not exist: a v2 document may legitimately carry `plans: []` (boot only
9694
+ // checks Array.isArray), and the header would then read "Plan 1" over a switcher holding zero rows. The
9695
+ // <select> rendered blank there — uninformative, but it did not invent an identity.
9696
+ const pl=(C.plans||[])[i];
9697
+ const label=pl?planLabel(pl,i):'';
9698
+ planTriggerLabel.textContent=label;
9699
+ // The trigger ellipsizes at 320px too, so the closed state needs the same escape hatch as the rows. This
9700
+ // REPLACES the static "Switch plan view" tip: the caret and the listbox already say what the control
9701
+ // does, and the accessible name (aria-labelledby) still carries the purpose — so the one thing the
9702
+ // tooltip can add that nothing else does is the part that got clipped.
9703
+ if(label)planTrigger.setAttribute('data-tip',label);
9704
+ for(const o of planOptions()){
9705
+ // Number(i), not a bare `i`: the index is not guaranteed to be a number here. C.active is copied
9706
+ // straight out of a localStorage draft (applyDraftFields, `d.active != null` and nothing else), so a
9707
+ // hand-edited or corrupt row can carry the STRING "1". Everything else tolerates that — P=C.plans["1"]
9708
+ // resolves, the label is right — but a strict === against a number would then match no row at all,
9709
+ // leaving every option aria-selected=false and no accent: a listbox that announces no selection while
9710
+ // the header shows a plan. (Found by the silent-failure review.)
9711
+ const on=Number(o.dataset.i)===Number(i);
9712
+ o.classList.toggle('selected',on);
9713
+ o.setAttribute('aria-selected',on?'true':'false');
9714
+ }
9715
+ // A switch that lands while the popover is OPEN must move the highlight with it, or the highlight and
9716
+ // aria-activedescendant stay on the previously-active row and the next Enter re-picks the row the user
9717
+ // just navigated away from.
9718
+ if(!planPopover.hidden)highlightPlan(i);
9719
+ }
9720
+
9721
+ function highlightPlan(i){
9722
+ const opts=planOptions();if(!opts.length)return;
9723
+ planHi=Math.max(0,Math.min(opts.length-1,i)); // clamp, so Up on the first row parks rather than wrapping
9724
+ opts.forEach((o,n)=>o.classList.toggle('active',n===planHi));
9725
+ const hi=opts[planHi];
9726
+ hi.scrollIntoView({block:'nearest'});
9727
+ planTrigger.setAttribute('aria-activedescendant',hi.id); // DOM focus never leaves the trigger, so the highlighted row is announced through it
9728
+ }
9729
+
9730
+ /** Commit a pick. The ORDER is the whole point and was measured, not assumed: setPlan() reaches
9731
+ * setMode() → cmHudClose(), which calls stage.focus(). So closing with focusTrigger=true and THEN
9732
+ * switching plans lands the user on the canvas — focus silently leaves the control they were operating.
9733
+ * Harmless-looking on a mouse click; on the keyboard it strands them, since the <select> this replaced
9734
+ * kept focus after a pick for free. Close quietly, switch, then take focus back last. */
9735
+ function pickPlan(i){
9736
+ closePlans(false);
9737
+ setPlan(i);
9738
+ planTrigger.focus();
9739
+ }
9740
+
9741
+ /** Give a row a tooltip ONLY when its label is actually clipped.
9742
+ *
9743
+ * A row ellipsizes inside the 400px panel, so a long "S-202 · Second Floor Framing At El 118'-6"" loses
9744
+ * its tail with no way to read the rest — the <select> this replaced had no such problem, since its OS
9745
+ * panel auto-sized to its content, so leaving that unaddressed would regress what a user can read.
9746
+ *
9747
+ * But setting it unconditionally (as the sibling page does, calling it "harmlessly redundant when the
9748
+ * label fits") is NOT harmless here: the shared tooltip renders at z-index 80, above this z-30 popover,
9749
+ * and positions itself just under the hovered element — so scanning a list of short names pops a panel
9750
+ * repeating text the user can already read, on top of the next row and a half. (Code review.)
9751
+ *
9752
+ * Measured at open rather than at build, because scrollWidth/clientWidth are both 0 while the popover is
9753
+ * `hidden` — computing it in buildPlanSwitcher would mark every row as clipped. */
9754
+ function tipClippedRows(){
9755
+ for(const o of planOptions()){
9756
+ if(o.scrollWidth>o.clientWidth)o.setAttribute('data-tip',o.textContent);
9757
+ else o.removeAttribute('data-tip');
9758
+ }
9759
+ }
9760
+
9761
+ function plansOpen(){return !planPopover.hidden;}
9762
+ function openPlans(){
9763
+ if(plansOpen())return;
9764
+ planPopover.hidden=false;
9765
+ planTrigger.classList.add('open');
9766
+ planTrigger.setAttribute('aria-expanded','true');
9767
+ tipClippedRows(); // now that the rows have layout, tooltip only the ones that actually lost their tail
9768
+ // Open ON the current plan, so ↓ steps to the next one rather than to the top — and take "current" from
9769
+ // the row the control is SHOWING, not from C.active. The two can disagree: "View my edits instead"
9770
+ // (showStaleDraftBanner) calls applyDraftFields, which writes C.active and then only render()s — it never
9771
+ // reaches setPlan, so P, the canvas and this control all stay on the old plan while C.active moves. That
9772
+ // desync predates this control and is not ours to fix here, but reading C.active would make this the
9773
+ // first thing to RENDER the contradiction: one row accented as selected, a different row highlighted,
9774
+ // and Enter committing the one the header never named. Opening on the selected row keeps the control
9775
+ // self-consistent whatever C.active says. (Found by the silent-failure review.)
9776
+ const cur=planOptions().findIndex(o=>o.classList.contains('selected'));
9777
+ highlightPlan(cur>=0?cur:0);
9778
+ planType=''; // a fresh open starts a fresh typeahead
9779
+ }
9780
+ function closePlans(focusTrigger){
9781
+ if(!plansOpen())return;
9782
+ planPopover.hidden=true;
9783
+ planTrigger.classList.remove('open');
9784
+ planTrigger.setAttribute('aria-expanded','false');
9785
+ planTrigger.removeAttribute('aria-activedescendant'); // must not survive the close — it would name a row nothing is showing
9786
+ planOptions().forEach(o=>o.classList.remove('active'));
9787
+ planHi=-1;
9788
+ if(focusTrigger)planTrigger.focus();
9789
+ }
9790
+
9791
+ planTrigger.addEventListener('click',()=>{plansOpen()?closePlans(false):openPlans();});
9792
+ planTrigger.addEventListener('keydown',e=>{
9793
+ // stopPropagation on every key this control handles, so none of them ALSO reaches the global editor
9794
+ // shortcuts below — the idle Space/Enter "repeat the last command" handler would otherwise fire while
9795
+ // the user is opening the list. The page's own convention for a control that owns its keys: the F12 RFI
9796
+ // pill and the F8 dimension-edit popup both stopPropagation for exactly this reason. The keys this does
9797
+ // NOT handle are covered instead by naming the trigger in that handler's `inForm` guard, which the old
9798
+ // <select> satisfied for free by being a SELECT.
9799
+ // (Deliberately no line numbers here. The three this comment first carried were all wrong — they were
9800
+ // written against pre-insertion positions and drifted further as the file grew — and a reference that
9801
+ // lands on unrelated code is worse than none, because it invites a reader to trust it. Name the thing.)
9802
+ if(!plansOpen()){
9803
+ if(e.key==='ArrowDown'||e.key==='ArrowUp'||e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();openPlans();}
9804
+ return;
9805
+ }
9806
+ if(e.key==='ArrowDown'){e.preventDefault();e.stopPropagation();highlightPlan(planHi+1);}
9807
+ else if(e.key==='ArrowUp'){e.preventDefault();e.stopPropagation();highlightPlan(planHi-1);}
9808
+ else if(e.key==='Home'){e.preventDefault();e.stopPropagation();highlightPlan(0);}
9809
+ else if(e.key==='End'){e.preventDefault();e.stopPropagation();highlightPlan(planOptions().length-1);}
9810
+ else if(e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();const i=planHi;if(i>=0)pickPlan(i);else closePlans(true);}
9811
+ else if(e.key==='Escape'){e.preventDefault();e.stopPropagation();closePlans(true);}
9812
+ // Tab must still MOVE — close on the way out rather than swallowing it, or the popover is left orphaned
9813
+ // over a control the user has already left.
9814
+ else if(e.key==='Tab'){closePlans(false);}
9815
+ // TYPEAHEAD — type "S-2" or "sec" to jump to a row. The <select> this replaced had it natively, and all
9816
+ // three reviewers flagged its loss independently; WAI-ARIA's select-only combobox lists it as expected
9817
+ // behaviour. It also failed as a pure SILENT no-op: an unhandled printable key fell through to the global
9818
+ // handler, where the new #planTrigger `inForm` clause suppressed it — swallowed at both ends, with
9819
+ // nothing happening and nothing logged.
9820
+ // Deliberately open-state only. A closed native <select> also types to CHANGE the value outright; doing
9821
+ // that here would commit a plan switch (a full re-render) per keystroke, which is a much larger surface
9822
+ // than the key was worth. Closed, the trigger still opens on Enter/Space/arrows.
9823
+ else if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){
9824
+ e.preventDefault();e.stopPropagation();
9825
+ const now=Date.now();
9826
+ if(now-planTypeAt>500)planType=''; // a pause starts a new search rather than extending a stale one
9827
+ planTypeAt=now;planType+=e.key.toLowerCase();
9828
+ const opts=planOptions();
9829
+ // Search from the row AFTER the highlight when the same single char is repeated, so pressing "s" walks
9830
+ // the S-sheets instead of pinning the first one — the native behaviour this restores.
9831
+ const rot=(planType.length===1&&planHi>=0)?planHi+1:0;
9832
+ const hit=opts.map((o,n)=>opts[(rot+n)%opts.length]).find(o=>o.textContent.toLowerCase().startsWith(planType));
9833
+ if(hit)highlightPlan(opts.indexOf(hit));
9834
+ }
9835
+ });
9836
+ // An open popover closes on a press anywhere outside it.
9837
+ //
9838
+ // pointerdown, not click, so the popover goes at the START of a press: this canvas begins a pan, a
9839
+ // marquee, a dimension placement or an add-member click on pointerdown, and a click-based listener would
9840
+ // leave the panel hanging over the drawing for the whole gesture.
9841
+ //
9842
+ // Capture phase is declared defence rather than a fact about today's code — nothing on the canvas path
9843
+ // calls stopPropagation() — but it costs nothing and means a future one can never strand this open.
9844
+ document.addEventListener('pointerdown',e=>{
9845
+ if(!plansOpen()||planCombo.contains(e.target))return;
9846
+ closePlans(false);
9847
+ // …and the dismissing press does ONLY that. Without this it closes the popover and then continues into
9848
+ // the canvas, which acts on pointerdown: the press that dismissed the list would also start a pan or a
9849
+ // marquee, place a dimension point, or drop an add-member click onto the drawing. The <select> this
9850
+ // replaced could not do that — its OS popup owned the pointer, so the dismissing press never reached the
9851
+ // page at all. (Codex review.)
9852
+ // stopPropagation, NOT stopImmediatePropagation: other document-capture listeners are unrelated and must
9853
+ // still run. And deliberately not preventDefault — the canvas commands are pointerdown-driven and are
9854
+ // already stopped here, while buttons act on `click`, which this does not touch. So a press on another
9855
+ // header control dismisses the list AND works, instead of costing the user a dead first click. That is a
9856
+ // considered divergence from the native popup, which swallowed both.
9857
+ e.stopPropagation();
9858
+ },true);
9859
+ // An open popover also closes when focus leaves the DOCUMENT, which the press listener above cannot see.
9860
+ // This editor runs INSIDE AN IFRAME in the workspaces shell (see wsShell() below), so a click anywhere in
9861
+ // the shell around it — the chat, the project rail, History — never enters this document; nor does
9862
+ // Alt+Tab, nor opening devtools. Without this the panel hangs over the canvas with aria-expanded=true and
9863
+ // the caret still flipped until the user happens to press inside the editor again. The <select> got this
9864
+ // for free: an OS popup closes on window blur. (Found by the silent-failure review.)
9865
+ addEventListener('blur',()=>closePlans(false));
9866
+ document.addEventListener('visibilitychange',()=>{if(document.hidden)closePlans(false);});
9867
+ buildPlanSwitcher();
8976
9868
  // "Revert to an earlier version…" — a POINTER into the workspaces shell's History step, never a
8977
9869
  // revert of its own. The project version ledger already restores any version as a NEW version
8978
9870
  // (audited, itself undoable, and it re-locks exports); this item only makes it reachable from
@@ -9016,6 +9908,10 @@ if(canWriteModel()){
9016
9908
  }
9017
9909
  setPlan(C.active==null?0:C.active);
9018
9910
  applyReadOnlyChrome(); // …after setPlan, so the controls it touches are the ones the render just wired
9911
+ // ONE WORD FOR BOTH MODES. This said "Grid restored ✓" on a read-only document, on the premise that the
9912
+ // grid is the only thing such a draft can hold — which review disproved (see RO_DRAFT_KEYS: the overlay
9913
+ // swatches, the confidence target and the palette are ungated too). A chip that names the grid over a
9914
+ // restored confidence target is a smaller lie than the banner's was, but it is the same lie.
9019
9915
  setSaved(_restored?'ok':'idle', _restored?'Restored ✓':'Auto-save on');
9020
9916
  try{stage.focus({preventScroll:true});}catch(_){} // grab keyboard focus on open so shortcuts work before the first click
9021
9917
  // --- ?selftest=1 — cheap regression guard for the only non-trivial new math (local frame). Logs PASS/FAIL