@floless/app 0.172.0 → 0.172.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,595 @@
1
+ // The section sketcher (epic #3382 slice P5, design §7.4, mockups 09 and 10).
2
+ //
3
+ // A full-window dialog over the steel editor in which a person draws a shape of their own: a name, a prefix, sizes, an outline
4
+ // and holes of corner points written as formulas over the sizes, and the order the sizes are written in a name. It shows a live
5
+ // drawing, the checks, area and weight at the default sizes, and an honest "where this shape can go".
6
+ //
7
+ // ONE sketch, shared with the AI chat. It lives on the server (`/api/steel/shape-sketch`), so the chat drives this same sketcher
8
+ // through the same routes a person uses and the person watches the draft fill in. This module keeps no durable state of its own.
9
+ // Each edit is sent as the person's, with the revision last seen; a change that arrives from elsewhere while the person is typing
10
+ // in a box is held behind a "Show the changes" button instead of being drawn over what they are typing.
11
+ //
12
+ // SAVING IS ALWAYS THE PERSON'S CLICK. Save shape puts the shape into their own "My shapes" add-on as a new version and turns it on.
13
+ // Nothing here ever saves for the person, and a draft the AI made says so, with each size it had to assume outlined in amber.
14
+ //
15
+ // Nothing refuses: an unfinished or invalid sketch is drawn as far as it can be and the checks say what is left, in plain words.
16
+ // Only Save shape waits, and it says why beside the button.
17
+ import {
18
+ SOURCE_WORDS, TEMPLATE_IDS, analyzeDraft, effectiveOrder, slugOf,
19
+ } from './steel-shape-sketch-core.js';
20
+ import { libraryDefinitions } from './steel-parametric-library.js';
21
+ import { SKETCHED_PREFIXES } from './steel-parametric-sketched-index.js';
22
+
23
+ const esc = (value) => String(value == null ? '' : value).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
24
+ const TEMPLATE_WORDS = { rectangle: 'Rectangle', l: 'L', t: 'T', blank: 'Blank' };
25
+ const KIND_WORDS = { length: 'length (mm)', angle: 'angle (°)', number: 'number' };
26
+ const NEXT_KIND = { length: 'angle', angle: 'number', number: 'length' };
27
+ const number = (text) => { const n = Number(String(text).replace(',', '.')); return String(text).trim() !== '' && Number.isFinite(n) ? n : null; };
28
+ const fmt = (n) => (Number.isInteger(n) ? String(n) : String(Math.round(n * 1000) / 1000));
29
+
30
+ export function ensureSketcherStyles(doc) {
31
+ if (doc.getElementById('steelShapeSketcherStyles')) return;
32
+ const style = doc.createElement('style');
33
+ style.id = 'steelShapeSketcherStyles';
34
+ style.textContent = `
35
+ .shsk{position:fixed;inset:0;z-index:130;display:none;align-items:stretch;justify-content:stretch;padding:14px;background:rgba(2,6,23,.55);color:var(--text);font:12px system-ui,sans-serif}.shsk.open{display:flex}
36
+ .shsk button,.shsk input,.shsk textarea{font:inherit}.shsk [hidden]{display:none!important}
37
+ .shsk-panel{flex:1;display:flex;flex-direction:column;min-width:0;min-height:0;border:1px solid var(--line);border-radius:10px;background:var(--bg);box-shadow:0 18px 60px rgba(0,0,0,.45);overflow:hidden}
38
+ .shsk button{border:1px solid var(--ctrl-border,var(--line));border-radius:6px;background:var(--field);color:var(--text);padding:6px 10px;cursor:pointer}.shsk button:hover{border-color:var(--brand)}
39
+ .shsk button:focus-visible,.shsk input:focus-visible,.shsk textarea:focus-visible{outline:2px solid var(--brand);outline-offset:1px}
40
+ .shsk button.primary{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:650}.shsk button.primary[aria-disabled=true]{opacity:.55;cursor:not-allowed}
41
+ .shsk button.ghost{background:transparent}.shsk button.warnb{border-color:var(--warn-edge,var(--warn));color:var(--warn)}
42
+ .shsk input,.shsk textarea{min-width:0;border:1px solid var(--ctrl-border,var(--line));border-radius:6px;background:var(--field);color:var(--text);padding:6px 8px;outline:0;box-sizing:border-box}
43
+ .shsk input:focus,.shsk textarea:focus{border-color:var(--brand)}
44
+ .shsk .mono,.shsk input.mono{font-family:ui-monospace,Consolas,monospace}
45
+ .shsk-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 14px;border-bottom:1px solid var(--line);background:var(--panel)}
46
+ .shsk-head .t{font-size:15px;font-weight:750}.shsk-head .s{color:var(--mut);margin-top:2px}.shsk-spacer{flex:1}.shsk-head .lbl{color:var(--mut)}
47
+ .shsk-pill{display:inline-block;padding:1px 9px;border-radius:999px;border:1px solid var(--brand);color:var(--info-ink,var(--brand));font-size:10px;font-weight:650;white-space:nowrap}
48
+ .shsk-banner{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:9px 14px;border-bottom:1px solid var(--warn-edge,var(--warn));background:var(--warn-bg);color:var(--warn-soft,var(--warn))}.shsk-banner:empty{display:none}.shsk-banner.info{background:var(--brand-soft,rgba(59,130,246,.14));border-color:var(--brand);color:var(--text)}
49
+ .shsk-body{flex:1;min-height:0;display:grid;grid-template-columns:minmax(250px,320px) minmax(300px,1fr) minmax(290px,370px)}
50
+ .shsk-left,.shsk-mid,.shsk-right{min-height:0;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}
51
+ .shsk-left::-webkit-scrollbar,.shsk-mid::-webkit-scrollbar,.shsk-right::-webkit-scrollbar,.shsk textarea::-webkit-scrollbar{width:8px;height:8px}.shsk-left::-webkit-scrollbar-thumb,.shsk-mid::-webkit-scrollbar-thumb,.shsk-right::-webkit-scrollbar-thumb,.shsk textarea::-webkit-scrollbar-thumb{background:var(--scroll);border-radius:8px}.shsk-left::-webkit-scrollbar-button,.shsk-mid::-webkit-scrollbar-button,.shsk-right::-webkit-scrollbar-button{display:none}
52
+ .shsk-left{padding:14px;border-right:1px solid var(--line)}.shsk-right{padding:14px;border-left:1px solid var(--line)}.shsk-mid{padding:14px;display:flex;flex-direction:column;gap:10px;background:var(--panel)}
53
+ .shsk h3{margin:16px 0 8px;color:var(--mut);font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.04em}.shsk h3:first-child{margin-top:0}
54
+ .shsk .row{display:grid;grid-template-columns:70px 1fr;gap:8px;align-items:center;margin-bottom:8px}.shsk .row>label{color:var(--mut)}
55
+ .shsk .hint{color:var(--mut);line-height:1.45;margin:4px 0 0}.shsk .note{color:var(--warn);line-height:1.45;margin:4px 0 0}
56
+ .shsk-size{display:grid;grid-template-columns:44px 1fr 68px auto;gap:6px;align-items:center;margin-bottom:6px}.shsk-size .sym{font-family:ui-monospace,Consolas,monospace;font-weight:700;color:var(--info-ink,var(--brand))}
57
+ .shsk-size .sub{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:-2px 0 4px 50px;color:var(--mut)}.shsk-size .sub input{width:58px;padding:3px 6px}
58
+ .shsk-size.assumed input.def{border:1.5px dashed var(--warn)}
59
+ .shsk-chip{display:inline-block;padding:1px 8px;border-radius:999px;border:1px solid var(--ctrl-border,var(--line));color:var(--mut);font-size:10px;white-space:nowrap}.shsk-chip.assumed{border:1px dashed var(--warn);color:var(--warn)}
60
+ .shsk-pattern{display:flex;flex-wrap:wrap;align-items:center;gap:4px;border:1px solid var(--line);border-radius:8px;background:var(--panel);padding:9px}
61
+ .shsk-pattern .pre{font-weight:700}.shsk-pattern .sep{color:var(--mut)}.shsk-pattern .chip{display:inline-flex;align-items:center;border:1px solid var(--ctrl-border,var(--line));border-radius:6px;background:var(--field)}
62
+ .shsk .shsk-pattern .chip button{border:0;background:transparent;padding:3px 4px;color:var(--mut)}.shsk .shsk-pattern .chip .sym{padding:3px 4px;font-family:ui-monospace,Consolas,monospace;font-style:italic}
63
+ .shsk-seg{display:inline-flex;gap:4px;margin-left:6px}.shsk-seg button[aria-pressed=true]{border-color:var(--brand);background:var(--brand-soft,rgba(59,130,246,.14));color:var(--info-ink,var(--brand))}
64
+ .shsk-corners{display:grid;grid-template-columns:34px 1fr 1fr 66px auto;gap:5px;align-items:center}.shsk-corners .hd{color:var(--mut);font-size:10px}.shsk-corners .pn{color:var(--mut);font-weight:700}.shsk-corners .val{color:var(--mut);font-size:11px;text-align:right;white-space:nowrap}
65
+ .shsk-hole{margin-top:12px;padding-top:8px;border-top:1px dashed var(--line)}.shsk-hole .hh{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px;font-weight:650}
66
+ .shsk-cond{display:grid;grid-template-columns:1fr auto;gap:5px;margin-bottom:8px}.shsk-cond textarea{grid-column:1/-1;resize:vertical;min-height:34px}
67
+ .shsk-checks{list-style:none;margin:0;padding:0}.shsk-checks li{display:flex;gap:8px;margin:0 0 6px;line-height:1.4}.shsk-checks .ic{flex:none;width:16px;text-align:center;font-weight:700}.shsk-checks .ok .ic{color:var(--ok)}.shsk-checks .bad .ic{color:var(--warn)}.shsk-checks .todo .ic{color:var(--mut)}
68
+ .shsk-sum{font-weight:650;margin-bottom:8px}
69
+ .shsk-reach{border:1px solid var(--line);border-radius:8px;overflow:hidden}.shsk-reach div{padding:8px 10px;border-top:1px solid var(--line);line-height:1.4}.shsk-reach div:first-child{border-top:0}.shsk-reach b{display:block}.shsk-reach .yes b span{color:var(--ok)}.shsk-reach .partly b span,.shsk-reach .no b span{color:var(--warn)}
70
+ .shsk-derived{display:grid;grid-template-columns:auto 1fr;gap:3px 10px;margin:0}.shsk-derived dt{color:var(--mut)}.shsk-derived dd{margin:0;font-weight:650}
71
+ .shsk-canvas{flex:1;min-height:260px;border:1px solid var(--line);border-radius:8px;background:var(--bg);display:grid;place-items:center;color:var(--brand)}.shsk-canvas svg{width:100%;height:100%;max-height:520px}
72
+ .shsk-foot{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:10px 14px;border-top:1px solid var(--line);background:var(--panel)}.shsk-foot .why{color:var(--mut);flex:1 1 260px;line-height:1.4}.shsk-foot .reason{color:var(--warn)}
73
+ .shsk-confirm{display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:9px 14px;border-bottom:1px solid var(--line);background:var(--panel)}
74
+ .shsk-start{max-width:560px;margin:40px auto;text-align:center;line-height:1.5}.shsk-start .tpl{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin:14px 0}
75
+ .shsk-saved{max-width:520px;margin:50px auto;line-height:1.55}.shsk-saved .big{font-size:16px;font-weight:750;margin-bottom:6px}
76
+ .shsk-new{outline:2px solid var(--brand);outline-offset:1px}
77
+ .shsk-saved-list button{display:block;width:100%;text-align:left;margin-bottom:4px}
78
+ .shsk .sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
79
+ @media(max-width:1000px){.shsk{padding:6px}.shsk-body{display:flex;flex-direction:column;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}.shsk-left,.shsk-mid,.shsk-right{flex:none;overflow:visible;border:0}.shsk-mid{order:-1;min-height:300px}.shsk-canvas{min-height:260px}}
80
+ `;
81
+ doc.head.appendChild(style);
82
+ }
83
+
84
+ /** The prefixes a new shape could be confused with: the built-ins, Tekla's sketched shapes and the person's own other shapes. */
85
+ function prefixesInUse(mine, exceptSlug) {
86
+ const out = [];
87
+ for (const d of libraryDefinitions()) {
88
+ const prefix = d?.payload?.grammar?.prefix;
89
+ if (prefix) out.push({ prefix, where: `FloLess’s built-in ${d.payload.name || 'shape'}` });
90
+ }
91
+ for (const p of SKETCHED_PREFIXES) out.push({ prefix: p, where: 'one of Tekla’s sketched shapes' });
92
+ for (const m of mine) if (m.slug !== exceptSlug && m.prefix) out.push({ prefix: m.prefix, where: `your shape “${m.name}”` });
93
+ return out;
94
+ }
95
+
96
+ /** Corner label: P1.. for the outline, H1.1.. for hole 1. */
97
+ const cornerLabel = (loop, i) => (loop === 'outer' ? `P${i + 1}` : `H${loop + 1}.${i + 1}`);
98
+
99
+ export function createShapeSketcher({ doc = document, win = doc.defaultView || window, fetchImpl = (...a) => fetch(...a), EventSourceImpl = win.EventSource, timers = { set: (f, ms) => setTimeout(f, ms), clear: (t) => clearTimeout(t) } } = {}) {
100
+ ensureSketcherStyles(doc);
101
+ const root = doc.createElement('div');
102
+ root.className = 'shsk'; root.id = 'shapeSketcher'; root.setAttribute('role', 'dialog'); root.setAttribute('aria-modal', 'true'); root.setAttribute('aria-labelledby', 'shskTitle');
103
+ doc.body.appendChild(root);
104
+
105
+ const state = {
106
+ open: false, loaded: false, rev: 0, by: 'person', sketch: null, myShapes: [], analysis: null, pending: null, confirm: null, askAi: false,
107
+ status: '', saved: null, saving: false, loadError: '', changed: new Set(), invoker: null,
108
+ };
109
+ let putTimer = null; let putChain = Promise.resolve(); let flashTimer = null; let source = null;
110
+
111
+ // ---- network ---------------------------------------------------------------------------------------------------
112
+ let busy = 0; // requests of ours still in flight: an event about a write of ours may arrive before its answer
113
+ async function api(method, url, body, ifMatch) {
114
+ busy += 1;
115
+ try { return await apiCall(method, url, body, ifMatch); } finally { busy -= 1; }
116
+ }
117
+ async function apiCall(method, url, body, ifMatch) {
118
+ const headers = { ...(body !== undefined ? { 'content-type': 'application/json' } : {}), ...(ifMatch !== undefined ? { 'if-match': String(ifMatch) } : {}) };
119
+ let res;
120
+ try { res = await fetchImpl(url, { method, headers, credentials: 'same-origin', ...(body !== undefined ? { body: JSON.stringify(body) } : {}) }); } catch {
121
+ return { ok: false, status: 0, body: { error: 'FloLess could not be reached just now. Check that it is still running, then try again.' } };
122
+ }
123
+ let json = null; try { json = await res.json(); } catch { json = null; }
124
+ return { ok: !!res.ok && json?.ok !== false, status: res.status, body: json || {} };
125
+ }
126
+
127
+ const analyze = () => {
128
+ if (!state.sketch) { state.analysis = null; return; }
129
+ state.analysis = analyzeDraft(state.sketch, { prefixes: prefixesInUse(state.myShapes, slugOf(state.sketch.name)), mine: state.myShapes.map((m) => ({ slug: m.slug, name: m.name })) });
130
+ };
131
+
132
+ let generation = 0; // counts the times the local sketch was replaced by the server's, so queued snapshots of the old one are dropped
133
+ function take(body) {
134
+ generation += 1;
135
+ state.pending = null; // whatever was held back is older than what is taken now
136
+ state.unreadable = typeof body.unreadable === 'string' ? body.unreadable : '';
137
+ state.rev =Number.isInteger(body.rev) ? body.rev : state.rev;
138
+ state.by = body.by === 'ai' ? 'ai' : 'person';
139
+ state.sketch = body.sketch ?? null;
140
+ state.myShapes = Array.isArray(body.myShapes) ? body.myShapes : state.myShapes;
141
+ analyze();
142
+ }
143
+
144
+ async function load({ remote = false } = {}) {
145
+ const r = await api('GET', '/api/steel/shape-sketch');
146
+ if (!r.ok) { state.loadError = r.body.error || 'FloLess could not open the sketcher. Close it and try again.'; render(); return; }
147
+ state.loadError = '';
148
+ const before = state.sketch;
149
+ if (remote && state.open && hasFocusInside()) { state.pending = r.body; refreshRegions(); return; }
150
+ take(r.body); state.loaded = true;
151
+ if (remote) markChanged(before, state.sketch);
152
+ render();
153
+ if (remote) say(state.sketch ? 'The AI changed the sketch.' : 'The sketch was cleared.');
154
+ }
155
+
156
+ function markChanged(a, b) {
157
+ state.changed = new Set();
158
+ if (!b) return;
159
+ const sz = new Map((a?.sizes || []).map((s) => [s.symbol, JSON.stringify(s)]));
160
+ for (const s of b.sizes) if (sz.get(s.symbol) !== JSON.stringify(s)) state.changed.add(`size:${s.symbol}`);
161
+ b.outer.forEach((p, i) => { if (!a || JSON.stringify(a.outer[i]) !== JSON.stringify(p)) state.changed.add(`c:outer:${i}`); });
162
+ if (flashTimer) timers.clear(flashTimer);
163
+ flashTimer = timers.set(() => { state.changed = new Set(); root.querySelectorAll('.shsk-new').forEach((e) => e.classList.remove('shsk-new')); }, 3500);
164
+ }
165
+
166
+ function schedulePut() {
167
+ if (putTimer) timers.clear(putTimer);
168
+ state.status = 'Keeping your changes…';
169
+ putTimer = timers.set(flush, 450);
170
+ }
171
+ /**
172
+ * Send what is on screen to the server. Answers whether the server now holds exactly that (true), or not (false): a write that
173
+ * conflicted or failed, or one overtaken because the local sketch was replaced by a newer one from the server. Nothing that
174
+ * needs "the person saw this" (Save) goes ahead on false.
175
+ */
176
+ function flush() {
177
+ if (putTimer) { timers.clear(putTimer); putTimer = null; }
178
+ if (!state.sketch) return putChain.then(() => true);
179
+ const sketch = structuredClone(state.sketch);
180
+ const mine = generation; // a snapshot is only good for the local sketch it was taken from
181
+ const job = putChain.then(async () => {
182
+ if (mine !== generation) return false; // the local sketch was replaced meanwhile: this snapshot must not ride on the new revision
183
+ const r = await api('PUT', '/api/steel/shape-sketch', { sketch }, state.rev);
184
+ if (r.ok) { state.rev = r.body.rev; state.by = 'person'; state.status = 'Your sketch is kept as you type.'; refreshRegions(); return true; }
185
+ if (r.body.code === 'shape-sketch-changed') { state.status = 'The sketch was changed somewhere else, so the last edit was not kept. It now shows the newer one.'; await load({ remote: false }); return false; }
186
+ state.status = r.body.error || 'FloLess could not keep that change. Your sketch on screen is unchanged.';
187
+ refreshRegions();
188
+ return false;
189
+ });
190
+ putChain = job.then(() => undefined, () => undefined);
191
+ return job;
192
+ }
193
+
194
+ // ---- events from elsewhere -------------------------------------------------------------------------------------
195
+ function listen() {
196
+ if (source || !EventSourceImpl) return;
197
+ try {
198
+ source = new EventSourceImpl('/api/events');
199
+ source.onmessage = (event) => {
200
+ let m; try { m = JSON.parse(event.data); } catch { return; }
201
+ if (!m || m.type !== 'shape-sketch-changed') return;
202
+ if (Number.isInteger(m.rev) && m.rev === state.rev && state.loaded) return; // our own write
203
+ if (m.by === 'person' && (busy > 0 || (Number.isInteger(m.rev) && m.rev <= state.rev))) return; // our own write, event ahead of its answer
204
+ if (!state.open && m.by === 'ai' && m.open) { open({ invoker: null, fromAi: true }); return; }
205
+ if (state.open) load({ remote: true });
206
+ };
207
+ } catch { source = null; }
208
+ }
209
+
210
+ // ---- rendering ---------------------------------------------------------------------------------------------------
211
+ const live = () => root.querySelector('[data-region=live]');
212
+ const say = (text) => { const el = live(); if (el) el.textContent = text; };
213
+ const hasFocusInside = () => { const a = doc.activeElement; return !!(a && root.contains(a) && /^(INPUT|TEXTAREA)$/.test(a.tagName)); };
214
+ const region = (name) => root.querySelector(`[data-region=${name}]`);
215
+
216
+ function sizeRow(s, i) {
217
+ const assumed = s.source === 'assumed';
218
+ const chip = `<span class="shsk-chip${assumed ? ' assumed' : ''}">${esc(assumed ? 'assumed' : SOURCE_WORDS[s.source] || '')}</span>`;
219
+ const new_ = state.changed.has(`size:${s.symbol}`) ? ' shsk-new' : '';
220
+ return `<div class="shsk-size${assumed ? ' assumed' : ''}" data-size="${i}">
221
+ <input class="mono sym" data-f=symbol value="${esc(s.symbol)}" aria-label="Size ${i + 1} symbol" maxlength=32 spellcheck=false autocomplete=off data-command-id="steel.shape-sketch-size-symbol#${esc(i + 1)}">
222
+ <input data-f=label value="${esc(s.label)}" aria-label="Size ${esc(s.symbol)} label" placeholder="Plain-English name" maxlength=80 autocomplete=off data-command-id="steel.shape-sketch-size-label#${esc(s.symbol)}">
223
+ <input class="def mono${new_}" data-f=default value="${esc(fmt(s.default))}" inputmode=decimal aria-label="Size ${esc(s.symbol)} default value${assumed ? ' (assumed, please check)' : ''}" autocomplete=off data-command-id="steel.shape-sketch-size-default#${esc(s.symbol)}">
224
+ <button type=button data-act=size-remove data-i="${i}" aria-label="Remove size ${esc(s.symbol)}" data-tip="Remove this size" data-command-id="steel.shape-sketch-size-remove#${esc(s.symbol)}">✕</button>
225
+ <div class=sub>${chip}<button type=button class=ghost data-act=size-kind data-i="${i}" aria-label="Size ${esc(s.symbol)} is a ${esc(KIND_WORDS[s.kind])}. Activate to change." data-command-id="steel.shape-sketch-size-kind#${esc(s.symbol)}">${esc(KIND_WORDS[s.kind])}</button>
226
+ <span>usual</span><input data-f=min value="${s.min === undefined ? '' : esc(fmt(s.min))}" inputmode=decimal placeholder="min" aria-label="Size ${esc(s.symbol)} smallest usual value" data-command-id="steel.shape-sketch-size-min#${esc(s.symbol)}"><span>to</span><input data-f=max value="${s.max === undefined ? '' : esc(fmt(s.max))}" inputmode=decimal placeholder="max" aria-label="Size ${esc(s.symbol)} largest usual value" data-command-id="steel.shape-sketch-size-max#${esc(s.symbol)}"></div>
227
+ </div>`;
228
+ }
229
+
230
+ function cornerRows(points, loop) {
231
+ const out = state.analysis?.drawing;
232
+ const values = loop === 'outer' ? out?.outer : out?.holes?.[loop];
233
+ return points.map((p, i) => {
234
+ const label = cornerLabel(loop, i);
235
+ const v = values?.[i];
236
+ const flash = state.changed.has(`c:${loop}:${i}`) ? ' shsk-new' : '';
237
+ return `<span class=pn>${label}</span>
238
+ <input class="mono${flash}" data-loop="${loop}" data-i="${i}" data-axis=0 value="${esc(p[0])}" aria-label="${label} x" spellcheck=false autocomplete=off data-command-id="steel.shape-sketch-corner-x#${esc(label)}">
239
+ <input class="mono${flash}" data-loop="${loop}" data-i="${i}" data-axis=1 value="${esc(p[1])}" aria-label="${label} y" spellcheck=false autocomplete=off data-command-id="steel.shape-sketch-corner-y#${esc(label)}">
240
+ <span class=val data-val="${loop}:${i}">${v ? `${fmt(v[0])}, ${fmt(v[1])}` : (p[0] === '' && p[1] === '' ? '' : '?')}</span>
241
+ <button type=button class=ghost data-act=corner-remove data-loop="${loop}" data-i="${i}" aria-label="Remove corner ${label}" data-tip="Remove this corner" data-command-id="steel.shape-sketch-corner-remove#${esc(label)}">✕</button>`;
242
+ }).join('');
243
+ }
244
+
245
+ function patternHtml() {
246
+ const s = state.sketch; const order = effectiveOrder(s);
247
+ const chips = order.map((sym, i) => `${i ? `<span class=sep>${esc(s.separator)}</span>` : ''}<span class=chip><button type=button data-act=pattern-earlier data-sym="${esc(sym)}" ${i === 0 ? 'disabled' : ''} aria-label="Move ${esc(sym)} earlier in the name" data-command-id="steel.shape-sketch-pattern-earlier#${esc(sym)}">‹</button><span class=sym>${esc(sym)}</span><button type=button data-act=pattern-later data-sym="${esc(sym)}" ${i === order.length - 1 ? 'disabled' : ''} aria-label="Move ${esc(sym)} later in the name" data-command-id="steel.shape-sketch-pattern-later#${esc(sym)}">›</button></span>`).join('');
248
+ const seps = ['*', '-', 'x'].map((c) => `<button type=button data-act=separator data-sep="${c}" aria-pressed="${s.separator === c}" aria-label="Write a ${esc(c)} between the sizes" data-command-id="steel.shape-sketch-separator#${esc(c)}">${esc(c)}</button>`).join('');
249
+ return `<div class=shsk-pattern><span class=pre>${esc(s.prefix || '…')}</span>${chips}</div>
250
+ <p class=hint>Move a size with ‹ and ›. Between sizes write <span class=shsk-seg role=group aria-label="Separator in the name">${seps}</span></p>`;
251
+ }
252
+
253
+ function checksHtml() {
254
+ const a = state.analysis; if (!a) return '';
255
+ const todo = a.problems.length;
256
+ const sum = a.ok ? 'This shape works. Everything checks out.' : `${todo} thing${todo === 1 ? '' : 's'} to finish`;
257
+ const rows = a.checks.map((c) => `<li class="${c.ok ? 'ok' : 'bad'}"><span class=ic aria-hidden=true>${c.ok ? '✓' : '!'}</span><span>${esc(c.text)}${c.ok ? '' : ' <span class=sr-only>needs attention</span>'}</span></li>`).join('');
258
+ const extra = a.problems.filter((p) => !a.checks.some((c) => !c.ok && c.text === p)).map((p) => `<li class=todo><span class=ic aria-hidden=true>○</span><span>${esc(p)}</span></li>`).join('');
259
+ return `<div class=shsk-sum>${esc(sum)}</div><ul class=shsk-checks>${rows}${extra}</ul>`;
260
+ }
261
+ function reachHtml() {
262
+ const a = state.analysis; if (!a) return '';
263
+ const word = { yes: 'Yes', partly: 'With a choice', no: 'Not yet' };
264
+ const name = { floless: 'FloLess 3D, bill and weight', ifc: 'IFC export', tekla: 'Tekla' };
265
+ return `<div class=shsk-reach>${a.reach.map((r) => `<div class="${esc(r.state)}"><b>${esc(name[r.id])} <span>· ${esc(word[r.state])}</span></b>${esc(r.text)}</div>`).join('')}</div>`;
266
+ }
267
+ function derivedHtml() {
268
+ const a = state.analysis; if (!a) return '';
269
+ return `<dl class=shsk-derived><dt>At the default sizes</dt><dd>${a.area !== null ? `${esc(fmt(Math.round(a.area * 100) / 100))} mm² · ${esc(fmt(a.kgPerM))} kg/m in ${esc(a.weightBasis)}` : 'not yet'}</dd>
270
+ <dt>A name reads</dt><dd class=mono>${a.example ? esc(a.example) : 'not yet'}</dd></dl>
271
+ <p class=hint>All sizes are stored in millimetres. A project set to feet and inches shows the same sizes in inches.</p>`;
272
+ }
273
+ function notesHtml() {
274
+ const a = state.analysis; if (!a || !a.notes.length) return '';
275
+ return a.notes.map((n) => `<p class=note>${esc(n)}</p>`).join('');
276
+ }
277
+
278
+ function drawingSvg() {
279
+ const a = state.analysis; const d = a?.drawing;
280
+ const loops = d ? [d.outer, ...d.holes] : [];
281
+ const pts = loops.flatMap((l) => l.filter(Boolean));
282
+ if (!pts.length) return `<div class=hint style="padding:20px;text-align:center">The drawing appears here as soon as the outline has corners.</div>`;
283
+ pts.push([0, 0]);
284
+ const xs = pts.map((p) => p[0]), ys = pts.map((p) => p[1]);
285
+ const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
286
+ const W = 420, H = 360, pad = 46;
287
+ const sc = Math.min((W - 2 * pad) / Math.max(maxX - minX, 1), (H - 2 * pad) / Math.max(maxY - minY, 1));
288
+ const ox = (W - (maxX - minX) * sc) / 2, oy = (H - (maxY - minY) * sc) / 2;
289
+ const X = (x) => Math.round((ox + (x - minX) * sc) * 10) / 10, Y = (y) => Math.round((H - oy - (y - minY) * sc) * 10) / 10;
290
+ const draw = (loop, name, dashed) => {
291
+ const valid = loop.map((p, i) => (p ? { p, i } : null)).filter(Boolean);
292
+ if (valid.length < 2) return '';
293
+ const path = `M${valid.map((v) => `${X(v.p[0])} ${Y(v.p[1])}`).join('L')}Z`;
294
+ const edges = loop.map((p, i) => {
295
+ const q = loop[(i + 1) % loop.length]; if (!p || !q) return '';
296
+ const hit = [...(d.crossings || [])].some((c) => c.loop === name && c.edges.some((e) => e[0] === i + 1));
297
+ return hit ? `<line x1="${X(p[0])}" y1="${Y(p[1])}" x2="${X(q[0])}" y2="${Y(q[1])}" stroke="var(--err,#ef4444)" stroke-width="3" stroke-dasharray="7 3"/>` : '';
298
+ }).join('');
299
+ return `<path d="${path}" fill="${dashed ? 'none' : 'var(--brand-soft,rgba(59,130,246,.18))'}" stroke="currentColor" stroke-width="1.6" ${dashed ? 'stroke-dasharray="5 4"' : ''}/>${edges}`;
300
+ };
301
+ const labels = (loop, which) => loop.map((p, i) => (p ? `<circle cx="${X(p[0])}" cy="${Y(p[1])}" r="3" fill="currentColor"/><text x="${X(p[0]) + 6}" y="${Y(p[1]) - 6}" fill="var(--text)" font-size="10" font-family="ui-monospace,Consolas,monospace" font-weight="700">${cornerLabel(which, i)}</text>` : '')).join('');
302
+ const axes = `<line x1="${X(0)}" y1="6" x2="${X(0)}" y2="${H - 6}" stroke="var(--mut)" stroke-width="1" stroke-dasharray="3 4" opacity=".6"/><line x1="6" y1="${Y(0)}" x2="${W - 6}" y2="${Y(0)}" stroke="var(--mut)" stroke-width="1" stroke-dasharray="3 4" opacity=".6"/><text x="${X(0) + 4}" y="${Y(0) + 12}" fill="var(--mut)" font-size="10">origin</text>`;
303
+ const outerOk = d.outer.filter(Boolean);
304
+ const w = outerOk.length ? Math.max(...outerOk.map((p) => p[0])) - Math.min(...outerOk.map((p) => p[0])) : 0;
305
+ const h = outerOk.length ? Math.max(...outerOk.map((p) => p[1])) - Math.min(...outerOk.map((p) => p[1])) : 0;
306
+ const dims = outerOk.length ? `<text x="${W / 2}" y="${H - 8}" text-anchor="middle" fill="var(--mut)" font-size="11">width ${fmt(Math.round(w * 100) / 100)} mm</text><text x="12" y="${H / 2}" fill="var(--mut)" font-size="11" transform="rotate(-90 12 ${H / 2})" text-anchor="middle">height ${fmt(Math.round(h * 100) / 100)} mm</text>` : '';
307
+ const crossings = (d.crossings || []).length;
308
+ const text = `Outline with ${d.outer.length} corner${d.outer.length === 1 ? '' : 's'}${d.holes.length ? ` and ${d.holes.length} hole${d.holes.length === 1 ? '' : 's'}` : ''}${crossings ? `, ${crossings} crossing` : ''}, drawn at the default sizes.`;
309
+ return `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(text)}" preserveAspectRatio="xMidYMid meet">${axes}${draw(d.outer, 'The outline', false)}${d.holes.map((l, i) => draw(l, `Hole ${i + 1}`, true)).join('')}${labels(d.outer, 'outer')}${d.holes.map((l, i) => labels(l, i)).join('')}${dims}</svg>`;
310
+ }
311
+
312
+ function bannerHtml() {
313
+ if (state.pending) return `<span>The AI changed this sketch while you were typing.</span><button type=button data-act=show-changes data-command-id="steel.shape-sketch-show-changes">Show the changes</button>`;
314
+ const a = state.analysis;
315
+ if (!state.sketch || !a) return '';
316
+ if (a.assumed.length) return `<span>The AI guessed ${a.assumed.length} size${a.assumed.length === 1 ? '' : 's'} (dashed amber outline): ${a.assumed.map(esc).join(', ')}. Check ${a.assumed.length === 1 ? 'it' : 'them'}, or change ${a.assumed.length === 1 ? 'it' : 'them'}. Nothing is saved until you click Save shape.</span>`;
317
+ return '';
318
+ }
319
+ function saveBarHtml() {
320
+ const a = state.analysis; const ok = !!a?.ok && !state.saving;
321
+ let reason = '';
322
+ if (state.sketch && a && !a.ok) reason = a.problems.length === 1 ? `Save shape is off: ${a.problems[0]}` : `Save shape is off: ${a.problems.length} things to fix (see Checks).`;
323
+ if (state.saveNote) reason = `${state.saveNote}${reason ? ` ${reason}` : ''}`;
324
+ const replaces = a?.replaces ? 'A shape with this name is already in My shapes: saving adds a new version of it. Members already placed keep the sizes they have.' : 'Saved to My shapes as a new version and turned on. Members keep their own sizes, so a later change never moves placed members without asking.';
325
+ return `<div class=why><span id=shskSaveWhy>${esc(replaces)}</span>${reason ? `<div class=reason id=shskReason role=status>${esc(reason)}</div>` : ''}</div>
326
+ <button type=button class=ghost data-act=discard data-command-id="steel.shape-sketch-discard">Discard sketch</button>
327
+ <button type=button class=ghost data-act=ask-ai data-command-id="steel.shape-sketch-ask-ai" aria-expanded="${state.askAi}">Ask AI to change</button>
328
+ <button type=button class=primary data-act=save aria-disabled="${!ok}" aria-describedby="${reason ? 'shskReason' : 'shskSaveWhy'}" data-command-id="steel.shape-sketch-save">${state.saving ? 'Saving…' : 'Save shape'}</button>`;
329
+ }
330
+ function confirmHtml() {
331
+ if (state.askAi) {
332
+ return `<label for=shskAsk>What should change?</label><textarea id=shskAsk rows=2 style="flex:1;min-width:220px" placeholder="For example: make the rebate 20 deep" data-command-id="steel.shape-sketch-ask-ai-text"></textarea><button type=button data-act=ask-copy data-command-id="steel.shape-sketch-ask-ai-copy">Copy request for AI Chat</button><button type=button class=ghost data-act=ask-close data-command-id="steel.shape-sketch-ask-ai-close">Close</button><span class=hint data-region=askhint></span>`;
333
+ }
334
+ if (!state.confirm) return '';
335
+ return `<span role=alert>${esc(state.confirm.text)}</span><button type=button class=warnb data-act=confirm-yes data-command-id="steel.shape-sketch-confirm-yes">${esc(state.confirm.yes)}</button><button type=button data-act=confirm-no data-command-id="steel.shape-sketch-confirm-no">Keep it</button>`;
336
+ }
337
+
338
+ function templatesHtml() {
339
+ return [...TEMPLATE_IDS, 'blank'].map((id) => `<button type=button data-act=template data-tpl="${id}" data-command-id="steel.shape-sketch-template#${esc(TEMPLATE_WORDS[id])}">${TEMPLATE_WORDS[id]}</button>`).join('');
340
+ }
341
+ function mineHtml() {
342
+ if (!state.myShapes.length) return '';
343
+ return `<h3>Change a shape you saved</h3><div class=shsk-saved-list>${state.myShapes.map((m) => `<button type=button data-act=open-shape data-slug="${esc(m.slug)}" data-command-id="steel.shape-sketch-open-shape#${esc(m.slug)}">${esc(m.name)} <span class=hint>· ${esc(m.prefix)} · saving adds a new version</span></button>`).join('')}</div>`;
344
+ }
345
+
346
+ function leftHtml() {
347
+ const s = state.sketch;
348
+ return `<h3>Shape</h3>
349
+ <div class=row><label for=shskName>Name</label><input id=shskName data-f=name value="${esc(s.name)}" maxlength=80 placeholder="Chamfered plate" autocomplete=off data-command-id="steel.shape-sketch-name"></div>
350
+ <div class=row><label for=shskPrefix>Prefix</label><input id=shskPrefix class=mono data-f=prefix value="${esc(s.prefix)}" maxlength=16 placeholder="CHP" autocomplete=off spellcheck=false data-command-id="steel.shape-sketch-prefix"></div>
351
+ <div data-region=notes>${notesHtml()}</div>
352
+ <div class=row><label for=shskGroup>Group</label><input id=shskGroup data-f=group value="${esc(s.group)}" maxlength=60 autocomplete=off data-command-id="steel.shape-sketch-group"></div>
353
+ <h3>Sizes</h3>
354
+ ${s.sizes.map(sizeRow).join('') || '<p class=hint>No sizes yet. A size is a number the shape depends on, such as a width or a thickness.</p>'}
355
+ <button type=button data-act=size-add data-command-id="steel.shape-sketch-size-add">+ Add size</button>
356
+ <h3>Name pattern</h3><div data-region=pattern>${patternHtml()}</div>
357
+ <h3>Conditions</h3>
358
+ ${s.predicates.map((p, i) => `<div class=shsk-cond><input class=mono data-pf=when data-i="${i}" value="${esc(p.when)}" aria-label="Condition ${i + 1}" placeholder="t < b" spellcheck=false data-command-id="steel.shape-sketch-condition-when#${esc(i + 1)}"><button type=button class=ghost data-act=cond-remove data-i="${i}" aria-label="Remove condition ${i + 1}" data-command-id="steel.shape-sketch-condition-remove#${esc(i + 1)}">✕</button><textarea data-pf=reason data-i="${i}" rows=1 aria-label="Why condition ${i + 1} matters" placeholder="Why this must hold, in plain words" data-command-id="steel.shape-sketch-condition-reason#${esc(i + 1)}">${esc(p.reason)}</textarea></div>`).join('')}
359
+ <button type=button data-act=cond-add data-command-id="steel.shape-sketch-condition-add">+ Add condition</button>
360
+ <p class=hint>A condition says when the shape exists, such as the thickness being less than the width.</p>
361
+ ${mineHtml()}`;
362
+ }
363
+ function rightHtml() {
364
+ const s = state.sketch;
365
+ return `<h3>Corner points</h3>
366
+ <div class=shsk-corners><span></span><span class=hd>x (mm)</span><span class=hd>y (mm)</span><span class=hd style="text-align:right">at defaults</span><span></span>${cornerRows(s.outer, 'outer')}</div>
367
+ <button type=button data-act=corner-add data-loop=outer data-command-id="steel.shape-sketch-corner-add#the outline">+ Add corner</button>
368
+ <p class=hint data-region=symbols>Your sizes: ${s.sizes.map((z) => `<b class=mono>${esc(z.symbol)}</b>`).join(', ') || 'none yet'}. Use them in the corners, like <span class=mono>b/2</span> or <span class=mono>h - t</span>. The origin should be the middle of the shape.</p>
369
+ ${s.holes.map((h, i) => `<div class=shsk-hole><div class=hh><span>Hole ${i + 1}</span><button type=button class=ghost data-act=hole-remove data-i="${i}" data-command-id="steel.shape-sketch-hole-remove#${esc(i + 1)}">Remove hole</button></div><div class=shsk-corners>${cornerRows(h, i)}</div><button type=button data-act=corner-add data-loop="${i}" data-command-id="steel.shape-sketch-corner-add#${esc(`hole ${i + 1}`)}">+ Add corner</button></div>`).join('')}
370
+ <div style="margin-top:10px"><button type=button data-act=hole-add data-command-id="steel.shape-sketch-hole-add">+ Add a hole</button></div>
371
+ <h3>Checks</h3><div data-region=checks tabindex=-1>${checksHtml()}</div>
372
+ <h3>Where this shape can go</h3><div data-region=reach>${reachHtml()}</div>
373
+ <h3>Area and weight</h3><div data-region=derived>${derivedHtml()}</div>`;
374
+ }
375
+
376
+ function startHtml() {
377
+ return `<div class=shsk-start><div style="font-size:16px;font-weight:750">Draw a shape of your own</div>
378
+ <p class=hint>Start from a template or from nothing. Every number is yours to change. Or describe the shape to the AI Chat and it draws it here while you watch; nothing is saved until you click Save shape.</p>
379
+ <div class=tpl>${templatesHtml()}</div>${state.loadError ? `<p class=note role=alert>${esc(state.loadError)}</p>` : ''}${state.unreadable ? `<p class=note role=alert>${esc(state.unreadable)} Starting from a template below replaces it.</p>` : ''}${mineHtml()}</div>`;
380
+ }
381
+ function savedHtml() {
382
+ const sv = state.saved;
383
+ return `<div class=shsk-saved><div class=big>Saved “${esc(sv.name)}” as version ${esc(sv.version)} of My shapes${sv.turnedOn === false ? ', but it is not on yet.' : ', and turned on.'}</div>
384
+ ${sv.turnedOn === false ? `<p class=note role=alert>${esc(sv.turnOnProblem || 'FloLess could not turn it on just now.')} Open ≡ → My add-ons and turn version ${esc(sv.version)} on there; nothing you drew is lost.</p>` : ''}
385
+ <p>${sv.newVersionOfExisting ? 'It is a new version of a shape you already had; models that use the old version keep it until you update them. ' : ''}To use it, select members, then open Inspect and choose <b>From an add-on…</b>${sv.example ? ` — a name of it reads like <span class=mono>${esc(sv.example)}</span>` : ''}.</p>
386
+ <p class=hint>You can go back to an earlier version in ≡ → My add-ons.</p>
387
+ <div class=tpl style="display:flex;gap:8px"><button type=button class=primary data-act=done data-command-id="steel.shape-sketch-saved-done">Done</button><button type=button data-act=another data-command-id="steel.shape-sketch-saved-another">Draw another shape</button></div></div>`;
388
+ }
389
+
390
+ function render() {
391
+ if (!state.open) { root.classList.remove('open'); return; }
392
+ const focusKey = doc.activeElement && root.contains(doc.activeElement) ? doc.activeElement.getAttribute('data-command-id') : null;
393
+ root.classList.add('open');
394
+ const sk = state.sketch;
395
+ const body = state.saved ? `<div style="grid-column:1/-1;overflow:auto">${savedHtml()}</div>` : !sk ? `<div style="grid-column:1/-1;overflow:auto">${startHtml()}</div>` : `<section class=shsk-left aria-label="Shape and sizes">${leftHtml()}</section><section class=shsk-mid aria-label="Drawing"><div class=shsk-canvas data-region=canvas>${drawingSvg()}</div><p class=hint>Drawn at the default sizes. A dashed outline is a hole; a red dashed edge crosses another.</p></section><section class=shsk-right aria-label="Corners, checks and reach">${rightHtml()}</section>`;
396
+ root.innerHTML = `<div class=shsk-panel>
397
+ <header class=shsk-head><button type=button class=ghost data-act=back data-command-id="steel.shape-sketch-back" aria-label="Back to the catalog. Your sketch is kept.">← Back</button>
398
+ <div><div class=t id=shskTitle>${sk && sk.name ? esc(sk.name) : 'New custom shape'}</div><div class=s>Straight edges, sizes by name. Your sketch is kept until you save or discard it.</div></div>
399
+ ${state.by === 'ai' && sk ? '<span class=shsk-pill>AI draft</span>' : ''}<span class=shsk-spacer></span><span class=lbl>Start from</span>${templatesHtml()}</header>
400
+ <div class="shsk-banner" data-region=banner>${bannerHtml()}</div>
401
+ <div class=shsk-confirm data-region=confirm ${state.confirm || state.askAi ? '' : 'hidden'}>${confirmHtml()}</div>
402
+ <div class=shsk-body>${body}</div>
403
+ <footer class=shsk-foot data-region=foot ${sk && !state.saved ? '' : 'hidden'}>${sk ? saveBarHtml() : ''}</footer>
404
+ <div class=sr-only role=status aria-live=polite data-region=live></div></div>`;
405
+ if (focusKey) { const again = [...root.querySelectorAll('[data-command-id]')].find((e) => e.getAttribute('data-command-id') === focusKey); if (again && again.focus) again.focus(); }
406
+ }
407
+
408
+ /** Redraw only what is worked out from the sketch, never the boxes a person may be typing in. */
409
+ function refreshRegions() {
410
+ const set = (name, html) => { const el = region(name); if (el) el.innerHTML = html; };
411
+ set('canvas', drawingSvg()); set('checks', checksHtml()); set('reach', reachHtml()); set('derived', derivedHtml()); set('notes', notesHtml());
412
+ set('pattern', state.sketch ? patternHtml() : ''); set('foot', state.sketch ? saveBarHtml() : '');
413
+ const banner = region('banner'); if (banner) banner.innerHTML = bannerHtml();
414
+ const conf = region('confirm'); if (conf) { conf.innerHTML = confirmHtml(); conf.hidden = !(state.confirm || state.askAi); }
415
+ root.querySelectorAll('[data-val]').forEach((el) => {
416
+ const [loop, i] = el.getAttribute('data-val').split(':'); const d = state.analysis?.drawing;
417
+ const v = (loop === 'outer' ? d?.outer : d?.holes?.[Number(loop)])?.[Number(i)];
418
+ el.textContent = v ? `${fmt(v[0])}, ${fmt(v[1])}` : '?';
419
+ });
420
+ const sym = region('symbols'); if (sym && state.sketch) sym.innerHTML = `Your sizes: ${state.sketch.sizes.map((z) => `<b class=mono>${esc(z.symbol)}</b>`).join(', ') || 'none yet'}. Use them in the corners, like <span class=mono>b/2</span> or <span class=mono>h - t</span>. The origin should be the middle of the shape.`;
421
+ const title = root.querySelector('#shskTitle'); if (title) title.textContent = state.sketch && state.sketch.name ? state.sketch.name : 'New custom shape';
422
+ }
423
+
424
+ const edited = () => { state.saveNote = ''; analyze(); refreshRegions(); schedulePut(); };
425
+ const structural = (focusSelector) => { analyze(); render(); schedulePut(); if (focusSelector) { const el = root.querySelector(focusSelector); if (el && el.focus) el.focus(); } };
426
+
427
+ // ---- actions -----------------------------------------------------------------------------------------------------
428
+ async function startTemplate(id, replace = false) {
429
+ await flush();
430
+ const r = await api('POST', '/api/steel/shape-sketch/template', { template: id, replace });
431
+ if (r.status === 409 && r.body.needsChoice === 'replace-sketch') { state.confirm = { text: `You already have “${state.sketch?.name || 'a sketch'}” here. Replace it with ${TEMPLATE_WORDS[id]}? It cannot be brought back.`, yes: 'Replace it', run: () => startTemplate(id, true) }; refreshRegions(); return; }
432
+ if (!r.ok) { state.status = r.body.error || 'FloLess could not start that sketch.'; state.loadError = state.status; render(); return; }
433
+ state.confirm = null; state.saved = null; take(r.body); render();
434
+ const first = root.querySelector('#shskName'); if (first) first.focus();
435
+ }
436
+ async function openShape(slug, replace = false) {
437
+ await flush();
438
+ const r = await api('POST', '/api/steel/shape-sketch/open', { slug, replace });
439
+ if (r.status === 409 && r.body.needsChoice === 'replace-sketch') { state.confirm = { text: `You already have “${state.sketch?.name || 'a sketch'}” here. Replace it with the saved shape? It cannot be brought back.`, yes: 'Replace it', run: () => openShape(slug, true) }; refreshRegions(); return; }
440
+ if (!r.ok) { state.status = r.body.error || 'FloLess could not open that shape.'; state.loadError = state.status; render(); say(state.status); return; }
441
+ state.confirm = null; state.saved = null; take(r.body); render();
442
+ }
443
+ async function save() {
444
+ if (state.saving) return; // a second click while the first save is working changes nothing
445
+ state.saveNote = '';
446
+ const a = state.analysis;
447
+ if (!a || !a.ok) { const c = region('checks'); if (c && c.focus) c.focus(); say(a?.problems?.[0] || 'Finish the sketch first.'); return; }
448
+ state.saving = true; refreshRegions();
449
+ // Save only what the person is looking at: if the server does not hold exactly the sketch on screen, nothing is saved.
450
+ const kept = await flush();
451
+ if (!kept) {
452
+ state.saving = false;
453
+ state.saveNote = 'The sketch changed — check it and press Save shape again. Nothing was saved.';
454
+ state.status = state.saveNote; refreshRegions(); say(state.saveNote);
455
+ return;
456
+ }
457
+ const r = await api('POST', '/api/steel/shape-sketch/save', { revision: state.rev });
458
+ state.saving = false;
459
+ if (!r.ok) {
460
+ if (r.body.code === 'shape-sketch-changed') { state.status = r.body.error; await load({ remote: false }); say(r.body.error); return; }
461
+ state.status = r.body.error || 'FloLess could not save the shape. Nothing was saved.'; refreshRegions(); say(state.status); return;
462
+ }
463
+ state.saved = r.body.saved; state.sketch = null; state.analysis = null; state.myShapes = [...state.myShapes]; render();
464
+ load({ remote: false }).then(() => { if (state.saved) render(); });
465
+ }
466
+ async function discard() {
467
+ const r = await api('DELETE', '/api/steel/shape-sketch', undefined, state.rev);
468
+ state.confirm = null;
469
+ if (!r.ok) { state.status = r.body.error || 'FloLess could not discard the sketch.'; await load({ remote: false }); return; }
470
+ state.rev = r.body.rev; state.sketch = null; state.analysis = null; state.by = 'person'; render();
471
+ }
472
+
473
+ function updateSize(i, f, raw) {
474
+ const s = state.sketch.sizes[i]; if (!s) return;
475
+ if (f === 'default') { const n = number(raw); if (n === null) return; s.default = n; s.source = 'person'; }
476
+ else if (f === 'label') s.label = raw;
477
+ else if (f === 'min' || f === 'max') { const n = number(raw); if (raw.trim() === '') delete s[f]; else if (n !== null) s[f] = n; }
478
+ else if (f === 'symbol') {
479
+ const old = s.symbol; s.symbol = raw;
480
+ state.sketch.order = (state.sketch.order || []).map((x) => (x === old ? raw : x));
481
+ }
482
+ }
483
+
484
+ root.addEventListener('input', (event) => {
485
+ const el = event.target; if (!state.sketch || !el.matches) return;
486
+ const sizeEl = el.closest('[data-size]');
487
+ if (el.dataset.loop !== undefined) {
488
+ const loop = el.dataset.loop === 'outer' ? state.sketch.outer : state.sketch.holes[Number(el.dataset.loop)];
489
+ if (loop && loop[Number(el.dataset.i)]) loop[Number(el.dataset.i)][Number(el.dataset.axis)] = el.value;
490
+ edited(); return;
491
+ }
492
+ if (sizeEl && el.dataset.f) { updateSize(Number(sizeEl.dataset.size), el.dataset.f, el.value); if (el.dataset.f === 'default') sizeEl.classList.remove('assumed'); edited(); return; }
493
+ if (el.dataset.pf) { const p = state.sketch.predicates[Number(el.dataset.i)]; if (p) p[el.dataset.pf] = el.value; edited(); return; }
494
+ if (['name', 'prefix', 'group'].includes(el.dataset.f)) { state.sketch[el.dataset.f] = el.value; edited(); }
495
+ });
496
+ root.addEventListener('change', (event) => {
497
+ // A size's symbol is the one edit that changes what other boxes mean, so the whole form is redrawn once it is settled.
498
+ const el = event.target;
499
+ if (el.dataset && el.dataset.f === 'symbol' && state.sketch) structural();
500
+ });
501
+
502
+ root.addEventListener('click', async (event) => {
503
+ const el = event.target.closest('[data-act]'); if (!el || !root.contains(el)) return;
504
+ const act = el.dataset.act; const s = state.sketch; const i = Number(el.dataset.i);
505
+ switch (act) {
506
+ case 'back': case 'done': await close(); return;
507
+ case 'template': if (s && hasWork(s) && !state.saved) { state.confirm = { text: `Replace your sketch “${s.name || 'unnamed'}” with ${TEMPLATE_WORDS[el.dataset.tpl]}? It cannot be brought back.`, yes: 'Replace it', run: () => startTemplate(el.dataset.tpl, true) }; refreshRegions(); const y = root.querySelector('[data-act=confirm-yes]'); if (y) y.focus(); } else await startTemplate(el.dataset.tpl, true); return;
508
+ case 'another': state.saved = null; render(); return;
509
+ case 'open-shape': if (s && hasWork(s)) { state.confirm = { text: `Replace your sketch “${s.name || 'unnamed'}” with the saved shape? It cannot be brought back.`, yes: 'Replace it', run: () => openShape(el.dataset.slug, true) }; refreshRegions(); const y = root.querySelector('[data-act=confirm-yes]'); if (y) y.focus(); } else await openShape(el.dataset.slug, true); return;
510
+ case 'confirm-yes': { const run = state.confirm?.run; state.confirm = null; refreshRegions(); if (run) await run(); return; }
511
+ case 'confirm-no': state.confirm = null; refreshRegions(); return;
512
+ case 'discard': state.confirm = { text: 'Discard this sketch? It cannot be brought back. Shapes you already saved are not affected.', yes: 'Discard it', run: discard }; refreshRegions(); { const y = root.querySelector('[data-act=confirm-yes]'); if (y) y.focus(); } return;
513
+ case 'ask-ai': state.askAi = !state.askAi; refreshRegions(); { const t = root.querySelector('#shskAsk'); if (t) t.focus(); } return;
514
+ case 'ask-close': state.askAi = false; refreshRegions(); return;
515
+ case 'ask-copy': {
516
+ const text = (root.querySelector('#shskAsk')?.value || '').trim();
517
+ const hint = root.querySelector('[data-region=askhint]');
518
+ if (!text) { if (hint) hint.textContent = 'Write what should change first.'; return; }
519
+ const message = `In the section sketcher, for the shape “${s?.name || 'my sketch'}”: ${text}`;
520
+ let copied = false; try { await win.navigator.clipboard.writeText(message); copied = true; } catch { copied = false; }
521
+ if (hint) hint.textContent = copied ? 'Copied. Paste it into AI Chat; it changes this sketch while you watch.' : `Send this to AI Chat: ${message}`;
522
+ return;
523
+ }
524
+ case 'show-changes': { const p = state.pending; state.pending = null; if (p && p.rev > state.rev) { const before = state.sketch; take(p); markChanged(before, state.sketch); render(); say('Showing the AI’s changes.'); } return; }
525
+ case 'save': await save(); return;
526
+ case 'size-add': {
527
+ const used = new Set(s.sizes.map((z) => z.symbol)); let sym = 'a'; for (const c of 'abcdefghijklmnopqrstuvwxyz') { if (!used.has(c)) { sym = c; break; } }
528
+ if (s.sizes.length >= 12) { say('A shape can have at most 12 sizes.'); return; }
529
+ s.sizes.push({ symbol: sym, label: '', kind: 'length', default: 10, source: 'person' }); s.order = [...effectiveOrder(s)]; structural(`[data-size="${s.sizes.length - 1}"] [data-f=label]`); return;
530
+ }
531
+ case 'size-remove': { const gone = s.sizes.splice(i, 1)[0]; s.order = (s.order || []).filter((x) => x !== gone?.symbol); structural(); say(`Removed size ${gone?.symbol}.`); return; }
532
+ case 'size-kind': s.sizes[i].kind = NEXT_KIND[s.sizes[i].kind]; structural(); return;
533
+ case 'pattern-earlier': case 'pattern-later': {
534
+ const order = effectiveOrder(s); const at = order.indexOf(el.dataset.sym); const to = act === 'pattern-earlier' ? at - 1 : at + 1;
535
+ if (at < 0 || to < 0 || to >= order.length) return;
536
+ [order[at], order[to]] = [order[to], order[at]]; s.order = order; analyze(); refreshRegions(); schedulePut(); say(`${el.dataset.sym} moved to position ${to + 1} of ${order.length}.`);
537
+ const again = root.querySelector(`[data-act=${act}][data-sym="${String(el.dataset.sym).replace(/["\\]/g, '\\$&')}"]`); if (again && again.focus) again.focus(); return;
538
+ }
539
+ case 'separator': s.separator = el.dataset.sep; analyze(); refreshRegions(); schedulePut(); return;
540
+ case 'corner-add': { const loop = el.dataset.loop === 'outer' ? s.outer : s.holes[Number(el.dataset.loop)]; loop.push(['', '']); structural(`[data-loop="${el.dataset.loop}"][data-i="${loop.length - 1}"][data-axis="0"]`); return; }
541
+ case 'corner-remove': { const loop = el.dataset.loop === 'outer' ? s.outer : s.holes[Number(el.dataset.loop)]; loop.splice(i, 1); structural(); return; }
542
+ case 'hole-add': if (s.holes.length >= 4) { say('A shape can have at most 4 holes.'); return; } s.holes.push([['', ''], ['', ''], ['', '']]); structural(`[data-loop="${s.holes.length - 1}"][data-i="0"][data-axis="0"]`); return;
543
+ case 'hole-remove': s.holes.splice(i, 1); structural(); return;
544
+ case 'cond-add': s.predicates.push({ when: '', reason: '' }); structural(`[data-pf=when][data-i="${s.predicates.length - 1}"]`); return;
545
+ case 'cond-remove': s.predicates.splice(i, 1); structural(); return;
546
+ default:
547
+ }
548
+ });
549
+
550
+ root.addEventListener('keydown', (event) => {
551
+ if (event.key === 'Escape') {
552
+ if (state.confirm || state.askAi) { event.preventDefault(); event.stopPropagation(); state.confirm = null; state.askAi = false; refreshRegions(); return; }
553
+ event.preventDefault(); event.stopPropagation(); close(); return;
554
+ }
555
+ if (event.altKey && (event.key === 'ArrowLeft' || event.key === 'ArrowRight')) {
556
+ const btn = event.target.closest && event.target.closest('.chip');
557
+ if (btn) { event.preventDefault(); btn.querySelector(`[data-act=${event.key === 'ArrowLeft' ? 'pattern-earlier' : 'pattern-later'}]`)?.click(); }
558
+ }
559
+ if (event.key === 'Tab') { // keep Tab inside the dialog
560
+ const items = [...root.querySelectorAll('button:not([disabled]),input,textarea,[tabindex="-1"][data-region=checks]')].filter((e) => !e.closest('[hidden]'));
561
+ if (!items.length) return;
562
+ const first = items[0], last = items[items.length - 1];
563
+ if (event.shiftKey && doc.activeElement === first) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && doc.activeElement === last) { event.preventDefault(); first.focus(); }
564
+ }
565
+ });
566
+
567
+ const hasWork = (s) => !!(s && (s.name.trim() || s.prefix.trim() || s.sizes.length || s.outer.length));
568
+
569
+ async function open({ invoker = null, fromAi = false } = {}) {
570
+ state.invoker = invoker || doc.activeElement; state.open = true; state.saved = null; state.pending = null; state.confirm = null; state.askAi = false;
571
+ listen(); render();
572
+ await load({ remote: false });
573
+ if (fromAi) say('The AI is drafting a shape in the sketcher.');
574
+ const first = root.querySelector('#shskName') || root.querySelector('[data-act=template]'); if (first && first.focus) first.focus();
575
+ }
576
+ async function close() {
577
+ await flush();
578
+ state.open = false; root.classList.remove('open'); root.innerHTML = '';
579
+ const back = state.invoker; state.invoker = null; if (back && back.focus && doc.contains(back)) back.focus();
580
+ }
581
+
582
+ win.addEventListener('floless:open-shape-sketcher', (event) => { open({ invoker: event?.detail?.invoker || null }); });
583
+ // Listening from the start, so a draft the AI chat makes opens the sketcher while the person watches.
584
+ listen();
585
+ return { open, close, state, root, flush, load };
586
+ }
587
+
588
+ /** Install the sketcher in the page once: the catalog's New menu and the AI chat both open it. */
589
+ export function installShapeSketcher(options = {}) {
590
+ const doc = options.doc || document;
591
+ if (doc.defaultView && doc.defaultView.__flolessShapeSketcher) return doc.defaultView.__flolessShapeSketcher;
592
+ const sketcher = createShapeSketcher(options);
593
+ if (doc.defaultView) doc.defaultView.__flolessShapeSketcher = sketcher;
594
+ return sketcher;
595
+ }