@floless/app 0.148.1 → 0.149.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 (43) hide show
  1. package/bin/floless.mjs +1 -1
  2. package/dist/floless-server.cjs +28663 -18914
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +156 -0
  4. package/dist/schemas/steel.model.v2.schema.json +43 -1
  5. package/dist/schemas/tekla.model.v2.schema.json +6 -2
  6. package/dist/skills/floless-app-steel-model/SKILL.md +54 -11
  7. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +9 -5
  8. package/dist/skills/floless-app-steel-takeoff/SKILL.md +128 -15
  9. package/dist/skills/floless-app-vectorize/SKILL.md +7 -4
  10. package/dist/templates/check-drawings.flo +46 -0
  11. package/dist/templates/drawing-check.flo +55 -0
  12. package/dist/templates/tekla-parser.flo +6 -2
  13. package/dist/web/app.css +143 -8
  14. package/dist/web/aware.js +444 -39
  15. package/dist/web/chat.css +171 -9
  16. package/dist/web/chat.js +2005 -759
  17. package/dist/web/commands-drawing-check.js +53 -0
  18. package/dist/web/commands-shell.js +275 -3
  19. package/dist/web/commands-steel.js +1 -0
  20. package/dist/web/commands-tekla-parser.js +3 -0
  21. package/dist/web/commands.js +1 -1
  22. package/dist/web/connections.js +382 -0
  23. package/dist/web/display-units.js +15 -1
  24. package/dist/web/drawing-check-editor.html +289 -0
  25. package/dist/web/drawing-check-editor.js +1242 -0
  26. package/dist/web/drawing-check-overlay.js +36 -0
  27. package/dist/web/filter-ai-proposal.js +32 -13
  28. package/dist/web/index.html +25 -3
  29. package/dist/web/instructor.js +2 -2
  30. package/dist/web/local-discovery.js +144 -2
  31. package/dist/web/model-display-units.js +23 -9
  32. package/dist/web/model-viewport-revit-adapter.js +12 -2
  33. package/dist/web/revit-editor.css +5 -0
  34. package/dist/web/revit-editor.js +141 -20
  35. package/dist/web/steel-editor.html +166 -27
  36. package/dist/web/steel-filter.html +60 -166
  37. package/dist/web/steel-model-v2-commands.js +13 -3
  38. package/dist/web/steel-model-v2-projection.js +20 -0
  39. package/dist/web/steel-units.js +3 -1
  40. package/dist/web/workspaces.js +306 -22
  41. package/launch.mjs +5 -5
  42. package/package.json +3 -1
  43. package/dist/web/filter-ai-context.js +0 -92
@@ -0,0 +1,1242 @@
1
+ // Drawing Checker profile page: one client's reference drawings, the ticked checklist, the runs (each
2
+ // shown as the marked-up drawing itself) and the markup colours.
3
+ //
4
+ // The page never composes anything. It shows what the server proposed from the reference drawings, sends
5
+ // the person's ticks, starts a run the server performs with fixed code, and draws the stored result with
6
+ // the SAME overlay module the run report uses (drawing-check-overlay.js), so the two cannot disagree.
7
+ // Wording rule: FloLess "looked at" a sheet; only a person marks one checked.
8
+ import { DEFAULT_COLOURS, hatchDefs, overlaySvg } from './drawing-check-overlay.js';
9
+
10
+ // ── pure helpers (exported for server/drawing-check-ui.test.ts) ─────────────────────────────────
11
+
12
+ /** Padding, in PDF points, around an item's evidence box when the view zooms to it. */
13
+ export const ITEM_PAD = 24;
14
+
15
+ /** A viewBox around `bbox` ([x0,y0,x1,y1], PDF points) with `pad` points on every side. */
16
+ export function paddedViewBox(bbox, pad) {
17
+ const [x0, y0, x1, y1] = bbox;
18
+ return { x: x0 - pad, y: y0 - pad, w: Math.max(1, x1 - x0) + 2 * pad, h: Math.max(1, y1 - y0) + 2 * pad };
19
+ }
20
+
21
+ /**
22
+ * What clicking an item in the list does to the view: zoom to its FIRST evidence box with ITEM_PAD
23
+ * points around it, or — for an item written in the sheet margin, or one with no box — fit the page.
24
+ * Returns the note to show beside the item, if any.
25
+ */
26
+ export function focusItem(view, item) {
27
+ const box = item && !item.margin && item.evidence && item.evidence[0] && item.evidence[0].bbox;
28
+ if (box) { view.fitTo(box, ITEM_PAD); return ''; }
29
+ view.fit();
30
+ return item && item.margin ? 'Written in the sheet margin.' : 'This item has no place on the drawing to show.';
31
+ }
32
+
33
+ /** Which tab the page opens on: Runs once a checklist is approved, else References until there are some. */
34
+ export function landingTab({ hasApproved, referenceCount }) {
35
+ if (hasApproved) return 'runs';
36
+ return referenceCount ? 'checklist' : 'references';
37
+ }
38
+
39
+
40
+ /** The run engine's markup colours keyed by result status, from the profile's {pass, fail, question}. */
41
+ export function statusColours(c) {
42
+ return { pass: (c && c.pass) || DEFAULT_COLOURS.pass, fail: (c && c.fail) || DEFAULT_COLOURS.fail,
43
+ 'dont-know': (c && c.question) || DEFAULT_COLOURS['dont-know'] };
44
+ }
45
+
46
+ /** `hsl(h s% l%)` or `#rrggbb` → `#rrggbb`, for the colour swatch input. Unknown → null. */
47
+ export function toHex(colour) {
48
+ const s = String(colour || '').trim();
49
+ if (/^#[0-9a-f]{6}$/i.test(s)) return s.toLowerCase();
50
+ const m = /^hsl\(\s*(-?\d+(?:\.\d+)?)(?:deg)?\s*,?\s+(\d+(?:\.\d+)?)%\s*,?\s+(\d+(?:\.\d+)?)%\s*\)$/i.exec(s);
51
+ if (!m) return null;
52
+ const h = ((Number(m[1]) % 360) + 360) % 360, sat = Number(m[2]) / 100, l = Number(m[3]) / 100;
53
+ const c = (1 - Math.abs(2 * l - 1)) * sat, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), mm = l - c / 2;
54
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
55
+ return '#' + [r, g, b].map((v) => Math.round((v + mm) * 255).toString(16).padStart(2, '0')).join('');
56
+ }
57
+
58
+ /**
59
+ * Run async jobs one at a time in call order: each starts only after the previous one settled (a failed
60
+ * job does not block the next). Used for checklist PUTs, which must each carry the latest etag.
61
+ */
62
+ export function serialise() {
63
+ let tail = Promise.resolve();
64
+ return (job) => {
65
+ const run = tail.then(() => job());
66
+ tail = run.catch(() => {});
67
+ return run;
68
+ };
69
+ }
70
+
71
+ export const STATUS_WORD = { pass: 'Fine', fail: 'Wrong', 'dont-know': 'Couldn’t tell' };
72
+ const LINE = { pass: { w: 1.2, dash: '' }, fail: { w: 2.4, dash: '' }, 'dont-know': { w: 1.6, dash: '3 2' } };
73
+
74
+ /** "12 fine · 1 wrong · 1 couldn’t tell" — counts only, never a score. */
75
+ export function countsLine(s) {
76
+ const parts = [`${s.pass} fine`, `${s.fail} wrong`];
77
+ if (s.dontKnow) parts.push(`${s.dontKnow} couldn’t tell`);
78
+ return parts.join(' · ');
79
+ }
80
+
81
+ const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
82
+
83
+ /** One number tag the export could not place, worded exactly as the cover page lists it. */
84
+ export function tagFailureNote(f) {
85
+ return `Item ${f.n} on page ${f.page}: number could not be placed${f.why ? ` (${f.why})` : ''}`;
86
+ }
87
+
88
+ /**
89
+ * The client this checklist is for, editable at the top of the Checklist tab. Proposing fills it from the
90
+ * CLIENT on the reference drawings; a person corrects it here. Every sheet naming another client asks.
91
+ */
92
+ export function clientFieldHtml(client) {
93
+ return `<label class="field client-field"><span>Client</span><input type="text" id="client-name" value="${esc(client)}" maxlength="200" autocomplete="off" spellcheck="false" data-command-id="drawing-check.client" data-tip="Sheets naming another client ask before they are checked"></label>`;
94
+ }
95
+
96
+ // ── keeping keyboard focus across a re-render (pure, exported for server/drawing-check-ui.test.ts) ─
97
+
98
+ /** The attributes that name a control stably across re-renders, in the order they are tried. */
99
+ const FOCUS_KEYS = ['data-tb-label', 'data-tb-required', 'data-tb-remove', 'data-typed-label', 'data-typed-use', 'data-type-label', 'data-item', 'data-tab', 'data-act', 'id'];
100
+ const attrEsc = (v) => String(v).replace(/["\\]/g, '\\$&');
101
+ /**
102
+ * A selector that finds "the same control" in freshly rendered markup, or null. A read-mode button is
103
+ * named by its field and mode, an answer by its question and choice.
104
+ */
105
+ export function focusKey(el) {
106
+ if (!el || !el.getAttribute) return null;
107
+ if (el.hasAttribute('data-tb-read')) return `[data-tb-read="${attrEsc(el.getAttribute('data-tb-read'))}"][data-mode="${attrEsc(el.getAttribute('data-mode'))}"]`;
108
+ if (el.hasAttribute('data-answer')) return `[data-answer="${attrEsc(el.getAttribute('data-answer'))}"][data-choice="${attrEsc(el.getAttribute('data-choice'))}"]`;
109
+ for (const k of FOCUS_KEYS) if (el.hasAttribute(k)) return `[${k}="${attrEsc(el.getAttribute(k))}"]`;
110
+ return null;
111
+ }
112
+ /**
113
+ * Replace `container`'s markup and put keyboard focus back on the same control, if it is still there.
114
+ * Every re-render of the page goes through this, so a re-render that lands while the person is on another
115
+ * control (a PUT answering after they pressed Tab, a review that loads late) never drops their focus.
116
+ */
117
+ export function paintKeepingFocus(doc, container, html) {
118
+ const active = doc.activeElement;
119
+ const key = active && container.contains(active) ? focusKey(active) : null;
120
+ // A text field being typed in keeps what was typed and where the caret was.
121
+ const typing = key && active.tagName === 'INPUT' && /^(text|search|)$/i.test(active.type || '')
122
+ ? { value: active.value, start: active.selectionStart, end: active.selectionEnd } : null;
123
+ container.innerHTML = html;
124
+ const again = key ? container.querySelector(key) : null;
125
+ if (again && typing) {
126
+ again.value = typing.value;
127
+ if (typeof again.setSelectionRange === 'function' && typing.start != null) again.setSelectionRange(typing.start, typing.end);
128
+ }
129
+ if (again && again.focus) again.focus();
130
+ return !!again;
131
+ }
132
+ /** After an edit: give focus back to the edited control only when nothing holds focus. */
133
+ export function refocusIfLost(doc, container, selector) {
134
+ if (doc.activeElement && doc.activeElement !== doc.body) return false;
135
+ const el = container.querySelector(selector);
136
+ if (el && el.focus) el.focus();
137
+ return !!el;
138
+ }
139
+
140
+ // ── the title block (pure, exported for server/drawing-check-ui.test.ts) ─────────────────────────
141
+
142
+ /** How a value is read from its label, in the words the page shows: always said from the label's side. */
143
+ export const READ_WORDS = {
144
+ right: 'Value right of the label',
145
+ below: 'Value under the label',
146
+ 'column-above': 'Rows above this heading, newest on top',
147
+ 'column-below': 'Rows below this heading, newest at the bottom',
148
+ };
149
+ /** What a built-in field is; a firm's own field is called by its label. */
150
+ export const FIELD_WORDS = {
151
+ client: 'Client', project: 'Project', 'drawing-number': 'Drawing number', rev: 'Revision', scale: 'Scale',
152
+ drawn: 'Drawn by', date: 'Date', checked: 'Checked by', title: 'Title',
153
+ };
154
+ export const fieldWhat = (f) => FIELD_WORDS[f.name] || 'Your own field';
155
+ /** The one consequence every title-block edit has, said where the edit happens. */
156
+ export const REAPPROVE_NOTE = 'Changes here apply to runs after you approve the checklist again.';
157
+
158
+ /**
159
+ * The ways a field may be read: always to the right or below; a revision table only for a header of the
160
+ * table the references showed, and only the way that table runs.
161
+ */
162
+ export function readModesFor(tb, f) {
163
+ const modes = ['right', 'below'];
164
+ const rev = tb && tb.revisions;
165
+ if (rev && rev.headerLabels.some((h) => normaliseWords(h) === normaliseWords(f.label))) modes.push(rev.direction === 'up' ? 'column-above' : 'column-below');
166
+ if (!modes.includes(f.read)) modes.push(f.read);
167
+ return modes;
168
+ }
169
+ const normaliseWords = (t) => String(t || '').toUpperCase().replace(/[.:#]/g, ' ').replace(/\s+/g, ' ').trim();
170
+
171
+ /** Where the field's reading came from, in a few words. `warn`: every drawing will say "couldn't tell". */
172
+ export function fieldOrigin(f, pages) {
173
+ if (f.source === 'person') return f.labelBox ? { text: 'set by you' } : { text: 'set by you · not found on the references', warn: true };
174
+ if (!f.support) return { text: 'never filled in on the references' };
175
+ return { text: pages ? `filled in on ${Math.round(f.support * pages)} of ${pages}` : 'learned from the references' };
176
+ }
177
+
178
+ /** Where on the sheet a learned label sits, in words ("bottom right"), from its page-relative box. */
179
+ export function whereOnSheet(box) {
180
+ if (!box) return '';
181
+ const x = (box[0] + box[2]) / 2, y = (box[1] + box[3]) / 2;
182
+ const v = y < 1 / 3 ? 'top' : y < 2 / 3 ? 'middle' : 'bottom', h = x < 1 / 3 ? 'left' : x < 2 / 3 ? 'centre' : 'right';
183
+ return v === 'middle' && h === 'centre' ? 'centre' : `${v} ${h}`;
184
+ }
185
+
186
+ /**
187
+ * One open question from proposing: the question, one button per candidate with where it was seen, and
188
+ * "Neither: I'll type the label". Deliberately NO default and no "Suggested" tag, unlike the preflight
189
+ * dialog: these questions exist because the references could not settle them, and pre-selecting one
190
+ * would be the tie-break by order the template refuses to make (A3).
191
+ */
192
+ /** @param {any} a @param {{ pages?: number, saving?: boolean, typed?: { value: string, error: string } | null }} [opts] */
193
+ export function askHtml(a, { pages = 0, saving = false, typed = null } = {}) {
194
+ const dis = saving ? ' disabled' : '';
195
+ return `<div class="ask" role="group" aria-labelledby="ask-q-${esc(a.id)}" data-ask="${esc(a.id)}"><p class="q"><span class="q-pill" aria-hidden="true">Question</span><span id="ask-q-${esc(a.id)}">${esc(a.question)}</span></p>
196
+ <p class="note">Until you answer, every drawing shows “couldn’t tell” for this.</p>
197
+ <div class="ask-choices">${a.choices.map((c) => {
198
+ const seen = [typeof c.field.support === 'number' && pages ? `seen on ${Math.round(c.field.support * pages)} of ${pages}` : '', whereOnSheet(c.field.labelBox)].filter(Boolean).join(' · ');
199
+ return `<button type="button" class="choice-btn" data-answer="${esc(a.id)}" data-choice="${esc(c.id)}" data-command-id="drawing-check.title-answer#${esc(a.id)}" data-command-instance-label="${esc(c.label)}"${dis}><span>${esc(c.label)}</span>${seen ? `<small>${esc(seen)}</small>` : ''}</button>`;
200
+ }).join('')}
201
+ <button type="button" class="choice-btn link-ish" data-type-label="${esc(a.id)}" data-command-id="drawing-check.title-answer#${esc(a.id)}" data-command-instance-label="Neither: I’ll type the label"${dis}><span>Neither: I’ll type the label</span></button></div>
202
+ <div class="ask-type" data-type-for="${esc(a.id)}"${typed ? '' : ' hidden'}><label class="field"><span>The label as printed on the drawings</span>
203
+ <input type="text" maxlength="80" spellcheck="false" autocomplete="off" data-typed-label="${esc(a.id)}" data-command-id="drawing-check.typed-label" aria-label="The label as printed on the drawings" value="${esc((typed && typed.value) || '')}"></label>
204
+ <button type="button" class="primary" data-typed-use="${esc(a.id)}" data-command-id="drawing-check.title-answer#${esc(a.id)}" data-command-instance-label="Use this label"${dis}>Use this label</button></div>
205
+ ${typed && typed.error ? `<p class="err-line" role="alert">${esc(typed.error)}</p>` : ''}
206
+ ${saving ? '<p class="note" role="status">Saving…</p>' : ''}</div>`;
207
+ }
208
+
209
+ /**
210
+ * Why a run reads "Not signed". A run whose stored results no longer match its signed record must not be
211
+ * read as merely unsigned: the results themselves are unverified, and the tip says so with the next step.
212
+ */
213
+ export function unsignedTip(signature) {
214
+ const why = signature && typeof signature.reason === 'string' ? signature.reason : '';
215
+ return signature && signature.unverified
216
+ ? `${why} Treat these results as unverified, and check the drawings again for a signed run.`
217
+ : 'The run record couldn’t be signed on this PC, so nothing proves these results were not changed since the run.';
218
+ }
219
+
220
+ /** "1 question about the title block": the notice at the top of the Checklist tab, or '' when none. */
221
+ export function pendingAsksNotice(tb) {
222
+ const n = (tb && tb.asks && tb.asks.length) || 0;
223
+ if (!n) return '';
224
+ return `<div class="band ask-band" role="status">${n} question${n === 1 ? '' : 's'} about the title block ${n === 1 ? 'is' : 'are'} unanswered. Until ${n === 1 ? 'it is' : 'they are'} answered, every drawing shows “couldn’t tell” for ${n === 1 ? 'that field' : 'those fields'}.
225
+ <button type="button" class="link" data-act="go-ask" data-command-id="drawing-check.go-to-question">Answer ${n === 1 ? 'it' : 'them'}</button></div>`;
226
+ }
227
+
228
+ /**
229
+ * The Title block table: one row per field — what it is, the label as written on this firm's drawings
230
+ * (editable), how its value is read (a segmented choice), whether it must be filled in — then the open
231
+ * questions and "Add a field". Every control sends one change to the server; nothing is decided here.
232
+ * `note` is the result of the last change, shown on the row it changed.
233
+ */
234
+ export function titleBlockHtml(tb, { pages = 0, note = '', noteField = '', saving = false, typed = {} } = {}) {
235
+ if (!tb) {
236
+ return `<section class="tb" aria-labelledby="tb-h"><h3 id="tb-h">Title block</h3>
237
+ <p class="note">Propose from the references to learn this client’s title block: which label holds what, and where its value sits.</p></section>`;
238
+ }
239
+ const rows = tb.fields.map((f) => {
240
+ const what = fieldWhat(f);
241
+ const modes = readModesFor(tb, f);
242
+ const origin = fieldOrigin(f, pages);
243
+ // Whether a field can be read comes from its geometry (a learned value cell, or a revision-table
244
+ // column), never from a flag alone. An undecided field that cannot be read shows NO chosen way.
245
+ const readable = f.read === 'column-above' || f.read === 'column-below' || (!!f.valueBox && !!f.labelBox);
246
+ const undecided = !!f.undecided && !readable;
247
+ const chosen = (m) => !undecided && m === f.read;
248
+ const seg = `<div class="seg" role="radiogroup" aria-label="How ${esc(f.label)} is read">${modes.map((m, i) =>
249
+ `<button type="button" role="radio" aria-checked="${chosen(m)}" tabindex="${chosen(m) || (undecided && i === 0) ? 0 : -1}" data-tb-read="${esc(f.name)}" data-mode="${m}" data-command-id="drawing-check.title-read#${esc(f.name)}" data-command-instance-label="${esc(f.label)}">${esc(READ_WORDS[m])}</button>`).join('')}</div>`;
250
+ return `<div class="tb-row" data-field="${esc(f.name)}">
251
+ <div class="what"><span class="w">${esc(what)}</span><span class="origin${origin.warn ? ' warn' : ''}"${origin.warn ? ' data-tip="Every drawing will show “couldn’t tell” for this until the label matches what is printed."' : ''}>${esc(origin.text)}</span></div>
252
+ <input type="text" class="tb-label" value="${esc(f.label)}" maxlength="80" spellcheck="false" autocomplete="off" data-tb-label="${esc(f.name)}" aria-label="${esc(what)}: label as written on the drawings" data-command-id="drawing-check.title-label#${esc(f.name)}" data-command-instance-label="${esc(f.label)}">
253
+ ${seg}
254
+ <label class="must"><input type="checkbox" data-tb-required="${esc(f.name)}" aria-label="${esc(what)}: must be filled in" data-command-id="drawing-check.title-required#${esc(f.name)}" data-command-instance-label="${esc(f.label)}"${f.required ? ' checked' : ''}><span>Must be filled in</span></label>
255
+ ${f.source === 'person' && f.name.startsWith('custom-')
256
+ ? `<button type="button" class="icon rm" data-tb-remove="${esc(f.name)}" data-command-id="drawing-check.title-remove#${esc(f.name)}" data-command-instance-label="${esc(f.label)}" aria-label="Remove ${esc(f.label)}" data-tip="Remove this field">×</button>`
257
+ : '<span class="rm"></span>'}
258
+ ${note && noteField === f.name ? `<p class="row-note" role="status">${esc(note)}</p>`
259
+ : readable ? '' : `<p class="row-note undecided">${undecided
260
+ ? 'Not decided yet: no filled value on the references shows where it goes. Choose how it is read; until then every drawing shows “couldn’t tell” for it.'
261
+ : 'Read way chosen, but no reference drawing shows this field filled in, so FloLess can’t check it yet — it is reported as “couldn’t tell”.'}${f.required
262
+ ? ' “Title block filled in” will report “couldn’t tell” until a reference drawing with it filled in is added.' : ''}</p>`}
263
+ </div>`;
264
+ }).join('');
265
+ const asks = (tb.asks || []).map((a) => askHtml(a, { pages, saving, typed: typed[a.id] || null })).join('');
266
+ const strayNote = note && !tb.fields.some((f) => f.name === noteField) ? `<p class="note" role="status">${esc(note)}</p>` : '';
267
+ if (!tb.fields.length) {
268
+ return `<section class="tb" aria-labelledby="tb-h"><h3 id="tb-h">Title block</h3>
269
+ <p class="note">No title block was recognised on the references. Add the fields your drawings use. ${esc(REAPPROVE_NOTE)}</p>
270
+ ${asks}${strayNote}
271
+ <div class="row-actions"><button type="button" class="primary" data-act="add-field" data-command-id="drawing-check.title-add">Add a field…</button></div></section>`;
272
+ }
273
+ return `<section class="tb" aria-labelledby="tb-h"><h3 id="tb-h">Title block</h3>
274
+ <p class="note">Learned from the reference drawings. Each value is read only the way set here; a sheet laid out differently is marked “couldn’t tell”, never guessed. <b>${esc(REAPPROVE_NOTE)}</b></p>
275
+ ${asks}${strayNote}
276
+ <div class="list tb-list"><div class="tb-head" aria-hidden="true"><span>Field</span><span>Label on the drawings, and how its value is read</span><span>Required</span><span></span></div>${rows}</div>
277
+ <div class="row-actions"><button type="button" data-act="add-field" data-command-id="drawing-check.title-add">Add a field…</button></div></section>`;
278
+ }
279
+
280
+ // ── the page ────────────────────────────────────────────────────────────────────────────────────
281
+
282
+ function boot() {
283
+ const qs = new URLSearchParams(location.search);
284
+ const APP = qs.get('app') || 'drawing-check';
285
+ const PROJECT = qs.get('project') || '';
286
+ const base = `/api/projects/${encodeURIComponent(PROJECT)}/drawing-check`;
287
+ const root = document.getElementById('dc-root');
288
+ root.style.cssText = 'display:flex;flex-direction:column;flex:1;min-height:0';
289
+
290
+ const S = {
291
+ draft: null, etag: null, review: null, reviewError: '', runs: [], runsError: '', colours: null, colourWarning: null,
292
+ tab: null, loadError: '', uploadNote: '', newSinceApproval: 0, checklistError: '', conflict: false, titleNote: '', titleNoteField: '', tbSaving: false, tbChanges: [], typed: {},
293
+ running: null, run: null, sheet: 0, selectedN: null, itemNote: '', exportCard: null, runError: '',
294
+ };
295
+
296
+ async function call(path, opts = {}) {
297
+ let res;
298
+ try { res = await fetch(path, { credentials: 'same-origin', ...opts }); }
299
+ catch { const e = new Error('FloLess could not be reached. Check that it is still running, then try again.'); e.status = 0; throw e; }
300
+ let body = null;
301
+ try { body = await res.json(); } catch { /* an empty or non-JSON body */ }
302
+ if (!res.ok || (body && body.ok === false)) {
303
+ const e = new Error((body && typeof body.error === 'string' && body.error) || 'That didn’t work. Try again.');
304
+ e.status = res.status; e.body = body; throw e;
305
+ }
306
+ return { body, res };
307
+ }
308
+ const jsonOpts = (method, data, extra = {}) => ({ method, headers: { 'content-type': 'application/json', ...extra }, body: JSON.stringify(data ?? {}) });
309
+
310
+ // ── loading ──
311
+ async function loadDraft() {
312
+ const res = await fetch(`/api/contract/${encodeURIComponent(APP)}?project=${encodeURIComponent(PROJECT)}&quietMissing=1`, { credentials: 'same-origin' });
313
+ if (res.status === 204) { S.draft = null; S.etag = null; return; }
314
+ if (res.status === 404) throw new Error('This profile could not be found. It may have been archived; open it again from Workspaces.');
315
+ // No Drawing Checker on this account: the server's own access copy explains it; "reload" would not help.
316
+ if (res.status === 403) {
317
+ let why = '';
318
+ try { const body = await res.json(); why = body && typeof body.error === 'string' ? body.error : ''; } catch { /* no body */ }
319
+ S.accessError = why || 'Drawing Checker is not included for this account. Ask your FloLess account owner to enable it.';
320
+ throw new Error(S.accessError);
321
+ }
322
+ if (!res.ok) throw new Error('This profile could not be read. Reload to try again.');
323
+ S.draft = await res.json();
324
+ S.etag = res.headers.get('ETag');
325
+ }
326
+ async function loadTitleChanges() {
327
+ try { S.tbChanges = (await call(`${base}/title-block`)).body.changes || []; } catch { S.tbChanges = []; }
328
+ }
329
+ /** The title-block changes to show in the approval dialog: a list, 'approved-unreadable', or 'failed'. */
330
+ async function titleChangesForApproval() {
331
+ try {
332
+ const { body } = await call(`${base}/title-block`);
333
+ return body.approvedUnreadable ? 'approved-unreadable' : (body.changes || []);
334
+ } catch { return 'failed'; }
335
+ }
336
+ async function loadReview() {
337
+ S.reviewError = '';
338
+ // Both land before anything renders: a title-block summary arriving late used to re-render after focus
339
+ // had been put back, dropping it.
340
+ const changes = loadTitleChanges();
341
+ try {
342
+ const { body } = await call(`/api/projects/${encodeURIComponent(PROJECT)}/approval-review`);
343
+ S.review = body && body.reviewable ? body : null;
344
+ } catch { S.review = null; S.reviewError = 'Approval status couldn’t be read. Reload to try again.'; }
345
+ await changes;
346
+ }
347
+ async function loadRuns() {
348
+ S.runsError = '';
349
+ try { const { body } = await call(`${base}/runs`); S.runs = body.runs || []; S.unreadableRuns = (body.unreadable || []).length; }
350
+ catch (e) { S.runs = []; S.unreadableRuns = 0; S.runsError = e.message; if (e.status === 403) S.accessError = e.message; }
351
+ }
352
+ async function loadColours() {
353
+ try { const { body } = await call(`${base}/colours`); S.colours = body.colours; S.colourWarning = body.warning; S.coloursUnread = false; }
354
+ catch { S.colours = null; S.coloursUnread = true; }
355
+ }
356
+ const approvedVersion = () => (S.review && S.review.base ? S.review.base.version : null);
357
+ const hasApproved = () => approvedVersion() !== null || S.runs.length > 0;
358
+ const references = () => (S.draft && S.draft.references) || [];
359
+ const items = () => (S.draft && S.draft.items) || [];
360
+ const referencePages = () => references().reduce((n, r) => n + (r.pages || 0), 0);
361
+
362
+ async function loadAll() {
363
+ S.accessError = '';
364
+ // allSettled, not all: every read must land before the page decides which failure to explain.
365
+ const settled = await Promise.allSettled([loadDraft(), loadReview(), loadRuns(), loadColours()]);
366
+ const failed = settled.find((r) => r.status === 'rejected');
367
+ S.loadError = failed ? (failed.reason && failed.reason.message) || 'This profile could not be read. Reload to try again.' : '';
368
+ // A module refusal (no Drawing Checker access) is the one answer that explains every other failure,
369
+ // so its own copy is what the page says.
370
+ if (S.accessError) S.loadError = S.accessError;
371
+ if (!S.tab) S.tab = landingTab({ hasApproved: hasApproved(), referenceCount: references().length });
372
+ render();
373
+ }
374
+
375
+ // ── shell ──
376
+ const TABS = [['references', 'Reference drawings'], ['checklist', 'Checklist'], ['runs', 'Runs'], ['colours', 'Markup colours']];
377
+ function render() {
378
+ const v = approvedVersion();
379
+ const client = (S.draft && S.draft.client) || 'Client profile';
380
+ paintKeepingFocus(document, root, `
381
+ <header><span class="name">${esc(client)}</span>
382
+ ${v !== null ? `<span class="pill approved">v${v} approved</span>` : '<span class="pill">Draft</span>'}
383
+ ${S.review && S.review.groups && S.review.groups.length && v !== null ? '<span class="pill">Changes not approved</span>' : ''}
384
+ <span class="sp"></span></header>
385
+ <nav role="tablist" aria-label="Drawing Checker">${TABS.map(([k, l]) =>
386
+ `<button type="button" role="tab" id="tab-${k}" aria-controls="panel-${k}" aria-selected="${S.tab === k}" tabindex="${S.tab === k ? 0 : -1}" data-tab="${k}" data-command-id="drawing-check.tab#${esc(k)}" data-command-instance-label="${l}">${l}</button>`).join('')}</nav>
387
+ <main>${S.loadError ? `<section role="tabpanel"><div class="wrap"><p class="${S.accessError ? 'band' : 'err-line'}" role="alert">${esc(S.loadError)}</p><button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div></section>` : panel()}</main>`);
388
+ if (S.tab === 'runs' && S.run) mountRunView();
389
+ }
390
+ function panel() {
391
+ const attrs = (k, cls = '') => `role="tabpanel" id="panel-${k}" aria-labelledby="tab-${k}"${cls ? ` class="${cls}"` : ''}`;
392
+ if (S.tab === 'references') return `<section ${attrs('references')}>${referencesHtml()}</section>`;
393
+ if (S.tab === 'checklist') return `<section ${attrs('checklist')}>${checklistHtml()}</section>`;
394
+ if (S.tab === 'colours') return `<section ${attrs('colours')}>${coloursHtml()}</section>`;
395
+ return S.run ? `<section ${attrs('runs', 'flush')}>${runViewHtml()}</section>` : `<section ${attrs('runs')}>${runsHtml()}</section>`;
396
+ }
397
+
398
+ // ── references ──
399
+ function referencesHtml() {
400
+ const refs = references();
401
+ const drop = (compact) => `<button type="button" class="drop${compact ? ' compact' : ''}" data-act="pick-refs" data-command-id="drawing-check.add-references">
402
+ <b>${compact ? 'Add more reference drawings' : 'Drop the shop drawings this client already signed off'}</b>
403
+ <span>${compact ? 'Drop PDFs here, or choose files' : 'PDF files. The checklist is proposed from what these drawings have in common.'}</span></button>`;
404
+ return `<div class="wrap"><h2>Reference drawings</h2>
405
+ <p class="lede">Drawings this client has already accepted. FloLess reads what they have in common and proposes a checklist from it.</p>
406
+ ${S.newSinceApproval && approvedVersion() !== null ? `<div class="band">${S.newSinceApproval} new drawing${S.newSinceApproval === 1 ? ' isn’t' : 's aren’t'} in version ${approvedVersion()}. Propose again on the Checklist to include ${S.newSinceApproval === 1 ? 'it' : 'them'}.</div>` : ''}
407
+ ${S.uploadNote ? `<p class="note" role="status">${esc(S.uploadNote)}</p>` : ''}
408
+ ${refs.length ? `<div class="list" style="margin-bottom:14px">${refs.map((r) => `<div><span class="grow">${esc(r.name)}</span><span class="meta">${r.pages} page${r.pages === 1 ? '' : 's'}</span></div>`).join('')}</div>${drop(true)}` : drop(false)}
409
+ <input type="file" id="ref-file" accept=".pdf,application/pdf" multiple hidden></div>`;
410
+ }
411
+ async function uploadReferences(files) {
412
+ const pdfs = [...files].filter((f) => /\.pdf$/i.test(f.name) || f.type === 'application/pdf');
413
+ const skipped = files.length - pdfs.length;
414
+ const failed = [];
415
+ let added = 0;
416
+ for (let i = 0; i < pdfs.length; i++) {
417
+ S.uploadNote = `Adding ${pdfs[i].name} (${i + 1} of ${pdfs.length})…`; render();
418
+ try {
419
+ const { body } = await call(`${base}/references?name=${encodeURIComponent(pdfs[i].name)}`, { method: 'POST', headers: { 'content-type': 'application/pdf' }, body: pdfs[i] });
420
+ if (S.draft) S.draft.references = body.references; added++;
421
+ } catch (e) { failed.push(e.message); }
422
+ }
423
+ if (added) S.newSinceApproval += added;
424
+ const notes = [];
425
+ if (added) notes.push(`${added} drawing${added === 1 ? '' : 's'} added.`);
426
+ if (skipped) notes.push(`${skipped} file${skipped === 1 ? '' : 's'} skipped: not PDF${skipped === 1 ? '' : 's'}.`);
427
+ notes.push(...failed);
428
+ S.uploadNote = notes.join(' ');
429
+ await Promise.all([loadDraft(), loadReview()]).catch(() => {});
430
+ render();
431
+ }
432
+
433
+ // ── checklist ──
434
+ function checklistHtml() {
435
+ if (!references().length) {
436
+ return `<div class="wrap"><h2>Checklist</h2><p class="lede">Add reference drawings first: the checklist is proposed from drawings this client already trusts.</p>
437
+ <button type="button" class="link" data-tab="references" data-command-id="drawing-check.tab#references" data-command-instance-label="Reference drawings">Go to Reference drawings</button></div>`;
438
+ }
439
+ const list = items();
440
+ const pages = referencePages();
441
+ const anyTicked = list.some((i) => i.enabled);
442
+ const changed = !!(S.review && S.review.groups && S.review.groups.length);
443
+ const rows = list.map((it) => {
444
+ const pct = typeof it.frequency === 'number' ? Math.round(it.frequency * 100) : null;
445
+ const origin = it.origin === 'client-standard'
446
+ ? 'added from client standard'
447
+ : it.origin === 'redline' ? 'added from a redline' : pct !== null && pages ? `seen on ${Math.round(it.frequency * pages)} of ${pages}` : 'proposed from the references';
448
+ return `<label class="check-row"><input type="checkbox" data-item="${esc(it.id)}" data-command-id="drawing-check.tick-item#${esc(it.id)}" data-command-instance-label="${esc(it.label)}"${it.enabled ? ' checked' : ''}>
449
+ <span class="lbl">${esc(it.label)}<span class="origin">${esc(origin)}</span></span>
450
+ ${pct !== null ? `<span class="freq${pct < 50 ? ' rare' : ''}" data-tip="How often this held on the reference drawings"><span class="bar"><i style="width:${pct}%"></i></span>${pct}%</span>` : '<span></span>'}
451
+ <span class="kind">by code</span></label>`;
452
+ }).join('');
453
+ return `<div class="wrap"><h2>Checklist</h2>
454
+ <p class="lede">Common doesn’t mean required. Tick only what this client needs.</p>
455
+ ${pendingAsksNotice(S.draft && S.draft.titleBlock)}
456
+ ${clientFieldHtml((S.draft && S.draft.client) || '')}
457
+ <div class="row-actions"><button type="button" class="${list.length ? '' : 'primary'}" data-act="propose" data-command-id="drawing-check.propose">${list.length ? 'Propose again from references' : 'Propose from references'}</button>
458
+ <button type="button" data-act="add-item" data-command-id="drawing-check.add-item">Add item from client standard…</button></div>
459
+ ${S.conflict ? '<div class="band">This checklist changed in another window. Reload to see the latest. <button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div>' : ''}
460
+ ${S.checklistError ? `<p class="err-line" role="alert">${esc(S.checklistError)}</p>` : ''}
461
+ ${list.length ? `<div class="list">${rows}</div>` : '<p class="note">No items yet. Propose them from the reference drawings.</p>'}
462
+ ${titleBlockHtml(S.draft && S.draft.titleBlock, { pages, note: S.titleNote, noteField: S.titleNoteField, saving: S.tbSaving, typed: S.typed })}
463
+ ${S.reviewError ? `<p class="note">${esc(S.reviewError)}</p>` : ''}
464
+ ${changed && anyTicked ? `<div class="sticky-foot"><span class="note">${S.tbChanges && S.tbChanges.length ? 'Title block changed · ' : ''}${list.filter((i) => i.enabled).length} of ${list.length} items ticked. Runs use the approved checklist only.</span><span class="sp"></span>
465
+ <button type="button" class="primary" data-act="approve" data-command-id="drawing-check.approve">Approve checklist…</button></div>` : ''}</div>`;
466
+ }
467
+ // Checklist edits go out ONE AT A TIME. Two quick ticks used to send the second PUT with the etag the
468
+ // page held before the first answered, which the server rightly refused (412) — shown as "changed in
469
+ // another window" and the tick reverted. Each queued PUT reads S.etag when it actually goes out.
470
+ const itemsQueue = serialise();
471
+ let itemsInFlight = 0;
472
+ function putItems(edits) {
473
+ itemsInFlight++;
474
+ return itemsQueue(async () => {
475
+ S.checklistError = '';
476
+ try {
477
+ const { body } = await call(`${base}/items`, jsonOpts('PUT', { items: edits }, S.etag ? { 'if-match': S.etag } : {}));
478
+ S.etag = body.etag;
479
+ // Only the LAST answer replaces the list: an earlier one predates ticks still queued behind it,
480
+ // and painting it would flick those ticks back until their own answer arrived.
481
+ if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
482
+ return body;
483
+ } catch (e) {
484
+ if (e.status === 412 || e.status === 428) S.conflict = true;
485
+ else S.checklistError = e.message;
486
+ await loadDraft().catch(() => {}); // show what the profile really holds, not the optimistic ticks
487
+ render();
488
+ return null;
489
+ } finally { itemsInFlight--; }
490
+ });
491
+ }
492
+ // The client goes out on the same queue as the ticks: one draft, one etag, one PUT at a time.
493
+ function putClient(client) {
494
+ itemsInFlight++;
495
+ return itemsQueue(async () => {
496
+ S.checklistError = '';
497
+ try {
498
+ const { body } = await call(`${base}/client`, jsonOpts('PUT', { client }, S.etag ? { 'if-match': S.etag } : {}));
499
+ S.etag = body.etag; S.draft.client = body.client;
500
+ await loadReview();
501
+ } catch (e) {
502
+ if (e.status === 412 || e.status === 428) S.conflict = true;
503
+ else S.checklistError = e.message;
504
+ await loadDraft().catch(() => {});
505
+ } finally { itemsInFlight--; }
506
+ render();
507
+ });
508
+ }
509
+ // Title-block edits ride the same queue: one draft, one etag, one PUT at a time.
510
+ function putTitleBlock(change) {
511
+ itemsInFlight++;
512
+ return itemsQueue(async () => {
513
+ S.checklistError = ''; S.titleNote = ''; S.titleNoteField = '';
514
+ try {
515
+ const { body } = await call(`${base}/title-block`, jsonOpts('PUT', change, S.etag ? { 'if-match': S.etag } : {}));
516
+ S.etag = body.etag;
517
+ if (itemsInFlight === 1) { S.draft.titleBlock = body.titleBlock; S.draft.items = body.items; }
518
+ if (body.note) { S.titleNote = body.note; S.titleNoteField = body.noteField || ''; }
519
+ if (change.answer) delete S.typed[change.answer.ask];
520
+ await loadReview();
521
+ return body;
522
+ } catch (e) {
523
+ if (e.status === 412 || e.status === 428) S.conflict = true;
524
+ // A typed answer the server refused stays in its field, with the reason beside it.
525
+ else if (change.answer && change.answer.label !== undefined) S.typed[change.answer.ask] = { value: change.answer.label, error: e.message };
526
+ else S.checklistError = e.message;
527
+ await loadDraft().catch(() => {});
528
+ return null;
529
+ } finally { itemsInFlight--; S.tbSaving = false; render(); }
530
+ });
531
+ }
532
+ function addFieldDialog() {
533
+ showDialog({
534
+ title: 'Add a title-block field',
535
+ body: `<label class="field"><span>Label as written on the drawings</span><input type="text" id="af-label" maxlength="80" placeholder="e.g. SHEET NO." autocomplete="off" spellcheck="false"></label>
536
+ <label class="choice"><input type="checkbox" id="af-required" checked><span>Must be filled in on every drawing</span></label>
537
+ <p class="note">FloLess finds the label on the reference drawings and learns where its value sits.</p>
538
+ <p class="err-line" id="af-err" role="alert" hidden></p>`,
539
+ foot: '<button type="button" data-dlg="cancel">Cancel</button><button type="button" class="primary" data-dlg="add">Add field</button>',
540
+ onOpen: (scrim) => {
541
+ scrim.querySelector('#af-label').focus();
542
+ scrim.addEventListener('keydown', (e) => { if (e.key === 'Enter' && e.target.id === 'af-label') scrim.querySelector('[data-dlg="add"]').click(); });
543
+ scrim.addEventListener('click', async (e) => {
544
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
545
+ if (act === 'cancel') { closeDialog(); return; }
546
+ if (act !== 'add') return;
547
+ const label = scrim.querySelector('#af-label').value.replace(/\s+/g, ' ').trim();
548
+ const err = scrim.querySelector('#af-err');
549
+ if (!label) { err.hidden = false; err.textContent = 'Write the label as it appears on the drawings.'; return; }
550
+ e.target.disabled = true; e.target.textContent = 'Looking for it…';
551
+ const res = await putTitleBlock({ add: { label, required: scrim.querySelector('#af-required').checked } });
552
+ if (!openDialog || openDialog.scrim !== scrim) return;
553
+ if (!res) { e.target.disabled = false; e.target.textContent = 'Add field'; err.hidden = false; err.textContent = S.checklistError || 'The field could not be added. Try again.'; return; }
554
+ closeDialog();
555
+ });
556
+ },
557
+ });
558
+ }
559
+
560
+ async function propose() {
561
+ S.checklistError = ''; S.uploadNote = '';
562
+ const btn = root.querySelector('[data-act="propose"]'); if (btn) { btn.disabled = true; btn.textContent = 'Reading the reference drawings…'; }
563
+ try {
564
+ const { body } = await call(`${base}/propose`, { method: 'POST' });
565
+ S.draft.items = body.items; S.etag = body.etag; S.newSinceApproval = 0;
566
+ if (body.titleBlock) S.draft.titleBlock = body.titleBlock; else delete S.draft.titleBlock;
567
+ if (body.client) S.draft.client = body.client;
568
+ if (body.unreadable && body.unreadable.length) S.checklistError = `Couldn’t read ${body.unreadable.join(', ')}; the other drawings were used.`;
569
+ await loadReview();
570
+ } catch (e) { S.checklistError = e.message; }
571
+ render();
572
+ }
573
+
574
+ // ── dialog (one at a time) ──
575
+ let openDialog = null;
576
+ function showDialog({ title, body, foot, onOpen, returnFocus }) {
577
+ closeDialog(false);
578
+ const scrim = document.createElement('div');
579
+ scrim.className = 'scrim';
580
+ scrim.innerHTML = `<div class="dialog" role="dialog" aria-modal="true" aria-labelledby="dlg-title"><h2 id="dlg-title">${esc(title)}</h2><div class="body">${body}</div><div class="foot">${foot}</div></div>`;
581
+ document.body.appendChild(scrim);
582
+ openDialog = { scrim, returnFocus: returnFocus || document.activeElement };
583
+ scrim.addEventListener('keydown', (e) => {
584
+ if (e.key === 'Escape') { e.preventDefault(); closeDialog(); return; }
585
+ if (e.key !== 'Tab') return;
586
+ const f = [...scrim.querySelectorAll('button:not([disabled]),input:not([disabled])')].filter((el) => !(el.type === 'radio' && !el.checked));
587
+ if (!f.length) return;
588
+ if (e.shiftKey && document.activeElement === f[0]) { e.preventDefault(); f.at(-1).focus(); }
589
+ else if (!e.shiftKey && document.activeElement === f.at(-1)) { e.preventDefault(); f[0].focus(); }
590
+ });
591
+ if (onOpen) onOpen(scrim);
592
+ return scrim;
593
+ }
594
+ function closeDialog(restore = true) {
595
+ if (!openDialog) return;
596
+ const { scrim, returnFocus } = openDialog;
597
+ openDialog = null; scrim.remove();
598
+ if (restore && returnFocus && returnFocus.isConnected) returnFocus.focus();
599
+ }
600
+
601
+ function addItemDialog() {
602
+ const pages = referencePages();
603
+ showDialog({
604
+ title: 'Add item from client standard',
605
+ body: `<label class="field"><span>What to call it</span><input type="text" id="ai-label" placeholder="e.g. Galvanising note"></label>
606
+ <label class="field"><span>Text to look for on the drawing</span><input type="text" id="ai-text" placeholder="e.g. HOT DIP GALVANIZE"></label>
607
+ <p class="note">The item is added and tested on the ${pages} reference page${pages === 1 ? '' : 's'}, so you see how often it holds.</p>
608
+ <p class="err-line" id="ai-err" role="alert" hidden></p><p id="ai-result" role="status" hidden></p>`,
609
+ foot: '<button type="button" data-dlg="cancel">Cancel</button><button type="button" class="primary" data-dlg="test">Add and test on reference drawings</button>',
610
+ onOpen: (scrim) => {
611
+ scrim.querySelector('#ai-label').focus();
612
+ scrim.addEventListener('click', async (e) => {
613
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
614
+ if (act === 'cancel' || act === 'done') { closeDialog(); return; }
615
+ if (act === 'remove') {
616
+ const id = scrim.dataset.added; closeDialog();
617
+ if (id) await putItems([{ id, remove: true }]);
618
+ return;
619
+ }
620
+ if (act !== 'test') return;
621
+ const label = scrim.querySelector('#ai-label').value.trim();
622
+ const text = scrim.querySelector('#ai-text').value.trim();
623
+ const err = scrim.querySelector('#ai-err');
624
+ if (!label || !text) { err.hidden = false; err.textContent = 'Give the item a name and the text to look for.'; return; }
625
+ e.target.disabled = true; e.target.textContent = 'Testing…';
626
+ const before = new Set(items().map((i) => i.id));
627
+ const res = await putItems([{ label, text, display: label, enabled: true }]);
628
+ if (!openDialog || openDialog.scrim !== scrim) return;
629
+ if (!res) { e.target.disabled = false; e.target.textContent = 'Add and test on reference drawings'; err.hidden = false; err.textContent = S.checklistError || 'The item could not be added. Try again.'; return; }
630
+ const added = res.items.find((i) => !before.has(i.id));
631
+ scrim.dataset.added = added ? added.id : '';
632
+ const f = added && typeof added.frequency === 'number' ? added.frequency : null;
633
+ const out = scrim.querySelector('#ai-result'); out.hidden = false;
634
+ out.textContent = f === null ? 'Added. It could not be tested, because no reference drawing could be read.'
635
+ : `Found on ${Math.round(f * pages)} of ${pages} (${Math.round(f * 100)}%). Rare is fine if the client requires it.`;
636
+ scrim.querySelector('.foot').innerHTML = '<button type="button" data-dlg="remove">Remove it</button><button type="button" class="primary" data-dlg="done">Keep item</button>';
637
+ scrim.querySelector('[data-dlg="done"]').focus();
638
+ });
639
+ },
640
+ });
641
+ }
642
+
643
+ async function approveDialog() {
644
+ const seen = S.review;
645
+ const ticked = items().filter((i) => i.enabled).length;
646
+ const v = approvedVersion();
647
+ // What changes in the title block, in plain words, from the server (draft against the approved version).
648
+ const changes = await titleChangesForApproval();
649
+ const tbHtml = changes === 'approved-unreadable' ? '<p class="note">The title-block changes couldn’t be worked out, because the approved checklist couldn’t be read to compare with. Whatever the title block says now is part of what you approve.</p>'
650
+ : changes === 'failed' ? '<p class="note">The title-block changes couldn’t be loaded. Whatever the title block says now is part of what you approve.</p>'
651
+ : changes.length ? `<div class="tb-changes"><b>Title block</b><ul>${changes.map((c) => `<li>${esc(c)}</li>`).join('')}</ul></div>` : '';
652
+ const open = (S.draft && S.draft.titleBlock && S.draft.titleBlock.asks) || [];
653
+ const openHtml = open.length ? `<p class="note ask-line">${open.length} question${open.length === 1 ? '' : 's'} about your title block ${open.length === 1 ? 'is' : 'are'} unanswered: ${open.map((a) => esc(a.question)).join(' ')} Until answered, every sheet shows “couldn’t tell” for ${open.length === 1 ? 'it' : 'them'}. You can still approve.</p>` : '';
654
+ showDialog({
655
+ title: `Approve ${ticked} item${ticked === 1 ? '' : 's'}?`,
656
+ body: `<p>New runs use the checklist you approve now.${v !== null ? ` Earlier runs keep version ${v}.` : ''}</p>${tbHtml}${openHtml}<p class="err-line" id="ap-err" role="alert" hidden></p>`,
657
+ foot: '<button type="button" data-dlg="cancel">Cancel</button><button type="button" class="primary" data-dlg="approve">Approve</button>',
658
+ onOpen: (scrim) => {
659
+ scrim.querySelector('[data-dlg="approve"]').focus();
660
+ scrim.addEventListener('click', async (e) => {
661
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
662
+ if (act === 'cancel' || act === 'close') { closeDialog(); return; }
663
+ if (act !== 'approve') return;
664
+ e.target.disabled = true; e.target.textContent = 'Approving…';
665
+ const err = scrim.querySelector('#ap-err');
666
+ try {
667
+ // The review the person SAW (loaded with the checklist on screen), never a fresh one fetched at
668
+ // click time: if the draft moved since, the server refuses that reviewId as stale.
669
+ const review = seen;
670
+ if (!review || !review.reviewId) throw new Error('There is nothing to approve yet.');
671
+ const decisions = Object.fromEntries((review.groups || []).map((g) => [g.id, 'approve']));
672
+ const { body } = await call(`/api/contract/${encodeURIComponent(APP)}/approve?project=${encodeURIComponent(PROJECT)}`,
673
+ jsonOpts('POST', { mode: review.mode || 'head', reviewId: review.reviewId, decisions, conflicts: {}, claimedChannel: 'browser' }));
674
+ const n = body && body.version && body.version.n;
675
+ scrim.querySelector('.body').innerHTML = `<p role="status">Approved${n ? ` as version ${n}` : ''}. New runs use this checklist.</p>`;
676
+ scrim.querySelector('.foot').innerHTML = '<button type="button" class="primary" data-dlg="close">Done</button>';
677
+ scrim.querySelector('[data-dlg="close"]').focus();
678
+ try { parent.postMessage({ type: 'floless:contract-save-state', appId: APP, projectId: PROJECT, generation: Date.now(), state: 'clean' }, location.origin); } catch { /* standalone tab */ }
679
+ await Promise.all([loadReview(), loadRuns()]); render();
680
+ } catch (x) {
681
+ if (!openDialog) return;
682
+ e.target.disabled = false; e.target.textContent = 'Approve';
683
+ err.hidden = false;
684
+ if (x.body && x.body.code === 'approval-review-stale') {
685
+ err.textContent = 'Nothing was approved. The checklist changed since you looked at it. Close this, check the list again, then approve.';
686
+ e.target.disabled = true;
687
+ await loadReview(); render();
688
+ } else err.textContent = `Nothing was approved. ${x.message}`;
689
+ }
690
+ });
691
+ },
692
+ });
693
+ }
694
+
695
+ // ── runs ──
696
+ function runsHtml() {
697
+ const head = `<h2>Runs</h2><p class="lede">Each run checks shop drawings against the approved checklist and marks them up. A person marks each sheet checked.</p>`;
698
+ const unreadable = S.unreadableRuns ? `<p class="warn-line" role="status">${S.unreadableRuns} stored run${S.unreadableRuns === 1 ? '' : 's'} could not be read, so ${S.unreadableRuns === 1 ? 'it is' : 'they are'} not listed. Check the drawings again to make a new run.</p>` : '';
699
+ if (!hasApproved()) {
700
+ return `<div class="wrap">${head}${unreadable}<p>Approve a checklist first. Runs check drawings against the approved version only.</p>
701
+ <button type="button" class="link" data-tab="checklist" data-command-id="drawing-check.tab#checklist" data-command-instance-label="Checklist">Go to Checklist</button></div>`;
702
+ }
703
+ const rows = S.runs.map((r) => {
704
+ const when = new Date(r.startedAt);
705
+ return `<button type="button" class="run-row" data-run="${esc(r.runId)}" data-command-id="drawing-check.open-run"><span class="when">${esc(when.toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }))}</span>
706
+ <span class="counts">${r.summary.sheets} sheet${r.summary.sheets === 1 ? '' : 's'} · ${esc(countsLine(r.summary))}</span>
707
+ <span class="meta note">${esc(r.summary.client)} · v${r.summary.version}</span></button>`;
708
+ }).join('');
709
+ return `<div class="wrap">${head}
710
+ <div class="row-actions"><button type="button" class="primary" data-act="check" data-command-id="drawing-check.check-drawings" ${S.running ? 'disabled' : ''}>Check drawings…</button></div>
711
+ ${S.runError ? `<p class="err-line" role="alert">${esc(S.runError)}</p>` : ''}
712
+ ${S.runsError ? `<p class="err-line">${esc(S.runsError)}</p>` : ''}
713
+ ${unreadable}
714
+ <div class="list">${S.running ? `<div role="status"><span class="spin" aria-hidden="true"></span><span class="grow">${esc(S.running)}</span></div>` : ''}${rows}</div>
715
+ ${!S.runs.length && !S.running ? '<p class="note">No runs yet.</p>' : ''}
716
+ <input type="file" id="run-file" accept=".pdf,application/pdf" multiple hidden></div>`;
717
+ }
718
+
719
+ /** Store each picked PDF where a run can read it (the same visual-input store the workflow inputs use). */
720
+ async function storeDrawings(files) {
721
+ const paths = [];
722
+ for (const f of files) {
723
+ const dataUrl = await new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = () => reject(new Error(`${f.name} could not be read.`)); r.readAsDataURL(f); });
724
+ const { body } = await call('/api/visual-input', jsonOpts('POST', { appId: APP, name: 'drawings', dataUrl }));
725
+ paths.push(body.path);
726
+ }
727
+ return paths;
728
+ }
729
+ /**
730
+ * The latest approved checklist cannot be read: offer the newest earlier approved version instead of
731
+ * stopping. Resolves to that version number, or null when there is none or the person cancels.
732
+ */
733
+ function fallbackDialog(e) {
734
+ const offered = e && e.body && e.body.code === 'profile-unreadable' && Array.isArray(e.body.previousApproved) ? e.body.previousApproved[0] : undefined;
735
+ if (typeof offered !== 'number') return Promise.resolve(null);
736
+ return new Promise((resolve) => {
737
+ let settled = false;
738
+ const finish = (v) => { if (settled) return; settled = true; closeDialog(); resolve(v); };
739
+ const scrim = showDialog({
740
+ title: 'The latest approved checklist can’t be read',
741
+ body: `<p>${esc(e.message)}</p><p>Check these drawings against approved version ${offered} instead? Every sheet will say this run used version ${offered}, not the latest.</p>`,
742
+ foot: `<button type="button" data-dlg="cancel">Cancel</button><button type="button" class="primary" data-dlg="fallback" data-command-id="drawing-check.check-with-version">Check with version ${offered}</button>`,
743
+ returnFocus: root.querySelector('[data-act="check"]'),
744
+ onOpen: (sc) => {
745
+ sc.querySelector('[data-dlg="fallback"]').focus();
746
+ sc.addEventListener('click', (ev) => {
747
+ const act = ev.target.closest('[data-dlg]')?.dataset.dlg;
748
+ if (act === 'cancel') finish(null);
749
+ if (act === 'fallback') finish(offered);
750
+ });
751
+ },
752
+ });
753
+ new MutationObserver((_, obs) => { if (!scrim.isConnected) { obs.disconnect(); if (!settled) { settled = true; resolve(null); } } }).observe(document.body, { childList: true });
754
+ });
755
+ }
756
+
757
+ async function checkDrawings(files) {
758
+ const pdfs = [...files];
759
+ if (!pdfs.length) return;
760
+ S.runError = '';
761
+ S.running = `Checking ${pdfs.length} drawing${pdfs.length === 1 ? '' : 's'}…`; render();
762
+ let paths;
763
+ try { paths = await storeDrawings(pdfs); }
764
+ catch (e) { S.running = null; S.runError = e.message; render(); return; }
765
+ let warnings = [];
766
+ let version; // undefined: the latest approved version; a number: the earlier one the person chose
767
+ try { warnings = (await call(`${base}/preflight`, jsonOpts('POST', { drawings: paths }))).body.warnings || []; }
768
+ catch (e) {
769
+ S.running = null; render();
770
+ version = await fallbackDialog(e);
771
+ if (version === null) { S.runError = e.message; render(); return; }
772
+ S.running = `Checking ${pdfs.length} drawing${pdfs.length === 1 ? '' : 's'} against version ${version}…`; render();
773
+ try { warnings = (await call(`${base}/preflight`, jsonOpts('POST', { drawings: paths, version }))).body.warnings || []; }
774
+ catch (e2) { S.running = null; S.runError = e2.message; render(); return; }
775
+ }
776
+ let decisions = {};
777
+ if (warnings.length) {
778
+ S.running = null; render();
779
+ decisions = await preflightDialog(warnings, pdfs.length);
780
+ if (!decisions) return;
781
+ S.running = `Checking ${pdfs.length} drawing${pdfs.length === 1 ? '' : 's'}…`; render();
782
+ }
783
+ try {
784
+ const { body } = await call(`${base}/runs`, jsonOpts('POST', { drawings: paths, decisions, ...(version !== undefined ? { version } : {}) }));
785
+ S.running = null;
786
+ await loadRuns();
787
+ await openRun(body.runId);
788
+ } catch (e) { S.running = null; S.runError = e.message; render(); }
789
+ }
790
+
791
+ function preflightDialog(warnings, count) {
792
+ return new Promise((resolve) => {
793
+ const groups = warnings.map((w, gi) => {
794
+ const where = w.where ? [w.where.drawing, w.where.page ? `page ${w.where.page}` : ''].filter(Boolean).join(' · ') : '';
795
+ return `<fieldset><legend>${esc(w.message)}</legend>${where ? `<p class="where">${esc(where)}</p>` : ''}
796
+ ${w.choices.map((c) => `<label class="choice"><input type="radio" name="w${gi}" value="${esc(c.id)}"${c.id === w.defaultChoice ? ' checked' : ''}><span>${esc(c.label)}${c.id === w.defaultChoice ? '<span class="suggested">Suggested</span>' : ''}</span></label>`).join('')}</fieldset>`;
797
+ }).join('');
798
+ let settled = false;
799
+ const finish = (v) => { if (settled) return; settled = true; closeDialog(); resolve(v); };
800
+ const scrim = showDialog({
801
+ title: `Before checking ${count} drawing${count === 1 ? '' : 's'}, ${warnings.length} thing${warnings.length === 1 ? ' needs' : 's need'} your decision`,
802
+ body: groups,
803
+ foot: '<span class="note">Whatever you choose is written into the report and the run record.</span><button type="button" data-dlg="cancel">Cancel</button><button type="button" class="primary" data-dlg="go">Check drawings</button>',
804
+ returnFocus: root.querySelector('[data-act="check"]'),
805
+ onOpen: (sc) => {
806
+ (sc.querySelector('input[type=radio]:checked') || sc.querySelector('input[type=radio]') || sc.querySelector('[data-dlg="go"]')).focus();
807
+ sc.addEventListener('click', (e) => {
808
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
809
+ if (act === 'cancel') finish(null);
810
+ if (act === 'go') {
811
+ const out = {};
812
+ warnings.forEach((w, gi) => { const c = sc.querySelector(`input[name="w${gi}"]:checked`); out[w.key] = c ? c.value : w.defaultChoice; });
813
+ finish(out);
814
+ }
815
+ });
816
+ },
817
+ });
818
+ // Esc / backdrop close resolves as Cancel too.
819
+ new MutationObserver((_, obs) => { if (!scrim.isConnected) { obs.disconnect(); if (!settled) { settled = true; resolve(null); } } }).observe(document.body, { childList: true });
820
+ });
821
+ }
822
+
823
+ async function openRun(runId) {
824
+ S.runError = '';
825
+ try {
826
+ const { body } = await call(`${base}/runs/${encodeURIComponent(runId)}`);
827
+ S.run = body.result; S.runLabels = body.labels || {}; S.sheet = 0; S.selectedN = null; S.itemNote = ''; S.exportCard = null; S.tab = 'runs';
828
+ } catch (e) { S.runError = e.message; }
829
+ render();
830
+ }
831
+
832
+ // ── run view ──
833
+ // The run's own version's item names first: renaming an item later never relabels an old run.
834
+ const labelOf = (id) => (S.runLabels && S.runLabels[id]) || (items().find((i) => i.id === id) || {}).label || id;
835
+ const sheetOf = () => (S.run ? S.run.sheets[S.sheet] : null);
836
+ const checkedFor = (s) => S.run && s && S.run.checkedBy.find((c) => c.drawing === s.drawing && c.page === s.page);
837
+
838
+ function runViewHtml() {
839
+ const r = S.run;
840
+ const when = new Date(r.startedAt).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
841
+ const s = sheetOf();
842
+ const strip = r.sheets.map((sh, i) => {
843
+ const f = sh.items.filter((x) => x.status === 'fail').length, q = sh.items.filter((x) => x.status === 'dont-know').length;
844
+ const sum = sh.status !== 'checked' ? 'Not looked at' : [f ? `${f} wrong` : '', q ? `${q} couldn’t tell` : ''].filter(Boolean).join(' · ') || 'All fine';
845
+ return `<button type="button" class="sheet-btn" data-sheet="${i}" data-command-id="drawing-check.sheet" aria-current="${i === S.sheet}"><span class="sl">${esc(sh.sheetLabel || `${sh.drawing} p${sh.page}`)}</span><span class="ss">${esc(sum)}</span>${checkedFor(sh) ? '<span class="done">Checked</span>' : ''}</button>`;
846
+ }).join('');
847
+ const colours = statusColours(S.colours);
848
+ const legend = ['pass', 'fail', 'dont-know'].map((k) => `<span><svg width="18" height="8" aria-hidden="true"><line x1="1" y1="4" x2="17" y2="4" stroke="${esc(colours[k])}" stroke-width="${LINE[k].w + 0.6}" ${LINE[k].dash ? `stroke-dasharray="${LINE[k].dash}"` : ''}/></svg>${STATUS_WORD[k]}</span>`).join('')
849
+ + '<span><i class="hatched" aria-hidden="true"></i>FloLess doesn’t check</span>';
850
+ const unsigned = r.signature && r.signature.status === 'unsigned';
851
+ return `<div class="runbar"><button type="button" data-act="back" data-command-id="drawing-check.back-to-runs">← Runs</button><span class="title">${esc(when)}</span><span class="note">${esc(r.profile.client)} · v${r.profile.version}</span>
852
+ ${r.warnings.length ? `<button type="button" class="chip warn" data-act="warnings" data-command-id="drawing-check.show-decisions">${r.warnings.length} decision${r.warnings.length === 1 ? '' : 's'}</button>` : ''}
853
+ ${unsigned ? `<span class="chip" data-tip="${esc(unsignedTip(r.signature))}">Not signed</span>` : ''}
854
+ <span class="sp"></span><button type="button" data-act="export" data-command-id="drawing-check.export" ${s && s.status === 'checked' ? '' : 'disabled'}>Export marked-up PDF</button></div>
855
+ <div class="runview"><div class="sheets" aria-label="Sheets">${strip}</div>
856
+ <div class="stage" id="stage" tabindex="0" aria-label="Marked-up drawing. Plus and minus zoom, 0 fits the page, arrows pan.">
857
+ <svg class="view" id="view" xmlns="http://www.w3.org/2000/svg"></svg>
858
+ <div class="msg" id="stage-msg" hidden></div>
859
+ <div class="legend" aria-label="Legend">${legend}</div>
860
+ <div class="zoom"><button type="button" data-command-id="drawing-check.zoom" data-zoom="fit" data-tip="Fit page (0)">Fit page</button><button type="button" data-command-id="drawing-check.zoom" data-zoom="in" data-tip="Zoom in (+)" aria-label="Zoom in">+</button><button type="button" data-command-id="drawing-check.zoom" data-zoom="out" data-tip="Zoom out (−)" aria-label="Zoom out">−</button></div>
861
+ </div>
862
+ <div class="side" id="side">${sideHtml()}</div></div>`;
863
+ }
864
+
865
+ function sideHtml() {
866
+ const r = S.run, s = sheetOf();
867
+ if (!s) return '<p class="note">This run has no sheets.</p>';
868
+ const colours = statusColours(S.colours);
869
+ const auto = r.warnings.filter((w) => w.decided === null).length;
870
+ const checked = checkedFor(s);
871
+ const open = s.items.filter((x) => x.status !== 'pass').length;
872
+ let out = auto ? `<div class="band">FloLess made ${auto} choice${auto === 1 ? '' : 's'} for you on safe defaults. <button type="button" class="link" data-act="warnings" data-command-id="drawing-check.show-decisions">See them</button></div>` : '';
873
+ out += `<div class="sheet-head"><div class="grow"><div class="t">Sheet ${S.sheet + 1} of ${r.sheets.length} · ${esc(s.sheetLabel || s.drawing)}</div><div class="s">${esc(s.drawing)} · page ${s.page}</div></div>
874
+ ${checked ? `<span class="marked" role="status">Checked by ${esc(checked.by)} · ${esc(new Date(checked.at).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }))}</span>` : `<button type="button" data-act="mark" data-command-id="drawing-check.mark-checked">Mark checked, by me</button>`}</div>`;
875
+ if (!checked && open) out += `<p class="note">${open} item${open === 1 ? ' is' : 's are'} still open. You can still mark it checked.</p>`;
876
+ if (s.labels && s.labels.length) out += s.labels.map((l) => `<p class="note">${esc(l)}</p>`).join('');
877
+ if (s.status !== 'checked') {
878
+ out += `<div class="band">FloLess didn’t look at this sheet. ${esc(s.uncheckedReason || '')}</div>`;
879
+ } else {
880
+ out += '<h3>Items</h3>' + s.items.map((it) => {
881
+ const on = S.selectedN === it.n;
882
+ return `<button type="button" class="item" data-n="${it.n}" data-command-id="drawing-check.item" aria-pressed="${on}"><span class="tag" style="color:${esc(colours[it.status])}">${it.n}</span>
883
+ <span><span class="lab">${esc(labelOf(it.itemId))}</span><span class="st"><i class="swatch" style="border-top:${LINE[it.status].w + 0.6}px ${LINE[it.status].dash ? 'dashed' : 'solid'} ${esc(colours[it.status])}"></i>${STATUS_WORD[it.status]}</span></span>
884
+ ${on ? `<span class="why">${esc(it.reason)}${S.itemNote ? ` ${esc(S.itemNote)}` : ''}</span>` : ''}</button>`;
885
+ }).join('');
886
+ const qs = s.items.filter((it) => it.status === 'dont-know');
887
+ if (qs.length) out += '<h3>Questions for you</h3>' + qs.map((it) => `<div class="qcard"><b>${it.n}. ${esc(labelOf(it.itemId))}</b><br>${esc(it.reason)}</div>`).join('');
888
+ if (s.uncovered && s.uncovered.length) out += `<h3>What FloLess doesn’t check</h3><p class="note"><i class="hatched" aria-hidden="true"></i> FloLess does not check geometry (dimensions, holes, welds), so the hatched drawing area is not checked. Check it yourself.</p>`;
889
+ }
890
+ if (S.exportCard) out += S.exportCard;
891
+ return out;
892
+ }
893
+
894
+ // The stage: page SVG + overlay in one pan/zoom viewBox (steel-filter.html's setVB/fit approach).
895
+ let vb = { x: 0, y: 0, w: 1000, h: 1000 }, pageBox = [0, 0, 1000, 1000], drag = null, anim = 0, pageUrl = null;
896
+ const reduceMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
897
+ function setVB() { const v = document.getElementById('view'); if (v) v.setAttribute('viewBox', `${vb.x} ${vb.y} ${vb.w} ${vb.h}`); }
898
+ function animateTo(target) {
899
+ cancelAnimationFrame(anim);
900
+ if (reduceMotion()) { vb = target; setVB(); return; }
901
+ const from = { ...vb }, t0 = performance.now();
902
+ const step = (t) => {
903
+ const k = Math.min(1, (t - t0) / 150), e = 1 - (1 - k) ** 3;
904
+ vb = { x: from.x + (target.x - from.x) * e, y: from.y + (target.y - from.y) * e, w: from.w + (target.w - from.w) * e, h: from.h + (target.h - from.h) * e };
905
+ setVB(); if (k < 1) anim = requestAnimationFrame(step);
906
+ };
907
+ anim = requestAnimationFrame(step);
908
+ }
909
+ const view = {
910
+ fitTo(bbox, pad) { animateTo(paddedViewBox(bbox, pad)); },
911
+ fit() { view.fitTo(pageBox, 12); },
912
+ zoom(k) { const cx = vb.x + vb.w / 2, cy = vb.y + vb.h / 2; vb = { x: cx - (vb.w * k) / 2, y: cy - (vb.h * k) / 2, w: vb.w * k, h: vb.h * k }; setVB(); },
913
+ pan(dx, dy) { vb = { ...vb, x: vb.x + dx * vb.w, y: vb.y + dy * vb.h }; setVB(); },
914
+ };
915
+
916
+ function paintOverlay() {
917
+ const svg = document.getElementById('view'); const s = sheetOf();
918
+ if (!svg || !s) return;
919
+ const colours = statusColours(S.colours);
920
+ const g = svg.querySelector('#ov');
921
+ if (!g) return;
922
+ g.innerHTML = s.status === 'checked' ? overlaySvg(s, colours, { selectedN: S.selectedN }) : '';
923
+ // Spotlight, not a new colour: the selected item's boxes go heavier, everything else steps back.
924
+ if (S.selectedN !== null) {
925
+ g.querySelectorAll('[data-n]').forEach((el) => {
926
+ if (Number(el.getAttribute('data-n')) !== S.selectedN) el.setAttribute('opacity', '0.35');
927
+ else if (el.tagName.toLowerCase() === 'rect') el.setAttribute('stroke-width', String(Number(el.getAttribute('stroke-width')) * 1.6));
928
+ });
929
+ }
930
+ }
931
+
932
+ async function mountRunView() {
933
+ const svg = document.getElementById('view'); const s = sheetOf();
934
+ if (!svg || !s) return;
935
+ const runId = S.run.runId;
936
+ const msg = document.getElementById('stage-msg');
937
+ // Until the page arrives, size the paper from the evidence so the boxes have somewhere to sit.
938
+ const ext = s.items.flatMap((it) => it.evidence.map((e) => e.bbox)).concat(s.uncovered || []);
939
+ pageBox = ext.length ? [0, 0, Math.max(...ext.map((b) => b[2])) + 36, Math.max(...ext.map((b) => b[3])) + 36] : [0, 0, 842, 595];
940
+ svg.innerHTML = `${hatchDefs()}<rect class="sheet-frame" id="paper" x="0" y="0" width="${pageBox[2]}" height="${pageBox[3]}"/><g id="page"></g><g id="ov"></g>`;
941
+ paintOverlay(); vb = paddedViewBox(pageBox, 12); setVB();
942
+ wireStage();
943
+ if (s.status !== 'checked') return;
944
+ const sheetAtRequest = S.sheet;
945
+ try {
946
+ const res = await fetch(`${base}/runs/${encodeURIComponent(runId)}/page-svg?drawing=${encodeURIComponent(s.drawing)}&page=${s.page}`, { credentials: 'same-origin' });
947
+ if (!res.ok) throw new Error('page');
948
+ const text = await res.text();
949
+ if (!S.run || S.run.runId !== runId || S.sheet !== sheetAtRequest) return;
950
+ const doc = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
951
+ const vbAttr = (doc.getAttribute('viewBox') || '').split(/[\s,]+/).map(Number);
952
+ const w = vbAttr.length === 4 ? vbAttr[2] : parseFloat(doc.getAttribute('width')), h = vbAttr.length === 4 ? vbAttr[3] : parseFloat(doc.getAttribute('height'));
953
+ if (!(w > 0 && h > 0)) throw new Error('size');
954
+ if (pageUrl) URL.revokeObjectURL(pageUrl);
955
+ // As an <image>, the page SVG can never run anything; it is pixels to this document.
956
+ pageUrl = URL.createObjectURL(new Blob([text], { type: 'image/svg+xml' }));
957
+ pageBox = [0, 0, w, h];
958
+ const paper = svg.querySelector('#paper'); paper.setAttribute('width', w); paper.setAttribute('height', h);
959
+ svg.querySelector('#page').innerHTML = `<image href="${pageUrl}" x="0" y="0" width="${w}" height="${h}"/>`;
960
+ if (S.selectedN === null) { vb = paddedViewBox(pageBox, 12); setVB(); }
961
+ } catch {
962
+ if (!msg || !S.run || S.run.runId !== runId) return;
963
+ msg.hidden = false;
964
+ msg.innerHTML = 'Couldn’t draw this sheet, so the boxes sit on blank paper. <button type="button" data-act="retry-page" data-command-id="drawing-check.retry-page">Try again</button>';
965
+ }
966
+ }
967
+
968
+ function wireStage() {
969
+ const svg = document.getElementById('view'), stage = document.getElementById('stage');
970
+ if (!svg || svg.dataset.wired) return;
971
+ svg.dataset.wired = '1';
972
+ svg.addEventListener('wheel', (e) => {
973
+ e.preventDefault();
974
+ const r = svg.getBoundingClientRect();
975
+ const mx = vb.x + ((e.clientX - r.left) / r.width) * vb.w, my = vb.y + ((e.clientY - r.top) / r.height) * vb.h;
976
+ const k = e.deltaY < 0 ? 0.85 : 1 / 0.85;
977
+ vb = { w: vb.w * k, h: vb.h * k, x: 0, y: 0 };
978
+ vb.x = mx - ((e.clientX - r.left) / r.width) * vb.w; vb.y = my - ((e.clientY - r.top) / r.height) * vb.h;
979
+ setVB();
980
+ }, { passive: false });
981
+ svg.addEventListener('pointerdown', (e) => { drag = { x: e.clientX, y: e.clientY, vx: vb.x, vy: vb.y, moved: false, target: e.target }; svg.setPointerCapture(e.pointerId); svg.classList.add('dragging'); });
982
+ svg.addEventListener('pointermove', (e) => {
983
+ if (!drag) return;
984
+ if (Math.abs(e.clientX - drag.x) + Math.abs(e.clientY - drag.y) > 3) drag.moved = true;
985
+ const r = svg.getBoundingClientRect();
986
+ vb = { ...vb, x: drag.vx - ((e.clientX - drag.x) / r.width) * vb.w, y: drag.vy - ((e.clientY - drag.y) / r.height) * vb.h };
987
+ setVB();
988
+ });
989
+ svg.addEventListener('pointerup', () => {
990
+ svg.classList.remove('dragging');
991
+ // Box → item: a click (no drag) on a numbered box selects its row; focus stays on the stage.
992
+ const hit = drag && !drag.moved && drag.target && drag.target.closest && drag.target.closest('[data-n]');
993
+ drag = null;
994
+ if (hit) {
995
+ S.selectedN = Number(hit.getAttribute('data-n')); S.itemNote = '';
996
+ paintOverlay(); paintSide();
997
+ document.querySelector(`#side .item[data-n="${S.selectedN}"]`)?.scrollIntoView({ block: 'nearest' });
998
+ }
999
+ });
1000
+ stage.addEventListener('keydown', (e) => {
1001
+ const keys = { '+': () => view.zoom(0.8), '=': () => view.zoom(0.8), '-': () => view.zoom(1.25), '0': () => view.fit(),
1002
+ ArrowLeft: () => view.pan(-0.1, 0), ArrowRight: () => view.pan(0.1, 0), ArrowUp: () => view.pan(0, -0.1), ArrowDown: () => view.pan(0, 0.1),
1003
+ j: () => stepItem(1), k: () => stepItem(-1) };
1004
+ if (keys[e.key]) { e.preventDefault(); keys[e.key](); }
1005
+ });
1006
+ }
1007
+ function paintSide() { const side = document.getElementById('side'); if (side) side.innerHTML = sideHtml(); }
1008
+
1009
+ /** Item → box: select the row, zoom to its first evidence box (ITEM_PAD around it), show the reason. */
1010
+ function selectItem(n) {
1011
+ const s = sheetOf(); const it = s && s.items.find((x) => x.n === n);
1012
+ if (!it) return;
1013
+ S.selectedN = n;
1014
+ S.itemNote = focusItem(view, it);
1015
+ paintOverlay(); paintSide();
1016
+ document.querySelector(`#side .item[data-n="${n}"]`)?.focus({ preventScroll: false });
1017
+ }
1018
+ function stepItem(d) {
1019
+ const s = sheetOf(); if (!s || !s.items.length) return;
1020
+ const i = s.items.findIndex((x) => x.n === S.selectedN);
1021
+ const next = s.items[Math.max(0, Math.min(s.items.length - 1, i < 0 ? 0 : i + d))];
1022
+ selectItem(next.n);
1023
+ document.getElementById('stage')?.focus();
1024
+ }
1025
+
1026
+ async function markChecked() {
1027
+ const s = sheetOf(); if (!s) return;
1028
+ const btn = root.querySelector('[data-act="mark"]'); if (btn) btn.disabled = true;
1029
+ try {
1030
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/checked`, jsonOpts('POST', { drawing: s.drawing, page: s.page }));
1031
+ S.run.checkedBy = body.checkedBy || S.run.checkedBy;
1032
+ // The record may have come back unsigned or unverified: the badge must say so now, not after a reload.
1033
+ if (body.signature) S.run.signature = body.signature;
1034
+ render();
1035
+ } catch (e) { if (btn) btn.disabled = false; S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; paintSide(); }
1036
+ }
1037
+
1038
+ async function exportPdf() {
1039
+ const s = sheetOf(); if (!s) return;
1040
+ const btn = root.querySelector('[data-act="export"]'); if (btn) { btn.disabled = true; btn.textContent = 'Exporting…'; }
1041
+ try {
1042
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/export`, jsonOpts('POST', { drawing: s.drawing }));
1043
+ const fails = body.tagFailures || [];
1044
+ S.exportCard = `<div class="export-card" role="status"><b>${esc(body.filename)}</b> saved.
1045
+ ${fails.length ? `<details><summary>${fails.length} item number${fails.length === 1 ? '' : 's'} couldn’t be placed on the sheet. ${fails.length === 1 ? 'It is' : 'They’re'} listed on the cover page.</summary>${fails.map((f) => `<div class="note">${esc(tagFailureNote(f))}</div>`).join('')}</details>` : ''}
1046
+ <div class="acts"><button type="button" data-file="open" data-path="${esc(body.path)}" data-command-id="drawing-check.export-open">Open</button><button type="button" data-file="reveal" data-path="${esc(body.path)}" data-command-id="drawing-check.export-reveal">Show in folder</button></div></div>`;
1047
+ } catch (e) { S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; }
1048
+ if (btn) { btn.disabled = false; btn.textContent = 'Export marked-up PDF'; }
1049
+ paintSide();
1050
+ }
1051
+
1052
+ function warningsDialog() {
1053
+ const r = S.run;
1054
+ showDialog({
1055
+ title: 'Decisions in this run',
1056
+ body: r.warnings.map((w) => {
1057
+ const chosen = (w.choices.find((c) => c.id === (w.decided ?? w.defaultChoice)) || {}).label || w.decided || w.defaultChoice;
1058
+ return `<fieldset><legend>${esc(w.message)}</legend><p class="where">${esc(w.decided === null ? 'FloLess applied the safe default:' : 'You chose:')} ${esc(chosen)}</p></fieldset>`;
1059
+ }).join(''),
1060
+ foot: '<button type="button" class="primary" data-dlg="close">Close</button>',
1061
+ onOpen: (sc) => { sc.querySelector('[data-dlg="close"]').focus(); sc.addEventListener('click', (e) => { if (e.target.closest('[data-dlg]')) closeDialog(); }); },
1062
+ });
1063
+ }
1064
+
1065
+ // ── colours ──
1066
+ const COLOUR_ROWS = [['pass', 'Fine'], ['fail', 'Wrong'], ['question', 'Couldn’t tell']];
1067
+ function coloursHtml() {
1068
+ const c = S.colours || { pass: DEFAULT_COLOURS.pass, fail: DEFAULT_COLOURS.fail, question: DEFAULT_COLOURS['dont-know'] };
1069
+ const lineOf = { pass: LINE.pass, fail: LINE.fail, question: LINE['dont-know'] };
1070
+ const rows = COLOUR_ROWS.map(([k, label]) => {
1071
+ const hex = toHex(c[k]) || '#000000';
1072
+ const ln = lineOf[k];
1073
+ return `<div class="colour-row"><span>${label}</span><input type="color" class="swc" data-colour="${k}" data-command-id="drawing-check.colour#${esc(k)}" data-command-instance-label="${label}" value="${hex}" aria-label="${label} colour">
1074
+ <input type="text" class="hex" data-hex="${k}" data-command-id="drawing-check.colour#${esc(k)}" data-command-instance-label="${label}" value="${hex}" aria-label="${label} colour as hex" maxlength="7">
1075
+ <svg class="paper-tile" viewBox="0 0 120 56" role="img" aria-label="${label} preview on paper"><rect x="18" y="14" width="64" height="28" rx="2" fill="none" stroke="${esc(c[k])}" stroke-width="${ln.w}"${ln.dash ? ` stroke-dasharray="${ln.dash}"` : ''}/><circle cx="84" cy="12" r="7" fill="white" stroke="${esc(c[k])}" stroke-width="1.4"/><text x="84" y="15" text-anchor="middle" font-size="9" font-weight="700" font-family="Inter, system-ui, sans-serif" fill="hsl(222 84% 5%)">1</text></svg></div>`;
1076
+ }).join('');
1077
+ return `<div class="wrap"><h2>Markup colours</h2>
1078
+ <p class="lede">The colours of the boxes on marked-up drawings. They belong to this profile and aren’t part of what is approved.</p>
1079
+ ${rows}
1080
+ ${S.coloursUnread ? `<p class="warn-line" role="status">Your saved markup colours couldn’t be read, so the default green and red are shown here and on the drawings. Changing a colour saves all three as you see them now.</p>` : ''}
1081
+ ${S.colourWarning ? `<p class="warn-line" role="status">${esc(S.colourWarning)}</p>` : ''}
1082
+ <p class="err-line" id="colour-err" role="alert" hidden></p>
1083
+ <div class="row-actions" style="margin-top:14px"><button type="button" data-act="reset-colours" data-command-id="drawing-check.reset-colours">Reset to green and red</button></div></div>`;
1084
+ }
1085
+ async function saveColours(next) {
1086
+ const err = document.getElementById('colour-err');
1087
+ try {
1088
+ const { body } = await call(`${base}/colours`, jsonOpts('PUT', next));
1089
+ S.colours = body.colours; S.colourWarning = body.warning; S.coloursUnread = false;
1090
+ render();
1091
+ } catch (e) { if (err) { err.hidden = false; err.textContent = e.message; } }
1092
+ }
1093
+
1094
+ // ── events ──
1095
+ root.addEventListener('click', async (e) => {
1096
+ const t = e.target.closest('button, [data-tab]');
1097
+ if (!t) return;
1098
+ if (t.dataset.tab) { S.tab = t.dataset.tab; if (S.tab !== 'runs') S.run = null; render(); document.getElementById(`tab-${S.tab}`)?.focus(); return; }
1099
+ if (t.dataset.run) { await openRun(t.dataset.run); return; }
1100
+ if (t.dataset.sheet) { S.sheet = Number(t.dataset.sheet); S.selectedN = null; S.itemNote = ''; S.exportCard = null; render(); return; }
1101
+ if (t.classList.contains('item')) { selectItem(Number(t.dataset.n)); return; }
1102
+ if (t.dataset.zoom) { ({ fit: () => view.fit(), in: () => view.zoom(0.8), out: () => view.zoom(1.25) })[t.dataset.zoom](); return; }
1103
+ if (t.dataset.file) {
1104
+ try { await call(t.dataset.file === 'open' ? '/api/open-file' : '/api/reveal', jsonOpts('POST', { path: t.dataset.path })); }
1105
+ catch { t.insertAdjacentHTML('afterend', '<span class="err-line"> That file could not be opened. It may have been moved.</span>'); }
1106
+ return;
1107
+ }
1108
+ if (t.dataset.answer) {
1109
+ // Saving is set at the click, before the job queues: a second click while the first answer is on its
1110
+ // way sends nothing.
1111
+ if (S.tbSaving) return;
1112
+ S.tbSaving = true; render();
1113
+ await putTitleBlock({ answer: { ask: t.dataset.answer, choice: t.dataset.choice } });
1114
+ return;
1115
+ }
1116
+ if (t.dataset.typeLabel) {
1117
+ S.typed[t.dataset.typeLabel] = S.typed[t.dataset.typeLabel] || { value: '', error: '' };
1118
+ render();
1119
+ root.querySelector(`[data-typed-label="${CSS.escape(t.dataset.typeLabel)}"]`)?.focus();
1120
+ return;
1121
+ }
1122
+ if (t.dataset.typedUse) {
1123
+ if (S.tbSaving) return;
1124
+ const id = t.dataset.typedUse;
1125
+ const label = (root.querySelector(`[data-typed-label="${CSS.escape(id)}"]`)?.value || '').replace(/\s+/g, ' ').trim();
1126
+ if (!label) { S.typed[id] = { value: '', error: 'Write the label as it appears on the drawings.' }; render(); return; }
1127
+ S.typed[id] = { value: label, error: '' };
1128
+ S.tbSaving = true; render();
1129
+ await putTitleBlock({ answer: { ask: id, label } });
1130
+ return;
1131
+ }
1132
+ if (t.dataset.tbRead) {
1133
+ const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === t.dataset.tbRead);
1134
+ const refocus = () => root.querySelector(`[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`)?.focus();
1135
+ if (f && f.read !== t.dataset.mode) { f.read = t.dataset.mode; render(); refocus(); await putTitleBlock({ field: f.name, read: t.dataset.mode }); }
1136
+ refocusIfLost(document, root, `[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`);
1137
+ return;
1138
+ }
1139
+ if (t.dataset.tbRemove) { await putTitleBlock({ remove: t.dataset.tbRemove }); return; }
1140
+ const act = t.dataset.act;
1141
+ if (act === 'add-field') { addFieldDialog(); return; }
1142
+ if (act === 'go-ask') {
1143
+ const first = root.querySelector('.ask .choice-btn');
1144
+ first?.closest('.ask')?.scrollIntoView({ block: 'center', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
1145
+ first?.focus({ preventScroll: true });
1146
+ return;
1147
+ }
1148
+ if (act === 'reload') { S.conflict = false; S.checklistError = ''; await loadAll(); return; }
1149
+ if (act === 'pick-refs') { document.getElementById('ref-file')?.click(); return; }
1150
+ if (act === 'propose') { await propose(); return; }
1151
+ if (act === 'add-item') { addItemDialog(); return; }
1152
+ if (act === 'approve') { approveDialog(); return; }
1153
+ if (act === 'check') { document.getElementById('run-file')?.click(); return; }
1154
+ if (act === 'back') { S.run = null; render(); return; }
1155
+ if (act === 'mark') { await markChecked(); return; }
1156
+ if (act === 'export') { await exportPdf(); return; }
1157
+ if (act === 'warnings') { warningsDialog(); return; }
1158
+ if (act === 'retry-page') { await mountRunView(); return; }
1159
+ if (act === 'reset-colours') { await saveColours({ pass: DEFAULT_COLOURS.pass, fail: DEFAULT_COLOURS.fail, question: DEFAULT_COLOURS['dont-know'] }); }
1160
+ });
1161
+ root.addEventListener('input', (e) => {
1162
+ const id = e.target.dataset && e.target.dataset.typedLabel;
1163
+ if (id) S.typed[id] = { value: e.target.value, error: '' };
1164
+ });
1165
+ root.addEventListener('change', async (e) => {
1166
+ const t = e.target;
1167
+ if (t.id === 'ref-file') { const files = [...t.files]; t.value = ''; if (files.length) await uploadReferences(files); return; }
1168
+ if (t.id === 'run-file') { const files = [...t.files]; t.value = ''; await checkDrawings(files); return; }
1169
+ if (t.id === 'client-name') {
1170
+ const client = t.value.replace(/\s+/g, ' ').trim();
1171
+ if (!client) { t.value = (S.draft && S.draft.client) || ''; S.checklistError = 'Say which client this checklist is for.'; render(); return; }
1172
+ if (client !== (S.draft && S.draft.client)) await putClient(client);
1173
+ document.getElementById('client-name')?.focus();
1174
+ return;
1175
+ }
1176
+ if (t.dataset.tbLabel) {
1177
+ const name = t.dataset.tbLabel;
1178
+ const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === name);
1179
+ const label = t.value.replace(/\s+/g, ' ').trim();
1180
+ if (!f) return;
1181
+ if (!label) { t.value = f.label; S.checklistError = 'Write the label as it appears on the drawings.'; render(); return; }
1182
+ if (label !== f.label) await putTitleBlock({ field: name, label });
1183
+ // `change` fires on blur: a person who typed and pressed Tab is already on the next control. Bring
1184
+ // focus back only if the re-render left it nowhere.
1185
+ refocusIfLost(document, root, `[data-tb-label="${CSS.escape(name)}"]`);
1186
+ return;
1187
+ }
1188
+ if (t.dataset.tbRequired) {
1189
+ const name = t.dataset.tbRequired;
1190
+ await putTitleBlock({ field: name, required: t.checked });
1191
+ refocusIfLost(document, root, `[data-tb-required="${CSS.escape(name)}"]`);
1192
+ return;
1193
+ }
1194
+ if (t.dataset.item) {
1195
+ // Optimistic: the box stays as clicked while its PUT waits its turn behind any earlier tick.
1196
+ const it = items().find((i) => i.id === t.dataset.item); if (it) it.enabled = t.checked;
1197
+ await putItems([{ id: t.dataset.item, enabled: t.checked }]);
1198
+ root.querySelector(`[data-item="${CSS.escape(t.dataset.item)}"]`)?.focus();
1199
+ return;
1200
+ }
1201
+ if (t.dataset.colour || t.dataset.hex) {
1202
+ const k = t.dataset.colour || t.dataset.hex;
1203
+ const v = t.value.trim();
1204
+ if (!/^#[0-9a-f]{6}$/i.test(v)) { const err = document.getElementById('colour-err'); if (err) { err.hidden = false; err.textContent = 'Use a colour like #22c55e.'; } return; }
1205
+ await saveColours({ ...(S.colours || {}), [k]: v.toLowerCase() });
1206
+ }
1207
+ });
1208
+ // Tabs: arrow keys move between them (role=tablist); in a read-mode radiogroup they move the choice.
1209
+ root.addEventListener('keydown', (e) => {
1210
+ if (e.key === 'Enter' && e.target.dataset && e.target.dataset.typedLabel) {
1211
+ e.preventDefault(); root.querySelector(`[data-typed-use="${CSS.escape(e.target.dataset.typedLabel)}"]`)?.click(); return;
1212
+ }
1213
+ const radio = e.target.closest('.seg [role=radio]');
1214
+ if (radio && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
1215
+ e.preventDefault();
1216
+ const all = [...radio.parentElement.querySelectorAll('[role=radio]')];
1217
+ const next = all[(all.indexOf(radio) + (e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : all.length - 1)) % all.length];
1218
+ next.click();
1219
+ return;
1220
+ }
1221
+ const tab = e.target.closest('[role=tab]');
1222
+ if (!tab || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
1223
+ e.preventDefault();
1224
+ const keys = TABS.map(([k]) => k), i = keys.indexOf(S.tab);
1225
+ const next = e.key === 'Home' ? 0 : e.key === 'End' ? keys.length - 1 : (i + (e.key === 'ArrowRight' ? 1 : -1) + keys.length) % keys.length;
1226
+ S.tab = keys[next]; if (S.tab !== 'runs') S.run = null; render(); document.getElementById(`tab-${S.tab}`)?.focus();
1227
+ });
1228
+ // Drop PDFs anywhere on the References tab.
1229
+ root.addEventListener('dragover', (e) => { if (S.tab !== 'references') return; e.preventDefault(); root.querySelector('.drop')?.classList.add('over'); });
1230
+ root.addEventListener('dragleave', (e) => { if (!root.contains(e.relatedTarget)) root.querySelector('.drop')?.classList.remove('over'); });
1231
+ root.addEventListener('drop', async (e) => {
1232
+ if (S.tab !== 'references') return;
1233
+ e.preventDefault(); root.querySelector('.drop')?.classList.remove('over');
1234
+ const files = [...(e.dataTransfer?.files || [])];
1235
+ if (files.length) await uploadReferences(files);
1236
+ });
1237
+
1238
+ if (!PROJECT) { root.innerHTML = '<section role="tabpanel"><p class="err-line">Open this page from a Drawing Checker project.</p></section>'; return; }
1239
+ loadAll();
1240
+ }
1241
+
1242
+ if (typeof document !== 'undefined' && document.getElementById('dc-root')) boot();