@floless/app 0.174.1 → 0.175.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 (85) hide show
  1. package/autostart.mjs +117 -10
  2. package/dist/floless-server.cjs +2 -2
  3. package/dist/pdf-engine/floless_pdf/__init__.py +7 -3
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +292 -13
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +25 -3
  6. package/dist/pdf-engine/floless_pdf/images.py +4 -3
  7. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  8. package/dist/schemas/steel.model.v2.schema.json +44 -1
  9. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  10. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  11. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  12. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  13. package/dist/skills/floless-app-steel-model/SKILL.md +11 -1
  14. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  15. package/dist/skills/floless-app-steel-takeoff/SKILL.md +11 -6
  16. package/dist/web/agents.js +1 -1
  17. package/dist/web/app.css +120 -15
  18. package/dist/web/app.js +89 -38
  19. package/dist/web/aware-hold.js +10 -0
  20. package/dist/web/aware.js +405 -51
  21. package/dist/web/boot-watchdog.js +249 -0
  22. package/dist/web/card-details.js +88 -0
  23. package/dist/web/chat.css +29 -0
  24. package/dist/web/chat.js +430 -128
  25. package/dist/web/commands-connection-design.js +23 -0
  26. package/dist/web/commands-revit.js +3 -0
  27. package/dist/web/commands-shell.js +226 -10
  28. package/dist/web/commands-steel.js +93 -4
  29. package/dist/web/commands-tekla-parser.js +21 -1
  30. package/dist/web/connection-design-editor.html +71 -0
  31. package/dist/web/connection-design-editor.js +794 -61
  32. package/dist/web/connection-design-handles.js +9 -3
  33. package/dist/web/element-approval.js +74 -0
  34. package/dist/web/element-context.js +76 -6
  35. package/dist/web/element-geometry.js +8 -2
  36. package/dist/web/element-holds.js +68 -5
  37. package/dist/web/element-type-actions.js +22 -3
  38. package/dist/web/element-types.js +12 -5
  39. package/dist/web/element-words.js +15 -11
  40. package/dist/web/grid-place.js +51 -0
  41. package/dist/web/guide.js +2 -0
  42. package/dist/web/index.html +13 -16
  43. package/dist/web/instructor.js +5 -2
  44. package/dist/web/missed-routines.js +6 -1
  45. package/dist/web/model-change-findings.js +100 -30
  46. package/dist/web/model-change-review.js +411 -27
  47. package/dist/web/model-clash-check.css +100 -0
  48. package/dist/web/model-clash-check.js +681 -0
  49. package/dist/web/model-clip-box.js +204 -0
  50. package/dist/web/model-clip-list.js +153 -3
  51. package/dist/web/model-clip-session.js +3 -3
  52. package/dist/web/model-clip-three-overlay.js +135 -25
  53. package/dist/web/model-editor.css +2 -0
  54. package/dist/web/model-elements.js +273 -18
  55. package/dist/web/model-fit-checks.js +354 -0
  56. package/dist/web/model-spatial-panel.js +9 -3
  57. package/dist/web/model-spatial-tools.js +12 -3
  58. package/dist/web/model-tekla-selection.js +74 -0
  59. package/dist/web/model-view-query.js +70 -14
  60. package/dist/web/model-viewport-revit-adapter.js +8 -7
  61. package/dist/web/model-viewport-toolbar.js +8 -4
  62. package/dist/web/pages.js +78 -1
  63. package/dist/web/project-history.js +31 -1
  64. package/dist/web/revit-editor.css +34 -1
  65. package/dist/web/revit-editor.js +174 -55
  66. package/dist/web/run-history.js +8 -0
  67. package/dist/web/sketch-editor.js +141 -2
  68. package/dist/web/sketches.js +192 -6
  69. package/dist/web/start-place.js +46 -0
  70. package/dist/web/steel-3d-core.js +70 -0
  71. package/dist/web/steel-3d-view.js +288 -47
  72. package/dist/web/steel-change-review.css +28 -0
  73. package/dist/web/steel-custom-connection.js +6 -0
  74. package/dist/web/steel-editor.html +532 -33
  75. package/dist/web/steel-filter.html +8 -3
  76. package/dist/web/steel-model-checks.css +76 -0
  77. package/dist/web/steel-model-v2-commands.js +17 -0
  78. package/dist/web/steel-view-generation.js +6 -2
  79. package/dist/web/teams.js +259 -19
  80. package/dist/web/tekla-editor.html +1 -0
  81. package/dist/web/terminal-requests.js +6 -0
  82. package/dist/web/vendor/connection-engine.js +886 -91
  83. package/dist/web/workspaces.js +630 -48
  84. package/package.json +2 -1
  85. package/preferences-file.mjs +27 -0
@@ -0,0 +1,354 @@
1
+ /**
2
+ * #3690 E1d (plan 2026-11-24-e1d-fit-checks-PLAN.md §5.3, ruling F7): the "Fit of walls, slabs and footings" group of
3
+ * the steel editor's Model checks drawer. Presentation only: the server measures the fit (element-fit.ts), words every
4
+ * sentence and records every choice; this lists what it says and sends the person's own choices back.
5
+ *
6
+ * - Every finding stays a finding. One the person proceeds on keeps its warning style and shows the server's
7
+ * `assumption.label`; nothing here ever says "fits" or "passed", and a finding has no Resolve or Dismiss.
8
+ * - Proceed on an assumption is two steps, inline (the drawer is not modal, so the model stays in view): the person's
9
+ * words, then a confirm that quotes the finding word for word. It posts `{identity, binding, statement}` as the person
10
+ * (the window's own request, `via: editor`). A 409 shows the finding as it reads now and asks again; nothing refuses.
11
+ * - The fold limit is a setting the person may change: the value, where it came from (the server's label), and after a
12
+ * save the server's line saying which findings it adds or removes.
13
+ * - Copy question copies the server's RFI question for one finding; no RFI is raised from here (#4117).
14
+ *
15
+ * Laid out as one <section> per check inside the drawer, so the clash check (#4029) can sit beside it as a sibling.
16
+ */
17
+
18
+ const LIMIT_NAME = 'Sharpest mitre before it is reported';
19
+ /** The longest assumption the server records (element-fit-assumption-routes.ts MAX_FIT_STATEMENT); a test keeps them equal. */
20
+ export const MAX_STATEMENT = 300;
21
+ const NOT_CHECKED_SPLIT = ' Not checked yet: ';
22
+
23
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
24
+
25
+ /**
26
+ * A measured key the way a detailer reads it: `gapMm` → ["gap", "mm"], `overlapAreaMm2` → ["overlap area", "mm²"].
27
+ * A key the server qualifies by element and piece keeps the element's id as written and counts pieces from 1:
28
+ * `overrunMm.W-A` → "overrun (W-A)", `gapMm.S-1#0` → "gap (S-1, piece 1)", `topOffsetMm#1` → "top offset (piece 2)".
29
+ */
30
+ export function measuredRow(key, value) {
31
+ const m = /^(.*?)(Mm2|Mm|Deg|Pct)(?:\.([^#]+))?(?:#(\d+))?$/.exec(key);
32
+ const stem = m ? m[1] : key;
33
+ const unit = m ? { Mm2: 'mm²', Mm: 'mm', Deg: '°', Pct: '%' }[m[2]] : '';
34
+ const of = m ? [m[3], m[4] != null ? `piece ${Number(m[4]) + 1}` : null].filter(Boolean).join(', ') : '';
35
+ const words = (stem.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().trim() || key) + (of ? ` (${of})` : '');
36
+ const n = Number(value);
37
+ const shown = Number.isFinite(n) ? (Math.abs(n) >= 100 ? Math.round(n).toLocaleString('en-GB') : String(Math.round(n * 1000) / 1000)) : String(value);
38
+ return { label: words, text: unit === '°' ? `${shown}°` : unit ? `${shown} ${unit}` : shown };
39
+ }
40
+
41
+ /** The measured values worth showing: the overlap region's corners are where, not what, so they are left to the chip. */
42
+ export function shownMeasured(measured) {
43
+ return Object.keys(measured || {}).filter((k) => !/^regionMm/.test(k)).sort().map((k) => measuredRow(k, measured[k]));
44
+ }
45
+
46
+ /** "C/1 · Level 2 at +3,000 mm", the location as text (never colour alone). */
47
+ export function whereText(where) {
48
+ if (!where || typeof where !== 'object') return '';
49
+ return [where.grid, where.level].filter((s) => typeof s === 'string' && s).join(' · ');
50
+ }
51
+
52
+ export function mountFitChecks({ host, doc = document, fetchJson, urls, setFoldLimit, copyText, onChanged = () => {} }) {
53
+ const st = { unsaved: false, status: 'idle', fit: null, error: '', live: '', change: '', limitError: '', limitDraft: null, open: new Map(), busy: false };
54
+ let seq = 0;
55
+
56
+ const findingsOf = () => (st.fit && Array.isArray(st.fit.findings) ? st.fit.findings : []);
57
+ const byIdentity = (id) => findingsOf().find((f) => f.identity === id);
58
+
59
+ /**
60
+ * Measure the saved model again. `unsavedEdits`: the page could not save the person's latest edits first, so this
61
+ * fit is of the older saved model and says so; a reload after the drawer's own action (keepLive) keeps that word.
62
+ */
63
+ async function load(keepLive, { unsavedEdits = false } = {}) {
64
+ const mine = ++seq;
65
+ if (!keepLive) { st.live = ''; st.unsaved = !!unsavedEdits; }
66
+ st.status = st.fit ? 'refreshing' : 'loading';
67
+ render();
68
+ try {
69
+ const body = await fetchJson(urls.evaluate, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
70
+ if (mine !== seq) return;
71
+ st.fit = body && body.fit && typeof body.fit === 'object' ? body.fit : null;
72
+ st.status = 'ready';
73
+ } catch (e) {
74
+ if (mine !== seq) return;
75
+ st.status = 'error';
76
+ st.error = errorWords(e, 'The fit could not be measured.');
77
+ }
78
+ render();
79
+ onChanged(st.fit);
80
+ }
81
+
82
+ function errorWords(e, lead) {
83
+ const b = e && e.body;
84
+ const said = b && typeof b.error === 'string' ? b.error : '';
85
+ return said ? `${lead} ${said}` : `${lead} Check that FloLess is running, then try again.`;
86
+ }
87
+
88
+ // ---- render ---------------------------------------------------------------------------------------------------
89
+
90
+ function summaryHtml(fit) {
91
+ const summary = typeof fit.summary === 'string' ? fit.summary : '';
92
+ const cut = summary.indexOf(NOT_CHECKED_SPLIT);
93
+ const lead = cut >= 0 ? summary.slice(0, cut) : summary;
94
+ const unchecked = cut >= 0 ? summary.slice(cut + 1) : '';
95
+ const c = fit.coverage || {};
96
+ const chips = [
97
+ [c.findings || 0, 'open', 'warn'], [c.notMeasured || 0, 'could not be measured', ''], [c.notes || 0, c.notes === 1 ? 'note' : 'notes', ''],
98
+ ].map(([n, w, cls]) => `<span class="mfc-chip${cls && n ? ` ${cls}` : ''}">${esc(n)} ${esc(w)}</span>`).join('');
99
+ // A log FloLess could not read (or lines in it it could not read) means a finding may rest on an assumption the
100
+ // person recorded that this list cannot show: say so, so "open" is never read as "nobody decided anything".
101
+ const log = fit.assumptions && fit.assumptions.log && typeof fit.assumptions.log === 'object' ? fit.assumptions.log : null;
102
+ const skipped = log && Number.isSafeInteger(log.skipped) && log.skipped > 0 ? log.skipped : 0;
103
+ const logLine = log && log.error
104
+ ? '<p class="mfc-error" role="alert" data-fit-log-unread>The assumptions recorded on these findings could not be read, so a finding below may rest on an assumption that is not shown. Close and open Model checks to try again.</p>'
105
+ : skipped ? `<p class="mfc-error" role="alert" data-fit-log-unread>${esc(skipped)} ${skipped === 1 ? 'line' : 'lines'} of the recorded assumptions could not be read, so a finding below may rest on an assumption that is not shown.</p>` : '';
106
+ const unsaved = st.unsaved ? '<p class="mfc-error" role="alert" data-fit-unsaved>Your latest edits are not saved; this fit is of the saved model.</p>' : '';
107
+ return `${unsaved}<p class="mfc-summary" data-fit-summary>${esc(lead)}</p>${logLine}<div class="mfc-chips" aria-label="Counts">${chips}</div>`
108
+ + (unchecked ? `<p class="mfc-unchecked" data-fit-unchecked>${esc(unchecked)}</p>` : '');
109
+ }
110
+
111
+ function findingHtml(f, i) {
112
+ const id = esc(f.identity || `f${i}`);
113
+ const sid = `mfcS${i}`;
114
+ const where = whereText(f.where);
115
+ const rows = shownMeasured(f.measured);
116
+ const measured = rows.length ? `<dl class="mfc-measured">${rows.map((r) => `<div><dt>${esc(r.label)}</dt><dd>${esc(r.text)}</dd></div>`).join('')}</dl>` : '';
117
+ const a = f.assumption && typeof f.assumption.label === 'string' ? f.assumption : null;
118
+ const assumption = a ? `<div class="mfc-assumed" data-fit-assumption><span class="mfc-chip warn">Open, on an assumption</span>`
119
+ + `<p>${esc(a.label)}</p><button type="button" class="mfc-link" data-fit-act="withdraw" data-id="${id}" data-command-id="steel.element-fit-withdraw" aria-describedby="${sid}">Withdraw</button></div>` : '';
120
+ const lapsed = Array.isArray(f.lapsedAssumptions) && f.lapsedAssumptions.length
121
+ ? `<ul class="mfc-lapsed" data-fit-lapsed>${f.lapsedAssumptions.map((l) => `<li>${esc(l.note || 'An earlier assumption no longer matches this finding')}: “${esc(l.statement)}” (${esc(l.by)}, ${esc(String(l.at || '').slice(0, 10))})</li>`).join('')}</ul>` : '';
122
+ const open = st.open.get(f.identity);
123
+ const editor = open ? editorHtml(f, open, id, sid) : '';
124
+ const actions = open ? '' : `<div class="mfc-actions">`
125
+ + (a ? '' : `<button type="button" data-fit-act="proceed" data-id="${id}" data-command-id="steel.element-fit-proceed" aria-expanded="false" aria-describedby="${sid}">Proceed on an assumption…</button>`)
126
+ + `<button type="button" data-fit-act="copy" data-id="${id}" data-command-id="steel.element-fit-copy-question" aria-describedby="${sid}">Copy question</button>`
127
+ + '<span class="mfc-note">No RFI raised yet</span></div>';
128
+ return `<li class="mfc-finding" data-fit-finding="${id}">`
129
+ + `<p class="mfc-sentence" id="${sid}">${esc(f.sentence)}</p>`
130
+ + (where ? `<span class="mfc-chip mfc-where" data-tip="${esc(where)}">${esc(where)}</span>` : '')
131
+ + measured + assumption + lapsed + editor + actions + '</li>';
132
+ }
133
+
134
+ function editorHtml(f, open, id, sid) {
135
+ const changed = open.changed ? `<p class="mfc-banner" role="status">This finding changed while you were writing. Here is how it reads now: “${esc(f.sentence)}”</p>` : '';
136
+ const err = open.error ? `<p class="mfc-error" role="alert">${esc(open.error)}</p>` : '';
137
+ if (open.step === 'confirm') {
138
+ return `<div class="mfc-confirm" data-fit-confirm><b tabindex="-1" data-fit-focus>Proceed on this assumption?</b>`
139
+ + `<p class="mfc-q-label">The finding</p><blockquote data-fit-confirm-finding>${esc(f.sentence)}</blockquote>`
140
+ + `<p class="mfc-q-label">Your assumption</p><blockquote data-fit-confirm-statement>${esc(open.text.trim())}</blockquote>`
141
+ + '<p class="mfc-hint">The finding stays open, labelled with your words, and approval records it. You can withdraw it later.</p>'
142
+ + err + `<div class="mfc-actions"><button type="button" class="primary" data-fit-act="confirm" data-id="${id}" data-command-id="steel.element-fit-confirm"${st.busy ? ' disabled' : ''}>Confirm assumption</button>`
143
+ + `<button type="button" data-fit-act="back" data-id="${id}" data-command-id="steel.element-fit-back">Back</button></div></div>`;
144
+ }
145
+ const n = open.text.length;
146
+ return `<div class="mfc-write">${changed}<label for="mfcT${sid}">Your assumption, in your own words</label>`
147
+ + `<textarea id="mfcT${sid}" data-fit-text data-id="${id}" data-command-id="steel.element-fit-statement" maxlength="${MAX_STATEMENT}" rows="3" placeholder="mortar bed 10 mm, see detail 4/S-501" aria-describedby="${sid} mfcC${sid}">${esc(open.text)}</textarea>`
148
+ + `<span class="mfc-count" id="mfcC${sid}">${n}/${MAX_STATEMENT}</span>${err}`
149
+ + `<div class="mfc-actions"><button type="button" class="primary" data-fit-act="next" data-id="${id}" data-command-id="steel.element-fit-next">Next</button>`
150
+ + `<button type="button" data-fit-act="cancel" data-id="${id}" data-command-id="steel.element-fit-cancel">Cancel</button></div></div>`;
151
+ }
152
+
153
+ function cellsHtml(cells) {
154
+ return `<ul class="mfc-cells">${cells.map((c) => `<li><b>${esc(c.id)}</b> · ${esc(c.check)}: ${esc(c.reason)}</li>`).join('')}</ul>`;
155
+ }
156
+
157
+ function settingHtml(fit) {
158
+ const s = (fit.measured && fit.measured.fitSettings) || {};
159
+ const deg = st.limitDraft != null ? st.limitDraft : (typeof s.foldLimitDeg === 'number' ? String(s.foldLimitDeg) : '');
160
+ const notDefault = s.foldLimitSource && s.foldLimitSource !== 'default';
161
+ return `<details class="mfc-fold mfc-setting" data-fit-setting${st.change || st.limitError || folds.has('setting') ? ' open' : ''}><summary>Setting: ${esc(LIMIT_NAME.toLowerCase())}</summary>`
162
+ + `<form class="mfc-limit" data-fit-limit-form novalidate><label for="mfcLimit">${esc(LIMIT_NAME)}</label>`
163
+ + `<div class="mfc-limit-row"><span class="mfc-deg"><input id="mfcLimit" type="text" inputmode="decimal" autocomplete="off" spellcheck="false" data-fit-limit data-command-id="steel.element-fit-limit" value="${esc(deg)}" aria-describedby="mfcLimitSource"><span aria-hidden="true">°</span></span>`
164
+ + `<button type="submit" class="primary" data-command-id="steel.element-fit-limit-save"${st.busy ? ' disabled' : ''}>Save</button>`
165
+ + (notDefault ? `<button type="button" class="mfc-link" data-fit-act="reset" data-command-id="steel.element-fit-limit-reset">Reset to FloLess's default</button>` : '')
166
+ + `</div><p class="mfc-source" id="mfcLimitSource" data-fit-limit-source>${esc(s.foldLimitLabel || '')}</p>`
167
+ + (st.limitError ? `<p class="mfc-error" role="alert">${esc(st.limitError)}</p>` : '')
168
+ + (st.change ? `<p class="mfc-banner" role="status" data-fit-change>${esc(st.change)}</p>` : '')
169
+ + '</form></details>';
170
+ }
171
+
172
+ // Every redraw replaces the drawer's markup, so a fold the person opened (the notes, the checks not measured, the
173
+ // setting) is read off the page first and drawn open again; otherwise Proceed on a note closed the very fold its form
174
+ // was in.
175
+ let folds = new Set();
176
+ function openFolds() {
177
+ const open = new Set();
178
+ for (const [key, sel] of [['notes', '[data-fit-notes]'], ['not-measured', '[data-fit-not-measured]'], ['setting', '[data-fit-setting]']]) {
179
+ const el = host.querySelector(sel);
180
+ if (el && el.hasAttribute('open')) open.add(key);
181
+ }
182
+ return open;
183
+ }
184
+
185
+ function render() {
186
+ const fit = st.fit;
187
+ folds = openFolds();
188
+ let body;
189
+ if (st.status === 'loading' || st.status === 'idle') {
190
+ body = '<div class="mfc-progress" role="progressbar" aria-label="Measuring the fit"><span></span></div><p class="mfc-state">Measuring the fit of walls, slabs and footings…</p>';
191
+ } else if (st.status === 'error') {
192
+ body = `<div class="mfc-state" role="alert"><p>${esc(st.error)}</p><button type="button" data-fit-act="retry" data-command-id="steel.element-fit-retry">Try again</button></div>`;
193
+ } else if (!fit) {
194
+ body = '<p class="mfc-state">This model has no walls, slabs or footings, so there is no fit to measure.</p>';
195
+ } else {
196
+ const all = findingsOf();
197
+ const warnings = all.map((f, i) => [f, i]).filter(([f]) => f.severity !== 'note');
198
+ const notes = all.map((f, i) => [f, i]).filter(([f]) => f.severity === 'note');
199
+ const nm = Array.isArray(fit.notMeasured) ? fit.notMeasured : [];
200
+ // A note whose proceed form is open is never drawn inside a closed fold.
201
+ const notesOpen = folds.has('notes') || notes.some(([f, i]) => st.open.has(f.identity || `f${i}`));
202
+ body = (st.status === 'refreshing' ? '<div class="mfc-progress" role="progressbar" aria-label="Measuring the fit again"><span></span></div>' : '')
203
+ + summaryHtml(fit)
204
+ + (warnings.length ? `<ul class="mfc-list" data-fit-findings>${warnings.map(([f, i]) => findingHtml(f, i)).join('')}</ul>`
205
+ : '<p class="mfc-state" data-fit-empty>Nothing found among what was measured.</p>')
206
+ + (notes.length ? `<details class="mfc-fold" data-fit-notes${notesOpen ? ' open' : ''}><summary>${notes.length} ${notes.length === 1 ? 'note' : 'notes'}</summary><ul class="mfc-list mfc-notes">${notes.map(([f, i]) => findingHtml(f, i)).join('')}</ul></details>` : '')
207
+ + (nm.length ? `<details class="mfc-fold" data-fit-not-measured${folds.has('not-measured') ? ' open' : ''}><summary>${nm.length} ${nm.length === 1 ? 'check' : 'checks'} could not be measured</summary>${cellsHtml(nm)}</details>` : '')
208
+ + settingHtml(fit);
209
+ }
210
+ const focused = doc.activeElement && host.contains(doc.activeElement) ? focusKey(doc.activeElement) : null;
211
+ host.innerHTML = `<section class="mfc-group" aria-labelledby="mfcFitTitle"><h3 id="mfcFitTitle" class="mfc-h">Fit of walls, slabs and footings</h3>${body}`
212
+ + `<p class="mfc-live" role="status" aria-live="polite" data-fit-live>${esc(st.live)}</p></section>`;
213
+ if (focused) restoreFocus(focused);
214
+ }
215
+
216
+ function focusKey(el) {
217
+ if (el.matches('[data-fit-text]')) return { sel: `[data-fit-text][data-id="${el.dataset.id}"]`, caret: el.selectionStart };
218
+ if (el.matches('[data-fit-limit]')) return { sel: '[data-fit-limit]', caret: el.selectionStart };
219
+ if (el.dataset && el.dataset.fitAct) return { sel: `[data-fit-act="${el.dataset.fitAct}"]${el.dataset.id ? `[data-id="${el.dataset.id}"]` : ''}` };
220
+ return null;
221
+ }
222
+ function restoreFocus(k) {
223
+ const el = host.querySelector(k.sel);
224
+ if (!el) return;
225
+ try { el.focus({ preventScroll: true }); if (k.caret != null && el.setSelectionRange) el.setSelectionRange(k.caret, k.caret); } catch { /* focus is a courtesy */ }
226
+ }
227
+ function focus(sel) { const el = host.querySelector(sel); if (el) { try { el.focus({ preventScroll: true }); } catch { /* courtesy */ } } }
228
+
229
+ // ---- the person's choices ---------------------------------------------------------------------------------------
230
+
231
+ async function confirmAssumption(identity) {
232
+ const f = byIdentity(identity); const open = st.open.get(identity);
233
+ if (!f || !open || st.busy) return;
234
+ st.busy = true; open.error = ''; render();
235
+ try {
236
+ await fetchJson(urls.assumptions, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ identity, binding: f.binding, statement: open.text.trim() }) });
237
+ st.open.delete(identity);
238
+ st.live = 'Recorded. The finding stays open, labelled with your assumption.';
239
+ st.busy = false;
240
+ await load(true);
241
+ focus(`[data-fit-finding="${identity}"] [data-fit-act]`);
242
+ } catch (e) {
243
+ st.busy = false;
244
+ const b = e && e.body;
245
+ if (e && e.status === 409 && b && b.code === 'fit-finding-changed' && b.finding) {
246
+ // The finding as it reads now: shown, and asked again with the person's words kept.
247
+ st.fit = { ...st.fit, findings: findingsOf().map((x) => (x.identity === identity ? { ...x, ...b.finding } : x)) };
248
+ open.step = 'write'; open.changed = true; open.error = '';
249
+ render(); focus(`[data-fit-text][data-id="${identity}"]`);
250
+ } else if (e && e.status === 409) {
251
+ open.error = errorWords(e, 'Nothing was recorded.');
252
+ render();
253
+ await load(true);
254
+ } else { open.error = errorWords(e, 'Nothing was recorded.'); render(); }
255
+ }
256
+ }
257
+
258
+ async function withdraw(identity) {
259
+ if (st.busy) return;
260
+ st.busy = true;
261
+ try {
262
+ const r = await fetchJson(urls.assumptions, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ withdraws: identity }) });
263
+ st.live = (r && r.sentence) || 'Withdrawn.';
264
+ } catch (e) { st.live = errorWords(e, 'Nothing was withdrawn.'); }
265
+ st.busy = false;
266
+ await load(true);
267
+ focus(`[data-fit-finding="${identity}"] [data-fit-act="proceed"]`);
268
+ }
269
+
270
+ async function copyQuestion(identity) {
271
+ try {
272
+ const q = await fetchJson(urls.rfiQuestion(identity), { method: 'GET' });
273
+ const question = q && typeof q.question === 'string' ? q.question.trim() : '';
274
+ if (!question) { st.live = 'The question could not be copied: FloLess returned no question for this finding. Try again.'; render(); return; }
275
+ await copyText(question);
276
+ st.live = `Question copied. ${q.label || 'No RFI raised yet'}.`;
277
+ } catch (e) { st.live = errorWords(e, 'The question could not be copied.'); }
278
+ render();
279
+ }
280
+
281
+ async function saveLimit(deg) {
282
+ if (st.busy) return;
283
+ // The change line is this save's outcome; an earlier action's status (a withdraw, a copy) is not left beside it.
284
+ st.busy = true; st.limitError = ''; st.change = ''; st.live = ''; render();
285
+ try {
286
+ const r = await setFoldLimit(deg);
287
+ st.limitDraft = null;
288
+ st.change = (r && typeof r.fitChange === 'string' && r.fitChange)
289
+ || (deg === null ? 'Back to FloLess\'s default. No finding was added or removed.' : 'Saved. No finding was added or removed.');
290
+ st.busy = false;
291
+ await load(true);
292
+ focus('[data-fit-limit]');
293
+ } catch (e) {
294
+ st.busy = false;
295
+ st.limitError = errorWords(e, 'The setting was not changed.');
296
+ render(); focus('[data-fit-limit]');
297
+ }
298
+ }
299
+
300
+ host.addEventListener('click', (e) => {
301
+ const b = e.target.closest('[data-fit-act]');
302
+ if (!b || !host.contains(b)) return;
303
+ const id = b.dataset.id;
304
+ switch (b.dataset.fitAct) {
305
+ case 'retry': load(); break;
306
+ case 'proceed': st.open.set(id, { step: 'write', text: '', error: '', changed: false }); render(); focus(`[data-fit-text][data-id="${id}"]`); break;
307
+ case 'cancel': st.open.delete(id); render(); focus(`[data-fit-act="proceed"][data-id="${id}"]`); break;
308
+ case 'next': {
309
+ const open = st.open.get(id); if (!open) break;
310
+ if (!open.text.trim()) { open.error = 'Say what you are assuming, so the finding can carry your words.'; render(); focus(`[data-fit-text][data-id="${id}"]`); break; }
311
+ open.step = 'confirm'; open.error = ''; render(); focus(`[data-fit-finding="${id}"] [data-fit-focus]`); break;
312
+ }
313
+ case 'back': { const open = st.open.get(id); if (open) { open.step = 'write'; render(); focus(`[data-fit-text][data-id="${id}"]`); } break; }
314
+ case 'confirm': confirmAssumption(id); break;
315
+ case 'withdraw': withdraw(id); break;
316
+ case 'copy': copyQuestion(id); break;
317
+ case 'reset': saveLimit(null); break;
318
+ default: break;
319
+ }
320
+ });
321
+ host.addEventListener('input', (e) => {
322
+ const t = e.target;
323
+ if (t.matches('[data-fit-text]')) {
324
+ const open = st.open.get(t.dataset.id); if (!open) return;
325
+ open.text = t.value;
326
+ const count = t.parentElement.querySelector('.mfc-count'); if (count) count.textContent = `${t.value.length}/${MAX_STATEMENT}`;
327
+ } else if (t.matches('[data-fit-limit]')) st.limitDraft = t.value;
328
+ });
329
+ host.addEventListener('submit', (e) => {
330
+ if (!e.target.matches('[data-fit-limit-form]')) return;
331
+ e.preventDefault();
332
+ const raw = String(host.querySelector('[data-fit-limit]').value || '').trim().replace(',', '.').replace(/°$/, '');
333
+ const deg = Number(raw);
334
+ if (!raw || !Number.isFinite(deg) || deg <= 0 || deg >= 180) {
335
+ st.limitError = 'Type an angle between 0° and 180°, or use Reset to go back to FloLess\'s default.';
336
+ render(); focus('[data-fit-limit]'); return;
337
+ }
338
+ saveLimit(deg);
339
+ });
340
+ // Escape in a step closes that step only, never the drawer (the drawer closes on an Escape nothing took).
341
+ host.addEventListener('keydown', (e) => {
342
+ if (e.key !== 'Escape') return;
343
+ const row = e.target.closest('[data-fit-finding]');
344
+ const id = row && row.dataset.fitFinding;
345
+ if (id && st.open.has(id)) {
346
+ e.preventDefault();
347
+ const open = st.open.get(id);
348
+ if (open.step === 'confirm') { open.step = 'write'; render(); focus(`[data-fit-text][data-id="${id}"]`); } else { st.open.delete(id); render(); focus(`[data-fit-act="proceed"][data-id="${id}"]`); }
349
+ }
350
+ });
351
+
352
+ render();
353
+ return { load, state: st };
354
+ }
@@ -237,14 +237,20 @@ export function mountModelSpatialPanel({
237
237
  const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = `Origin · ${units()}`; grid.append(a); vectorFields(documentRef, grid, 'clip-origin', clip.origin, ['X', 'Y', 'Z'], lengthPresentation);
238
238
  const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = 'Normal'; grid.append(b); vectorFields(documentRef, grid, 'clip-normal', clip.normal);
239
239
  } else {
240
- const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = `Minimum · ${units()}`; grid.append(a); vectorFields(documentRef, grid, 'clip-min', clip.min, ['X', 'Y', 'Z'], lengthPresentation);
241
- const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = `Maximum · ${units()}`; grid.append(b); vectorFields(documentRef, grid, 'clip-max', clip.max, ['X', 'Y', 'Z'], lengthPresentation);
240
+ // A turned box keeps its corners as they were BEFORE turning (model-clip-box.js), so a turned box
241
+ // says so — the numbers are not the world corners of what is drawn — and Update keeps the turn.
242
+ const rotation = Array.isArray(clip.rotationDeg) ? clip.rotationDeg : [0, 0, 0];
243
+ const turned = rotation.some((angle) => angle !== 0);
244
+ const r = documentRef.createElement('div'); r.className = 'model-spatial-panel-grid-label'; r.textContent = 'Rotation · degrees'; grid.append(r); vectorFields(documentRef, grid, 'clip-rotation', rotation);
245
+ const a = documentRef.createElement('div'); a.className = 'model-spatial-panel-grid-label'; a.textContent = `${turned ? 'Minimum, before turning' : 'Minimum'} · ${units()}`; grid.append(a); vectorFields(documentRef, grid, 'clip-min', clip.min, ['X', 'Y', 'Z'], lengthPresentation);
246
+ const b = documentRef.createElement('div'); b.className = 'model-spatial-panel-grid-label'; b.textContent = `${turned ? 'Maximum, before turning' : 'Maximum'} · ${units()}`; grid.append(b); vectorFields(documentRef, grid, 'clip-max', clip.max, ['X', 'Y', 'Z'], lengthPresentation);
242
247
  }
243
248
  card.append(grid); const actions = actionRow(documentRef);
244
249
  const update = button(documentRef, 'Update', { action: 'clip-update', tip: `Apply edited values to ${name.textContent}` });
245
250
  update.addEventListener('click', () => run(() => tools.updateClip(clip.id, clip.kind === 'plane'
246
251
  ? { origin: lengthValuesFrom(card, 'clip-origin', 'Clip origin'), normal: valuesFrom(card, 'clip-normal', 'Clip normal') }
247
- : { min: lengthValuesFrom(card, 'clip-min', 'Clip minimum'), max: lengthValuesFrom(card, 'clip-max', 'Clip maximum') }), 'Clip updated.'));
252
+ : { min: lengthValuesFrom(card, 'clip-min', 'Clip minimum'), max: lengthValuesFrom(card, 'clip-max', 'Clip maximum'), rotationDeg: valuesFrom(card, 'clip-rotation', 'Clip rotation') }), 'Clip updated.'));
253
+
248
254
  const remove = button(documentRef, 'Remove', { action: 'clip-remove', tip: `Remove ${name.textContent}` });
249
255
  remove.addEventListener('click', () => run(() => tools.removeClip(clip.id), 'Clip removed.'));
250
256
  const enabled = button(documentRef, clip.enabled === false ? 'Disabled' : 'Enabled', { action: 'clip-enabled', tip: `Enable or disable ${name.textContent}`, pressed: clip.enabled !== false });
@@ -7,6 +7,8 @@
7
7
  * semantics identical.
8
8
  */
9
9
 
10
+ import { canonicalClipAngle } from './model-clip-box.js';
11
+
10
12
  export const MODEL_SPATIAL_STATE_SCHEMA = 'floless.model-spatial-state/v1';
11
13
  export const MODEL_SPATIAL_LIMITS = Object.freeze({ savedViews: 256, frames: 128, clips: 64 });
12
14
 
@@ -94,9 +96,16 @@ function validatePlane(value, label = 'plane') {
94
96
  return snapshot({ origin: vec3(value.origin, `${label}.origin`), normal: unit(vec3(value.normal, `${label}.normal`), `${label}.normal`) });
95
97
  }
96
98
 
97
- function validateBox(value, label = 'box') {
99
+ function validateBox(value, label = 'box', { rotation = false } = {}) {
98
100
  const min = vec3(value?.min, `${label}.min`); const max = vec3(value?.max, `${label}.max`);
99
101
  if (min.some((item, index) => item >= max[index])) throw Object.assign(new TypeError(`${label} must have positive extents.`), { code: 'E_MODEL_SPATIAL_EXTENTS' });
102
+ // A clip box may be turned about its own centre (see model-clip-box.js). Any finite angle is accepted
103
+ // and folded into (−180°, 180°]; an all-zero rotation is stored as no rotation at all, so an unrotated
104
+ // box stays exactly the record it always was. The work area stays axis-aligned.
105
+ if (rotation && value?.rotationDeg !== undefined && value?.rotationDeg !== null) {
106
+ const rotationDeg = vec3(value.rotationDeg, `${label}.rotationDeg`).map(canonicalClipAngle);
107
+ if (rotationDeg.some((angle) => angle !== 0)) return snapshot({ min, max, rotationDeg });
108
+ }
100
109
  return snapshot({ min, max });
101
110
  }
102
111
 
@@ -108,7 +117,7 @@ function validateClip(value, label = 'clip') {
108
117
  return value.kind === 'plane'
109
118
  ? snapshot({ ...common, kind: 'plane', ...validatePlane({ origin: value.origin, normal: value.normal }, label) })
110
119
  : value.kind === 'box'
111
- ? snapshot({ ...common, kind: 'box', ...validateBox({ min: value.min, max: value.max }, label) })
120
+ ? snapshot({ ...common, kind: 'box', ...validateBox({ min: value.min, max: value.max, rotationDeg: value.rotationDeg }, label, { rotation: true }) })
112
121
  : (() => { throw new TypeError(`${label} kind must be plane or box.`); })();
113
122
  }
114
123
 
@@ -221,7 +230,7 @@ export function createModelSpatialTools({ initial = null, onChange = () => {} }
221
230
  updateView(id, patch) { ensureLive(); const at = state.savedViews.findIndex((item) => item.id === id); if (at < 0) throw Object.assign(new Error('Saved view not found.'), { code: 'E_MODEL_VIEW_NOT_FOUND' }); state.savedViews[at] = snapshot({ ...state.savedViews[at], ...clone(patch), id }); return emit('view-update'); },
222
231
  deleteView(id) { ensureLive(); const before = state.savedViews.length; state.savedViews = state.savedViews.filter((item) => item.id !== id); return before === state.savedViews.length ? snapshot(state) : emit('view-delete'); },
223
232
  addClipPlane({ id, origin, normal, enabled = true, label = id }) { ensureLive(); if (state.clips.length >= MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' }); if (!id || state.clips.some((item) => item.id === id)) throw new TypeError('Clip needs a unique id.'); state.clips.push(validateClip({ id, kind: 'plane', origin, normal, enabled, label })); return emit('clip-add'); },
224
- addClipBox({ id, min, max, enabled = true, label = id }) { ensureLive(); if (state.clips.length >= MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' }); if (!id || state.clips.some((item) => item.id === id)) throw new TypeError('Clip needs a unique id.'); state.clips.push(validateClip({ id, kind: 'box', min, max, enabled, label })); return emit('clip-add'); },
233
+ addClipBox({ id, min, max, rotationDeg = undefined, enabled = true, label = id }) { ensureLive(); if (state.clips.length >= MODEL_SPATIAL_LIMITS.clips) throw Object.assign(new Error('The clip limit was reached.'), { code: 'E_MODEL_CLIP_LIMIT' }); if (!id || state.clips.some((item) => item.id === id)) throw new TypeError('Clip needs a unique id.'); state.clips.push(validateClip({ id, kind: 'box', min, max, rotationDeg, enabled, label })); return emit('clip-add'); },
225
234
  updateClip(id, patch) { ensureLive(); const at = state.clips.findIndex((item) => item.id === id); if (at < 0) throw Object.assign(new Error('Clip not found.'), { code: 'E_MODEL_CLIP_NOT_FOUND' }); state.clips[at] = validateClip({ ...state.clips[at], ...clone(patch), id }, 'clip'); return emit('clip-update'); },
226
235
  /** @param {{clips?:any[],workArea?:any}} sections */
227
236
  replaceSections(sections = {}) { ensureLive(); const next = canonicalSections(sections); state.clips = next.clips; state.workArea = next.workArea; return emit('sections-replace'); },
@@ -49,6 +49,80 @@ export function teklaGeometrySelection(ids, entityById, membersByAssembly = new
49
49
  return [...selected];
50
50
  }
51
51
 
52
+ /* -- Objects read but not drawn yet (#4008) ------------------------------------------------------------------------------
53
+ A read that draws nothing publishes with AWARE's signed "nothing drawable yet" label, and only then does the verifier write
54
+ `undrawn` on an object: the audit's own code for why it has no shape. Those objects are browsed, searched and selected like
55
+ drawn ones, never lit in 3D. A model that is drawn, wholly or partly, has no object with `undrawn`. */
56
+
57
+ /** @param {any} entity */
58
+ export function isTeklaUndrawn(entity) { return typeof entity?.undrawn === 'string' && !entity.geometry?.length; }
59
+
60
+ /** What a view query matches: an object that is drawn, or read but not drawn yet; never the structural grid. @param {any} entity */
61
+ export function isTeklaQueryable(entity) {
62
+ return entity?.structuralGrid?.mapping?.kind !== 'symmetric' && (entity?.geometry?.length > 0 || isTeklaUndrawn(entity));
63
+ }
64
+
65
+ /**
66
+ * The undrawn objects a selection resolves to, through the given authenticated memberships; null when they and the
67
+ * `alreadySelected` drawn ones are together more than the viewer selects at once.
68
+ * @param {string[]} ids
69
+ * @param {Map<string, any>} entityById
70
+ * @param {Map<string, string[]>[]} memberships
71
+ */
72
+ export function teklaUndrawnSelection(ids, entityById, memberships = [], alreadySelected = 0) {
73
+ const undrawn = [], visited = new Set(), stack = [...(ids || [])].reverse();
74
+ while (stack.length) {
75
+ const id = stack.pop();
76
+ if (visited.has(id)) continue;
77
+ visited.add(id);
78
+ const entity = entityById.get(id); if (!entity) continue;
79
+ if (isTeklaUndrawn(entity) && undrawn.push(id) + alreadySelected > TEKLA_GEOMETRY_SELECTION_CAP) return null;
80
+ for (const membership of memberships) {
81
+ const members = membership.get(id) || [];
82
+ for (let at = members.length - 1; at >= 0; at--) stack.push(members[at]);
83
+ }
84
+ }
85
+ return undrawn;
86
+ }
87
+
88
+ /**
89
+ * The objects of an import audit whose geometry could not be drawn, by the code that says why.
90
+ * @param {readonly { entityId: string, check: string, code: string, hasGeometry: boolean }[]} findings
91
+ * @returns {Map<string, string>}
92
+ */
93
+ export function teklaAuditUndrawn(findings) {
94
+ const undrawn = new Map();
95
+ for (const finding of findings) {
96
+ if (finding.hasGeometry || (finding.check !== 'geometry-reconstruction' && finding.code !== 'unsupported-native-type')) continue;
97
+ if (!undrawn.has(finding.entityId) || finding.check === 'geometry-reconstruction') undrawn.set(finding.entityId, finding.code);
98
+ }
99
+ return undrawn;
100
+ }
101
+
102
+ /**
103
+ * What a model can answer about its undrawn objects, from its objects and its verified audit (null: it has none):
104
+ * `all` every undrawn object is listed (a properties-only model), `none` there is none, `partial` some are named only by
105
+ * the audit (`notListed` of them) and cannot be listed or selected yet, `unknown` no audit says. `undrawn` counts the
106
+ * listed ones. The page and the server both ask this, so a search cannot get two answers.
107
+ * @param {any[]} entities
108
+ * @param {readonly any[] | null | undefined} findings
109
+ */
110
+ export function teklaDrawnState(entities, findings) {
111
+ const listed = new Set(entities.filter(isTeklaUndrawn).map((entity) => entity.id));
112
+ if (!Array.isArray(findings)) return Object.freeze({ class: 'unknown', notListed: 0, undrawn: listed.size });
113
+ const notListed = [...teklaAuditUndrawn(findings).keys()].filter((id) => !listed.has(id)).length;
114
+ return Object.freeze({ class: notListed ? 'partial' : listed.size ? 'all' : 'none', notListed, undrawn: listed.size });
115
+ }
116
+
117
+ /** Where the properties of selected undrawn objects are, in the editor's words and in chat's. */
118
+ export function undrawnPropertiesWords(count) { return `${count === 1 ? 'its' : 'their'} properties are in the Model tab`; }
119
+
120
+ /** What the editor says of a selection with undrawn objects: `undrawn` of the `selected` objects. */
121
+ export function teklaUndrawnWords(undrawn, selected) {
122
+ if (undrawn < selected) return `${undrawn.toLocaleString()} of ${selected.toLocaleString()} selected ${undrawn === 1 ? 'is' : 'are'} not drawn yet; ${undrawnPropertiesWords(undrawn)}`;
123
+ return `Selected, not drawn yet; ${undrawnPropertiesWords(undrawn)}`;
124
+ }
125
+
52
126
  /** The verifier exposes legacy `contains` and native-v2 assembly membership explicitly. */
53
127
  export function teklaAssemblyMembership(relationships) {
54
128
  const members = new Map();