@floless/app 0.104.2 → 0.105.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.
@@ -0,0 +1,691 @@
1
+ /*
2
+ * steel-model-commands.js — the WRITE side of the steel editor's model boundary (unit 5, P3).
3
+ *
4
+ * The read half is steel-model-adapter.js; this half mutates the live contract objects that adapter
5
+ * hands out. Same rules: pure, framework-free, node-tested from server/steel-model-commands.test.ts.
6
+ *
7
+ * DISPLAY SPACE IS THE CORE, WORLD MM IS A WRAPPER — and that order is deliberate. The contract stores
8
+ * per-sheet display pixels today, so pushing the 2D pick flow through mm would round-trip px→mm→px and
9
+ * change stored floats, breaking the characterization baseline that is this refactor's only proof of
10
+ * invariance. Only the callers that ALREADY speak mm (the 3D API, which converted inline at three sites
11
+ * with its own rounding each time) go through the mm wrappers. Pixels go away at v2 activation, not here.
12
+ *
13
+ * SCOPE — as of P3b-2a the MOVE/COPY FAMILY and the FOUR NAMED GEOMETRY OPERATIONS ARE CLOSED.
14
+ * Behind this boundary: `cmApplyOffsets` (2D pick + HUD + the 3D transform commit), `onCopyDrag3d`,
15
+ * `toLevelCommit`, `doDup`, the 2D Ctrl+drag copy and its live translate, `onMoveMember` — and now
16
+ * `addMember` (all three paths: `drawClick`, `addFromSeg`, `onAddMember3d`), `moveEndpoint` (the 2D handle
17
+ * drag AND the 3D `onMoveEndpoint`, which are two different sites), `doSplit`, and `snapEndMulti`.
18
+ * `view3dApi.onSplit` and `onTrimExtend` delegate to the last two, so the 3D entry points come with them.
19
+ * `cloneMember`, `translateMembers` and `retargetTos` are DELETED from the editor.
20
+ *
21
+ * P3b-2b closed the last four: `swapMemberEnds` (member reverse), `_dpCommit` (the inspector's
22
+ * definition-point coordinate fields), `dimEditCommit` (a typed dimension value driving a pinned member),
23
+ * and the dim-grip drag inside the `dimend` pointermove. All four reused the primitives above; none needed
24
+ * a new one.
25
+ *
26
+ * SO: NO MEMBER WORK-POINT WRITER BYPASSES THIS SEAM ANY MORE. A sweep of `web/steel-editor.html` for
27
+ * `.wp =` / `.wp[i] =` now returns exactly three hits, and none is a live geometry write:
28
+ * `mergeCollinearJS` (which mutates a DETACHED local copy rather than a contract member), `doDup`'s
29
+ * already-routed line (matched on the `c.wp=[[…],[…]]` in its TRAILING COMMENT, not on code), and one
30
+ * `?selftest=1` fixture. The middle one is why P3c-3b's guard must PARSE rather than grep.
31
+ *
32
+ * P3c-1 CLOSED THE ELEVATION FAMILY — the second axis, and the first thing this boundary owns that is not
33
+ * geometry. Sixteen statements routed across nine sites: `swapMemberEnds` (both the `m.ends` reorder and
34
+ * the `m.col` swap this module's previous header called out as unclaimed), `syncDefaults`, the "reset all
35
+ * ends to default" button, BOTH inspectors' TOS checkbox + input handlers, BOTH inspectors' BOS inputs,
36
+ * BOTH `matchEnds` buttons, `_dpCommit`'s three `zChg` branches, `onElevateMember` and `onBasePick`.
37
+ * A sweep for `.tos =` / `.bos =` / `.tosDef =` now returns ZERO hits.
38
+ *
39
+ * The remaining `.ends =` / `.col =` writes are all MEMBER CONSTRUCTION, deliberately out of scope:
40
+ * `doSplit`'s fresh end objects on the two halves, `onAddMember3d` building a new member's initial shape,
41
+ * and `mergeCollinearJS` on its detached copy. Building a member and re-elevating one are different
42
+ * operations; a member constructor is its own unit, and P3c-3's review round 2 (D7) confirmed it is NOT
43
+ * P3c-3's — an earlier version of this line labelled it so. `m.brace.*` is likewise still unclaimed.
44
+ *
45
+ * P3c-2a GREW THE FIRST PLAN-LEVEL SURFACE — the first thing this boundary owns that is not addressed by
46
+ * member. Fifteen statements routed: the grid OBJECT's identity (`gridEnsureForLine`'s construction,
47
+ * `gridReadFromDrawing`, the Auto / Blank / re-infer / Remove buttons), its LINE COLLECTION
48
+ * (`gridAddFreeLine`, both deletes — the inspector's `deleteSelGrids` and the keyboard Delete's bundled
49
+ * edit — "Clear lines", both branches of `gridRenameBubble`, and the live free-line drag), and
50
+ * `P.default_tos` at both its writers (`#defTos` and `setPlan`).
51
+ *
52
+ * A sweep of `web/steel-editor.html` for `P.grid =`, `P.grid.lines`, `delete P.grid.lines` and
53
+ * `.default_tos =` now returns only Class-B lifecycle writers (below).
54
+ *
55
+ * The scoping note called this family "~10 writers, all plan-level". Measured, the grid is ~35 statements
56
+ * across TWO files, so P3c-2 is two PRs split by write SHAPE — see the plan for the argument.
57
+ *
58
+ * P3c-2b CLOSED THE GRID FAMILY. Twenty-one more statements — every SCALAR key of the grid object
59
+ * (`on`, `origin`, `x`, `y`, `z`, `labels_x`, `labels_y`, `labels_z`, `hidden_z`, `ext`, `ends_x`,
60
+ * `ends_y`) across the grid inspector's six `wire()` handlers, both `[data-z*]` handlers,
61
+ * `#gridResetExtB`, `#gridDropZLabels`, `gridSetVisible` and the armed origin pick — all through
62
+ * `patchGrid`, whose `undefined`-means-delete convention finally has real callers.
63
+ *
64
+ * **A sweep of `web/steel-editor.html` for `P.grid` now returns ZERO writes.** Not "only Class-B ones":
65
+ * zero. The lifecycle writers listed below address the PLAN (`p.grid = …`), never `P.grid` itself.
66
+ *
67
+ * WHAT THAT CLAIM DOES *NOT* COVER, stated because the distinction is easy to lose:
68
+ * `web/grid-core.js` still contains the raw mutators. `moveGridLine` writes `g.origin[0|1]` plus
69
+ * `g.x`/`g.y`; `moveGridLineEnd` writes `g[key][i]` on a COMPUTED key and deletes both the entry and the
70
+ * key. This boundary owns their **entry points** — `moveGridLine` / `moveGridLineEnd` above, with `gc`
71
+ * injected — not the algorithm. So `grid-core.js` is a **declared allowlisted algorithm module**: P3c-3's
72
+ * static guard must name it, and must match **computed-key assignment and deletion** (`g[key][i] = …`,
73
+ * `delete g[key]`), because a guard shaped like `g.<key> =` sees none of it. That blind spot is exactly
74
+ * how this surface stayed invisible for three PRs.
75
+ *
76
+ * (`inferGrid`, `defaultGrid` and `gridFromDrawing` are NOT writers — they build a detached object the
77
+ * caller then assigns, and that assignment is what P3c-2a routed.)
78
+ *
79
+ * P3c-3a CLOSED THE MERGE WRITE — two statements, one site (`#mrgB`), but two different object graphs:
80
+ * `setPlanMembers` replaces `P.members` wholesale with the array `mergeCollinearJS` returned, and
81
+ * `detachDimRefs` deletes `d.aRef`/`d.bRef` on the active plan's DIMENSIONS for every merged id. The
82
+ * second is the only write this boundary owns that touches a dimension, which is why it is its own
83
+ * primitive rather than a flag on the first.
84
+ *
85
+ * WHAT THE ORDER ACTUALLY REQUIRES, stated precisely because the first draft of this header got it wrong
86
+ * (caught in review): the detach must complete before the next `render()`, because `render()` opens with
87
+ * `reanchorAllPlans()`. The survivor keeps the first segment's id with moved endpoints, so a ref left
88
+ * attached still RESOLVES, and `reanchorDim` would drag the dimension's anchor out to the merged member's
89
+ * new end with no toast and no error.
90
+ *
91
+ * `edit()` guarantees that for BOTH calls — it renders only after its callback returns — so the two are
92
+ * order-independent with respect to each other: `detachDimRefs` reads `plan.dims` and the id list, never
93
+ * `plan.members`. The call site keeps the original's order anyway, because a refactor that reorders
94
+ * statements is no longer only a refactor.
95
+ *
96
+ * A NOTE FOR THE GUARD: `d.aRef`/`d.bRef` are ROUTED here but deliberately NOT TRACKED by P3c-3b's static
97
+ * guard. Three non-merge writers exist — `reanchorDim`, `doSplit` and the `dimend` pointerup branch — so
98
+ * tracking the key would fail CI on day one. Dimensions belong to a later unit; the guard's output has to
99
+ * say that rather than let a green run imply the key is covered.
100
+ *
101
+ * P3c IS CLOSED. P3c-3b added the static guard — `npm run verify:boundary`
102
+ * (`server/build/verify-model-boundary.mjs`), wired into CI. It fails the build when a write to the
103
+ * P3-owned key set appears outside this module without an allowlist entry.
104
+ *
105
+ * READ ITS OUTPUT, NOT JUST ITS EXIT CODE. It is scoped to the P3-owned keys and to what a SYNTACTIC
106
+ * matcher can see, and it prints what it cannot see on every run (no count here on purpose — the list is
107
+ * the guard's, and it grows): every file except
108
+ * `steel-editor.html` (exactly one classic `<script>` is parsed), writes through a parameter (all of
109
+ * `grid-core.js`, and `sanitizeGridLines(g)`), writes through a local alias, array mutators
110
+ * (`P.members.push`), a key computed from a VARIABLE on an untracked receiver, reflective writes other
111
+ * than `Object.assign`/`defineProperty`/`defineProperties` (those three ARE matched), and every key
112
+ * outside the tracked set. `grid-core.js` and this module are reported as EXEMPT rather than clean,
113
+ * because "not examined" and "no violations" are different states.
114
+ *
115
+ * IT MATCHES A WRITE *INTO* A TRACKED KEY, not only a write OF one — `m.wp[i] = pt` and
116
+ * `m.wp[0] = a; m.wp[1] = b;` are exactly the bodies of `setEndpoint` and `setEndpointsInPlace` below, and
117
+ * the guard's first version was blind to both (found in P3c-3b's second review). A handler that inlines
118
+ * those two lines instead of calling them is the regression this guard exists to catch.
119
+ *
120
+ * Its allowlist is 11 entries over 30 tracked writes, MEASURED via `--list` rather than guessed — a first
121
+ * draft that guessed function names got four of nine wrong. Two categories, deliberately distinct:
122
+ * LIFECYCLE (should not be routed — undo/redo, the draft overlay, boot normalisation, the three
123
+ * delete-selection sites, `toLevelCommit`, and `setPlan`, which nests both its own member-list
124
+ * normalisation and the once-per-plan dedupe) and DETACHED-object builders (nothing TO route —
125
+ * `gridReadFromDrawing`, `#gridAutoB2` and `mergeCollinearJS` each write an object that a routed
126
+ * `ModelCmd` call then assigns). Adding a write inside an allowlisted function RAISES its count and fails;
127
+ * that is intentional, and it is why the allowlist keys on enclosing function plus count rather than on a
128
+ * DOM id (`getElementById('del').onclick` names two distinct sites). It is a tripwire for growth, not a
129
+ * proof of sameness — swapping one allowlisted write for another in the same function, for the same key,
130
+ * keeps the total equal and passes, so a diff touching an allowlisted function still wants human eyes.
131
+ *
132
+ * The `server/steel-merge.ts` reconciliation is DONE, by deletion: that module had zero production
133
+ * callers and had already drifted from the editor's `mergeCollinearJS` (it never gained the
134
+ * `affectedIds` the dim-ref detach depends on), so keeping it meant maintaining a second copy whose
135
+ * own header falsely called itself the source of truth. Its rules are now pinned against the live
136
+ * copy in `server/steel-editor-characterization.test.ts` ("merge (live copy): …"). (P3c-3c.)
137
+ *
138
+ * Separately, a class of writers P3c's guard must ALLOWLIST rather than route, because they are document
139
+ * lifecycle rather than member geometry. Named by IDENTIFIER, so the guard's allowlist can key off source
140
+ * rather than off a label: undo/redo `apply()`, autofill hydration, delete-selection, **`restoreSaved`**
141
+ * (the localStorage draft overlay — not a sheet import, which is what an earlier version of this list
142
+ * called it), `sanitizePlanGrid` / `sanitizeGridLines` boot normalisation, and the `?selftest=1` fixtures.
143
+ *
144
+ * Search for the function names rather than trusting a line number — every line number in this header's
145
+ * previous version was stale within one PR, twice.
146
+ */
147
+
148
+ const FT_MM = 304.8;
149
+ const IN_MM = 25.4;
150
+
151
+ /** Display-pixel scale for one plan, identical to the adapter's `scaleOf`. Change one, change both. */
152
+ const scaleOf = (plan) => FT_MM / (plan && plan.pt_per_ft > 0 ? plan.pt_per_ft : 1);
153
+
154
+ /** Kill float noise before it persists into `wp` — the same r6 the three inline call sites applied. */
155
+ const r6 = (n) => Math.round(n * 1e6) / 1e6;
156
+
157
+ /**
158
+ * World-mm offsets → one plan's display-pixel offsets, with dz in INCHES. Order is preserved because
159
+ * copy order is offset-major and therefore observable in the stored contract.
160
+ *
161
+ * Y IS NEGATED: display Y grows down, world Y grows up the plan — the inverse of the adapter's
162
+ * `dispToMm`. A ROUNDED inverse, not an exact one: `r6` quantises to 6dp, so a round trip lands within
163
+ * ~1e-5 mm rather than exactly. The tests assert the quantised values rather than pretending otherwise,
164
+ * because the quantisation is the pre-existing behaviour being preserved.
165
+ */
166
+ export function mmToDispOffsets(plan, offsMm) {
167
+ const k = scaleOf(plan);
168
+ return offsMm.map(o => [r6(o[0] / k), r6(-o[1] / k), r6((o[2] || 0) / IN_MM)]);
169
+ }
170
+
171
+ /** Normalise a member's optional metadata in place. Moved verbatim from steel-editor.html's `function ensureMeta`. */
172
+ export function ensureMeta(m) {
173
+ if (!m.role) m.role = 'beam';
174
+ const moment = /(^|[^A-Z])MF/i.test(m.profile || '') ? 'moment' : '';
175
+ if (!m.ends) m.ends = [{ tos: null, note: moment, tosDef: true, detail: '' },
176
+ { tos: null, note: moment, tosDef: true, detail: '' }];
177
+ if (!m.col) m.col = { bos: null, tos: null, note: moment, tosDef: true, detail: '' };
178
+ return m;
179
+ }
180
+
181
+ /**
182
+ * Re-datum a member's T.O.S when it changes level. An end still linked to its level default (`tosDef` not
183
+ * false) re-datums to the new default outright; an overridden end shifts by the delta so the override is
184
+ * preserved. A column's `bos` always shifts by the delta, which is what keeps its height.
185
+ *
186
+ * NOTE which branches actually read `srcDef`: only the overridden end and the column's `bos`. A
187
+ * default-following end is assigned `dstDef` and never sees it — so a test fixture whose members all
188
+ * follow their sheet default cannot discriminate the per-source datum read at all.
189
+ *
190
+ * Moved verbatim from steel-editor.html (unit 5, P3b-1).
191
+ */
192
+ export function retargetTos(m, srcDef, dstDef) {
193
+ const d = dstDef - srcDef; ensureMeta(m);
194
+ if (m.role === 'column') {
195
+ if (m.col.tosDef !== false) m.col.tos = dstDef; else if (m.col.tos != null) m.col.tos += d;
196
+ if (m.col.bos != null) m.col.bos += d;
197
+ } else for (const en of m.ends) { if (en.tosDef !== false) en.tos = dstDef; else if (en.tos != null) en.tos += d; }
198
+ return m;
199
+ }
200
+
201
+ /* ------------------------------------------------------------------ the ELEVATION family (unit 5, P3c-1)
202
+ *
203
+ * A SECOND AXIS, not more geometry. Everything P3a–P3b-2b closed writes `m.wp`; these write `tos`, `bos`
204
+ * and `tosDef` on `m.col` / `m.ends[i]`. They are free functions rather than methods on
205
+ * `createModelCommands` because not one of them needs the contract, the active plan or the id policy —
206
+ * and `onElevateMember` in particular must NOT reach for the boundary's `defaultTosIn` (see `elevateBy`).
207
+ *
208
+ * One primitive per distinct WRITE SHAPE, not per call site. Consolidating further would unify behaviours
209
+ * that genuinely differ today, and reproducing those differences exactly is the point of a refactor.
210
+ */
211
+
212
+ /** The elevation-carrying objects of a member: a column's single `col`, or a beam's two `ends`. */
213
+ export function elevTargets(m) {
214
+ ensureMeta(m);
215
+ return m.role === 'column' ? [m.col] : m.ends;
216
+ }
217
+
218
+ /**
219
+ * A typed elevation value: set it and drop the "follows the level default" link.
220
+ *
221
+ * The two inspector inputs (`wireTos`, `wMTos`) and BOTH of `_dpCommit`'s tos branches do exactly this.
222
+ * `tosDef=false` is NOT redundant with the checkbox having been unticked — a user can type into the field
223
+ * of an end that is still following the default, and that keystroke is what breaks the link.
224
+ */
225
+ export function setTosValue(target, tos) { target.tos = tos; target.tosDef = false; }
226
+
227
+ /**
228
+ * The "default" checkbox: store the flag, and re-datum to `defTos` ONLY when turning it back ON.
229
+ *
230
+ * ASYMMETRIC ON PURPOSE. Turning it OFF leaves `tos` exactly where it was, so the field the user is about
231
+ * to edit shows the value they were looking at. Restoring some previously-stored override on the way out
232
+ * would be a feature, not this refactor. `applyTosAll` reuses this with `on=true` over every target,
233
+ * which is precisely its body.
234
+ */
235
+ export function setTosDefault(target, on, defTos) { target.tosDef = on; if (on) target.tos = defTos; }
236
+
237
+ /** A column's base elevation. The inspector BOS inputs, `_dpCommit`'s Bottom branch, and `onBasePick`. */
238
+ export function setBos(col, bos) { col.bos = bos; }
239
+
240
+ /**
241
+ * Re-datum one member to a sheet default — `syncDefaults`, reached from BOTH `setPlan`'s boot path and
242
+ * the live Default-TOS input, which is why it is Class A and not a lifecycle allowlist entry.
243
+ *
244
+ * Three details that look like noise and are not:
245
+ * - it re-datums only ends still FOLLOWING the default; an override survives. That is the whole
246
+ * difference from `applyTosAll`, which overwrites everything.
247
+ * - the `defTos != null` guard is LOCAL to this writer. The other elevation writers have no such guard,
248
+ * so hoisting it into `setTosValue` would change three other call sites.
249
+ * - it materialises `col.bos = 0` when null, and does so even when `defTos` IS null. Only the `tos`
250
+ * writes sit behind that guard.
251
+ */
252
+ export function syncToDefault(m, defTos) {
253
+ ensureMeta(m);
254
+ if (m.role === 'column') {
255
+ if (m.col.tosDef !== false && defTos != null) m.col.tos = defTos;
256
+ if (m.col.bos == null) m.col.bos = 0;
257
+ } else for (const en of m.ends) if (en.tosDef !== false && defTos != null) en.tos = defTos;
258
+ return m;
259
+ }
260
+
261
+ /**
262
+ * Raise or lower by `dIn` inches — the 3D Alt-drag (`onElevateMember`).
263
+ *
264
+ * `base` IS INJECTED, and that is the single most important thing about this function. The caller reads
265
+ * the OWNING SHEET's `default_tos`; the boundary's own `defaultTosIn` is the editor GLOBAL, which
266
+ * `translate` uses. Those two datums disagree, the disagreement is pre-existing, and this module's header
267
+ * already records that reproducing it exactly — rather than quietly unifying it — is the job. Resolving
268
+ * `base` in here would unify them invisibly.
269
+ *
270
+ * A column rises RIGIDLY: `bos` shifts too (null → `0 + dIn`), so the column is moved, not stretched.
271
+ */
272
+ export function elevateBy(m, dIn, base) {
273
+ ensureMeta(m);
274
+ if (m.role === 'column') {
275
+ m.col.tos = (m.col.tos != null ? m.col.tos : base) + dIn;
276
+ m.col.bos = (m.col.bos != null ? m.col.bos : 0) + dIn;
277
+ m.col.tosDef = false;
278
+ } else m.ends.forEach(en => { en.tos = (en.tos != null ? en.tos : base) + dIn; en.tosDef = false; });
279
+ return m;
280
+ }
281
+
282
+ /**
283
+ * Swap a column's top and bottom — the `m.col` half of `swapMemberEnds`.
284
+ *
285
+ * BOTH sides materialise first: `bos` null → 0 and `tos` null → `defTos`. Reading them before assigning
286
+ * either is what makes this a swap rather than a copy, and the temporaries are not stylistic.
287
+ * `tosDef` is forced false because a swapped top is by definition no longer the level default.
288
+ *
289
+ * Applied to ANY member carrying a `col`, which after `ensureMeta` is every member — a beam's vestigial
290
+ * `col` is swapped too. That is what the editor does today, and it is observable in the stored contract.
291
+ */
292
+ export function swapColElevation(col, defTos) {
293
+ const b = (col.bos != null ? col.bos : 0), t = (col.tos != null ? col.tos : defTos);
294
+ col.bos = t; col.tos = b; col.tosDef = false;
295
+ return col;
296
+ }
297
+
298
+ /**
299
+ * Reverse a member's two ends — the `m.ends` half of `swapMemberEnds`.
300
+ *
301
+ * REPLACES the outer array rather than swapping in place, exactly as the editor does. The distinction is
302
+ * reference identity, which serializes identically, so the characterization baseline cannot see it; the
303
+ * unit tests pin it instead. Same argument as `replaceEndpoints` vs `setEndpointsInPlace`.
304
+ *
305
+ * The caller keeps its own `length >= 2` guard: a member reaching here with one end is broken, and
306
+ * swallowing that here would hide it at every call site.
307
+ */
308
+ export function reverseEnds(m) { m.ends = [m.ends[1], m.ends[0]]; return m; }
309
+
310
+ /**
311
+ * Copy one end onto the other — the inspector's "Match ends", in both the single and multi panels.
312
+ *
313
+ * SIX KEYS, LISTED, and deliberately not a spread or a deep copy. The literal DROPS any other key the
314
+ * source end carries, and that dropping is real stored behaviour. It also builds a FRESH object, so the
315
+ * two ends never alias — which matters the moment anything edits one of them afterwards.
316
+ */
317
+ export function copyEndTo(m, from, to) {
318
+ const s = m.ends[from];
319
+ m.ends[to] = { tos: s.tos, note: s.note, tosDef: s.tosDef, detail: s.detail, conn: s.conn, connVerified: s.connVerified };
320
+ return m;
321
+ }
322
+
323
+ /* ------------------------------------------------------------------ the PLAN-LEVEL surface (P3c-2a)
324
+ *
325
+ * The first thing this boundary owns that is not a member. Everything above is addressed by member; the
326
+ * grid and the sheet datum belong to the PLAN, so these take the plan explicitly rather than reading an
327
+ * `activePlan` captured at construction — several of their callers already hold a plan that is not the
328
+ * active one, and `setPlan` runs one of them mid-switch, when "active" is ambiguous.
329
+ *
330
+ * They are module-level exports, called as `ModelCmd.<fn>(…)`, exactly like the elevation set above: they
331
+ * need none of `createModelCommands`' captured `contract` / `activePlan` / `defaultTosIn` / `mintId`.
332
+ *
333
+ * WRITES ONLY. A `planGrid(plan)` selector was drafted alongside these and cut before merge: it had no
334
+ * caller anywhere, and its docblock claimed a pairing with the mutators that did not exist in the code.
335
+ * The elevation set's `elevTargets` earns its place by having one. P3c-2b routes the grid READS (
336
+ * `renderGridPanel`'s `const g = P.grid`, and the two delete sites' `Array.isArray(P.grid.lines)` guard),
337
+ * and a selector should arrive with them rather than one PR ahead, unused.
338
+ */
339
+
340
+ /**
341
+ * Replace the plan's grid outright — the detected grid, the inferred one, the blank one, and (with
342
+ * `null`) Remove. Every caller has already BUILT the object; the merge logic that makes "re-infer but
343
+ * keep my levels" different from "infer" runs on that detached object, before it gets here.
344
+ */
345
+ export function setPlanGrid(plan, grid) { plan.grid = grid; return plan; }
346
+
347
+ /**
348
+ * Create a grid ONLY when the plan has none — `gridEnsureForLine`, which the free-line tool calls before
349
+ * every single add.
350
+ *
351
+ * THE GUARD STAYS IN HERE. Hoisting it to the caller turns this into an unconditional constructor, and
352
+ * `gridAddFreeLine` would then wipe the user's grid every time they drew a line. `make` is a thunk rather
353
+ * than a value so the caller does not build a grid it is about to throw away.
354
+ */
355
+ export function ensurePlanGrid(plan, make) {
356
+ if (plan.grid) return plan.grid;
357
+ plan.grid = make();
358
+ return plan.grid;
359
+ }
360
+
361
+ /**
362
+ * Append a free grid line, materialising `lines` when the grid has none.
363
+ *
364
+ * MUTATES the existing array rather than replacing it: `refreshGridLayer` and the live drag read
365
+ * `P.grid.lines` while a gesture is in flight, and JSON cannot see reference identity — so the difference
366
+ * is invisible to the characterization baseline and has to be preserved by construction.
367
+ */
368
+ export function addGridLine(grid, line) {
369
+ if (!Array.isArray(grid.lines)) grid.lines = [];
370
+ grid.lines.push(line);
371
+ return grid;
372
+ }
373
+
374
+ /**
375
+ * Drop free grid lines BY STABLE ID. Both callers reach this only when at least one line matches, and
376
+ * both are guarded upstream on `Array.isArray(grid.lines)` — the guard is repeated here so the two sites
377
+ * keep their identical shape rather than one of them gaining a throw the other has not got.
378
+ *
379
+ * By id, never by index: `gridLines()` skips degenerate entries, so a geometry index and a stored index
380
+ * can diverge. The editor's own keyboard-Delete comment already says so.
381
+ */
382
+ export function removeGridLines(grid, ids) {
383
+ if (!grid || !Array.isArray(grid.lines)) return grid;
384
+ grid.lines = grid.lines.filter(l => !ids.has(String(l.id)));
385
+ return grid;
386
+ }
387
+
388
+ /**
389
+ * "Clear lines" — DELETES the key; it does not assign `[]`.
390
+ *
391
+ * `sanitizeGridLines` also deletes when the list empties, and whether the key is present is observable in
392
+ * the stored contract. `= []` would be a data change wearing a refactor's clothes.
393
+ */
394
+ export function clearGridLines(grid) { delete grid.lines; return grid; }
395
+
396
+ /**
397
+ * Rename one free grid line, addressed by INDEX into the stored array — the bubble rename.
398
+ *
399
+ * The index comes from resolved GEOMETRY while the write lands in stored data, and those two orders can
400
+ * diverge (see `removeGridLines`). That is pre-existing behaviour, reproduced deliberately: no reachable
401
+ * editor state can construct the skew today, so changing it would be an unobservable behaviour change
402
+ * made on a hunch. `steel-model-commands.test.ts` pins the semantics so a later move to id-addressing has
403
+ * to be deliberate.
404
+ */
405
+ export function setGridLineLabel(grid, i, label) {
406
+ if (grid.lines && grid.lines[i]) grid.lines[i].label = label;
407
+ return grid;
408
+ }
409
+
410
+ /**
411
+ * Move a free grid line's two endpoints — the live drag, once per `pointermove`.
412
+ *
413
+ * ABSOLUTE, never relative, for the same reason `setEndpointsInPlace` is: the caller resolves both points
414
+ * from the GRAB-TIME origin every frame, so a relative primitive would accumulate the delta per mouse
415
+ * event. With a single pointermove the two are numerically identical, which is why the characterization
416
+ * op fires two.
417
+ */
418
+ export function setGridLineEnds(line, a, b) { line.a = a; line.b = b; return line; }
419
+
420
+ /**
421
+ * Assign grid keys, `undefined` meaning DELETE.
422
+ *
423
+ * The delete convention is not sugar: five existing sites conditionally delete
424
+ * (`if (hidden.length) grid.hidden_z = hidden; else delete grid.hidden_z`), and a separate
425
+ * `deleteGridKeys` would double the primitive count for one statement. P3c-2b routes the rest of the
426
+ * scalar surface through here; P3c-2a has one caller, the regular-line bubble rename, because splitting
427
+ * `gridRenameBubble` across two PRs would be worse than landing this one primitive early.
428
+ */
429
+ export function patchGrid(grid, patch) {
430
+ for (const k of Object.keys(patch)) {
431
+ if (patch[k] === undefined) delete grid[k];
432
+ else grid[k] = patch[k];
433
+ }
434
+ return grid;
435
+ }
436
+
437
+ /** The plan's own T.O.S datum. Distinct from the editor's GLOBAL `defaultTOS` — see `elevateBy`. */
438
+ export function setPlanDefaultTos(plan, tos) { plan.default_tos = tos; return plan; }
439
+
440
+ /**
441
+ * Replace a plan's member list WHOLESALE — the merge (`#mrgB`), which swaps in the array
442
+ * `mergeCollinearJS` returned rather than editing members in place.
443
+ *
444
+ * DELIBERATELY NOT `addMembers`/`removeMembers`: those keep the existing array and mutate it, and this
445
+ * assigns a new one.
446
+ *
447
+ * IT ASSIGNS BY REFERENCE BECAUSE THE INLINE ORIGINAL DID — not because anything depends on it. An
448
+ * earlier draft of this comment claimed a copy would "change which objects the editor holds"; that is
449
+ * FALSE and review caught it. A `slice()` preserves every member OBJECT reference and only replaces the
450
+ * array wrapper, nothing retains `r.members` afterwards, and a sandbox mutation to `slice()` left all 62
451
+ * characterization tests green. So the difference is invisible to the baseline, which is exactly why the
452
+ * unit test pins it directly: preserving it is by construction rather than by luck.
453
+ *
454
+ * No normalisation, no `ensureMeta`, no filtering — the merge already produced a complete list, and adding
455
+ * any of that would be a behaviour change wearing a refactor's clothes.
456
+ */
457
+ export function setPlanMembers(plan, members) { plan.members = members; return plan; }
458
+
459
+ /**
460
+ * Drop every dimension anchor pointing at one of `ids` — the merge's dim-ref detach.
461
+ *
462
+ * WHY IT EXISTS AT ALL: the survivor of a merged run KEEPS the first segment's id with MOVED endpoints, so
463
+ * a ref to it still resolves. Without this, `reanchorDim` silently drags the dimension's anchor from the
464
+ * old junction out to the merged member's new end — no toast, no error, a changed reading.
465
+ *
466
+ * A DIFFERENT OBJECT GRAPH from every other mutator here, which is why it is its own primitive rather than
467
+ * a flag on `setPlanMembers`: it deletes a member-shaped key off a DIMENSION. It is also the only write
468
+ * this boundary owns that P3c-3b's guard deliberately does NOT police — `d.aRef`/`d.bRef` have three
469
+ * non-merge writers (`reanchorDim`, `doSplit`, the `dimend` pointerup), so tracking the key would fail CI
470
+ * on day one. Routed, not guarded, until the dimensions unit runs.
471
+ *
472
+ * Takes the id ITERABLE and ALWAYS copies it into a Set, exactly as the inline original did. Reusing a
473
+ * caller's Set would be marginally faster and is deliberately not done: it would make the primitive's
474
+ * result depend on that Set staying unmodified (and on its `has` not being overridden) where the original
475
+ * never could. A refactor that widens semantics is not a refactor.
476
+ *
477
+ * PLAN-SCOPED, not model-wide: the loop is `plan.dims`, matching the original's `P.dims`. The distinction
478
+ * is real in a multi-sheet contract and this codebase keeps it elsewhere too (`resolveDimAnchor` is
479
+ * likewise strictly plan-scoped).
480
+ *
481
+ * `d[rk].m` is `undefined` for a GRID anchor (`{g:…}`). Those survive because `undefined` is not IN the id
482
+ * set — NOT because this checks for it. `mergeCollinearJS` builds `affectedIds` with `.filter(Boolean)`,
483
+ * so that filter is load-bearing: pass an unfiltered list and every grid-anchored dimension ON THIS PLAN
484
+ * unlinks at once. Inherited from the inline original and preserved deliberately rather than endorsed —
485
+ * hardening it here would be a behaviour change, so it is pinned by a test instead.
486
+ */
487
+ export function detachDimRefs(plan, ids) {
488
+ const aff = new Set(ids);
489
+ for (const d of (plan.dims || [])) for (const rk of ['aRef', 'bRef']) if (d[rk] && aff.has(d[rk].m)) delete d[rk];
490
+ return plan;
491
+ }
492
+
493
+ /**
494
+ * The regular-grid-line drag, delegating to `grid-core`'s `moveGridLine` — which mutates the LIVE grid
495
+ * (`g.origin[0|1]` plus `g.x`/`g.y`) rather than returning a new one.
496
+ *
497
+ * `gc` IS INJECTED, the way `elevateBy` takes `base`. `grid-core.js` is loaded through the editor's
498
+ * module shim (`GC()`), so importing it here would fix a load order this module has no business owning —
499
+ * and the injection keeps the seam visible instead of hiding a second write surface behind an import.
500
+ *
501
+ * WHY A PASS-THROUGH IS NOT CEREMONY: `moveGridLine` converts px→mm inline (`mmPerPx(ptPerFt)`) and emits
502
+ * a *spacing string*. Centralising that conversion is the entire point of v2, and this wrapper is where
503
+ * the interception will have to go. It looks thin today and is load-bearing later.
504
+ *
505
+ * `base` MUST be forwarded, not recomputed: it is the drag-start positions, and it exists so one gesture
506
+ * quantises the string ONCE — re-reading the just-written string each move lets 1/16" rounding creep onto
507
+ * lines that never moved.
508
+ *
509
+ * AND IT MUST RETURN. The caller feeds `(applied != null ? applied : np)` into the cursor readout, so a
510
+ * wrapper that mutates correctly but drops the return value leaves the stored contract — and therefore
511
+ * the whole characterization baseline — green while the readout reports the raw pointer position instead
512
+ * of the clamped or snapped one.
513
+ */
514
+ export function moveGridLine(gc, grid, ptPerFt, axis, i, np, base) {
515
+ return gc.moveGridLine(grid, ptPerFt, axis, i, np, base);
516
+ }
517
+
518
+ /**
519
+ * The bubble-end drag, delegating to `grid-core`'s `moveGridLineEnd` — the per-line extent override.
520
+ *
521
+ * Same injection and same return contract as `moveGridLine`. Note what it writes: `g[key][i]` on a
522
+ * COMPUTED key (`ends_x`/`ends_y`), and `delete g[key][i]` — then `delete g[key]` once no line has an
523
+ * override left. No sweep or static guard shaped like `g.<key> =` can see any of that, which is exactly
524
+ * how this surface stayed invisible for three PRs.
525
+ */
526
+ export function moveGridLineEnd(gc, grid, ptPerFt, axis, i, end, np) {
527
+ return gc.moveGridLineEnd(grid, ptPerFt, axis, i, end, np);
528
+ }
529
+
530
+ /**
531
+ * The write half of the model boundary over one contract.
532
+ *
533
+ * `activePlan` is the plan OBJECT, not a sheet label: v1 does not enforce unique sheet names and the
534
+ * editor's own `P` is `C.plans[C.active]`, so resolving by label would silently pick the first duplicate.
535
+ *
536
+ * `defaultTosIn` is the editor's GLOBAL default T.O.S in inches. `translateMembers` reads that global
537
+ * while the editor's `onElevateMember` reads the owning sheet's `default_tos` (and documents why it does). The inconsistency is pre-existing; reproducing it exactly is the point of a refactor, and
538
+ * fixing it is a behaviour change that needs its own PR and its own baseline diff.
539
+ *
540
+ * `mintId` keeps id policy in the editor, where the characterization harness pins `Date.now()`.
541
+ */
542
+ export function createModelCommands(contract, { activePlan, defaultTosIn, mintId } = {}) {
543
+ /** Translate in DISPLAY PIXELS with dz in inches — the moved `translateMembers`. */
544
+ const translate = (members, off) => {
545
+ const dz = off[2] || 0;
546
+ for (const m of members) {
547
+ ensureMeta(m);
548
+ m.wp[0] = [m.wp[0][0] + off[0], m.wp[0][1] + off[1]];
549
+ m.wp[1] = [m.wp[1][0] + off[0], m.wp[1][1] + off[1]];
550
+ if (dz) {
551
+ if (m.role === 'column') {
552
+ m.col.tos = (m.col.tos != null ? m.col.tos : defaultTosIn) + dz;
553
+ m.col.bos = (m.col.bos != null ? m.col.bos : 0) + dz;
554
+ m.col.tosDef = false;
555
+ } else {
556
+ m.ends.forEach(en => {
557
+ en.tos = (en.tos != null ? en.tos : defaultTosIn) + dz;
558
+ en.tosDef = false;
559
+ });
560
+ }
561
+ }
562
+ }
563
+ };
564
+
565
+ /**
566
+ * Deep copy + a fresh id. NO translate, NO normalisation, NO push — byte-for-byte the editor's old
567
+ * `cloneMember`, which is what makes this a refactor rather than a behaviour change.
568
+ *
569
+ * `mint` is a per-call override because id policy is NOT uniform: `doDup` mints
570
+ * 'm'+Date.now()+'_'+(i++) with its own counter while everything else mints 'm'+Date.now()+'_c'+(cmSeq++).
571
+ * Both land in the stored contract, so collapsing them to one policy would be a data change wearing a
572
+ * refactor's clothes.
573
+ */
574
+ const clone = (src, mint) => {
575
+ const c = JSON.parse(JSON.stringify(src));
576
+ c.id = (mint || mintId)();
577
+ return c;
578
+ };
579
+
580
+ /**
581
+ * Append to a plan. Deliberately does NOT materialise a missing `members` array: `toLevelCommit`
582
+ * materialises it BEFORE its `snapshot()`, and moving that here would let a non-array value be captured
583
+ * into the undo entry, where restore code calling `.map()` on it breaks.
584
+ */
585
+ const addMembers = (plan, members) => { plan.members.push(...members); return plan; };
586
+
587
+ /** Drop these ids from EVERY plan. Model-wide by design — a selection spans sheets. */
588
+ const removeMembers = (ids) => {
589
+ for (const pl of (contract.plans || [])) pl.members = (pl.members || []).filter(m => !ids.has(m.id));
590
+ };
591
+
592
+ /**
593
+ * Replace the whole `wp` array — the 3D member drag (`onMoveMember`), which assigns the array the 3D
594
+ * module built.
595
+ */
596
+ const replaceEndpoints = (member, wp) => { member.wp = wp; };
597
+
598
+ /**
599
+ * Write both endpoints, KEEPING the outer array — the 2D grab drag, which does `m.wp[0]=…; m.wp[1]=…`.
600
+ *
601
+ * The distinction from `replaceEndpoints` is reference identity, which serializes identically, so the
602
+ * characterization baseline cannot see it. Two primitives rather than one is the only way that
603
+ * difference is preserved by construction instead of by luck.
604
+ *
605
+ * ABSOLUTE, never relative: the caller fires this once per `pointermove` from the grab-time origin, so a
606
+ * relative primitive would accumulate the delta per mouse event and fling the member off the sheet.
607
+ */
608
+ const setEndpointsInPlace = (member, a, b) => { member.wp[0] = a; member.wp[1] = b; };
609
+
610
+ /**
611
+ * Write ONE endpoint, addressed by index, keeping the outer `wp` array — `snapEndMulti` (index computed
612
+ * from which end is nearer the intersection), the 2D handle drag, and the 3D end-node callback.
613
+ *
614
+ * The index is DATA at two of the three sites, which is why this is not expressed through
615
+ * `setEndpointsInPlace` with the untouched endpoint passed back in. That would be behaviourally
616
+ * identical — a self-assign preserves both value and reference identity — but it reads as a bug at every
617
+ * call site, and reconstructing the endpoint you did not mean to touch is exactly where an off-by-one
618
+ * lives.
619
+ *
620
+ * ABSOLUTE, never relative: the 2D drag fires this once per `pointermove` with a snapped absolute point
621
+ * and the 3D view hands over an absolute one, so a relative primitive would accumulate per event.
622
+ *
623
+ * No `wp`-shape guard on purpose. `onMoveEndpoint` checks `Array.isArray(m.wp)` before calling, and
624
+ * moving that guard in here would silence a broken member at the other two sites too.
625
+ */
626
+ const setEndpoint = (member, i, pt) => { member.wp[i] = pt; };
627
+
628
+ const cloneOnto = (src, plan, off) => {
629
+ const c = clone(src);
630
+ translate([c], off);
631
+ plan.members = plan.members || []; // cloneOnto's own callers rely on this; addMembers does not do it
632
+ addMembers(plan, [c]);
633
+ return c.id;
634
+ };
635
+
636
+ return {
637
+ translate, clone, addMembers, removeMembers, replaceEndpoints, setEndpointsInPlace, setEndpoint,
638
+ retargetTos,
639
+
640
+ /**
641
+ * The model half of `cmApplyOffsets` (the editor's `function cmApplyOffsets`), in display pixels.
642
+ *
643
+ * ORDER IS OFFSET-MAJOR, MEMBER-MINOR, matching the original's nested loop — clone ids are minted in
644
+ * that order, so the order lands in the stored contract and is not cosmetic. A move consumes only
645
+ * `offs[0]`, exactly as the original does. Returns the new ids for a copy, `[]` for a move.
646
+ */
647
+ applyOffsets(members, offsetsDisp, { copy } = {}) {
648
+ if (!copy) { translate(members, offsetsDisp[0]); return []; }
649
+ const made = [];
650
+ for (const off of offsetsDisp) for (const m of members) made.push(cloneOnto(m, activePlan, off));
651
+ return made;
652
+ },
653
+
654
+ /**
655
+ * World-mm offsets → rounded display offsets in the ACTIVE plan's scale. `sel2d()` is active-plan
656
+ * scoped (`const sel2d=()=>P.members.filter(...)`), so that is the correct scale for this selection.
657
+ *
658
+ * MUTATES NOTHING, deliberately. `onTransform3d`'s job is to convert and then hand off to
659
+ * `cmApplyOffsets`, which owns the empty-selection toast, the 100-copy cap, the distance toast and
660
+ * `panel()`. A method that also moved would apply every 3D transform twice.
661
+ *
662
+ * Returning the ROUNDED offsets is what keeps the toast identical: it measures distance from these
663
+ * same numbers today — `cmApplyOffsets` measures via `Math.hypot(offs[0]…)` — and recomputing from
664
+ * world mm would differ near a rounding threshold and for a missing or zero `pt_per_ft`.
665
+ */
666
+ toDisplayOffsets(offsMm) {
667
+ return mmToDispOffsets(activePlan, offsMm);
668
+ },
669
+
670
+ /**
671
+ * The 3D Ctrl+drag copy — the editor's `onCopyDrag3d:` entry on `view3dApi`. Each clone lands on ITS SOURCE's
672
+ * plane, converted at THAT plane's scale — two sheets at different `pt_per_ft` must not share one
673
+ * conversion.
674
+ *
675
+ * `planeOf` is INJECTED and must be the editor's own `const planeOf=id=>{…}` — NOT the adjacent `byId` or
676
+ * `planeOfMember`. It is first-match-by-id, falling back to the active plane. Member ids are only sheet-unique, so first-match differs from object identity on a
677
+ * collision. Substituting the "more correct" lookup here would be a behaviour change wearing a
678
+ * refactor's clothes; if it should change, that is its own PR with its own baseline diff.
679
+ */
680
+ copyDragMm(ids, offMm, planeOf) {
681
+ const made = [];
682
+ for (const id of (ids || [])) {
683
+ const plan = planeOf(id);
684
+ const src = (plan && Array.isArray(plan.members)) ? plan.members.find(m => m && m.id === id) : null;
685
+ if (!src) continue;
686
+ made.push(cloneOnto(src, plan, mmToDispOffsets(plan, [[offMm[0], offMm[1], 0]])[0]));
687
+ }
688
+ return made;
689
+ },
690
+ };
691
+ }