@floless/app 0.141.0 → 0.142.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.
@@ -0,0 +1,480 @@
1
+ /* ──────────────────────────────────────────────────────────────────────────
2
+ Leave guard — "is everything saved?" before FloLess stops or signs out.
3
+
4
+ Two actions leave the workspace for good: "Stop FloLess" in the ≡ menu ends the local server,
5
+ and "Sign Out" in the account menu reloads onto the sign-in screen. Both would silently lose
6
+ unsaved work, so both ask this module first — the normal procedure before closing an app.
7
+
8
+ PROVIDERS. Each surface that can hold unsaved work registers a provider: a function returning
9
+ the items it has unresolved RIGHT NOW. An item is
10
+ { id, label, detail, save?(): Promise<boolean>, discard?(), unchecked? }
11
+ aware.js registers the workflow inputs, the running workflow and the full-window editor overlay;
12
+ workspaces.js registers the project's editor frames. `save()` resolves true only when the
13
+ surface re-reads as saved; the guard re-collects after saving regardless, so a surface that says
14
+ "done" but is still dirty keeps the dialog open.
15
+
16
+ FAIL CLOSED. A probe that throws (a frame mid-navigation, an unexpected page) is reported as
17
+ "could not be checked" — it blocks the silent path; the user can still choose to go on without
18
+ saving. An editor frame is saved only when its own state reads exactly `clean`.
19
+
20
+ THE DIALOG is its own #leave-guard-modal (the #confirm-modal look, not its owner): modal over the
21
+ whole window, so nothing is edited behind it. Immediately before resolving "go ahead" it probes
22
+ once more, and returns to the dialog if something new became unsaved or a run started meanwhile.
23
+
24
+ Also here: the Stop FloLess flow itself and the "FloLess has stopped" screen, because stopping is
25
+ the one caller that must also quieten the page (polls, live streams, the reconnect overlay).
26
+ ────────────────────────────────────────────────────────────────────────── */
27
+ (function () {
28
+ 'use strict';
29
+
30
+ var providers = [];
31
+
32
+ /* Live streams are tracked so a stopped page can close them. Without this, every EventSource
33
+ retries forever against a server that is gone on purpose, and each retry is a console error. */
34
+ var liveStreams = new Set();
35
+ if (typeof window.EventSource === 'function') {
36
+ var NativeEventSource = window.EventSource;
37
+ var TrackedEventSource = function (url, init) {
38
+ var es = new NativeEventSource(url, init);
39
+ if (window.__flolessStopped) { es.close(); return es; }
40
+ liveStreams.add(es);
41
+ return es;
42
+ };
43
+ TrackedEventSource.prototype = NativeEventSource.prototype;
44
+ ['CONNECTING', 'OPEN', 'CLOSED'].forEach(function (k) { TrackedEventSource[k] = NativeEventSource[k]; });
45
+ window.EventSource = TrackedEventSource;
46
+ }
47
+
48
+ /* ── probing ───────────────────────────────────────────────────────────── */
49
+
50
+ var FRAME_PAGES = [
51
+ { match: /steel-filter\.html/, label: 'The Drawing Filter' },
52
+ { match: /steel-editor\.html/, label: 'The model editor' },
53
+ { match: /vector-editor\.html/, label: 'The drawing editor' },
54
+ ];
55
+ var STATE_DETAIL = {
56
+ dirty: 'has changes that are not saved yet.',
57
+ saving: 'is still saving your last change.',
58
+ error: 'could not save your last change.',
59
+ conflict: 'was changed somewhere else, so your last change did not save. Open it to choose which version to keep.',
60
+ };
61
+
62
+ function frameLabel(src) {
63
+ for (var i = 0; i < FRAME_PAGES.length; i++) if (FRAME_PAGES[i].match.test(src)) return FRAME_PAGES[i].label;
64
+ return 'An open editor';
65
+ }
66
+
67
+ /** One frame's unresolved items. Shared by aware.js and workspaces.js through registerFrame(). */
68
+ function probeFrame(frame, key) {
69
+ if (!frame) return [];
70
+ var src = frame.getAttribute('src') || '';
71
+ if (!src || src === 'about:blank') return [];
72
+ var id = 'frame:' + key;
73
+ var label = frameLabel(src);
74
+ var win;
75
+ try {
76
+ win = frame.contentWindow;
77
+ if (!win) return [];
78
+ void win.location.href; // same-origin proof; throws for a foreign page
79
+ } catch (_) {
80
+ return [{ id: id, label: label, detail: 'could not be checked for unsaved changes.', unchecked: true }];
81
+ }
82
+ try {
83
+ var guard = win.__floGuard;
84
+ if (guard && typeof guard.isDirty === 'function') {
85
+ if (!guard.isDirty()) return [];
86
+ return [{
87
+ id: id, label: label, detail: STATE_DETAIL.dirty,
88
+ save: async function () { var ok = await guard.save(); return ok === true && !guard.isDirty(); },
89
+ discard: function () { try { guard.discard(); } catch (_) { /* the page is going away */ } },
90
+ }];
91
+ }
92
+ if (typeof win.contractSaveState === 'function') {
93
+ var state = win.contractSaveState();
94
+ if (state === 'clean') return [];
95
+ var flush = typeof win.flushContract === 'function' ? win.flushContract : null;
96
+ return [{
97
+ id: id, label: label, detail: STATE_DETAIL[state] || STATE_DETAIL.dirty,
98
+ save: flush ? async function () { await flush(); return win.contractSaveState() === 'clean'; } : null,
99
+ }];
100
+ }
101
+ return []; // a page with no save state (a viewer, or one still loading) holds nothing to lose
102
+ } catch (_) {
103
+ return [{ id: id, label: label, detail: 'could not be checked for unsaved changes.', unchecked: true }];
104
+ }
105
+ }
106
+
107
+ function register(provider) { if (typeof provider === 'function') providers.push(provider); }
108
+ function registerFrame(frame, key) { register(function () { return probeFrame(frame, key); }); }
109
+
110
+ /** Everything unresolved right now: { items, running } — never throws. */
111
+ async function collect() {
112
+ var items = [];
113
+ var running = null;
114
+ for (var i = 0; i < providers.length; i++) {
115
+ var got;
116
+ try { got = await providers[i](); }
117
+ catch (_) { got = [{ id: 'provider:' + i, label: 'Part of FloLess', detail: 'could not be checked for unsaved changes.', unchecked: true }]; }
118
+ (Array.isArray(got) ? got : []).forEach(function (item) {
119
+ if (!item || !item.id) return;
120
+ if (item.kind === 'running') running = item;
121
+ else items.push(item);
122
+ });
123
+ }
124
+ return { items: items, running: running };
125
+ }
126
+
127
+ /* ── the dialog ────────────────────────────────────────────────────────── */
128
+
129
+ var COPY = {
130
+ stop: {
131
+ title: 'Stop FloLess?',
132
+ clean: 'FloLess will close on this computer. Open it again from the Start menu or the desktop shortcut whenever you need it.',
133
+ unsaved: 'Some of your work is not saved yet. Save it before FloLess closes?',
134
+ running: 'A workflow is running. Stopping FloLess ends it.',
135
+ confirm: 'Stop FloLess', save: 'Save and stop', discard: 'Stop without saving',
136
+ working: 'Stopping FloLess…',
137
+ failed: 'FloLess could not stop just now, so it is still running. Try again in a moment.',
138
+ },
139
+ signout: {
140
+ title: 'Sign out of FloLess?',
141
+ clean: 'You will need to sign in again to keep working.',
142
+ unsaved: 'Some of your work is not saved yet. Save it before you sign out?',
143
+ running: 'A workflow is still running. It will finish on its own; you’ll need to sign in again to see the result.',
144
+ confirm: 'Sign out', save: 'Save and sign out', discard: 'Sign out without saving',
145
+ working: 'Signing out…',
146
+ failed: 'FloLess could not sign you out just now, so you are still signed in. Try again in a moment.',
147
+ },
148
+ };
149
+
150
+ var $modal = null;
151
+ var openPromise = null;
152
+ // The open question's handlers. The buttons, backdrop and keys are wired ONCE (wireOnce) and
153
+ // route here, so no listener is left behind between questions.
154
+ var current = null;
155
+ var wired = false;
156
+ function wireOnce() {
157
+ if (wired) return;
158
+ wired = true;
159
+ var route = function (name) { return function (e) { if (current) current[name](e); }; };
160
+ el('leave-guard-cancel').addEventListener('click', route('cancel'));
161
+ el('leave-guard-confirm').addEventListener('click', route('confirm'));
162
+ el('leave-guard-discard').addEventListener('click', route('discard'));
163
+ el('leave-guard-save').addEventListener('click', route('save'));
164
+ $modal.addEventListener('mousedown', route('backdropDown'));
165
+ $modal.addEventListener('click', route('backdropClick'));
166
+ // Capture: this question sits above every other dialog, so its keys must not reach them.
167
+ document.addEventListener('keydown', route('key'), true);
168
+ }
169
+
170
+ function el(id) { return document.getElementById(id); }
171
+
172
+ function renderItems(items, failed) {
173
+ var list = el('leave-guard-list');
174
+ list.replaceChildren();
175
+ items.forEach(function (item) {
176
+ var li = document.createElement('li');
177
+ li.dataset.itemId = item.id;
178
+ var name = document.createElement('strong');
179
+ name.textContent = item.label;
180
+ li.append(name, document.createTextNode(' ' + item.detail));
181
+ if (failed && failed.has(item.id)) {
182
+ li.classList.add('lg-failed');
183
+ var why = document.createElement('span');
184
+ why.className = 'lg-why';
185
+ why.textContent = item.unchecked || !item.save
186
+ ? 'FloLess cannot save this for you. Open it and save it, or continue without saving.'
187
+ : 'Saving did not finish. Open it to see what went wrong, or continue without saving.';
188
+ li.appendChild(why);
189
+ }
190
+ list.appendChild(li);
191
+ });
192
+ el('leave-guard-unsaved').hidden = items.length === 0;
193
+ }
194
+
195
+ function render(action, snapshot, note, failed) {
196
+ var copy = COPY[action];
197
+ var unsaved = snapshot.items.length > 0;
198
+ el('leave-guard-title').textContent = copy.title;
199
+ el('leave-guard-sub').textContent = unsaved ? copy.unsaved : copy.clean;
200
+ renderItems(snapshot.items, failed);
201
+ var run = el('leave-guard-running');
202
+ run.textContent = snapshot.running ? copy.running : '';
203
+ run.hidden = !snapshot.running;
204
+ var noteEl = el('leave-guard-note');
205
+ noteEl.textContent = note || '';
206
+ noteEl.hidden = !note;
207
+ el('leave-guard-confirm').textContent = copy.confirm;
208
+ el('leave-guard-save').textContent = copy.save;
209
+ el('leave-guard-discard').textContent = copy.discard;
210
+ el('leave-guard-confirm').hidden = unsaved;
211
+ el('leave-guard-save').hidden = !unsaved;
212
+ el('leave-guard-discard').hidden = !unsaved;
213
+ }
214
+
215
+ /** Resolves like `p`, or false once `ms` pass — a save that never answers counts as not saved,
216
+ * so one stuck write cannot hold the whole-window question busy for good. */
217
+ function withTimeout(p, ms) {
218
+ var timer;
219
+ var timeout = new Promise(function (resolve) { timer = setTimeout(function () { resolve(false); }, ms); });
220
+ return Promise.race([Promise.resolve(p), timeout]).finally(function () { clearTimeout(timer); });
221
+ }
222
+
223
+ function idsOf(snapshot) { return new Set(snapshot.items.map(function (i) { return i.id; })); }
224
+
225
+ /** Something the user was NOT shown appeared since they decided: a new unsaved item or a new run. */
226
+ function grewSince(decided, fresh) {
227
+ var seen = idsOf(decided);
228
+ if (fresh.running && !decided.running) return true;
229
+ return fresh.items.some(function (i) { return !seen.has(i.id); });
230
+ }
231
+
232
+ /**
233
+ * Ask before stopping or signing out. Resolves true when the caller should go ahead NOW (the last
234
+ * probe has just run), false when the user cancelled. Idempotent while open.
235
+ *
236
+ * opts.commit (optional): the action itself — async, resolving { ok, message }. It runs while the
237
+ * dialog stays open and busy, so nothing can be edited between the last probe and the server's
238
+ * answer; "without saving" discards only after it succeeded; and a refusal is explained in the
239
+ * dialog, which stays open (nothing was discarded, nothing was left).
240
+ */
241
+ function confirm(opts) {
242
+ var action = opts && opts.action === 'signout' ? 'signout' : 'stop';
243
+ if (openPromise) return openPromise;
244
+ $modal = $modal || el('leave-guard-modal');
245
+ var other = el('confirm-modal');
246
+ if (!$modal || (other && other.classList.contains('show'))) return Promise.resolve(false);
247
+
248
+ openPromise = new Promise(function (resolve) {
249
+ var returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
250
+ var covered = Array.from(document.querySelectorAll('.modal-backdrop.show'))
251
+ .filter(function (m) { return m !== $modal; })
252
+ .map(function (m) { return { m: m, inert: !!m.inert, hidden: m.getAttribute('aria-hidden') }; });
253
+ covered.forEach(function (c) { c.m.inert = true; c.m.setAttribute('aria-hidden', 'true'); });
254
+ var snapshot = { items: [], running: null };
255
+ var busy = false;
256
+ var settled = false;
257
+
258
+ function setBusy(on, label) {
259
+ busy = on;
260
+ ['leave-guard-confirm', 'leave-guard-save', 'leave-guard-discard'].forEach(function (id) { el(id).disabled = on; });
261
+ $modal.setAttribute('aria-busy', on ? 'true' : 'false');
262
+ if (label) el('leave-guard-save').textContent = label;
263
+ }
264
+
265
+ function done(result) {
266
+ if (settled) return;
267
+ settled = true;
268
+ $modal.classList.remove('show');
269
+ covered.forEach(function (c) {
270
+ c.m.inert = c.inert;
271
+ if (c.hidden === null) c.m.removeAttribute('aria-hidden'); else c.m.setAttribute('aria-hidden', c.hidden);
272
+ });
273
+ current = null;
274
+ openPromise = null;
275
+ if (!result) {
276
+ // Back to whatever opened the question; a menu row that has since closed with its menu
277
+ // is not reachable, so the caller's opener (the ≡ button, the avatar) takes it instead.
278
+ var usable = function (n) { return n && n.isConnected && (typeof n.getClientRects !== 'function' || n.getClientRects().length) && !n.matches(':disabled,[aria-disabled="true"]'); };
279
+ var target = usable(returnFocus) ? returnFocus : (opts && usable(opts.returnFocus) ? opts.returnFocus : null);
280
+ if (target) target.focus();
281
+ }
282
+ resolve(result);
283
+ }
284
+
285
+ /* The last word before acting: probe again, and go back to the dialog if the picture grew. */
286
+ async function proceed(decided, discardAll) {
287
+ var fresh = await collect();
288
+ if (settled) return;
289
+ if (grewSince(decided, fresh)) {
290
+ snapshot = fresh;
291
+ render(action, snapshot, 'Something changed while you were deciding. Check the list again.');
292
+ setBusy(false);
293
+ focusDefault();
294
+ return;
295
+ }
296
+ if (opts && typeof opts.commit === 'function') {
297
+ el('leave-guard-sub').textContent = COPY[action].working;
298
+ var outcome = null;
299
+ try { outcome = await opts.commit(); } catch (_) { outcome = null; }
300
+ if (settled) return;
301
+ if (!outcome || !outcome.ok) {
302
+ snapshot = fresh;
303
+ render(action, snapshot, (outcome && outcome.message) || COPY[action].failed);
304
+ setBusy(false);
305
+ focusDefault();
306
+ return;
307
+ }
308
+ }
309
+ if (discardAll) fresh.items.forEach(function (i) { if (typeof i.discard === 'function') i.discard(); });
310
+ window.__flolessLeaving = true; // no browser "Leave site?" prompt on the way out
311
+ done(true);
312
+ }
313
+
314
+ async function saveAll() {
315
+ setBusy(true, 'Saving…');
316
+ var failed = new Set();
317
+ for (var i = 0; i < snapshot.items.length; i++) {
318
+ var item = snapshot.items[i];
319
+ if (typeof item.save !== 'function') { failed.add(item.id); continue; }
320
+ try { if (!(await withTimeout(item.save(), api.saveTimeoutMs))) failed.add(item.id); }
321
+ catch (_) { failed.add(item.id); }
322
+ }
323
+ if (settled) return;
324
+ var fresh = await collect();
325
+ if (settled) return;
326
+ // A save that said it failed keeps us here even if its item no longer shows up (an editor
327
+ // closed mid-save): its change is not known to be saved, so it stays on the list.
328
+ var freshIds = idsOf(fresh);
329
+ snapshot.items.forEach(function (it) { if (failed.has(it.id) && !freshIds.has(it.id)) fresh.items.push(it); });
330
+ // Anything still unresolved after saving — whether its save said so or not — keeps us here.
331
+ fresh.items.forEach(function (it) { failed.add(it.id); });
332
+ if (fresh.items.length || (fresh.running && !snapshot.running)) {
333
+ snapshot = fresh;
334
+ render(action, snapshot, fresh.items.length ? 'Some of your work could not be saved:' : '', failed);
335
+ setBusy(false);
336
+ el('leave-guard-save').textContent = COPY[action].save;
337
+ focusDefault();
338
+ return;
339
+ }
340
+ await proceed(fresh, false);
341
+ }
342
+
343
+ function focusDefault() { setTimeout(function () { el('leave-guard-cancel').focus(); }, 0); }
344
+
345
+ function onKey(e) {
346
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); if (!busy) done(false); return; }
347
+ if (e.key !== 'Tab') return;
348
+ e.stopPropagation();
349
+ var focusable = Array.from($modal.querySelectorAll('button:not([disabled]):not([hidden])'))
350
+ .filter(function (b) { return b.getClientRects().length; });
351
+ if (!focusable.length) { e.preventDefault(); return; }
352
+ var first = focusable[0]; var last = focusable[focusable.length - 1];
353
+ if (e.shiftKey && (document.activeElement === first || !$modal.contains(document.activeElement))) { e.preventDefault(); last.focus(); }
354
+ else if (!e.shiftKey && (document.activeElement === last || !$modal.contains(document.activeElement))) { e.preventDefault(); first.focus(); }
355
+ }
356
+
357
+ var downOnBackdrop = false;
358
+ wireOnce();
359
+ current = {
360
+ cancel: function () { if (!busy) done(false); },
361
+ confirm: function () { if (busy) return; setBusy(true); proceed(snapshot, false); },
362
+ discard: function () { if (busy) return; setBusy(true); proceed(snapshot, true); },
363
+ save: function () { if (!busy) saveAll(); },
364
+ // A backdrop click closes only when the press also began on it (a text-selection drag doesn't).
365
+ backdropDown: function (e) { downOnBackdrop = e.target === $modal; },
366
+ backdropClick: function (e) { var hit = e.target === $modal && downOnBackdrop; downOnBackdrop = false; if (hit && !busy) done(false); },
367
+ key: onKey,
368
+ };
369
+
370
+ // Show the dialog at once (modal: nothing is edited behind it while we look), then fill it in.
371
+ el('leave-guard-title').textContent = COPY[action].title;
372
+ el('leave-guard-sub').textContent = 'Checking for unsaved work…';
373
+ el('leave-guard-unsaved').hidden = true;
374
+ el('leave-guard-running').hidden = true;
375
+ el('leave-guard-note').hidden = true;
376
+ ['leave-guard-save', 'leave-guard-discard'].forEach(function (id) { el(id).hidden = true; });
377
+ el('leave-guard-confirm').hidden = false;
378
+ el('leave-guard-confirm').textContent = COPY[action].confirm;
379
+ setBusy(true);
380
+ $modal.classList.add('show');
381
+ focusDefault();
382
+ collect().then(function (s) {
383
+ if (settled) return;
384
+ snapshot = s;
385
+ render(action, snapshot);
386
+ setBusy(false);
387
+ });
388
+ });
389
+ return openPromise;
390
+ }
391
+
392
+ /* ── Stop FloLess ──────────────────────────────────────────────────────── */
393
+
394
+ var stopping = false;
395
+
396
+
397
+ /** After the server confirmed: quieten the page so it neither polls nor shows "Reconnecting…". */
398
+ function quiesce() {
399
+ window.__flolessStopped = true;
400
+ liveStreams.forEach(function (es) { try { es.close(); } catch (_) { /* already closed */ } });
401
+ liveStreams.clear();
402
+ // Anything the page still asks for would only fail against a server that is gone on purpose.
403
+ var nativeFetch = window.fetch;
404
+ window.fetch = function (input, init) {
405
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
406
+ var sameOrigin = url.charAt(0) === '/' || url.indexOf(location.origin) === 0;
407
+ return sameOrigin ? new Promise(function () { /* never: the server is gone */ }) : nativeFetch.call(window, input, init);
408
+ };
409
+ document.querySelectorAll('iframe').forEach(function (f) { try { f.src = 'about:blank'; } catch (_) { /* detached */ } });
410
+ var overlay = document.getElementById('server-offline-overlay');
411
+ if (overlay) overlay.remove();
412
+ }
413
+
414
+ function renderStopped() {
415
+ if (document.getElementById('app-stopped')) return;
416
+ var mark = document.querySelector('header .brand .mark svg');
417
+ var wrap = document.createElement('div');
418
+ wrap.id = 'app-stopped';
419
+ wrap.setAttribute('role', 'alertdialog');
420
+ wrap.setAttribute('aria-modal', 'true');
421
+ wrap.setAttribute('aria-labelledby', 'app-stopped-title');
422
+ wrap.setAttribute('aria-describedby', 'app-stopped-body');
423
+ wrap.innerHTML =
424
+ '<div class="as-card" tabindex="-1">' +
425
+ '<div class="as-mark" aria-hidden="true"></div>' +
426
+ '<h1 id="app-stopped-title">FloLess has stopped</h1>' +
427
+ '<p id="app-stopped-body">FloLess is no longer running. You can close this tab.</p>' +
428
+ '<a class="as-start" id="app-stopped-start" href="floless://start" data-command-id="app.start-again"' +
429
+ ' data-tip="Opens FloLess again on this computer">Start FloLess again</a>' +
430
+ '<p class="as-status" id="app-stopped-status" role="status"></p>' +
431
+ '</div>';
432
+ if (mark) wrap.querySelector('.as-mark').appendChild(mark.cloneNode(true));
433
+ // Everything behind the panel is dead — take it out of the tab order and the accessibility tree.
434
+ Array.from(document.body.children).forEach(function (child) { if (child !== wrap) child.inert = true; });
435
+ document.body.appendChild(wrap);
436
+ // A real link the user clicks: a scripted click on an external protocol is dropped by Chromium.
437
+ document.getElementById('app-stopped-start').addEventListener('click', function () {
438
+ document.getElementById('app-stopped-status').textContent =
439
+ 'Starting FloLess… When it is ready, reload this tab. If nothing happens, open FloLess from the Start menu.';
440
+ });
441
+ wrap.querySelector('.as-card').focus();
442
+ }
443
+
444
+ /** The server's answer to POST /api/app/stop, in words for the dialog. Only a refusal the server
445
+ * words for people is passed through; anything else gets the generic sentence. */
446
+ var STOP_REFUSALS = { 'supervisor-still-running': true };
447
+ async function requestStop() {
448
+ var res;
449
+ try { res = await fetch('/api/app/stop', { method: 'POST' }); }
450
+ catch (_) {
451
+ return { ok: false, message: 'FloLess could not be reached to stop it. It may already have stopped — reload this tab to check.' };
452
+ }
453
+ if (res.status === 202) return { ok: true };
454
+ var body = await res.json().catch(function () { return {}; });
455
+ return { ok: false, message: body && STOP_REFUSALS[body.code] && body.error ? body.error : null };
456
+ }
457
+
458
+ async function stopApp() {
459
+ if (stopping || window.__flolessStopped) return;
460
+ stopping = true;
461
+ try {
462
+ var go = await confirm({ action: 'stop', returnFocus: document.getElementById('menu-btn'), commit: requestStop });
463
+ if (!go) return;
464
+ quiesce();
465
+ renderStopped();
466
+ } finally {
467
+ if (!window.__flolessStopped) stopping = false;
468
+ }
469
+ }
470
+
471
+ var api = window.flolessLeaveGuard = {
472
+ saveTimeoutMs: 20000, // how long one item's save may take before it counts as not saved
473
+ register: register,
474
+ registerFrame: registerFrame,
475
+ probeFrame: probeFrame,
476
+ collect: collect,
477
+ confirm: confirm,
478
+ stopApp: stopApp,
479
+ };
480
+ })();
@@ -215,7 +215,31 @@
215
215
  stack.append(sections[first], split, sections[second], empty);
216
216
  }
217
217
 
218
+ // The model objects selected in the live editor, as AI Chat may attach them to a question (#1653): a frozen copy,
219
+ // or null whenever no editor is live here or nothing it can name is selected. The editor's own shape is checked,
220
+ // not trusted: the server validates again, but a pill must never count what it cannot send.
221
+ function readSelection() {
222
+ const subjects = state.modelAvailable && modelVisible() ? state.snapshot?.subjects : null;
223
+ if (!subjects || typeof subjects !== 'object' || typeof subjects.source !== 'string') return null;
224
+ const items = Array.isArray(subjects.items) ? subjects.items.filter((item) => item && typeof item.kind === 'string'
225
+ && typeof item.id === 'string' && item.id).map((item) => Object.freeze({ kind: item.kind, id: item.id,
226
+ label: typeof item.label === 'string' ? item.label : item.id })) : [];
227
+ const total = Number.isSafeInteger(subjects.total) && subjects.total >= items.length ? subjects.total : items.length;
228
+ if (!total || !items.length) return null;
229
+ return Object.freeze({ source: subjects.source, revision: Number.isSafeInteger(subjects.revision) ? subjects.revision : null,
230
+ total, key: typeof subjects.key === 'string' && subjects.key.length <= 64 ? subjects.key : null, items: Object.freeze(items) });
231
+ }
232
+ let selectionKey = 'null';
233
+ // Chat repaints its pill when this changes. Called from reflect(), which every path that forgets a model reaches.
234
+ function announceSelection() {
235
+ const next = readSelection();
236
+ const key = JSON.stringify(next);
237
+ if (key === selectionKey) return;
238
+ selectionKey = key;
239
+ window.dispatchEvent(new window.CustomEvent('floless:model-selection'));
240
+ }
218
241
  function reflect() {
242
+ announceSelection();
219
243
  const both = presented('narrative') && presented('model');
220
244
  const first = state.order[0];
221
245
  const splitLocked = approvalSplitLocked(first);
@@ -691,7 +715,9 @@
691
715
  state.snapshot.selectedId = typeof data.selectedId === 'string' ? data.selectedId : null;
692
716
  state.snapshot.selectedIds = Array.isArray(data.selectedIds) ? data.selectedIds.filter((id) => typeof id === 'string') : (state.snapshot.selectedId ? [state.snapshot.selectedId] : []);
693
717
  state.snapshot.selectionOrigin = data.selectionOrigin || 'tree';
718
+ state.snapshot.subjects = data.subjects && typeof data.subjects === 'object' ? data.subjects : null;
694
719
  }
720
+ announceSelection();
695
721
  pendingSelectIds = null;
696
722
  const picked = selectedIdsOf(data);
697
723
  modelContent.querySelectorAll('[data-entity-id]').forEach((row) => {
@@ -701,6 +727,20 @@
701
727
  if (state.followSelection && state.snapshot?.selectedIds?.length === 1) { renderModel(); revealSelectedEntity(); }
702
728
  return;
703
729
  }
730
+ // An object card's Show in chat: the editor names a conversation and one message in it (#1653).
731
+ if (data.type === 'open-chat') {
732
+ state.revision = data.revision;
733
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
734
+ if (!uuid.test(String(data.chatId)) || !uuid.test(String(data.messageEventId))
735
+ || typeof data.projectId !== 'string' || !data.projectId || data.projectId.length > 200) return;
736
+ // Said where a sighted person looks, not only to a screen reader: the click happened in the model panel.
737
+ const refuse = (message) => { status.textContent = message; window.showToast?.(message, 'info'); };
738
+ const open = window.flolessChat?.openConversation;
739
+ if (typeof open !== 'function') { refuse('AI Chat is not ready yet. Try Show in chat again in a moment.'); return; }
740
+ Promise.resolve().then(() => open(data.chatId, { messageEventId: data.messageEventId, projectId: data.projectId }))
741
+ .catch((error) => refuse(error?.message || 'That conversation could not be opened. Try Show in chat again.'));
742
+ return;
743
+ }
704
744
  if (data.type !== 'snapshot') return;
705
745
  state.revision = data.revision; state.snapshot = data.snapshot; state.modelAvailable = true;
706
746
  if (state.datasetKey !== data.snapshot.datasetKey) state.datasetKey = data.snapshot.datasetKey || null;
@@ -725,6 +765,9 @@
725
765
  frame.addEventListener('load', onModelFrameLoad);
726
766
 
727
767
  window.flolessLeftPane = Object.freeze({
768
+ readSelection,
769
+ // AI Chat stored a question about model objects: the live editor reads its links again.
770
+ chatLinksChanged() { if (state.modelAvailable) send({ type: 'chat-links-changed' }); },
728
771
  showSection(key) {
729
772
  if (!available(key)) return false;
730
773
  const changed = !shown(key); sessionVisible[key] = true; reflect(); return changed;
@@ -50,7 +50,6 @@ export function createModelClipSession({
50
50
  let sequence = 0;
51
51
  let disposed = false;
52
52
  let mutationDepth = 0;
53
- let pendingReason = null;
54
53
 
55
54
  const clips = () => tools.state().clips ?? [];
56
55
  const orderedIds = () => clips().map((clip) => clip.id);
@@ -76,7 +75,7 @@ export function createModelClipSession({
76
75
  return value;
77
76
  };
78
77
  const publish = (reason) => {
79
- if (mutationDepth) { pendingReason = reason; return current(); }
78
+ if (mutationDepth) return current();
80
79
  return emit(reason);
81
80
  };
82
81
  const beginEdit = (reason) => {
@@ -87,7 +86,7 @@ export function createModelClipSession({
87
86
  try { beginEdit(reason); return operation(); }
88
87
  finally {
89
88
  mutationDepth -= 1;
90
- if (!mutationDepth) { pendingReason = null; emit(reason); }
89
+ if (!mutationDepth) emit(reason);
91
90
  }
92
91
  };
93
92
  const nextIdentity = (kind) => {
@@ -12,6 +12,16 @@ Object.freeze(MODEL_NAMED_VIEWS);
12
12
 
13
13
  export const MODEL_VIEW_KEYS = Object.freeze({ t: 'top', f: 'front', r: 'right', b: 'back', l: 'left' });
14
14
 
15
+ /** Keep an entire model sphere inside the camera frustum as navigation changes its distance. */
16
+ export function modelCameraClipRange(distance, radius, orthographic = false) {
17
+ if (!Number.isFinite(distance) || distance < 0 || !Number.isFinite(radius) || radius < 0) throw new RangeError('Camera clipping needs a finite distance and radius.');
18
+ // Orthographic zoom changes magnification without moving the camera. Its near plane must
19
+ // reach behind a camera that sits inside the model after framing a close detail.
20
+ const near = orthographic ? distance - radius * 1.05 : Math.max(0.1, (distance - radius) * 0.5);
21
+ const far = Math.max(near + 1, (distance + radius) * 1.05);
22
+ return { near, far };
23
+ }
24
+
15
25
  /** Apply FloLess CAD mouse conventions to an OrbitControls-compatible controller. */
16
26
  export function applyCadOrbitPolicy(controls, mouse = THREE.MOUSE) {
17
27
  if (!controls) throw new Error('CAD navigation needs OrbitControls.');
@@ -85,9 +95,12 @@ function cadRepivotAction({ controls, getCamera, pickPoint, cursor }) {
85
95
  }
86
96
 
87
97
  /** Shared keyboard pan/rotate/named-view behavior. Escape remains owned by the active tool plugin. */
88
- export function handleCadNavigationKey({ getCamera, getControls, applyView, fitSelection, canFitSelection = () => true, canApplyView = () => true }, event) {
98
+ export function handleCadNavigationKey({ getCamera, getControls, applyView, fitAll, fitSelection, canFitSelection = () => true, canApplyView = () => true }, event) {
89
99
  const arrows = Object.freeze({ ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] });
90
100
  if (event.defaultPrevented) return false;
101
+ if (event.key === 'Home' && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && fitAll) {
102
+ event.preventDefault(); fitAll(); return true;
103
+ }
91
104
  if (((event.key === ' ' && event.shiftKey) || ((event.key === 'z' || event.key === 'Z') && event.altKey)) && canFitSelection(event)) {
92
105
  event.preventDefault(); fitSelection?.(); return true;
93
106
  }
@@ -122,7 +135,7 @@ export function handleCadNavigationKey({ getCamera, getControls, applyView, fitS
122
135
  * parallel listener set or copying camera behavior.
123
136
  */
124
137
  export function mountCadInputArbiter({
125
- surface, controls, mouse = THREE.MOUSE, win = window, getCamera, pickPoint, applyView, fitSelection,
138
+ surface, controls, mouse = THREE.MOUSE, win = window, getCamera, pickPoint, applyView, fitAll, fitSelection,
126
139
  isActive = () => true, canFitSelection, canApplyView, orbitInput = null, orbitThreshold = 5, plugin = {},
127
140
  }) {
128
141
  if (!surface || !controls || !win) throw new Error('CAD input arbiter needs a surface, controls, and window.');
@@ -212,13 +225,14 @@ export function mountCadInputArbiter({
212
225
  if (!isActive()) return;
213
226
  if (event.defaultPrevented || event.cancelBubble === true) return;
214
227
  const active = win.document?.activeElement; if (active && /^(INPUT|SELECT|TEXTAREA)$/.test(active.tagName)) return;
228
+ const menuOwnsHome = event.key === 'Home' && !!active?.closest?.('.m3dmenu,[role="menu"]');
215
229
  dispatch('keyDown', event);
216
230
  if (event.key === 'Escape' && orbitGesture) {
217
231
  if (!orbitGesture.pending) orbitInput?.cancel(orbitGesture.down);
218
232
  orbitGesture = null;
219
233
  }
220
234
  if (orbitInput && !event.defaultPrevented) orbitInput.document(event);
221
- if (!event.defaultPrevented) handleCadNavigationKey({ getCamera, getControls: () => controls, applyView, fitSelection, canFitSelection, canApplyView }, event);
235
+ if (!event.defaultPrevented && !menuOwnsHome) handleCadNavigationKey({ getCamera, getControls: () => controls, applyView, fitAll, fitSelection, canFitSelection, canApplyView }, event);
222
236
  });
223
237
  listen(win, 'keyup', (event) => { dispatch('keyUp', event); if (orbitInput && !event.defaultPrevented) orbitInput.document(event); });
224
238
  controls.addEventListener('start', repivot); removers.push(() => controls.removeEventListener('start', repivot));
@@ -61,7 +61,6 @@ export function modelCubeDirection(point) {
61
61
  }
62
62
 
63
63
  export function nextModelCubeKeyboardView(current, key) {
64
- if (key === 'Home') return 'iso';
65
64
  return KEY_ADJACENCY[current]?.[key] ?? current;
66
65
  }
67
66
 
@@ -102,7 +101,7 @@ function disposeScene(scene) {
102
101
  function renderAccessibleName(canvas, status, highlighted) {
103
102
  const face = FACE_LABELS[highlighted];
104
103
  const label = highlighted === 'iso' ? 'Isometric' : `${face[0]}${face.slice(1).toLowerCase()}`;
105
- canvas.setAttribute('aria-label', `ViewCube. ${label} view selected. Arrow keys choose a face, Home chooses isometric, Enter applies.`);
104
+ canvas.setAttribute('aria-label', `ViewCube. ${label} view selected. Arrow keys choose a face, Enter applies. Home fits the whole model.`);
106
105
  status.textContent = `${label} view selected`;
107
106
  }
108
107
 
@@ -129,7 +128,7 @@ export function mountModelOrientationOverlay({
129
128
  cleanup(() => { cubeRenderer.dispose(); cubeRenderer.forceContextLoss?.(); });
130
129
  cubeRenderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2)); cubeRenderer.setSize(MODEL_VIEW_CUBE_PX, MODEL_VIEW_CUBE_PX);
131
130
  const cubeCanvas = cubeRenderer.domElement; cubeCanvas.tabIndex = 0; cubeCanvas.setAttribute('role', 'button');
132
- cubeCanvas.dataset.tip = 'ViewCube: arrows choose a face, Home chooses ISO, Enter applies, Escape returns to the model';
131
+ cubeCanvas.dataset.tip = 'ViewCube: arrows choose a face, Enter applies, Home fits the whole model, Escape returns to the model';
133
132
  cubeHost.appendChild(cubeCanvas); cleanup(() => cubeCanvas.remove());
134
133
 
135
134
  const status = document.createElement('span'); status.className = 'model-view-cube-status'; status.setAttribute('aria-live', 'polite'); status.setAttribute('aria-atomic', 'true');