@floless/app 0.174.0 → 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 (89) 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 +53 -0
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +823 -0
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +245 -0
  6. package/dist/pdf-engine/floless_pdf/geometry.py +115 -0
  7. package/dist/pdf-engine/floless_pdf/images.py +75 -0
  8. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  9. package/dist/pdf-engine/floless_pdf/textrules.py +200 -0
  10. package/dist/schemas/steel.model.v2.schema.json +45 -1
  11. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  12. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  13. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  14. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  15. package/dist/skills/floless-app-steel-model/SKILL.md +14 -1
  16. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  17. package/dist/skills/floless-app-steel-takeoff/SKILL.md +18 -7
  18. package/dist/skills/floless-app-tweak-contract/SKILL.md +3 -2
  19. package/dist/web/agents.js +1 -1
  20. package/dist/web/app.css +120 -15
  21. package/dist/web/app.js +89 -38
  22. package/dist/web/aware-hold.js +10 -0
  23. package/dist/web/aware.js +405 -51
  24. package/dist/web/boot-watchdog.js +249 -0
  25. package/dist/web/card-details.js +88 -0
  26. package/dist/web/chat.css +29 -0
  27. package/dist/web/chat.js +430 -128
  28. package/dist/web/commands-connection-design.js +23 -0
  29. package/dist/web/commands-revit.js +3 -0
  30. package/dist/web/commands-shell.js +226 -10
  31. package/dist/web/commands-steel.js +95 -5
  32. package/dist/web/commands-tekla-parser.js +21 -1
  33. package/dist/web/connection-design-editor.html +71 -0
  34. package/dist/web/connection-design-editor.js +794 -61
  35. package/dist/web/connection-design-handles.js +9 -3
  36. package/dist/web/element-approval.js +74 -0
  37. package/dist/web/element-context.js +76 -6
  38. package/dist/web/element-geometry.js +8 -2
  39. package/dist/web/element-holds.js +68 -5
  40. package/dist/web/element-type-actions.js +22 -3
  41. package/dist/web/element-types.js +12 -5
  42. package/dist/web/element-words.js +15 -11
  43. package/dist/web/grid-place.js +51 -0
  44. package/dist/web/guide.js +2 -0
  45. package/dist/web/index.html +13 -16
  46. package/dist/web/instructor.js +5 -2
  47. package/dist/web/missed-routines.js +6 -1
  48. package/dist/web/model-change-findings.js +147 -32
  49. package/dist/web/model-change-review.js +435 -32
  50. package/dist/web/model-clash-check.css +100 -0
  51. package/dist/web/model-clash-check.js +681 -0
  52. package/dist/web/model-clip-box.js +204 -0
  53. package/dist/web/model-clip-list.js +153 -3
  54. package/dist/web/model-clip-session.js +3 -3
  55. package/dist/web/model-clip-three-overlay.js +135 -25
  56. package/dist/web/model-editor.css +2 -0
  57. package/dist/web/model-elements.js +273 -18
  58. package/dist/web/model-fit-checks.js +354 -0
  59. package/dist/web/model-spatial-panel.js +9 -3
  60. package/dist/web/model-spatial-tools.js +12 -3
  61. package/dist/web/model-tekla-selection.js +74 -0
  62. package/dist/web/model-view-query.js +70 -14
  63. package/dist/web/model-viewport-revit-adapter.js +8 -7
  64. package/dist/web/model-viewport-toolbar.js +8 -4
  65. package/dist/web/pages.js +78 -1
  66. package/dist/web/project-history.js +31 -1
  67. package/dist/web/revit-editor.css +34 -1
  68. package/dist/web/revit-editor.js +176 -55
  69. package/dist/web/run-history.js +8 -0
  70. package/dist/web/sketch-editor.js +141 -2
  71. package/dist/web/sketches.js +192 -6
  72. package/dist/web/start-place.js +46 -0
  73. package/dist/web/steel-3d-core.js +70 -0
  74. package/dist/web/steel-3d-view.js +288 -47
  75. package/dist/web/steel-change-review.css +29 -0
  76. package/dist/web/steel-custom-connection.js +6 -0
  77. package/dist/web/steel-editor.html +532 -33
  78. package/dist/web/steel-filter.html +8 -3
  79. package/dist/web/steel-model-checks.css +76 -0
  80. package/dist/web/steel-model-commands.js +1 -1
  81. package/dist/web/steel-model-v2-commands.js +17 -0
  82. package/dist/web/steel-view-generation.js +6 -2
  83. package/dist/web/teams.js +259 -19
  84. package/dist/web/tekla-editor.html +1 -0
  85. package/dist/web/terminal-requests.js +6 -0
  86. package/dist/web/vendor/connection-engine.js +890 -89
  87. package/dist/web/workspaces.js +630 -48
  88. package/package.json +4 -1
  89. package/preferences-file.mjs +27 -0
@@ -0,0 +1,681 @@
1
+ /**
2
+ * #4029: a clash check of the current steel model, in the steel editor (plan
3
+ * docs/superpowers/specs/2026-11-23-current-model-clash-check-PLAN.md §9, §12a, §12b, §14).
4
+ *
5
+ * Two surfaces: the settings dialog ("Check for clashes…" in the ⋯ menu's Model checks) and the results, in the drawer
6
+ * beside the model that Review changes also uses. Presentation only: AWARE measures, the server records the check, its
7
+ * settings and the person's decisions, and every sentence about what a result proves (the headline, "clean", the
8
+ * banners, what was not checked) is the server's, shown as it is. Nothing here works out a clash, and no control is
9
+ * ever shown disabled: a choice that would find nothing to check still runs, and the server asks.
10
+ *
11
+ * The finding cards are Change Review's own (web/model-change-findings.js), over this check's routes and in its words.
12
+ */
13
+ import { createFindings } from './model-change-findings.js';
14
+
15
+ export const CLASH_CHECK_NOT_KEPT = 'This result is no longer kept. Run the check again to see the model as it is now.';
16
+
17
+ /** The four kinds a check measures and their ten pairs, in the server's order (clash-settings.ts). */
18
+ export const CLASH_KINDS = ['member', 'plate', 'bolt', 'weld'];
19
+ export const CLASH_PAIR_KEYS = CLASH_KINDS.flatMap((a, i) => CLASH_KINDS.slice(i).map((b) => `${a}|${b}`));
20
+ const KIND_WORDS = { member: 'members', plate: 'plates', bolt: 'bolts', weld: 'welds' };
21
+ const cap = (text) => text.charAt(0).toUpperCase() + text.slice(1);
22
+ /** "Plates against bolts": a pair named in the grid's order. */
23
+ export const pairLabel = (key) => { const [a, b] = key.split('|'); return `${cap(KIND_WORDS[a])} against ${KIND_WORDS[b]}`; };
24
+
25
+ const SCOPES = [
26
+ { kind: 'all', label: () => 'Whole model', explain: () => 'Every member, plate, bolt and weld in the saved model.' },
27
+ { kind: 'selection', label: (n) => `Selected (${n})`,
28
+ explain: (n) => (n ? 'The selected objects, their connection parts, and anything touching them.' : 'Nothing is selected. When you run, FloLess offers the whole model instead.') },
29
+ { kind: 'work-area', label: () => 'Inside work area',
30
+ explain: (_n, box) => (box ? 'Objects inside the 3D work area, their connection parts, and anything touching them.' : 'There is no work area in the 3D view. When you run, FloLess offers the whole model instead.') },
31
+ ];
32
+ const SWITCHES = [
33
+ { key: 'reportUnjoinedTouching', label: 'Report parts that touch but aren’t bolted or welded',
34
+ help: 'Steel that touches with nothing joining it is listed under Touching.' },
35
+ { key: 'checkBoltedPlies', label: 'Check bolted plies bear on each other',
36
+ help: 'Each bolt’s plies are checked to sit tight, with no gap between them.' },
37
+ { key: 'setAsideUnbuiltJointOverlaps', label: 'Set aside overlaps at joints not connected yet',
38
+ help: 'Members that run into each other where no connection is modelled yet, as in a stick model, are listed separately instead of as clashes.' },
39
+ ];
40
+ const LENGTHS = [
41
+ { key: 'contactToleranceMm', label: 'Touching within', help: 'Parts this close or closer count as touching.' },
42
+ { key: 'minOverlapMm', label: 'Report overlaps deeper than', help: 'Shallower overlaps are counted but not listed.' },
43
+ ];
44
+ const GROUP_WORDS = { overlap: 'Clashes', contact: 'Touching', bolted: 'Bolted plies apart' };
45
+ const BANNER_ORDER = ['stale', 'model-unreadable', 'partial', 'approximate', 'not-checked-yet', 'truncated'];
46
+ const PROCEED = { 'whole-model': 'whole-model', proceed: 'proceed' };
47
+ const NOT_CHECKED_YET = 'Concrete, anchor rods and base plates are not clash-checked yet (#3998).';
48
+
49
+ /** The words Change Review's cards use, said for a check of the model as it is now (no earlier state to compare). */
50
+ const WORDS = {
51
+ presenceChip: false,
52
+ fixing: 'Being fixed in the model',
53
+ fixTitle: 'Fix it in the model', fixSub: 'Change the model, then check again.', fixButton: 'I’ll fix it in the model',
54
+ fixSaid: (title) => `Recorded: you’re fixing “${title}” in the model.`,
55
+ fixRecorded: (chat) => `${chat ? 'AI Chat recorded that this will be fixed in the model' : 'You said you’d fix this in the model'}`,
56
+ fixCheck: 'To check it, change the model, save it, then check for clashes again.',
57
+ fixMeta: 'This records that you are fixing it; only a later check can show it fixed.',
58
+ acceptRecorded: 'This check now says it proceeds on this assumption.',
59
+ acceptMeta: 'This is written into the check’s record as your assumption, with your name and the time.',
60
+ newerState: 'Decided after the model had changed from the one checked.',
61
+ recordFailed: 'That could not be recorded. Open the result again and try again.',
62
+ reloadFailed: 'The result could not be shown again: open it again to see where the findings stand.',
63
+ findingsFailed: 'This result could not be opened. Check for clashes again.',
64
+ locateFailed: (error) => (typeof error?.said === 'string' && error.said ? error.said : 'The 3D view could not show it. Open the 3D view and try again.'),
65
+ say: (text) => text,
66
+ };
67
+
68
+ export function el(doc, tag, attrs = {}, ...children) {
69
+ const node = doc.createElement(tag);
70
+ for (const [key, value] of Object.entries(attrs)) {
71
+ if (value === undefined || value === null || value === false) continue;
72
+ if (key === 'class') node.className = value;
73
+ else if (key === 'text') node.textContent = value;
74
+ else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
75
+ else node.setAttribute(key, value === true ? '' : String(value));
76
+ }
77
+ for (const child of children.flat()) if (child) node.append(child);
78
+ return node;
79
+ }
80
+
81
+ const plural = (n, one, many = `${one}s`) => `${Number(n).toLocaleString()} ${n === 1 ? one : many}`;
82
+ const clock = (iso) => {
83
+ try { return new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }); } catch { return ''; }
84
+ };
85
+ const day = (iso) => {
86
+ try { return new Date(iso).toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch { return String(iso || ''); }
87
+ };
88
+ const mm = (value) => `${Math.round(Number(value) * 1000) / 1000} mm`;
89
+ const onOff = (value) => (value ? 'on' : 'off');
90
+ /** The settings a person sets, from a stored check's full resolved set (the hidden values left out). */
91
+ const shownSettings = (s) => (s ? {
92
+ contactToleranceMm: s.contactToleranceMm, minOverlapMm: s.minOverlapMm, reportUnjoinedTouching: s.reportUnjoinedTouching !== false,
93
+ checkBoltedPlies: s.checkBoltedPlies !== false, setAsideUnbuiltJointOverlaps: s.setAsideUnbuiltJointOverlaps !== false,
94
+ pairs: Object.fromEntries(CLASH_PAIR_KEYS.map((key) => [key, s.pairs?.[key] !== false])),
95
+ } : null);
96
+ const sameSettings = (a, b) => Boolean(a && b) && JSON.stringify(shownSettings(a)) === JSON.stringify(shownSettings(b));
97
+ const pairsOn = (s) => CLASH_PAIR_KEYS.filter((key) => s?.pairs?.[key] !== false).length;
98
+ /** Every setting a result was checked under, hidden ones too, for the settings line's tip. */
99
+ export function settingsTip(check) {
100
+ const s = check?.settings || {};
101
+ const off = CLASH_PAIR_KEYS.filter((key) => s.pairs?.[key] === false);
102
+ return [
103
+ `Checked: ${check?.scope?.label || 'Whole model'}`,
104
+ `Touching within ${mm(s.contactToleranceMm)}`,
105
+ `Report overlaps deeper than ${mm(s.minOverlapMm)}`,
106
+ `Touching parts with nothing joining them: ${onOff(s.reportUnjoinedTouching !== false)}`,
107
+ `Bolted plies: ${onOff(s.checkBoltedPlies !== false)}`,
108
+ `Set aside overlaps at joints not connected yet: ${onOff(s.setAsideUnbuiltJointOverlaps !== false)}`,
109
+ off.length ? `Type pairs: ${CLASH_PAIR_KEYS.length - off.length} of ${CLASH_PAIR_KEYS.length} (off: ${off.map(pairLabel).join(', ')})` : `Type pairs: all ${CLASH_PAIR_KEYS.length}`,
110
+ `Gap search ${mm(s.gapSearchMm)}`,
111
+ `Weld tolerance ${mm(s.weldToleranceMm)}`,
112
+ `Curve accuracy ${mm(s.sagittaMm)}`,
113
+ check?.origin === 'one-off' ? 'Settings used for this check only' : 'The project’s saved settings',
114
+ `${day(check?.at)}, ${check?.via === 'chat' ? 'from AI Chat' : check?.via === 'terminal' ? 'from a terminal' : 'from the FloLess window'}`,
115
+ ].join('. ') + '.';
116
+ }
117
+
118
+ /**
119
+ * Mount the clash check.
120
+ * @param {{
121
+ * host: Element, doc: Document, projectId: string,
122
+ * fetchJson: (path: string, init?: object) => Promise<any>,
123
+ * locate: (target: {kind: 'members'|'part'|'joint', ids: string[], note?: string}) => Promise<{ok: boolean, said?: string}|null>,
124
+ * dialog: { body: Element, foot: Element, open: () => void, close: () => void, isOpen: () => boolean },
125
+ * editor: { selection: () => string[], workArea: () => ({min: number[], max: number[]}|null), hasUnsavedEdits: () => boolean, save: () => Promise<unknown> },
126
+ * showDrawer?: () => void, clipboard?: (text: string) => Promise<void>,
127
+ * updateAware?: () => (true|string),
128
+ * }} opts
129
+ * `updateAware` opens FloLess's own AWARE update (the footer's Upgrade AWARE) and answers true, or the sentence to show
130
+ * when there is no update to offer; without it, the too-old warning offers no button.
131
+ */
132
+ export function mountClashCheck({ host, doc, projectId, fetchJson, locate, dialog, editor, showDrawer = () => {}, clipboard = null, updateAware = null }) {
133
+ const cid = (name) => `steel.clash-check-${name}`;
134
+ const base = () => `/api/change-review/steel/${encodeURIComponent(projectId)}`;
135
+ const live = el(doc, 'p', { class: 'tekla-changes-live ccx-live', role: 'status', 'aria-live': 'polite' });
136
+ const items = (reply) => (reply?.check?.groups ?? []).flatMap((g) => g.items);
137
+ const findings = createFindings({
138
+ doc, el, api: (path, init) => fetchJson(path, init), projectId, live, locate: null, sideState: () => null, rerender: () => render(),
139
+ focusCompare: () => {}, clipboard, source: 'steel', cid, words: WORDS, items,
140
+ endpoints: { load: (id) => `${base()}/clash-checks/${id}`, act: (id, name) => `${base()}/clash-checks/${id}/${name === 'decisions' ? 'decide' : name}` },
141
+ locateView: (view) => showIn3d(view.locate, view.words?.title),
142
+ });
143
+ // phase: idle (no check yet) · opening (a result is being read) · ready · running · error · too-old · not-kept
144
+ const S = { phase: 'idle', error: null, tooOld: null, tooOldPart: null, updateSaid: null, lastRequest: null, warnings: [], confirmRestart: false, opened: 0, busy: false };
145
+ const check = () => findings.data()?.check ?? null;
146
+
147
+ async function showIn3d(target, title) {
148
+ if (!target || !Array.isArray(target.ids) || !target.ids.length) return 'FloLess could not tell which objects these are, so they cannot be shown in 3D.';
149
+ const answer = await locate(target);
150
+ if (answer === null) return null;
151
+ if (!answer || answer.ok !== true) return answer?.said || 'The 3D view could not show it. Open the 3D view and try again.';
152
+ const what = title ? `“${title}”` : target.ids.length > 1 ? 'both' : 'it';
153
+ return [`Showing ${what} in 3D.`, target.note, answer.said].filter((text) => typeof text === 'string' && text).join(' ');
154
+ }
155
+
156
+ // ── the drawer ────────────────────────────────────────────────────────────────────────────────────────
157
+ const button = (attrs, text, onclick) => el(doc, 'button', { type: 'button', ...attrs, text, onclick });
158
+ const banner = (tone, lead, sub, extra = []) => el(doc, 'section', { class: `tekla-changes-banner tekla-changes-gate ${tone}`, role: 'note', 'aria-label': lead },
159
+ el(doc, 'strong', { text: lead }), sub ? el(doc, 'span', { text: sub }) : null, ...extra);
160
+
161
+ function bar(c) {
162
+ const n = c ? (c.counts?.clashes ?? 0) + (c.counts?.touching ?? 0) : null;
163
+ const tip = c ? [plural(c.counts?.clashes ?? 0, 'clash', 'clashes'), `${c.counts?.touching ?? 0} touching`, c.counts?.boltedApart ? `${c.counts.boltedApart} bolted apart` : null].filter(Boolean).join(', ') : null;
164
+ return el(doc, 'div', { class: 'ccx-bar' },
165
+ c ? el(doc, 'span', { class: 'tekla-changes-chip ccx-count', 'data-tip': tip, 'aria-label': tip, text: String(n) }) : null,
166
+ button({ class: 'tekla-changes-linkbtn ccx-settings', 'data-command-id': cid('settings'), 'data-tip': 'Change what is checked and at what tolerance, then check again.' }, 'Settings…',
167
+ () => openSettings(c ? { settings: c.settings, scope: c.scope?.kind } : {})));
168
+ }
169
+
170
+ function settingsLine(c) {
171
+ const line = c.origin === 'default' && !/default settings/i.test(c.settingsLine || '') ? `${c.settingsLine} (default settings)` : c.settingsLine;
172
+ return el(doc, 'p', { class: 'ccx-line', tabindex: '0', 'data-tip': settingsTip(c), text: `${c.scope?.label || 'Whole model'} · ${line} · ${clock(c.at)}` });
173
+ }
174
+
175
+ function banners(c) {
176
+ const out = [];
177
+ // Known kinds in their fixed order; a kind this window does not know (the server may add one) follows, never dropped.
178
+ const rank = (kind) => { const i = BANNER_ORDER.indexOf(kind); return i < 0 ? BANNER_ORDER.length : i; };
179
+ const list = [...(c.banners || [])].filter((b) => b && typeof b.text === 'string' && b.text).sort((a, b) => rank(a.kind) - rank(b.kind));
180
+ for (const b of list) {
181
+ const amber = b.kind === 'stale' || b.kind === 'partial' || b.kind === 'model-unreadable';
182
+ const extra = b.kind === 'stale' ? [button({ class: 'tekla-changes-linkbtn', 'data-command-id': cid('run-again') }, 'Run again', () => runAgain(c))]
183
+ : b.kind === 'truncated' ? [button({ class: 'tekla-changes-linkbtn', 'data-command-id': cid('settings') }, 'Check by work area…', () => openSettings({ settings: c.settings, scope: 'work-area' }))]
184
+ : [];
185
+ // The server's own title when it sends one; these are the fallbacks for a server that names none.
186
+ const lead = typeof b.title === 'string' && b.title ? b.title : { stale: 'The model has changed since this check', partial: 'Not everything was checked', approximate: 'Some shapes are approximate', 'not-checked-yet': 'Not clash-checked yet', truncated: 'Not every problem is listed', 'model-unreadable': 'The saved model could not be read' }[b.kind] || 'Note';
187
+ out.push(el(doc, 'section', { class: `tekla-changes-banner tekla-changes-gate ${amber ? 'crv-choice' : 'neutral'} ccx-banner`, role: 'note', 'data-banner': b.kind, 'aria-label': lead },
188
+ el(doc, 'strong', { text: lead }), el(doc, 'span', { text: b.text }), ...extra));
189
+ }
190
+ for (const w of [...(c.warnings || []), ...S.warnings.filter((w) => !(c.warnings || []).some((x) => x.message === w.message))]) {
191
+ if (typeof w?.message === 'string' && w.message) out.push(el(doc, 'p', { class: 'tekla-changes-banner tekla-changes-gate neutral ccx-warning', role: 'note', 'data-warning': w.code || null, text: w.message }));
192
+ }
193
+ if (c.ledger === 'damaged') {
194
+ const restart = S.confirmRestart
195
+ ? el(doc, 'div', { class: 'tekla-changes-finding-actions' },
196
+ el(doc, 'span', { text: 'This sets aside every earlier decision on this model’s clashes (the old history is kept). Start again?' }),
197
+ button({ class: 'primary', 'data-command-id': cid('decisions-restart') }, 'Yes, start again', () => restartDecisions()),
198
+ button({ class: 'tekla-changes-cancel', 'data-command-id': cid('decisions-restart') }, 'Cancel', () => { S.confirmRestart = false; render(); }))
199
+ : button({ class: 'tekla-changes-locate', 'data-command-id': cid('decisions-restart') }, 'Start the decision history again', () => { S.confirmRestart = true; render(); });
200
+ out.push(banner('danger', 'The record of decisions on these clashes could not be verified',
201
+ 'Earlier decisions are not applied, so every finding shows as needing a decision. You can start the decision history again; the old one is kept.', [restart]));
202
+ }
203
+ if (c.ledgerTorn) out.push(banner('danger', 'The last decision was not finished being saved', 'It is not applied, so its finding shows as it was before. Make that decision again if it is missing.'));
204
+ return out;
205
+ }
206
+
207
+ function notChecked(c) {
208
+ const lines = [...(c.unchecked || []), ...(c.checksOff || [])].filter((text) => typeof text === 'string' && text);
209
+ return lines.length ? el(doc, 'ul', { class: 'tekla-audit-omissions ccx-unchecked', 'aria-label': 'What was not checked' }, ...lines.map((text) => el(doc, 'li', { text }))) : null;
210
+ }
211
+
212
+ function groups(c) {
213
+ const out = [];
214
+ const list = c.groups || [];
215
+ for (const g of list) {
216
+ const section = el(doc, 'section', { class: 'tekla-audit-list tekla-changes-list tekla-changes-findings ccx-group', 'data-group': g.id, 'aria-label': GROUP_WORDS[g.id] || g.title },
217
+ el(doc, 'h4', { class: 'ccx-group-head' }, el(doc, 'span', { text: GROUP_WORDS[g.id] || g.title }), el(doc, 'span', { class: 'tekla-changes-chip', text: String(g.items.length) })),
218
+ el(doc, 'p', { class: 'tekla-changes-finding-meta ccx-group-sub', text: g.title }),
219
+ ...findings.cards(g.items));
220
+ if (g.id === 'overlap' && c.belowThresholdLine) section.append(el(doc, 'p', { class: 'tekla-changes-finding-meta ccx-below', text: c.belowThresholdLine }));
221
+ out.push(section);
222
+ }
223
+ if (c.belowThresholdLine && !list.some((g) => g.id === 'overlap')) out.push(el(doc, 'p', { class: 'tekla-changes-finding-meta ccx-below', text: c.belowThresholdLine }));
224
+ return out;
225
+ }
226
+
227
+ function setAside(c) {
228
+ const rows = c.setAside || [];
229
+ if (!rows.length) return null;
230
+ return el(doc, 'details', { class: 'tekla-changes-group ccx-setaside' },
231
+ el(doc, 'summary', { 'data-command-id': cid('setaside'), text: `${plural(rows.length, 'overlap')} at joints not connected yet — set aside` }),
232
+ el(doc, 'p', { class: 'tekla-changes-finding-meta', text: 'Members that run into each other where no connection is modelled yet are listed here instead of as clashes. Each is still part of this check’s record.' }),
233
+ el(doc, 'ul', { class: 'tekla-audit-omissions ccx-setaside-list' }, ...rows.map((row) => el(doc, 'li', { class: 'crv-zone' },
234
+ el(doc, 'span', { text: row.label }),
235
+ button({ class: 'tekla-changes-locate', 'data-command-id': cid('setaside-locate'), 'aria-label': `Show in 3D: ${row.label}` }, 'Show in 3D', async () => {
236
+ const mine = S.opened;
237
+ let said;
238
+ try { said = await showIn3d(row.locate, null); } catch (error) { console.warn('[clash-check] Show in 3D failed:', error); said = WORDS.locateFailed(error); }
239
+ if (mine === S.opened && said) live.textContent = said;
240
+ })))));
241
+ }
242
+
243
+ function result(c) {
244
+ const out = [settingsLine(c)];
245
+ const headline = el(doc, 'h3', { class: 'tekla-changes-result-title ccx-headline', tabindex: '-1', 'data-clean': c.clean || 'none', text: c.headline });
246
+ out.push(headline);
247
+ // "Among what was checked" says what was not, right under it: never a bare "no clashes".
248
+ if (c.clean === 'clean-among-checked') { const list = notChecked(c); if (list) out.push(list); }
249
+ out.push(...banners(c));
250
+ if (c.findingsReadable === false) out.push(banner('danger', 'The findings of this check could not be opened', 'Check for clashes again.'));
251
+ out.push(...groups(c));
252
+ const aside = setAside(c);
253
+ if (aside) out.push(aside);
254
+ if (c.clean !== 'clean-among-checked') {
255
+ const list = notChecked(c);
256
+ if (list) out.push(el(doc, 'details', { class: 'tekla-changes-group tekla-changes-coverage ccx-notchecked', open: true }, el(doc, 'summary', { text: 'What was not checked' }), list));
257
+ }
258
+ return out;
259
+ }
260
+
261
+ function idle() {
262
+ return el(doc, 'div', { class: 'tekla-audit-state ccx-idle' },
263
+ el(doc, 'strong', { text: 'No check yet' }), el(doc, 'span', { text: 'Find parts in the saved model that overlap or touch.' }),
264
+ button({ class: 'primary ccx-primary', 'data-command-id': cid('open') }, 'Check for clashes…', () => openSettings({})));
265
+ }
266
+
267
+ function render() {
268
+ const c = check();
269
+ const nodes = [bar(c)];
270
+ if (S.phase === 'running') {
271
+ nodes.push(el(doc, 'div', { class: 'ccx-running', role: 'status' },
272
+ el(doc, 'div', { class: 'ccx-progress', role: 'progressbar', 'aria-label': 'Checking the saved model', 'aria-busy': 'true' }, el(doc, 'span')),
273
+ el(doc, 'span', { text: 'Checking the saved model…' })));
274
+ }
275
+ if (S.phase === 'opening') nodes.push(el(doc, 'p', { class: 'tekla-audit-omissions', role: 'status', text: 'Opening the result…' }));
276
+ if (S.phase === 'error') {
277
+ nodes.push(banner('danger', 'The check didn’t finish', S.error, [
278
+ c ? el(doc, 'span', { class: 'ccx-last', text: `Last result from ${clock(c.at)}, shown below.` }) : null,
279
+ button({ class: 'tekla-changes-linkbtn', 'data-command-id': cid('retry') }, 'Try again', () => (S.lastRequest ? run(S.lastRequest) : openSettings({}))),
280
+ ]));
281
+ }
282
+ if (S.phase === 'too-old') {
283
+ // AWARE itself (or its bridge) is too old: FloLess's own AWARE update is offered right here, as the footer offers it.
284
+ const offer = updateAware && (S.tooOldPart === 'aware' || S.tooOldPart === 'aware-bridge');
285
+ nodes.push(banner('neutral', 'This computer can’t check for clashes yet', S.tooOld, [
286
+ c ? el(doc, 'span', { class: 'ccx-last', text: `Last result from ${clock(c.at)}, shown below.` }) : null,
287
+ offer ? button({ class: 'tekla-changes-linkbtn', 'data-command-id': cid('update-aware'), 'aria-haspopup': 'dialog' }, 'Update AWARE…', () => {
288
+ let answer;
289
+ try { answer = updateAware(); } catch { answer = null; }
290
+ S.updateSaid = answer === true ? null : (typeof answer === 'string' && answer ? answer : 'The AWARE update could not be opened from here. Choose Upgrade AWARE beside the AWARE version at the bottom of the window.');
291
+ render();
292
+ }) : null,
293
+ offer && S.updateSaid ? el(doc, 'span', { class: 'ccx-update-said', role: 'status', text: S.updateSaid }) : null,
294
+ ]));
295
+ }
296
+ if (S.unreadableChecks > 0 && S.phase !== 'running') {
297
+ nodes.push(el(doc, 'section', { class: 'tekla-changes-banner tekla-changes-gate crv-choice ccx-banner', role: 'note', 'data-banner': 'results-unreadable', 'aria-label': 'Some results are not shown' },
298
+ el(doc, 'strong', { text: 'Some results are not shown' }),
299
+ el(doc, 'span', { text: `${S.unreadableChecks === 1 ? '1 clash check result' : `${S.unreadableChecks} clash check results`} could not be verified and ${S.unreadableChecks === 1 ? 'is' : 'are'} not shown. Check for clashes again to see the model as it is now.` }),
300
+ c ? null : button({ class: 'primary ccx-primary', 'data-command-id': cid('open') }, 'Check for clashes…', () => openSettings({}))));
301
+ }
302
+ if (S.phase === 'not-kept') {
303
+ nodes.push(el(doc, 'div', { class: 'tekla-audit-state ccx-not-kept' }, el(doc, 'span', { text: CLASH_CHECK_NOT_KEPT }),
304
+ button({ class: 'primary ccx-primary', 'data-command-id': cid('open') }, 'Check for clashes…', () => openSettings({}))));
305
+ }
306
+ if (c && S.phase !== 'not-kept' && S.phase !== 'opening') {
307
+ const wrap = el(doc, 'div', { class: `ccx-result${S.phase === 'running' ? ' ccx-dim' : ''}`, 'aria-busy': S.phase === 'running' ? 'true' : null, inert: S.phase === 'running' ? true : null }, ...result(c));
308
+ nodes.push(wrap);
309
+ } else if (!c && S.phase === 'idle' && !(S.unreadableChecks > 0)) nodes.push(idle());
310
+ nodes.push(live);
311
+ host.replaceChildren(...nodes);
312
+ findings.restoreFocus(host);
313
+ }
314
+
315
+ // ── reading and running ─────────────────────────────────────────────────────────────────────────────────
316
+ /** Show the newest check (the drawer opened), or the idle state when there is none. */
317
+ async function showLatest() {
318
+ // A check still running stays on screen; it shows its own result when it finishes.
319
+ if (S.phase === 'running') { render(); return; }
320
+ const mine = ++S.opened;
321
+ // Every opening reads the list again (a check from AI Chat may be newer), with what was shown kept meanwhile.
322
+ if (!check()) { S.phase = 'opening'; render(); }
323
+ let list = [];
324
+ try {
325
+ const reply = await fetchJson(`${base()}/clash-checks`);
326
+ list = reply?.checks ?? [];
327
+ if (mine === S.opened) S.unreadableChecks = Number.isFinite(reply?.unreadable) ? reply.unreadable : 0;
328
+ }
329
+ catch (error) {
330
+ if (mine !== S.opened) return;
331
+ S.phase = 'error'; S.error = error?.body?.userMessage || 'The clash checks of this project could not be read. Try again in a moment.'; S.lastRequest = null; render(); return;
332
+ }
333
+ if (mine !== S.opened) return;
334
+ if (!list.length) { findings.adopt(null, null); S.phase = 'idle'; render(); return; }
335
+ await showCheck(list[0].checkId, mine);
336
+ }
337
+
338
+ /** Show one stored check (History's row, the chat's link). Resolves `{ok}` with the sentence when it could not be shown. */
339
+ async function showCheck(checkId, mine = ++S.opened) {
340
+ if (!check() || check().checkId !== checkId) { findings.adopt(null, null); S.phase = 'opening'; render(); }
341
+ let reply;
342
+ try { reply = await fetchJson(`${base()}/clash-checks/${encodeURIComponent(checkId)}`); }
343
+ catch (error) {
344
+ if (mine !== S.opened) return { superseded: true };
345
+ findings.adopt(null, null);
346
+ if (error?.body?.code === 'clash-check-not-kept') { S.phase = 'not-kept'; render(); return { ok: false, said: CLASH_CHECK_NOT_KEPT }; }
347
+ S.phase = 'error'; S.error = error?.body?.userMessage || WORDS.findingsFailed; S.lastRequest = null; render();
348
+ return { ok: false, said: S.error };
349
+ }
350
+ if (mine !== S.opened) return { superseded: true };
351
+ if (!reply?.check) { S.phase = 'error'; S.error = WORDS.findingsFailed; render(); return { ok: false, said: S.error }; }
352
+ findings.adopt(checkId, reply);
353
+ S.phase = 'ready'; S.warnings = []; render();
354
+ return { ok: true };
355
+ }
356
+
357
+ function counted(c) {
358
+ // A check that measured nothing says so in the server's own headline, never "0 clashes".
359
+ if (c?.state && c.state !== 'ran') return `Check finished. ${c.headline}`;
360
+ const n = c?.counts || {};
361
+ const parts = [plural(n.clashes ?? 0, 'clash', 'clashes'), `${n.touching ?? 0} touching`];
362
+ if (n.boltedApart) parts.push(`${n.boltedApart} bolted apart`);
363
+ if (n.setAside) parts.push(`${n.setAside} set aside`);
364
+ return `Check finished: ${parts.join(', ')}.${c?.clean === 'clean-among-checked' && c.headline ? ` ${c.headline}` : ''}`;
365
+ }
366
+
367
+ /** Run a check. A question the server asks (409 with choices) goes back to the dialog; the run is sent again with `proceed`. */
368
+ async function run(request) {
369
+ if (S.phase === 'running') return;
370
+ const before = S.phase === 'not-kept' || S.phase === 'error' || S.phase === 'too-old' ? (check() ? 'ready' : 'idle') : S.phase;
371
+ S.lastRequest = request; S.phase = 'running'; S.error = null; S.confirmRestart = false;
372
+ // A result being opened meanwhile gives way: this run's answer is the newest.
373
+ ++S.opened;
374
+ showDrawer();
375
+ render();
376
+ let reply;
377
+ try {
378
+ reply = await fetchJson(`${base()}/clash-check`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(request) });
379
+ } catch (error) {
380
+ const body = error?.body || {};
381
+ if (error?.status === 409 && Array.isArray(body.choices) && body.choices.length) {
382
+ S.phase = before; render();
383
+ openSettings({ request, ask: { code: body.code, message: body.userMessage || body.error, choices: body.choices } });
384
+ return;
385
+ }
386
+ if (body.code === 'clash-aware-too-old') {
387
+ S.phase = 'too-old'; S.tooOld = body.userMessage || body.error; S.tooOldPart = typeof body.component === 'string' ? body.component : null; S.updateSaid = null;
388
+ render(); return;
389
+ }
390
+ S.phase = 'error'; S.error = body.userMessage || 'FloLess could not reach the checker just now. Try again in a moment.'; render();
391
+ return;
392
+ }
393
+ const c = reply?.check;
394
+ if (!c) { S.phase = 'error'; S.error = 'The check answered with nothing to show. Try again; if it keeps happening, use Report an issue.'; render(); return; }
395
+ findings.adopt(c.checkId, { ok: true, check: c });
396
+ S.phase = 'ready'; S.warnings = Array.isArray(reply.warnings) ? reply.warnings : [];
397
+ live.textContent = counted(c);
398
+ render();
399
+ }
400
+
401
+ function runAgain(c) {
402
+ const kind = c.scope?.kind || 'all';
403
+ const scope = kind === 'selection' ? { kind, ids: editor.selection() } : kind === 'work-area' ? workAreaScope() : { kind: 'all' };
404
+ if (!scope) { openSettings({ settings: c.settings, scope: kind }); return; }
405
+ run({ scope, ...(c.origin === 'one-off' ? { settings: shownSettings(c.settings), save: false } : {}) });
406
+ }
407
+
408
+ function workAreaScope() {
409
+ const box = editor.workArea();
410
+ return box ? { kind: 'work-area', box: { min: box.min, max: box.max } } : null;
411
+ }
412
+
413
+ async function restartDecisions() {
414
+ if (S.busy) return;
415
+ S.busy = true;
416
+ try {
417
+ const reply = await fetchJson(`${base()}/clash-decisions/restart`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
418
+ S.confirmRestart = false;
419
+ const id = check()?.checkId;
420
+ if (id) await findings.load({ reviewId: id });
421
+ live.textContent = reply?.restarted === false ? 'The decision history could be verified again, so nothing was set aside.' : 'The decision history was started again; the old one is kept. Every finding needs a decision.';
422
+ } catch (error) {
423
+ live.textContent = error?.body?.userMessage || 'The decision history could not be started again. Try again in a moment.';
424
+ } finally { S.busy = false; render(); }
425
+ }
426
+
427
+ // ── the settings dialog ─────────────────────────────────────────────────────────────────────────────────
428
+ const D = { draft: null, saved: null, limits: null, savedFlag: false, unreadable: null, scope: 'all', save: true, notes: {}, texts: {}, ask: null, request: null, loadFailed: false, token: 0 };
429
+
430
+ async function openSettings({ settings = null, scope = null, ask = null, request = null } = {}) {
431
+ const token = ++D.token;
432
+ D.ask = ask; D.request = request; D.notes = {}; D.texts = {};
433
+ if (scope) D.scope = scope;
434
+ else if (!request) D.scope = editor.selection().length ? 'selection' : 'all';
435
+ if (request?.scope?.kind) D.scope = request.scope.kind;
436
+ dialog.open();
437
+ if (!ask || !D.draft) {
438
+ paintDialog(true);
439
+ try {
440
+ const reply = await fetchJson(`${base()}/clash-settings`);
441
+ if (token !== D.token) return;
442
+ D.saved = shownSettings(reply.settings); D.savedFlag = reply.saved === true; D.limits = reply.limits || null; D.loadFailed = false;
443
+ // Saved settings that could not be read: the defaults are shown, and saving over them is the person's choice.
444
+ D.unreadable = Boolean(reply.unreadable) || (Array.isArray(reply.warnings) && reply.warnings.some((w) => w?.code === 'settings-unreadable'));
445
+ D.save = !D.unreadable;
446
+ D.draft = shownSettings(request?.settings || settings || reply.settings);
447
+ } catch (error) {
448
+ if (token !== D.token) return;
449
+ console.warn('[clash-check] the clash settings could not be read:', error);
450
+ D.loadFailed = true; D.unreadable = false; D.save = false; D.draft = settings ? shownSettings(settings) : null;
451
+ }
452
+ }
453
+ if (request && 'save' in request) D.save = request.save !== false;
454
+ paintDialog(false);
455
+ // A question goes to its first answer; otherwise the scope comes first.
456
+ const first = ask ? dialog.body.querySelector?.('.ccd-ask button') : null;
457
+ if (first) { try { first.focus({ preventScroll: true }); } catch { /* focus is a courtesy */ } } else focusScope();
458
+ }
459
+
460
+ function focusScope() {
461
+ const target = dialog.body.querySelector?.(`[data-scope="${D.scope}"]`);
462
+ try { target?.focus({ preventScroll: true }); } catch { /* focus is a courtesy */ }
463
+ }
464
+
465
+ const note = (text, cls = '') => el(doc, 'p', { class: `ccd-note ${cls}`.trim(), role: 'note', text });
466
+
467
+ function lengthNote(key) {
468
+ const value = D.draft?.[key];
469
+ const limits = D.limits?.[key];
470
+ if (D.notes[key]) return D.notes[key];
471
+ if (limits && Number.isFinite(value) && (value < limits.min || value > limits.max)) {
472
+ const to = Math.min(limits.max, Math.max(limits.min, value));
473
+ return `${mm(value)} is outside what the check can use (${mm(limits.min)} to ${mm(limits.max)}), so ${mm(to)} is used.`;
474
+ }
475
+ if (key === 'minOverlapMm' && D.draft && D.draft.minOverlapMm < D.draft.contactToleranceMm) {
476
+ return `This is less than Touching within ${mm(D.draft.contactToleranceMm)}, so overlaps deeper than ${mm(D.draft.contactToleranceMm)} are reported.`;
477
+ }
478
+ return null;
479
+ }
480
+
481
+ function scopeControl() {
482
+ const n = editor.selection().length;
483
+ const box = editor.workArea();
484
+ const group = el(doc, 'div', { class: 'grp ccd-scope', role: 'radiogroup', 'aria-label': 'What to check' });
485
+ const pick = (kind) => { D.scope = kind; paintDialog(false); focusScope(); };
486
+ for (const s of SCOPES) {
487
+ const on = D.scope === s.kind;
488
+ group.append(button({ class: on ? 'on' : null, role: 'radio', 'aria-checked': String(on), tabindex: on ? '0' : '-1', 'data-scope': s.kind,
489
+ 'data-command-id': `${cid('scope')}#${s.kind}` }, s.label(n), () => pick(s.kind)));
490
+ }
491
+ group.addEventListener('keydown', (event) => {
492
+ const step = event.key === 'ArrowRight' || event.key === 'ArrowDown' ? 1 : event.key === 'ArrowLeft' || event.key === 'ArrowUp' ? -1 : 0;
493
+ if (!step) return;
494
+ event.preventDefault();
495
+ const i = SCOPES.findIndex((s) => s.kind === D.scope);
496
+ pick(SCOPES[(i + step + SCOPES.length) % SCOPES.length].kind);
497
+ });
498
+ const current = SCOPES.find((s) => s.kind === D.scope) || SCOPES[0];
499
+ return el(doc, 'div', { class: 'ccd-section' }, el(doc, 'span', { class: 'ccd-label', id: 'ccdScopeLabel', text: 'What to check' }), group,
500
+ el(doc, 'p', { class: 'ccd-help', text: current.explain(n, box) }));
501
+ }
502
+
503
+ function lengthField(f) {
504
+ const id = `ccd-${f.key}`;
505
+ const value = D.texts[f.key] ?? (Number.isFinite(D.draft?.[f.key]) ? String(D.draft[f.key]) : '');
506
+ const input = el(doc, 'input', { id, type: 'text', inputmode: 'decimal', autocomplete: 'off', spellcheck: 'false', class: 'ccd-input', value,
507
+ 'data-command-id': `${cid('length')}#${f.key === 'contactToleranceMm' ? 'touching' : 'overlap'}`, 'aria-describedby': `${id}-help` });
508
+ input.value = value;
509
+ input.addEventListener('input', () => { D.texts[f.key] = input.value; });
510
+ // Read on blur, in place: repainting the dialog here would replace the button the person is pressing.
511
+ input.addEventListener('blur', () => {
512
+ const raw = String(input.value).trim().replace(',', '.').replace(/\s*mm$/i, '');
513
+ const n = Number(raw);
514
+ delete D.texts[f.key];
515
+ if (raw === '' || !Number.isFinite(n)) {
516
+ D.notes[f.key] = `“${String(input.value).trim().slice(0, 20)}” isn’t a length, so ${mm(D.draft[f.key])} is kept. Type a length in millimetres, for example 0.5.`;
517
+ input.value = String(D.draft[f.key]);
518
+ } else { D.notes[f.key] = null; D.draft[f.key] = n; }
519
+ refreshLengthNotes();
520
+ });
521
+ return el(doc, 'div', { class: 'ccd-field' },
522
+ el(doc, 'label', { for: id, class: 'ccd-label', text: f.label }),
523
+ el(doc, 'div', { class: 'ccd-length' }, input, el(doc, 'span', { class: 'ccd-unit', 'aria-hidden': 'true', text: 'mm' })),
524
+ el(doc, 'p', { class: 'ccd-help', id: `${id}-help`, text: f.help }),
525
+ el(doc, 'div', { class: 'ccd-note-slot', 'data-note-for': f.key, 'aria-live': 'polite' }));
526
+ }
527
+
528
+ /** The amber line under each length: what the check will use instead, from the server's limits. */
529
+ function refreshLengthNotes() {
530
+ for (const f of LENGTHS) {
531
+ const slot = dialog.body.querySelector(`[data-note-for="${f.key}"]`);
532
+ if (!slot) continue;
533
+ const warn = lengthNote(f.key);
534
+ slot.replaceChildren(...(warn ? [note(warn, 'ccd-warn')] : []));
535
+ }
536
+ }
537
+
538
+ function switchRow(s) {
539
+ const on = D.draft?.[s.key] !== false;
540
+ const id = `ccd-${s.key}`;
541
+ return el(doc, 'div', { class: 'ccd-switch-row' },
542
+ button({ class: `ccd-switch${on ? ' on' : ''}`, role: 'switch', 'aria-checked': String(on), id, 'aria-describedby': `${id}-help`, 'data-command-id': `${cid('switch')}#${s.key}` },
543
+ null, () => { D.draft[s.key] = !on; paintDialog(false); doc.getElementById(id)?.focus(); }),
544
+ el(doc, 'div', { class: 'ccd-switch-text' },
545
+ el(doc, 'label', { for: id, class: 'ccd-switch-label', text: s.label }),
546
+ el(doc, 'p', { class: 'ccd-help', id: `${id}-help`, text: s.help })));
547
+ }
548
+
549
+ function pairGrid() {
550
+ const n = pairsOn(D.draft);
551
+ const summary = n === CLASH_PAIR_KEYS.length ? `All ${n} type pairs` : `${n} of ${CLASH_PAIR_KEYS.length} type pairs`;
552
+ const details = el(doc, 'details', { class: 'ccd-pairs', open: D.pairsOpen ? true : null },
553
+ el(doc, 'summary', { 'data-command-id': cid('pairs') }, el(doc, 'span', { text: 'Which types are checked against which' }), el(doc, 'span', { class: 'ccd-pairs-sum', text: summary })));
554
+ details.addEventListener('toggle', () => { D.pairsOpen = details.open; });
555
+ const head = el(doc, 'tr', {}, el(doc, 'th', { scope: 'col' }, el(doc, 'span', { class: 'sr-only', text: 'Type' })), ...CLASH_KINDS.map((k) => el(doc, 'th', { scope: 'col', text: cap(KIND_WORDS[k]) })));
556
+ const rows = CLASH_KINDS.map((rowKind, i) => el(doc, 'tr', {}, el(doc, 'th', { scope: 'row', text: cap(KIND_WORDS[rowKind]) }),
557
+ ...CLASH_KINDS.map((colKind, j) => {
558
+ if (j > i) return el(doc, 'td', { class: 'ccd-pair-empty' });
559
+ const key = `${CLASH_KINDS[j]}|${CLASH_KINDS[i]}`;
560
+ const box = el(doc, 'input', { type: 'checkbox', 'aria-label': pairLabel(key), 'data-pair': key, 'data-command-id': `${cid('pair')}#${key}`, checked: D.draft?.pairs?.[key] !== false ? true : null });
561
+ box.checked = D.draft?.pairs?.[key] !== false;
562
+ box.addEventListener('change', () => { D.draft.pairs[key] = box.checked; D.pairsOpen = true; paintDialog(false); dialog.body.querySelector(`[data-pair="${key}"]`)?.focus(); });
563
+ return el(doc, 'td', {}, box);
564
+ })));
565
+ details.append(el(doc, 'div', { class: 'ccd-pairs-body' },
566
+ el(doc, 'table', { class: 'ccd-pairs-table' }, el(doc, 'caption', { class: 'sr-only', text: 'Which types are checked against which' }), el(doc, 'thead', {}, head), el(doc, 'tbody', {}, ...rows)),
567
+ n === CLASH_PAIR_KEYS.length ? null : button({ class: 'tekla-changes-linkbtn ccd-all-on', 'data-command-id': cid('pairs-all') }, 'Turn all on', () => {
568
+ for (const key of CLASH_PAIR_KEYS) D.draft.pairs[key] = true; D.pairsOpen = true; paintDialog(false);
569
+ })));
570
+ return details;
571
+ }
572
+
573
+ function askNote() {
574
+ if (!D.ask) return null;
575
+ return el(doc, 'div', { class: 'ccd-note ccd-warn ccd-ask', role: 'alert' }, el(doc, 'span', { text: D.ask.message }),
576
+ el(doc, 'div', { class: 'ccd-ask-actions' }, ...D.ask.choices.map((choice, i) => button({ class: i === 0 ? 'primary' : 'ghost', 'data-command-id': `${cid('ask')}#${choice.id}`, 'data-choice': choice.id },
577
+ choice.label, () => answerAsk(choice.id)))));
578
+ }
579
+
580
+ function answerAsk(id) {
581
+ const request = D.request;
582
+ D.ask = null;
583
+ if (id === 'pick-again') { paintDialog(false); focusScope(); return; }
584
+ if (id === 'check-saved') { runFromDialog(false); return; }
585
+ if (id === 'turn-pairs-on') {
586
+ if (D.draft) { for (const key of CLASH_PAIR_KEYS) D.draft.pairs[key] = true; D.draft.reportUnjoinedTouching = true; D.draft.checkBoltedPlies = true; }
587
+ D.pairsOpen = true; paintDialog(false); return;
588
+ }
589
+ if (PROCEED[id] && request) {
590
+ dialog.close();
591
+ run({ ...request, proceed: [...new Set([...(request.proceed || []), PROCEED[id]])] });
592
+ return;
593
+ }
594
+ paintDialog(false);
595
+ }
596
+
597
+ /** The request the dialog stands for: the scope, and the settings only when they differ from the saved ones (or are saved). */
598
+ function requestOf() {
599
+ const scope = D.scope === 'selection' ? { kind: 'selection', ids: editor.selection() } : D.scope === 'work-area' ? (workAreaScope() || null) : { kind: 'all' };
600
+ const out = { scope };
601
+ // Unchanged settings are the saved ones: sent as nothing, so the record says so. Saving defaults never saved writes them.
602
+ const unchanged = sameSettings(D.draft, D.saved) && (D.savedFlag || !D.save);
603
+ if (D.draft && !unchanged) { out.settings = shownSettings(D.draft); out.save = D.save; }
604
+ return out;
605
+ }
606
+
607
+ async function runFromDialog(saveFirst) {
608
+ // A blurred field may still hold unread text: read it first, so what runs is what the person sees.
609
+ const active = doc.activeElement;
610
+ if (active && active.classList?.contains('ccd-input')) active.blur?.();
611
+ const request = requestOf();
612
+ if (!request.scope) {
613
+ // No work area to check: the same question the server asks for an empty scope, asked here.
614
+ D.ask = { code: 'clash-scope-empty', message: 'There is no work area in the 3D view, so there is nothing to check. Check the whole model instead, or pick again.',
615
+ choices: [{ id: 'whole-model', label: 'Check the whole model instead' }, { id: 'pick-again', label: 'Pick again' }] };
616
+ D.request = { ...request, scope: { kind: 'all' } };
617
+ paintDialog(false);
618
+ return;
619
+ }
620
+ if (saveFirst) {
621
+ try { await editor.save(); }
622
+ catch (error) {
623
+ console.warn('[clash-check] saving the edits before the check failed:', error);
624
+ D.ask = { code: 'save-failed', message: 'Your edits could not be saved just now, so the check would use the last saved version. Check the saved version, or try saving again.',
625
+ choices: [{ id: 'check-saved', label: 'Check saved version' }, { id: 'pick-again', label: 'Not now' }] };
626
+ D.request = request; paintDialog(false); return;
627
+ }
628
+ }
629
+ dialog.close();
630
+ run(request);
631
+ }
632
+
633
+ function paintDialog(loading) {
634
+ const body = dialog.body; const foot = dialog.foot;
635
+ if (loading && !D.draft) {
636
+ body.replaceChildren(el(doc, 'p', { class: 'ccd-sub', text: 'Checks the saved model. Edits you haven’t saved aren’t included.' }),
637
+ el(doc, 'p', { class: 'ccd-help', role: 'status', text: 'Reading the settings…' }));
638
+ foot.replaceChildren(button({ class: 'ghost', 'data-command-id': 'steel.dialog-cancel#Check for clashes' }, 'Cancel', () => dialog.close()));
639
+ return;
640
+ }
641
+ const unsaved = editor.hasUnsavedEdits();
642
+ const parts = [el(doc, 'p', { class: 'ccd-sub', text: 'Checks the saved model. Edits you haven’t saved aren’t included.' })];
643
+ if (unsaved) parts.push(note('You have edits that aren’t saved. The check uses the last saved version.', 'ccd-warn ccd-unsaved'));
644
+ const ask = askNote();
645
+ if (ask) parts.push(ask);
646
+ parts.push(scopeControl());
647
+ if (D.loadFailed) {
648
+ parts.push(el(doc, 'div', { class: 'ccd-note ccd-warn ccd-load-failed', role: 'alert' },
649
+ el(doc, 'span', { text: D.draft
650
+ ? 'This project’s clash settings could not be read just now. The settings shown are the ones from the last result, not necessarily the saved ones.'
651
+ : 'This project’s clash settings could not be read just now, so they can’t be shown. Run check uses the project’s saved settings as they are.' }),
652
+ ' ', button({ class: 'tekla-changes-linkbtn', 'data-command-id': cid('settings') }, 'Try again', () => openSettings({ request: D.request }))));
653
+ }
654
+ if (D.unreadable) parts.push(note('Your saved settings could not be read, so the defaults are shown. Saving will keep the unreadable file aside.', 'ccd-warn ccd-unreadable'));
655
+ if (D.draft) {
656
+ parts.push(el(doc, 'div', { class: 'ccd-section ccd-lengths' }, ...LENGTHS.map(lengthField)));
657
+ parts.push(el(doc, 'div', { class: 'ccd-section ccd-switches' }, ...SWITCHES.map(switchRow)));
658
+ parts.push(pairGrid());
659
+ }
660
+ parts.push(el(doc, 'p', { class: 'ccd-help ccd-static', text: NOT_CHECKED_YET }));
661
+ if (D.draft) {
662
+ const box = el(doc, 'input', { type: 'checkbox', id: 'ccdSave', 'data-command-id': cid('save-settings'), checked: D.save ? true : null });
663
+ box.checked = D.save;
664
+ box.addEventListener('change', () => { D.save = box.checked; paintDialog(false); doc.getElementById('ccdSave')?.focus(); });
665
+ parts.push(el(doc, 'div', { class: 'ccd-section ccd-save' }, el(doc, 'label', { class: 'ccd-check', for: 'ccdSave' }, box, el(doc, 'span', { text: 'Save as this project’s settings' })),
666
+ D.save ? null : el(doc, 'p', { class: 'ccd-help', text: 'These settings are used for this check only.' })));
667
+ }
668
+ body.replaceChildren(...parts);
669
+ const cancel = button({ class: 'ghost', 'data-command-id': 'steel.dialog-cancel#Check for clashes' }, 'Cancel', () => dialog.close());
670
+ foot.replaceChildren(...(unsaved
671
+ ? [cancel, button({ class: 'ghost', 'data-command-id': cid('run-saved') }, 'Check saved version', () => runFromDialog(false)),
672
+ button({ class: 'primary', 'data-command-id': cid('save-and-run') }, 'Save and check', () => runFromDialog(true))]
673
+ : [cancel, button({ class: 'primary', 'data-command-id': cid('run') }, 'Run check', () => runFromDialog(false))]));
674
+ refreshLengthNotes();
675
+ }
676
+
677
+ return {
678
+ showLatest, showCheck, run, openSettings, render,
679
+ state: () => ({ phase: S.phase, checkId: check()?.checkId ?? null, clean: check()?.clean ?? null, scope: D.scope, ask: D.ask?.code ?? null }),
680
+ };
681
+ }