@floless/app 0.153.0 → 0.155.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.
Files changed (53) hide show
  1. package/dist/floless-server.cjs +51767 -38222
  2. package/dist/schemas/revit.model.v1.schema.json +5 -0
  3. package/dist/schemas/steel.model.v2.schema.json +19 -5
  4. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -2
  5. package/dist/skills/floless-app-onboarding/SKILL.md +31 -19
  6. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +20 -11
  7. package/dist/skills/floless-app-queue/SKILL.md +23 -4
  8. package/dist/skills/floless-app-steel-model/SKILL.md +23 -2
  9. package/dist/skills/floless-app-steel-takeoff/SKILL.md +158 -65
  10. package/dist/skills/floless-app-workflows/SKILL.md +23 -5
  11. package/dist/skills/floless-app-workflows/references/blender-exec.md +183 -0
  12. package/dist/skills/floless-app-workflows/references/dev-server-and-run-trace.md +27 -12
  13. package/dist/templates/blender-construction-sequence.flo +96 -0
  14. package/dist/web/agents.js +33 -13
  15. package/dist/web/app.css +331 -34
  16. package/dist/web/app.js +12 -1
  17. package/dist/web/aware.js +1167 -137
  18. package/dist/web/chat-question-card.js +477 -0
  19. package/dist/web/chat.css +237 -25
  20. package/dist/web/chat.js +2156 -889
  21. package/dist/web/commands-shell.js +578 -21
  22. package/dist/web/commands-steel.js +105 -4
  23. package/dist/web/guide.js +217 -16
  24. package/dist/web/index.html +104 -10
  25. package/dist/web/instructor.js +10 -9
  26. package/dist/web/left-pane.js +43 -6
  27. package/dist/web/media-player.js +234 -0
  28. package/dist/web/model-editor-contract.js +2 -0
  29. package/dist/web/model-editor-revit-adapter.js +1 -0
  30. package/dist/web/model-editor-steel-adapter.js +89 -1
  31. package/dist/web/model-panel-bridge.js +16 -2
  32. package/dist/web/model-view-query.js +590 -0
  33. package/dist/web/model-viewport-revit-adapter.js +15 -1
  34. package/dist/web/model-viewport-toolbar.js +5 -2
  35. package/dist/web/pages.js +592 -0
  36. package/dist/web/panels.js +2 -1
  37. package/dist/web/revit-editor.js +182 -16
  38. package/dist/web/run-progress.js +193 -0
  39. package/dist/web/run-strip.js +173 -0
  40. package/dist/web/steel-3d-core.js +70 -0
  41. package/dist/web/steel-editor.html +2751 -219
  42. package/dist/web/steel-frames-core.js +958 -0
  43. package/dist/web/steel-last-seen.js +315 -0
  44. package/dist/web/steel-marks-core.js +530 -0
  45. package/dist/web/steel-model-slim.js +95 -0
  46. package/dist/web/steel-model-v2-client-validation.js +14 -2
  47. package/dist/web/steel-model-v2-commands.js +258 -27
  48. package/dist/web/steel-model-v2-projection.js +78 -18
  49. package/dist/web/steel-read-confidence.js +11 -2
  50. package/dist/web/tekla-structural-grid-adapter.js +7 -1
  51. package/dist/web/tool-updates.js +141 -33
  52. package/dist/web/workspaces.js +446 -30
  53. package/package.json +3 -2
@@ -0,0 +1,958 @@
1
+ /**
2
+ * The moment-frame schedule — the girder sizes the Frame Elevations give each frame, per floor level — and the
3
+ * ONE rule for letting a revision read ADD to it (#2210).
4
+ *
5
+ * WHY THIS MODULE EXISTS. Before #2210 nothing could write `moment_frames` on a v2 model: a re-read was refused
6
+ * if it tried, no skill step told the AI to record it, and the Frames dialog only drew a table. So the
7
+ * girder-size suggestions in the member panel were unreachable. The owner ruled that the schedule must be
8
+ * recordable by a read (a person confirms it in Review & approve) AND addable by hand. Both go through the
9
+ * rules below, so a frame a person types and a frame the read proposes are checked by the same code.
10
+ *
11
+ * THE SAME PROPERTY AS THE CALLOUTS (steel-marks-core.js): **an incoming schedule can only ADD frames.**
12
+ * Stored rows are kept verbatim and in order, omission is a no-op, a frame that matches a stored one is
13
+ * reported as `differs` and never applied. A read can therefore never delete or overwrite a frame a person
14
+ * typed or corrected.
15
+ *
16
+ * PURE and framework-free (no DOM, no node: imports) so the server and the browser share one answer. Anything
17
+ * that needs a hash (deterministic ids) takes it as an argument.
18
+ *
19
+ * STRICTNESS IS IN CODE, NOT IN THE SCHEMA. `moment_frames` stays `{"type":"array"}`: stored models carry the
20
+ * legacy row `{grid, span:[2,3], roof:[…], second:[…], columns:[…]}` and one that stopped validating would fail
21
+ * every autosave. The validators here are applied ONLY to rows that are NEW to a document (a read adding one,
22
+ * a hand-add). A stored row is never re-validated, and a legacy row is rewritten into the new shape only when
23
+ * a person edits THAT row (`toV2Row`).
24
+ *
25
+ * ROW SHAPE (new):
26
+ * { id, grid, span: [from, to],
27
+ * girders: [ { level, elevationMm?, sizes: [designation…], views?: [planViewId…] } … ],
28
+ * columns: [designation…], source?: { sheet }, origin: 'read' | 'manual' }
29
+ *
30
+ * `level` is the name AS DRAWN ("Roof", "2nd floor", "3rd floor"): any number of levels, named by the person.
31
+ * `views` is the explicit "this sheet is this level" link (R1.6): the Frames dialog writes it, a read never
32
+ * does. It is the ONLY thing that ties a level to a sheet besides the legacy sheet-name fallback; the sheet's
33
+ * cut elevation is never overwritten by it.
34
+ * `origin` is stamped by whoever admitted the row, never trusted from the document. `source` is the drawing
35
+ * citation ("S-301") and is never touched.
36
+ *
37
+ * LEGACY ROW (read, never written by new code): `{grid, span, roof:[…], second:[…], columns}`. `normaliseFrameRow`
38
+ * shows it as the new shape WITHOUT mutating it: `roof` is the level "Roof", `second` is "2nd floor".
39
+ */
40
+ import { planViewId } from './steel-plan-view-id.js';
41
+ import { MODEL_V2_TOL } from './steel-3d-core.js';
42
+
43
+ /** NEEDS OWNER: most frames a read may ADD to one schedule. A schedule already past this is kept untouched. */
44
+ export const MOMENT_FRAMES_MAX = 200;
45
+ export const FRAME_GRID_MAX = 16;
46
+ export const FRAME_LEVEL_MAX = 64;
47
+ export const FRAME_SIZE_MAX = 48;
48
+ export const FRAME_SIZES_PER_LEVEL_MAX = 12;
49
+ export const FRAME_LEVELS_PER_ROW_MAX = 12;
50
+ export const FRAME_COLUMNS_MAX = 24;
51
+ export const FRAME_VIEWS_PER_LEVEL_MAX = 64;
52
+ const FRAME_ID_MAX = 96;
53
+ const FRAME_VIEW_ID_MAX = 96;
54
+ /**
55
+ * A plan's cut elevation and a level's stated elevation count as the same level within this. The tight
56
+ * drafting tolerance on purpose: a plan is cut at the floor and a girder level is usually stated at the top of
57
+ * steel, so a loose tolerance would link a sheet to the wrong floor. Looser links are made by hand.
58
+ */
59
+ export const LEVEL_MATCH_TOL_MM = MODEL_V2_TOL.CUT_PLANE_MM;
60
+
61
+ /**
62
+ * NEEDS OWNER: the sheet numbering of the ONE project this feature was first built for (S-202 was its second
63
+ * floor, S-203 its roof). Kept ONLY as the last resort, for LEGACY-shaped rows that no explicit link and no
64
+ * elevation can place, and shown with a visible "matched by sheet name" hint. Flagged for deletion.
65
+ */
66
+ export const LEGACY_SHEET_LEVELS = Object.freeze({ 'S-202': 'second', 'S-203': 'roof' });
67
+ const LEGACY_LEVEL_NAME = Object.freeze({ roof: 'Roof', second: '2nd floor' });
68
+ const LEGACY_KEYS = Object.freeze(['roof', 'second']);
69
+
70
+ const CONTROL = /[\u0000-\u001f\u007f]/;
71
+ const ID_PATTERN = /^[A-Za-z0-9._:\-/ ]{1,96}$/;
72
+
73
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
74
+ const finiteNumber = (v) => typeof v === 'number' && Number.isFinite(v);
75
+ const str = (v) => (v == null ? '' : String(v)).trim();
76
+ /**
77
+ * Set `obj[key]` as an OWN data property, whatever the key is called. `obj['__proto__'] = value` runs the legacy
78
+ * setter (it re-points the prototype, or does nothing for a non-object), so a key a stored row carries — and
79
+ * `JSON.parse` DOES make an own `"__proto__"` key — would silently not be copied. Any write into an object keyed
80
+ * by names a document supplied goes through here (the same helper as steel-marks-core.js).
81
+ */
82
+ function own(obj, key, value) {
83
+ Object.defineProperty(obj, key, { value, enumerable: true, writable: true, configurable: true });
84
+ return value;
85
+ }
86
+ /** A grid label or a span end: text, or a finite number a reader wrote without quotes. */
87
+ const labelOf = (v) => (typeof v === 'string' ? v.trim() : (finiteNumber(v) ? String(v) : ''));
88
+ const problem = (code, reason) => ({ code, reason });
89
+
90
+ // ── normalisation ──────────────────────────────────────────────────────────────────────────────────────
91
+
92
+ /** A level NAME as compared: trim, lower-case, collapse whitespace. "Roof", " roof " and "ROOF" are one level. */
93
+ export const normLevel = (name) => str(name).toLowerCase().replace(/\s+/g, ' ');
94
+ /** A grid label as compared: no whitespace, upper-case. */
95
+ export const normGrid = (g) => str(g).toUpperCase().replace(/\s+/g, '');
96
+ /** A girder designation as compared: no whitespace, upper-case. */
97
+ export const normSize = (s) => str(s).toUpperCase().replace(/\s+/g, '');
98
+ const normSheet = (s) => str(s).replace(/\s+/g, '').toUpperCase();
99
+
100
+ const sortedPair = (a, b) => [a, b].sort((x, y) => x.localeCompare(y, 'en', { numeric: true }));
101
+
102
+ /**
103
+ * A frame's IDENTITY (R2.2): the normalised grid line and the normalised span, the two span ends in either
104
+ * order. The `id` is only a handle for the editor and never decides whether two rows are the same frame.
105
+ * Returns '' for a row that states no grid.
106
+ */
107
+ export function frameKey(row) {
108
+ const n = normaliseFrameRow(row);
109
+ if (!n || !normGrid(n.grid)) return '';
110
+ const span = n.span.length === 2 ? sortedPair(normGrid(n.span[0]), normGrid(n.span[1])) : ['', ''];
111
+ return `${normGrid(n.grid)}|${span[0]}|${span[1]}`;
112
+ }
113
+
114
+ const sizeList = (v) => {
115
+ const out = [];
116
+ const seen = new Set();
117
+ for (const s of Array.isArray(v) ? v : []) {
118
+ const t = typeof s === 'string' ? s.trim() : '';
119
+ if (!t || seen.has(normSize(t))) continue;
120
+ seen.add(normSize(t));
121
+ out.push(t);
122
+ }
123
+ return out;
124
+ };
125
+ const viewList = (v) => [...new Set((Array.isArray(v) ? v : []).filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()))];
126
+
127
+ /**
128
+ * The new-shape VIEW of a stored row — never a mutation of it, and tolerant of everything a stored row may
129
+ * carry (numbers for span ends, no girders, a legacy `roof`/`second`). `legacy` on a group names the legacy
130
+ * key it came from (it drives the sheet-name fallback and nothing else).
131
+ *
132
+ * @returns {null | {id: string, grid: string, span: string[], girders: {level: string, elevationMm?: number, sizes: string[], views: string[], legacy?: string}[],
133
+ * columns: string[], source?: object, origin?: string, legacyShaped: boolean}}
134
+ */
135
+ export function normaliseFrameRow(row) {
136
+ if (!isObject(row)) return null;
137
+ const span = Array.isArray(row.span) ? row.span.map(labelOf) : [];
138
+ let girders = [];
139
+ let legacyShaped = false;
140
+ if (Array.isArray(row.girders)) {
141
+ for (const g of row.girders) {
142
+ if (!isObject(g)) continue;
143
+ girders.push({
144
+ level: str(g.level),
145
+ ...(finiteNumber(g.elevationMm) ? { elevationMm: g.elevationMm } : {}),
146
+ sizes: sizeList(g.sizes),
147
+ views: viewList(g.views),
148
+ });
149
+ }
150
+ } else {
151
+ for (const key of LEGACY_KEYS) {
152
+ if (!Array.isArray(row[key])) continue;
153
+ legacyShaped = true;
154
+ girders.push({ level: LEGACY_LEVEL_NAME[key], sizes: sizeList(row[key]), views: [], legacy: key });
155
+ }
156
+ }
157
+ return {
158
+ id: typeof row.id === 'string' ? row.id : '',
159
+ grid: labelOf(row.grid),
160
+ span: span.length === 2 ? span : [],
161
+ girders,
162
+ columns: sizeList(row.columns),
163
+ ...(isObject(row.source) ? { source: row.source } : {}),
164
+ ...(typeof row.origin === 'string' ? { origin: row.origin } : {}),
165
+ legacyShaped,
166
+ };
167
+ }
168
+
169
+ /**
170
+ * A stored row rewritten into the NEW shape, keeping everything it carried that the new shape does not
171
+ * replace. Called ONLY when a person edits that row (or links a sheet to one of its levels). The input is
172
+ * never touched; a row already in the new shape comes back as a copy.
173
+ *
174
+ * A legacy row has no `views`: the sheets it feeds are placed on it ONLY by the sheet-name table, and that table
175
+ * answers for legacy-shaped rows alone. Rewriting the row would therefore take it out of the very rule that placed it.
176
+ * So the link the table implied is written DOWN here: `ctx.carryViews` (from `legacyViewLinks`, computed over the schedule
177
+ * BEFORE the edit) names, per legacy key, the sheets that were placed that way, and each rewritten `roof` / `second`
178
+ * group takes its own. A row already in the new shape carries nothing, and a group never gets a sheet it did not have
179
+ * implicitly, so a sheet still belongs to one level.
180
+ *
181
+ * @param {object} row
182
+ * @param {{mintId?: () => string, carryViews?: {roof?: string[], second?: string[]}}} [ctx]
183
+ */
184
+ export function toV2Row(row, ctx = {}) {
185
+ const n = normaliseFrameRow(row);
186
+ if (!n) return null;
187
+ const rest = { ...row };
188
+ delete rest.roof; delete rest.second;
189
+ const id = n.id || (typeof ctx.mintId === 'function' ? ctx.mintId() : '');
190
+ const carry = isObject(ctx.carryViews) ? ctx.carryViews : {};
191
+ return {
192
+ ...rest,
193
+ ...(id ? { id } : {}),
194
+ grid: n.grid,
195
+ span: n.span.length === 2 ? [...n.span] : [],
196
+ girders: n.girders.map((g) => {
197
+ const views = viewList([...g.views, ...(g.legacy && Array.isArray(carry[g.legacy]) ? carry[g.legacy] : [])]);
198
+ return {
199
+ level: g.level, ...(g.elevationMm !== undefined ? { elevationMm: g.elevationMm } : {}),
200
+ sizes: [...g.sizes], ...(views.length ? { views } : {}),
201
+ };
202
+ }),
203
+ columns: [...n.columns],
204
+ };
205
+ }
206
+
207
+ /** "H (2–3)" — how a frame is named to a person. */
208
+ export function frameLabel(row) {
209
+ const n = normaliseFrameRow(row);
210
+ if (!n) return 'a moment frame';
211
+ const span = n.span.length === 2 ? ` (${n.span[0]}–${n.span[1]})` : '';
212
+ return `${n.grid || '?'}${span}`;
213
+ }
214
+
215
+ // ── validation of ONE new row ──────────────────────────────────────────────────────────────────────────
216
+
217
+ /**
218
+ * Validate and clean a NEW row. Accepts the new shape and, for convenience, a legacy-shaped one (a reader that
219
+ * wrote `roof`/`second` gets the same row as one that wrote `girders`). Numbers for the grid and the span ends
220
+ * are written out as text. Nothing here ever runs on a STORED row.
221
+ *
222
+ * @returns {{ok: true, entry: object} | {ok: false, problems: {code: string, reason: string}[]}}
223
+ */
224
+ export function cleanFrameRow(raw) {
225
+ if (!isObject(raw)) return { ok: false, problems: [problem('shape', "it isn't a moment-frame record")] };
226
+ const problems = [];
227
+ const grid = labelOf(raw.grid);
228
+ if (!grid) problems.push(problem('grid', "it doesn't say which grid line it is on"));
229
+ else if (grid.length > FRAME_GRID_MAX || CONTROL.test(grid)) problems.push(problem('grid', `its grid line is longer than ${FRAME_GRID_MAX} characters or has characters that cannot be printed`));
230
+
231
+ const spanRaw = Array.isArray(raw.span) ? raw.span.map(labelOf) : [];
232
+ if (spanRaw.length !== 2 || spanRaw.some((s) => !s)) problems.push(problem('span', "it doesn't say between which two grid lines it spans"));
233
+ else if (spanRaw.some((s) => s.length > FRAME_GRID_MAX || CONTROL.test(s))) problems.push(problem('span', `a grid line in its span is longer than ${FRAME_GRID_MAX} characters or has characters that cannot be printed`));
234
+
235
+ const girders = [];
236
+ const groupsRaw = [];
237
+ if (raw.girders !== undefined) {
238
+ if (!Array.isArray(raw.girders)) problems.push(problem('girders', "its girder sizes aren't given as a list of levels"));
239
+ else groupsRaw.push(...raw.girders);
240
+ } else {
241
+ for (const key of LEGACY_KEYS) if (Array.isArray(raw[key])) groupsRaw.push({ level: LEGACY_LEVEL_NAME[key], sizes: raw[key] });
242
+ }
243
+ if (groupsRaw.length > FRAME_LEVELS_PER_ROW_MAX) problems.push(problem('girders', `it lists more than ${FRAME_LEVELS_PER_ROW_MAX} levels`));
244
+ const seenLevels = new Set();
245
+ for (const g of groupsRaw.slice(0, FRAME_LEVELS_PER_ROW_MAX)) {
246
+ if (!isObject(g)) { problems.push(problem('girders', "one of its levels isn't a level record")); continue; }
247
+ const level = typeof g.level === 'string' ? g.level.trim() : '';
248
+ if (!level) { problems.push(problem('level', "one of its levels has no name")); continue; }
249
+ if (level.length > FRAME_LEVEL_MAX || CONTROL.test(level)) { problems.push(problem('level', `a level name is longer than ${FRAME_LEVEL_MAX} characters or has characters that cannot be printed`)); continue; }
250
+ if (seenLevels.has(normLevel(level))) { problems.push(problem('level', `it lists the level "${level}" twice`)); continue; }
251
+ seenLevels.add(normLevel(level));
252
+ if (g.elevationMm !== undefined && g.elevationMm !== null && (!finiteNumber(g.elevationMm) || Math.abs(g.elevationMm) > 1e7)) {
253
+ problems.push(problem('elevation', `the elevation it gives for "${level}" isn't a number`)); continue;
254
+ }
255
+ const sizesRaw = g.sizes === undefined ? [] : g.sizes;
256
+ if (!Array.isArray(sizesRaw) || sizesRaw.some((s) => typeof s !== 'string' || !s.trim() || s.trim().length > FRAME_SIZE_MAX || CONTROL.test(s))) {
257
+ problems.push(problem('sizes', `the girder sizes it gives for "${level}" aren't a list of section names`)); continue;
258
+ }
259
+ const sizes = sizeList(sizesRaw);
260
+ if (sizes.length > FRAME_SIZES_PER_LEVEL_MAX) { problems.push(problem('sizes', `it gives more than ${FRAME_SIZES_PER_LEVEL_MAX} girder sizes for "${level}"`)); continue; }
261
+ const viewsRaw = g.views === undefined ? [] : g.views;
262
+ if (!Array.isArray(viewsRaw) || viewsRaw.length > FRAME_VIEWS_PER_LEVEL_MAX
263
+ || viewsRaw.some((v) => typeof v !== 'string' || !v.trim() || v.length > FRAME_VIEW_ID_MAX || CONTROL.test(v))) {
264
+ problems.push(problem('views', `the sheets it links to "${level}" aren't a list of sheet names`)); continue;
265
+ }
266
+ girders.push({
267
+ level, ...(finiteNumber(g.elevationMm) ? { elevationMm: g.elevationMm } : {}),
268
+ sizes, ...(viewsRaw.length ? { views: viewList(viewsRaw) } : {}),
269
+ });
270
+ }
271
+
272
+ let columns = [];
273
+ if (raw.columns !== undefined) {
274
+ if (!Array.isArray(raw.columns) || raw.columns.length > FRAME_COLUMNS_MAX
275
+ || raw.columns.some((s) => typeof s !== 'string' || !s.trim() || s.trim().length > FRAME_SIZE_MAX || CONTROL.test(s))) {
276
+ problems.push(problem('columns', `its columns aren't a list of at most ${FRAME_COLUMNS_MAX} section names`));
277
+ } else columns = sizeList(raw.columns);
278
+ }
279
+ if (problems.length) return { ok: false, problems };
280
+
281
+ const entry = { grid, span: spanRaw, girders, columns };
282
+ if (isObject(raw.source) && typeof raw.source.sheet === 'string' && raw.source.sheet.trim() && raw.source.sheet.length <= 64 && !CONTROL.test(raw.source.sheet)) {
283
+ entry.source = { sheet: raw.source.sheet.trim() };
284
+ }
285
+ return { ok: true, entry };
286
+ }
287
+
288
+ /** @returns {{ok: boolean, problems: {code: string, reason: string}[]}} */
289
+ export function validateFrameRow(row) {
290
+ const r = cleanFrameRow(row);
291
+ return r.ok ? { ok: true, problems: [] } : { ok: false, problems: r.problems };
292
+ }
293
+
294
+ // ── content comparison ─────────────────────────────────────────────────────────────────────────────────
295
+
296
+ /**
297
+ * The levels of a normalised row that SAY something (a level with no sizes says nothing), keyed by the
298
+ * normalised level name, one entry per level however many groups the row spells it with.
299
+ *
300
+ * A `Map`, never an object keyed by the name: a level may be called `constructor`, `__proto__` or `toString`,
301
+ * and an object keyed by those throws or answers with an inherited member (#2210 review round 1).
302
+ *
303
+ * @returns {Map<string, {name: string, sizes: string[], elevationMm?: number}>}
304
+ */
305
+ function levelContent(n) {
306
+ const out = new Map();
307
+ for (const g of n.girders) {
308
+ if (!g.sizes.length) continue;
309
+ const key = normLevel(g.level);
310
+ const have = out.get(key);
311
+ if (!have) { out.set(key, { name: g.level, sizes: [...g.sizes], ...(g.elevationMm !== undefined ? { elevationMm: g.elevationMm } : {}) }); continue; }
312
+ for (const size of g.sizes) if (!have.sizes.some((x) => normSize(x) === normSize(size))) have.sizes.push(size);
313
+ if (have.elevationMm === undefined && g.elevationMm !== undefined) have.elevationMm = g.elevationMm;
314
+ }
315
+ return out;
316
+ }
317
+
318
+ /**
319
+ * Every level a normalised row NAMES, with the elevation it states, whether or not it has girder sizes yet. (`levelContent` leaves a level with
320
+ * no sizes out, because such a level says nothing about the girders; an elevation is a different thing it says, so it is read here.)
321
+ *
322
+ * @returns {Map<string, {name: string, elevationMm?: number}>}
323
+ */
324
+ function levelElevations(n) {
325
+ const out = new Map();
326
+ for (const g of n.girders) {
327
+ const key = normLevel(g.level);
328
+ if (!key) continue;
329
+ const have = out.get(key);
330
+ if (!have) out.set(key, { name: g.level, ...(g.elevationMm !== undefined ? { elevationMm: g.elevationMm } : {}) });
331
+ else if (have.elevationMm === undefined && g.elevationMm !== undefined) have.elevationMm = g.elevationMm;
332
+ }
333
+ return out;
334
+ }
335
+
336
+ /** What a frame SAYS, with the editor's own bookkeeping (id, origin, sheet links, elevations) left out. */
337
+ function contentOf(row) {
338
+ const n = normaliseFrameRow(row);
339
+ if (!n) return null;
340
+ // An ARRAY sorted by level key, not an object: the order a row lists its levels in (Roof first or 2nd floor
341
+ // first) is not something it says, so two rows that list the same levels in a different order are the same.
342
+ const levels = [...levelContent(n)]
343
+ .map(([key, v]) => [key, v.sizes.map(normSize).sort()])
344
+ .sort((x, y) => (x[0] < y[0] ? -1 : x[0] > y[0] ? 1 : 0));
345
+ return { key: frameKey(row), levels, columns: n.columns.map(normSize).sort() };
346
+ }
347
+ export function framesSayTheSame(a, b) {
348
+ const x = contentOf(a), y = contentOf(b);
349
+ return !!x && !!y && JSON.stringify(x) === JSON.stringify(y);
350
+ }
351
+
352
+ const mmText = (mm) => `${Number.isInteger(mm) ? mm : Math.round(mm * 10) / 10} mm`;
353
+
354
+ /**
355
+ * The FIRST thing two versions of one frame disagree on, in words a detailer uses — "the read gives grid H (2–3)
356
+ * a 2nd floor girder of W24X76; Frames has W24X68" — or '' when they say the same. Compared level by level in
357
+ * the order the stored row lists them, then the columns. Sizes are shown as written.
358
+ */
359
+ export function frameDifference(existing, incoming) {
360
+ const a = normaliseFrameRow(existing), b = normaliseFrameRow(incoming);
361
+ if (!a || !b) return '';
362
+ const who = `grid ${frameLabel(existing)}`;
363
+ const list = (xs) => (xs.length ? xs.join(', ') : 'none');
364
+ const stored = levelContent(a), read = levelContent(b);
365
+ for (const key of [...new Set([...stored.keys(), ...read.keys()])]) {
366
+ const x = stored.get(key), y = read.get(key);
367
+ const xs = x ? x.sizes.map(normSize).sort().join('|') : '', ys = y ? y.sizes.map(normSize).sort().join('|') : '';
368
+ if (xs === ys) continue;
369
+ const name = (y || x).name;
370
+ return y
371
+ ? `The read gives ${who} a ${name} girder of ${list(y.sizes)}; Frames has ${list(x ? x.sizes : [])}`
372
+ : `The read gives ${who} no ${name} girder; Frames has ${list(x.sizes)}`;
373
+ }
374
+ const colsA = a.columns.map(normSize).sort().join('|'), colsB = b.columns.map(normSize).sort().join('|');
375
+ if (colsA !== colsB) return `The read gives ${who} columns of ${list(b.columns)}; Frames has ${list(a.columns)}`;
376
+ // The same sizes, but a different (or newly stated) elevation for a level. Never filled in by a read: the
377
+ // stored frame stays exactly as it is and the difference is said. Compared across EVERY level both frames name,
378
+ // whatever sizes it has: a level still waiting for its girders has an elevation too.
379
+ const storedEl = levelElevations(a), readEl = levelElevations(b);
380
+ for (const [key, y] of readEl) {
381
+ const x = storedEl.get(key);
382
+ if (!x || y.elevationMm === undefined) continue;
383
+ if (x.elevationMm === undefined) return `The read gives ${who} a ${y.name} level at ${mmText(y.elevationMm)}; Frames states no elevation for it`;
384
+ if (Math.abs(x.elevationMm - y.elevationMm) > LEVEL_MATCH_TOL_MM) return `The read puts the ${y.name} level of ${who} at ${mmText(y.elevationMm)}; Frames has ${mmText(x.elevationMm)}`;
385
+ }
386
+ return '';
387
+ }
388
+
389
+ // ── differential admission ─────────────────────────────────────────────────────────────────────────────
390
+
391
+ const stableJson = (v) => JSON.stringify(v, (_k, val) => (isObject(val)
392
+ ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, val[k]]))
393
+ : val));
394
+
395
+ /**
396
+ * Admit the NEW rows of `after` into `before`, and nothing else (R1.2, R2.1, R2.2, R2.5).
397
+ *
398
+ * Identity is the frame's grid and span (`frameKey`). An incoming row that is canonically a stored row is
399
+ * simply present. One that names a stored frame but says something different is `differs` and NOT applied.
400
+ * One whose `id` belongs to a DIFFERENT stored frame is `malformed`. Only the rest are validated, capped and
401
+ * given a deterministic id (`mf-` and the first ten hex of a hash of the identity; `-2`, `-3`… on a
402
+ * collision), stamped `origin`. Stored rows are returned verbatim and first, legacy and odd ones included.
403
+ *
404
+ * @param {unknown} before the stored schedule (undefined and a non-list are [])
405
+ * @param {unknown} after the incoming schedule (undefined and null add nothing)
406
+ * @param {{origin: 'read'|'manual', hash10: (s: string) => string, cap?: number}} ctx
407
+ * A READ never writes `views` (the sheet-to-level link is a person's, R1.6): they are left out of the row it
408
+ * adds, and so is any field a frame does not keep. Both are reported in `trimmed`, never silently.
409
+ *
410
+ * @returns {{merged: unknown[], added: object[], differs: {index: number, existing: object, incoming: object}[],
411
+ * malformed: {index: number, entry: unknown, problems: {code: string, reason: string}[]}[],
412
+ * trimmed: {index: number, entry: object, links: boolean, fields: string[]}[],
413
+ * overCap: number, notAList: boolean}}
414
+ */
415
+ export function admitFrames(before, after, ctx) {
416
+ const stored = Array.isArray(before) ? before : [];
417
+ const result = { merged: stored.slice(), added: [], differs: [], malformed: [], trimmed: [], overCap: 0, notAList: false };
418
+ if (after === undefined || after === null) return result;
419
+ if (!Array.isArray(after)) {
420
+ result.notAList = true;
421
+ result.malformed.push({ index: -1, entry: after, problems: [problem('shape', "the moment-frame schedule isn't a list")] });
422
+ return result;
423
+ }
424
+ const cap = Number.isInteger(ctx.cap) && ctx.cap >= 0 ? ctx.cap : MOMENT_FRAMES_MAX;
425
+ const storedForms = new Set(stored.map(stableJson));
426
+ const usedIds = new Set();
427
+ for (const row of stored) if (isObject(row) && typeof row.id === 'string' && row.id) usedIds.add(row.id);
428
+
429
+ for (let index = 0; index < after.length; index += 1) {
430
+ const raw = after[index];
431
+ if (storedForms.has(stableJson(raw))) continue; // a legacy row copied forward verbatim is simply present
432
+ if (!isObject(raw)) {
433
+ result.malformed.push({ index, entry: raw, problems: [problem('shape', "it isn't a moment-frame record")] });
434
+ continue;
435
+ }
436
+ const key = frameKey(raw);
437
+ // An id that already belongs to a DIFFERENT frame cannot be reused for this one (R2.2). Checked BEFORE the
438
+ // identity match, so a row that names a frame's id but sits on another grid line cannot hide behind it.
439
+ const supplied = typeof raw.id === 'string' ? raw.id.trim() : '';
440
+ if (supplied) {
441
+ const owner = result.merged.find((row) => isObject(row) && row.id === supplied);
442
+ if (owner && frameKey(owner) !== key) {
443
+ result.malformed.push({ index, entry: raw, problems: [problem('id', 'its number already belongs to a different frame in the schedule')] });
444
+ continue;
445
+ }
446
+ }
447
+ const hit = key ? result.merged.find((row) => frameKey(row) === key) : undefined;
448
+ if (hit) {
449
+ if (frameDifference(hit, raw) !== '') result.differs.push({ index, existing: hit, incoming: raw });
450
+ continue;
451
+ }
452
+ const cleaned = cleanFrameRow(raw);
453
+ if (!cleaned.ok) {
454
+ result.malformed.push({ index, entry: raw, problems: cleaned.problems });
455
+ continue;
456
+ }
457
+ if (stored.length + result.added.length >= cap) {
458
+ result.overCap += 1;
459
+ continue;
460
+ }
461
+ const entry = cleaned.entry;
462
+ let links = false;
463
+ if (ctx.origin === 'read') {
464
+ entry.girders = entry.girders.map((g) => {
465
+ if (!g.views) return g;
466
+ links = true;
467
+ const { views: _left, ...rest } = g;
468
+ return rest;
469
+ });
470
+ }
471
+ const fields = droppedFields(raw);
472
+ if (links || fields.length) result.trimmed.push({ index, entry: raw, links, fields });
473
+ let id = typeof raw.id === 'string' && ID_PATTERN.test(raw.id.trim()) && raw.id.trim().length <= FRAME_ID_MAX ? raw.id.trim() : '';
474
+ if (id && usedIds.has(id)) id = '';
475
+ if (!id) {
476
+ const base = `mf-${ctx.hash10(frameKey(entry))}`;
477
+ id = base;
478
+ for (let n = 2; usedIds.has(id); n += 1) id = `${base}-${n}`;
479
+ }
480
+ usedIds.add(id);
481
+ const stamped = { id, ...entry, origin: ctx.origin };
482
+ result.added.push(stamped);
483
+ result.merged.push(stamped);
484
+ }
485
+ return result;
486
+ }
487
+
488
+ const KEPT_ROW_KEYS = new Set(['id', 'grid', 'span', 'girders', 'columns', 'source', 'origin', 'roof', 'second']);
489
+ const KEPT_LEVEL_KEYS = new Set(['level', 'elevationMm', 'sizes', 'views']);
490
+ /** The names of the fields a read gave a frame that a frame does not keep, made safe to show. */
491
+ function droppedFields(raw) {
492
+ const out = new Set();
493
+ const add = (name) => { const t = String(name).replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 32); if (t) out.add(t); };
494
+ for (const k of Object.keys(raw)) if (!KEPT_ROW_KEYS.has(k)) add(k);
495
+ if (Array.isArray(raw.girders)) for (const g of raw.girders) if (isObject(g)) for (const k of Object.keys(g)) if (!KEPT_LEVEL_KEYS.has(k)) add(k);
496
+ return [...out].sort().slice(0, 6);
497
+ }
498
+
499
+ /** "Left out the moment frame on grid H (2–3): it doesn't say …" */
500
+ export function malformedFrameMessage(entry, problems) {
501
+ const named = isObject(entry) && labelOf(entry.grid) ? `the moment frame on grid ${frameLabel(entry)}` : 'one moment frame';
502
+ return `Left out ${named}: ${problems.map((p) => p.reason).join(', and ')}.`;
503
+ }
504
+
505
+ // ── levels, links and the girder sizes a sheet shows ───────────────────────────────────────────────────
506
+
507
+ /**
508
+ * The levels the schedule names, in the order first seen. Rows that are not objects are skipped. A level that
509
+ * appears in several rows is ONE level (normalised name); its display name is the first spelling seen.
510
+ *
511
+ * @returns {{key: string, name: string, elevationMm?: number, rows: number}[]}
512
+ */
513
+ export function levelsOf(rows) {
514
+ const out = new Map();
515
+ for (const row of Array.isArray(rows) ? rows : []) {
516
+ const n = normaliseFrameRow(row);
517
+ if (!n) continue;
518
+ for (const g of n.girders) {
519
+ const key = normLevel(g.level);
520
+ if (!key) continue;
521
+ const have = out.get(key);
522
+ if (have) {
523
+ have.rows += 1;
524
+ if (have.elevationMm === undefined && g.elevationMm !== undefined) have.elevationMm = g.elevationMm;
525
+ } else out.set(key, { key, name: g.level, ...(g.elevationMm !== undefined ? { elevationMm: g.elevationMm } : {}), rows: 1 });
526
+ }
527
+ }
528
+ return [...out.values()];
529
+ }
530
+
531
+ /**
532
+ * Which level is this view linked to, by the explicit link only (`views`)?
533
+ * @returns {{state: 'none'} | {state: 'level', key: string, name: string} | {state: 'conflict', names: string[]}}
534
+ */
535
+ export function linkedLevelOf(rows, viewId) {
536
+ const names = new Map();
537
+ if (viewId) {
538
+ for (const row of Array.isArray(rows) ? rows : []) {
539
+ const n = normaliseFrameRow(row);
540
+ if (!n) continue;
541
+ for (const g of n.girders) if (g.views.includes(viewId) && normLevel(g.level)) names.set(normLevel(g.level), names.get(normLevel(g.level)) || g.level);
542
+ }
543
+ }
544
+ if (names.size === 0) return { state: 'none' };
545
+ if (names.size === 1) { const [key, name] = [...names][0]; return { state: 'level', key, name }; }
546
+ return { state: 'conflict', names: [...names.values()] };
547
+ }
548
+
549
+ /** Every sheet (by view id) linked to a level, across all rows, in first-seen order. */
550
+ export function viewsOfLevel(rows, key) {
551
+ const out = [];
552
+ for (const row of Array.isArray(rows) ? rows : []) {
553
+ const n = normaliseFrameRow(row);
554
+ if (!n) continue;
555
+ for (const g of n.girders) if (normLevel(g.level) === key) for (const v of g.views) if (!out.includes(v)) out.push(v);
556
+ }
557
+ return out;
558
+ }
559
+
560
+ /** Every girder size the schedule gives for a level, across all rows, in first-seen order (the old behaviour: one list per level). */
561
+ function sizesForLevel(rows, key) {
562
+ const seen = new Set();
563
+ const out = [];
564
+ for (const row of Array.isArray(rows) ? rows : []) {
565
+ const n = normaliseFrameRow(row);
566
+ if (!n) continue;
567
+ for (const g of n.girders) {
568
+ if (normLevel(g.level) !== key) continue;
569
+ for (const s of g.sizes) if (!seen.has(normSize(s))) { seen.add(normSize(s)); out.push(s); }
570
+ }
571
+ }
572
+ return out;
573
+ }
574
+
575
+ /**
576
+ * The girder sizes to offer on a plan view (R1.6, R2.3). Resolution order:
577
+ * 1. the EXPLICIT link a person made in Frames (`views` holds this view's id) — two different levels
578
+ * linked to one sheet is a CONFLICT and gives no sizes;
579
+ * 2. the plan's cut elevation, ONLY when exactly one level states an elevation within the tolerance;
580
+ * 3. the legacy sheet-name table, LAST, and only for legacy-shaped rows — flagged `via: 'sheet-name'`.
581
+ * It never writes anything, and it never reads the plan's `elevation_mm` as a claim about which level it is
582
+ * beyond rule 2.
583
+ *
584
+ * @param {{plans?: unknown[], moment_frames?: unknown} | null | undefined} model
585
+ * @param {{id?: unknown, sheet?: unknown, elevation_mm?: unknown} | null | undefined} plan
586
+ * @returns {{levelName: string|null, sizes: string[], via: 'view'|'elevation'|'sheet-name'|null,
587
+ * conflict: string[]|null, scheduled: boolean}}
588
+ */
589
+ export function girderSizesFor(model, plan) {
590
+ const rows = Array.isArray(model?.moment_frames) ? model.moment_frames : [];
591
+ const levels = levelsOf(rows);
592
+ // "scheduled" = the model has at least one frame. A frame with no levels yet still means the person has begun
593
+ // the schedule, so the panel asks which level the sheet is instead of claiming there is no schedule.
594
+ const scheduled = rows.some((row) => normaliseFrameRow(row) !== null);
595
+ const none = (extra = {}) => ({ levelName: null, sizes: [], via: null, conflict: null, scheduled, ...extra });
596
+ if (!levels.length || !plan) return none();
597
+ const viewId = planViewId(plan);
598
+
599
+ const linked = linkedLevelOf(rows, viewId);
600
+ if (linked.state === 'conflict') return none({ conflict: linked.names });
601
+ if (linked.state === 'level') {
602
+ return { levelName: levels.find((l) => l.key === linked.key)?.name ?? linked.name, sizes: sizesForLevel(rows, linked.key), via: 'view', conflict: null, scheduled: true };
603
+ }
604
+
605
+ const cut = plan.elevation_mm;
606
+ if (finiteNumber(cut)) {
607
+ const near = levels.filter((l) => l.elevationMm !== undefined && Math.abs(l.elevationMm - cut) <= LEVEL_MATCH_TOL_MM);
608
+ if (near.length === 1) return { levelName: near[0].name, sizes: sizesForLevel(rows, near[0].key), via: 'elevation', conflict: null, scheduled: true };
609
+ }
610
+
611
+ // The legacy table answers ONLY while the schedule still holds a legacy-shaped row that states that level. A schedule
612
+ // made of rows in the new shape (a hand-typed frame, a frame a read added) says which sheet is which level by an
613
+ // explicit link or an elevation, never by the numbering of the one project the table was built for; and a legacy row
614
+ // an edit rewrites takes its sheets with it as explicit links (`toV2Row`), so it leaves the table without losing them.
615
+ const legacyKey = legacyKeyOfPlan(plan);
616
+ if (legacyKey && legacyRowStates(rows, legacyKey)) {
617
+ // The level the table names, by NAME across every row (the legacy rows' sizes and any other row's for the same level).
618
+ const name = LEGACY_LEVEL_NAME[legacyKey];
619
+ const sizes = sizesForLevel(rows, normLevel(name));
620
+ if (sizes.length) return { levelName: name, sizes, via: 'sheet-name', conflict: null, scheduled: true };
621
+ }
622
+ return none();
623
+ }
624
+
625
+ /** The legacy key (`roof` / `second`) the old sheet-name table gives a plan's sheet, or null. */
626
+ function legacyKeyOfPlan(plan) {
627
+ const sheet = normSheet(isObject(plan) ? plan.sheet : '');
628
+ if (!sheet) return null;
629
+ const hit = Object.keys(LEGACY_SHEET_LEVELS).find((k) => normSheet(k) === sheet);
630
+ return hit === undefined ? null : LEGACY_SHEET_LEVELS[hit];
631
+ }
632
+
633
+ /** Does a LEGACY-shaped row (the old `roof` / `second` keys, never rewritten) state girder sizes under this legacy key? */
634
+ function legacyRowStates(rows, legacyKey) {
635
+ return rows.some((row) => {
636
+ const n = normaliseFrameRow(row);
637
+ return !!n && n.legacyShaped && n.girders.some((g) => g.legacy === legacyKey && g.sizes.length > 0);
638
+ });
639
+ }
640
+
641
+ /**
642
+ * The sheets the OLD sheet-name table is placing on a level right now, as `{roof: [viewId…], second: [viewId…]}`: exactly
643
+ * the plans for which `girderSizesFor` answers `via: 'sheet-name'` (no link, no single elevation match, and a legacy-shaped
644
+ * row that states the level). The page passes this to every edit as `ctx.carryViews`, so that the edit that rewrites a legacy
645
+ * row writes those sheets down as explicit links instead of dropping the row out of the table that placed them.
646
+ * Computed over the schedule as it is BEFORE the edit; a plan with no sheet name or no view id is skipped.
647
+ *
648
+ * @param {unknown} rows the stored schedule
649
+ * @param {unknown[]} plans the plan views the page offers (the ones a girder size can be picked on)
650
+ * @returns {{roof: string[], second: string[]}}
651
+ */
652
+ export function legacyViewLinks(rows, plans) {
653
+ const out = { roof: [], second: [] };
654
+ const model = { moment_frames: Array.isArray(rows) ? rows : [] };
655
+ for (const plan of Array.isArray(plans) ? plans : []) {
656
+ const key = legacyKeyOfPlan(plan);
657
+ const viewId = key ? planViewId(plan) : '';
658
+ if (!key || !viewId || out[key].includes(viewId)) continue;
659
+ if (girderSizesFor(model, plan).via === 'sheet-name') out[key].push(viewId);
660
+ }
661
+ return out;
662
+ }
663
+
664
+ /** "Roof", "Roof and 2nd floor", "Roof, 2nd floor and 3rd floor". */
665
+ export function joinNames(names) {
666
+ const list = names.filter(Boolean);
667
+ if (list.length <= 1) return list.join('');
668
+ return `${list.slice(0, -1).join(', ')} and ${list[list.length - 1]}`;
669
+ }
670
+
671
+ /**
672
+ * What the member panel's moment-frame box should SAY about a plan view, as data the page only has to draw:
673
+ * sizes a level was found (link or elevation): offer its girder sizes
674
+ * sheet-name the same, but matched only by the old sheet-name table: say so and point at Frames
675
+ * conflict the sheet is linked to two levels: no sizes, ask for one choice
676
+ * no-sizes the level is known but the schedule has no girder size for it yet
677
+ * no-level the schedule exists but does not say which level this sheet is
678
+ * no-schedule there is no schedule at all
679
+ */
680
+ export function suggestionFor(model, plan) {
681
+ const r = girderSizesFor(model, plan);
682
+ if (r.conflict) return { kind: 'conflict', names: r.conflict };
683
+ if (!r.scheduled) return { kind: 'no-schedule' };
684
+ if (!r.levelName) return { kind: 'no-level' };
685
+ if (!r.sizes.length) return { kind: 'no-sizes', levelName: r.levelName };
686
+ return { kind: r.via === 'sheet-name' ? 'sheet-name' : 'sizes', levelName: r.levelName, sizes: r.sizes, via: r.via };
687
+ }
688
+
689
+ // ── hand edits (the Frames dialog) ─────────────────────────────────────────────────────────────────────
690
+ // Pure functions from a schedule to a NEW schedule. A row that an edit does not touch is returned as the
691
+ // SAME object, so a legacy row is rewritten into the new shape only when the edit reaches it.
692
+
693
+ /**
694
+ * Check one row a person typed against the rest of the schedule: the same rules a read's rows meet, plus that
695
+ * no OTHER row already is this frame.
696
+ * @returns {{ok: true, row: object} | {ok: false, problems: {code: string, reason: string}[]}}
697
+ */
698
+ export function checkFrameEdit(rows, index, candidate) {
699
+ const cleaned = cleanFrameRow(candidate);
700
+ if (!cleaned.ok) return cleaned;
701
+ const key = frameKey(cleaned.entry);
702
+ const list = Array.isArray(rows) ? rows : [];
703
+ const clash = list.findIndex((row, i) => i !== index && frameKey(row) === key);
704
+ if (clash >= 0) {
705
+ return { ok: false, problems: [problem('duplicate', `there is already a moment frame on grid ${frameLabel(list[clash])}`)] };
706
+ }
707
+ if (list.length >= MOMENT_FRAMES_MAX && (index < 0 || index >= list.length)) {
708
+ return { ok: false, problems: [problem('cap', `FloLess keeps at most ${MOMENT_FRAMES_MAX} moment frames`)] };
709
+ }
710
+ const existing = index >= 0 && index < list.length && isObject(list[index]) ? list[index] : null;
711
+ // carry EVERYTHING the stored row held that the edit did not change: the id, the drawing citation, how it got
712
+ // here and any field this version does not know. Only the legacy roof/second keys are replaced (by `girders`).
713
+ const keep = {};
714
+ if (existing) {
715
+ for (const k of Object.keys(existing)) if (!['roof', 'second', 'grid', 'span', 'girders', 'columns'].includes(k)) own(keep, k, existing[k]); // `own`: a stored field may be called "__proto__"
716
+ }
717
+ const id = existing && typeof existing.id === 'string' && existing.id ? existing.id : (isObject(candidate) && typeof candidate.id === 'string' && candidate.id ? candidate.id : '');
718
+ if (id) keep.id = id;
719
+ return { ok: true, row: { ...keep, ...cleaned.entry } };
720
+ }
721
+
722
+ const withNames = (rows) => (Array.isArray(rows) ? rows : []);
723
+
724
+ /**
725
+ * Add a level to every row that lacks it. A row already at the most levels a row keeps is left as it is and
726
+ * named in `skipped`, never passed over silently.
727
+ * @returns {{ok: true, rows: unknown[], skipped: string[]} | {ok: false, reason: string}}
728
+ */
729
+ export function addLevel(rows, name, ctx = {}) {
730
+ const level = str(name);
731
+ if (!level) return { ok: false, reason: 'Give the level a name, for example 3rd floor.' };
732
+ if (level.length > FRAME_LEVEL_MAX || CONTROL.test(level)) return { ok: false, reason: `Keep the level name under ${FRAME_LEVEL_MAX} characters.` };
733
+ const list = withNames(rows);
734
+ if (!list.length) return { ok: false, reason: 'Add a frame first, then add its levels.' };
735
+ if (levelsOf(list).some((l) => l.key === normLevel(level))) return { ok: false, reason: `There is already a level called ${level}.` };
736
+ const skipped = [];
737
+ const out = list.map((row) => {
738
+ const v2 = toV2Row(row, ctx);
739
+ if (!v2) return row;
740
+ if (v2.girders.length >= FRAME_LEVELS_PER_ROW_MAX) { skipped.push(frameLabel(row)); return row; }
741
+ return { ...v2, girders: [...v2.girders, { level, sizes: [] }] };
742
+ });
743
+ return { ok: true, rows: out, skipped };
744
+ }
745
+
746
+ /** Rename a level across the schedule. @returns {{ok: true, rows: unknown[]} | {ok: false, reason: string}} */
747
+ export function renameLevel(rows, key, name, ctx = {}) {
748
+ const level = str(name);
749
+ if (!level) return { ok: false, reason: 'Give the level a name, for example 3rd floor.' };
750
+ if (level.length > FRAME_LEVEL_MAX || CONTROL.test(level)) return { ok: false, reason: `Keep the level name under ${FRAME_LEVEL_MAX} characters.` };
751
+ const list = withNames(rows);
752
+ if (normLevel(level) !== key && levelsOf(list).some((l) => l.key === normLevel(level))) return { ok: false, reason: `There is already a level called ${level}.` };
753
+ return {
754
+ ok: true,
755
+ rows: list.map((row) => {
756
+ const n = normaliseFrameRow(row);
757
+ if (!n || !n.girders.some((g) => normLevel(g.level) === key)) return row;
758
+ const v2 = toV2Row(row, ctx);
759
+ return { ...v2, girders: v2.girders.map((g) => (normLevel(g.level) === key ? { ...g, level } : g)) };
760
+ }),
761
+ };
762
+ }
763
+
764
+ /**
765
+ * The levels `before` names that `after` no longer does, each with the sheets that were linked to it: what a
766
+ * removal (of a level, or of the last frame that had it) took with it, so the page can say so.
767
+ * @returns {{name: string, key: string, views: string[]}[]}
768
+ */
769
+ export function lostLevels(before, after) {
770
+ const still = new Set(levelsOf(after).map((l) => l.key));
771
+ return levelsOf(before).filter((l) => !still.has(l.key)).map((l) => ({ name: l.name, key: l.key, views: viewsOfLevel(before, l.key) }));
772
+ }
773
+
774
+ /** Remove a level (and every sheet link on it) from the schedule. */
775
+ export function removeLevel(rows, key, ctx = {}) {
776
+ return withNames(rows).map((row) => {
777
+ const n = normaliseFrameRow(row);
778
+ if (!n || !n.girders.some((g) => normLevel(g.level) === key)) return row;
779
+ const v2 = toV2Row(row, ctx);
780
+ return { ...v2, girders: v2.girders.filter((g) => normLevel(g.level) !== key) };
781
+ });
782
+ }
783
+
784
+ /**
785
+ * Fold one level into another (a rename that landed on a name the schedule already has). Each row's sizes and
786
+ * sheet links for the two are combined under the SURVIVING level's name; a row that only has the folded level
787
+ * simply takes the surviving name. The surviving level keeps ITS elevation (the folded one's only fills a level
788
+ * that stated none); when both state one and they differ, `elevationConflict` says so, so the page can tell.
789
+ *
790
+ * A level keeps at most FRAME_SIZES_PER_LEVEL_MAX girder sizes and FRAME_VIEWS_PER_LEVEL_MAX sheet links, and a row
791
+ * that broke either would no longer pass `checkFrameEdit`: the person could not change one cell of that frame again.
792
+ * So a merge whose combined level would not fit is NEVER written over the limit. The result already holds the row
793
+ * as it can be kept (the first sizes and links, in the order the row lists them) and `trimmed` says, per frame, what
794
+ * did not fit — the page turns it into a question BEFORE it writes ("keep the first 12, or cancel?") and into a note
795
+ * AFTER ("left out W27X84"), so nothing is dropped without the person having been told. `trimmed` is empty when the
796
+ * merge fits, which is every merge that stays within the limits.
797
+ *
798
+ * @returns {{ok: true, rows: unknown[], elevationConflict: null | {from: {name: string, elevationMm: number}, into: {name: string, elevationMm: number}},
799
+ * trimmed: MergeTrim[]}
800
+ * | {ok: false, reason: string}}
801
+ *
802
+ * @typedef {{frame: string, level: string, sizes: null | {had: number, kept: number, left: string[]}, views: null | {had: number, kept: number, left: string[]}}} MergeTrim
803
+ */
804
+ export function mergeLevel(rows, fromKey, intoKey, ctx = {}) {
805
+ const list = withNames(rows);
806
+ const all = levelsOf(list);
807
+ const into = all.find((l) => l.key === intoKey);
808
+ const from = all.find((l) => l.key === fromKey);
809
+ if (!into || fromKey === intoKey) return { ok: false, reason: 'Pick two different levels to merge.' };
810
+ const keepEl = into.elevationMm !== undefined ? into.elevationMm : from?.elevationMm;
811
+ const elevationConflict = from && into.elevationMm !== undefined && from.elevationMm !== undefined
812
+ && Math.abs(into.elevationMm - from.elevationMm) > LEVEL_MATCH_TOL_MM
813
+ ? { from: { name: from.name, elevationMm: from.elevationMm }, into: { name: into.name, elevationMm: into.elevationMm } }
814
+ : null;
815
+ const trimmed = [];
816
+ const out = list.map((row) => {
817
+ const n = normaliseFrameRow(row);
818
+ if (!n || !n.girders.some((g) => normLevel(g.level) === fromKey)) return row;
819
+ const v2 = toV2Row(row, ctx);
820
+ const girders = [];
821
+ let combined = false;
822
+ for (const g of v2.girders) {
823
+ const key = normLevel(g.level);
824
+ if (key !== fromKey && key !== intoKey) { girders.push(g); continue; }
825
+ const at = girders.findIndex((x) => normLevel(x.level) === intoKey);
826
+ if (at < 0) {
827
+ const { elevationMm: _was, ...bare } = g;
828
+ girders.push({ ...bare, level: into.name, ...(keepEl !== undefined ? { elevationMm: keepEl } : (g.elevationMm !== undefined ? { elevationMm: g.elevationMm } : {})) });
829
+ continue;
830
+ }
831
+ combined = true;
832
+ const prior = girders[at];
833
+ const sizes = sizeList([...prior.sizes, ...g.sizes]);
834
+ const views = viewList([...(prior.views || []), ...(g.views || [])]);
835
+ const elevationMm = keepEl !== undefined ? keepEl : (prior.elevationMm !== undefined ? prior.elevationMm : g.elevationMm);
836
+ girders[at] = { level: into.name, ...(elevationMm !== undefined ? { elevationMm } : {}), sizes, ...(views.length ? { views } : {}) };
837
+ }
838
+ if (combined) {
839
+ // Only a level this merge COMBINED can have been pushed over a limit by it.
840
+ const at = girders.findIndex((x) => normLevel(x.level) === intoKey);
841
+ const g = girders[at];
842
+ const fit = (items, max) => (items.length > max ? { had: items.length, kept: max, left: items.slice(max) } : null);
843
+ const overSizes = fit(g.sizes, FRAME_SIZES_PER_LEVEL_MAX);
844
+ const overViews = fit(g.views || [], FRAME_VIEWS_PER_LEVEL_MAX);
845
+ if (overSizes || overViews) {
846
+ const { views: _all, ...rest } = g;
847
+ const keptViews = (g.views || []).slice(0, FRAME_VIEWS_PER_LEVEL_MAX);
848
+ girders[at] = { ...rest, sizes: g.sizes.slice(0, FRAME_SIZES_PER_LEVEL_MAX), ...(keptViews.length ? { views: keptViews } : {}) };
849
+ trimmed.push({ frame: frameLabel(row), level: into.name, sizes: overSizes, views: overViews });
850
+ }
851
+ }
852
+ return { ...v2, girders };
853
+ });
854
+ return { ok: true, elevationConflict, rows: out, trimmed };
855
+ }
856
+
857
+ /**
858
+ * The QUESTION the page asks before a merge that would not fit, in a detailer's words — "Merging puts 14 girder sizes on
859
+ * Roof for grid H (2–3). A level keeps up to 12 girder sizes." — and the label of the button that goes ahead.
860
+ * @param {MergeTrim[]} trimmed from `mergeLevel`
861
+ * @returns {{question: string, proceed: string}}
862
+ */
863
+ export function mergeTrimQuestion(trimmed) {
864
+ const list = Array.isArray(trimmed) ? trimmed : [];
865
+ if (!list.length) return { question: '', proceed: '' };
866
+ const first = list[0];
867
+ const sizesOver = list.some((t) => t.sizes), viewsOver = list.some((t) => t.views);
868
+ const what = joinNames([first.sizes && `${first.sizes.had} girder sizes`, first.views && `${first.views.had} sheet links`]);
869
+ const more = list.length - 1;
870
+ const alsoOn = more > 0 ? `, and on ${more} other ${more === 1 ? 'frame' : 'frames'} too` : '';
871
+ const keeps = joinNames([sizesOver && `${FRAME_SIZES_PER_LEVEL_MAX} girder sizes`, viewsOver && `${FRAME_VIEWS_PER_LEVEL_MAX} sheet links`]);
872
+ const proceed = sizesOver && !viewsOver ? `Merge and keep the first ${FRAME_SIZES_PER_LEVEL_MAX}`
873
+ : viewsOver && !sizesOver ? `Merge and keep the first ${FRAME_VIEWS_PER_LEVEL_MAX} links` : 'Merge and keep what fits';
874
+ return { question: `Merging puts ${what} on ${first.level} for grid ${first.frame}${alsoOn}. A level keeps up to ${keeps}.`, proceed };
875
+ }
876
+
877
+ /**
878
+ * What a merge LEFT OUT, said once it has happened (the page puts it in the undo toast): "Kept the first 12 girder sizes
879
+ * on Roof for grid H (2–3); left out W27X84 and W30X99." At most three names are listed per frame; the rest are counted.
880
+ * @param {MergeTrim[]} trimmed from `mergeLevel`
881
+ * @param {{viewName?: (viewId: string) => string}} [o] turns a sheet link's id into the name a person knows it by
882
+ */
883
+ export function mergeTrimNote(trimmed, o = {}) {
884
+ const list = Array.isArray(trimmed) ? trimmed : [];
885
+ const nameOf = typeof o.viewName === 'function' ? o.viewName : (id) => id;
886
+ const named = (names) => {
887
+ const shown = names.slice(0, 3), rest = names.length - shown.length;
888
+ return rest > 0 ? `${shown.join(', ')} and ${rest} more` : joinNames(shown);
889
+ };
890
+ const one = (t) => {
891
+ const parts = [];
892
+ if (t.sizes) parts.push(`Kept the first ${t.sizes.kept} girder sizes on ${t.level} for grid ${t.frame}; left out ${named(t.sizes.left)}.`);
893
+ if (t.views) parts.push(`Kept the first ${t.views.kept} sheet links on ${t.level} for grid ${t.frame}; left out ${named(t.views.left.map(nameOf))}.`);
894
+ return parts.join(' ');
895
+ };
896
+ if (!list.length) return '';
897
+ const more = list.length - 1;
898
+ return more > 0 ? `${one(list[0])} The same for ${more} other ${more === 1 ? 'frame' : 'frames'}.` : one(list[0]);
899
+ }
900
+
901
+ /**
902
+ * Is this the SAME answer to "what would the merge leave out?" as the one the person was shown? Compared in full — which frames,
903
+ * which level, which limit (sizes, links or both) and exactly which entries would not fit — never just "does anything overflow",
904
+ * so a merge confirmed after the schedule changed under the question (more links, other sizes, another frame) is asked again
905
+ * instead of dropping something the person was never told about. Two empty summaries are the same.
906
+ * @param {MergeTrim[]} shown what the offer said
907
+ * @param {MergeTrim[]} now what the merge would do right now
908
+ */
909
+ export function mergeTrimSame(shown, now) {
910
+ return JSON.stringify(Array.isArray(shown) ? shown : []) === JSON.stringify(Array.isArray(now) ? now : []);
911
+ }
912
+
913
+ /**
914
+ * Link a sheet to ONE level, or to none (`key` null), in one pass (R2.3). The sheet is taken out of every other
915
+ * level's `views` in the same edit, so no edit through this function can leave a sheet on two levels.
916
+ * Touches only rows that carry the sheet or the level; a legacy row is rewritten only if it must change.
917
+ */
918
+ export function linkViewToLevel(rows, viewId, key, ctx = {}) {
919
+ return withNames(rows).map((row) => {
920
+ const n = normaliseFrameRow(row);
921
+ if (!n) return row;
922
+ const wants = n.girders.map((g) => {
923
+ const has = g.views.includes(viewId);
924
+ const should = key !== null && normLevel(g.level) === key;
925
+ return { has, should };
926
+ });
927
+ if (wants.every((w) => w.has === w.should)) return row;
928
+ const v2 = toV2Row(row, ctx);
929
+ return {
930
+ ...v2,
931
+ girders: v2.girders.map((g, i) => {
932
+ const views = (g.views || []).filter((v) => v !== viewId);
933
+ if (wants[i].should) views.push(viewId);
934
+ const { views: _drop, ...rest } = g;
935
+ return views.length ? { ...rest, views } : rest;
936
+ }),
937
+ };
938
+ });
939
+ }
940
+
941
+ /** Set a row's girder sizes for one level (adds the level to the row if it lacks it). */
942
+ export function setLevelSizes(row, key, name, sizes, ctx = {}) {
943
+ const v2 = toV2Row(row, ctx);
944
+ if (!v2) return row;
945
+ const list = sizeList(sizes);
946
+ const has = v2.girders.some((g) => normLevel(g.level) === key);
947
+ return {
948
+ ...v2,
949
+ girders: has
950
+ ? v2.girders.map((g) => (normLevel(g.level) === key ? { ...g, sizes: list } : g))
951
+ : [...v2.girders, { level: name, sizes: list }],
952
+ };
953
+ }
954
+
955
+ /** Split typed text ("W24X68, W21X44") into designations. */
956
+ export function parseSizeText(text) {
957
+ return sizeList(String(text ?? '').split(/[,;\n]/).map((s) => s.trim()));
958
+ }