@floless/app 0.131.1 → 0.132.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,1119 @@
1
+ /* ──────────────────────────────────────────────────────────────────────────
2
+ The Instructor — a docked band that narrates what you are doing.
3
+
4
+ VERTICAL SLICE (shell only). Proves the interaction model in the real app:
5
+ an idle readout of your own project state, a plain-English reason when a
6
+ control is blocked, and `?` to explain any control on demand.
7
+
8
+ Design contract this slice honours (docs/plans/2026-08-17-instructor-dynamic-docs.md):
9
+
10
+ • ONE PURE PRODUCER. `guidanceFor(snapshot)` is a pure function — no DOM
11
+ reads, no side effects — so it is testable and so consumers cannot drift
12
+ apart. Rendering is a separate step that only paints what it is handed.
13
+ • NO ECHO. An entry must carry at least one derived, non-visible fact (what
14
+ it acts on, where it sits, its keyboard route, whether it applies right
15
+ now). A line that would merely restate the control's own label is
16
+ suppressed — silence beats an echo.
17
+ • NOT A SECOND LIVE REGION. #run-state already announces gate changes to
18
+ screen readers. The band is aria-live="off" so hovering a toolbar cannot
19
+ flood the queue; `?` is an explicit user action, so it announces via the
20
+ existing status element instead.
21
+
22
+ NOT in this slice, deliberately: the command registry, the cross-frame
23
+ reporter, the steel editor, the CI guards. See phase 0 in the plan.
24
+ ────────────────────────────────────────────────────────────────────────── */
25
+ (function () {
26
+ 'use strict';
27
+
28
+ var COLLAPSE_KEY = 'floless:instructor:collapsed';
29
+ /* On/off is a SEPARATE key from collapsed, because they are different questions:
30
+ collapsed keeps a thin rail and remembers where you were, off reclaims the grid
31
+ row entirely. A user who turns the strip off and later back on should find their
32
+ collapse preference where they left it. Default ON — only the literal '0' turns
33
+ it off, so a new user (null) gets the Instructor. */
34
+ var ENABLED_KEY = 'floless:instructor:enabled';
35
+
36
+ /* ── the producer ─────────────────────────────────────────────────────────
37
+ snapshot → structured guidance. Pure. Everything the band shows comes
38
+ from here, and nothing else in this file authors narration text. */
39
+
40
+ /* Shown when a surface arms a command the registry does not know. The
41
+ alternative — falling back to a generic "something is armed" — would let a
42
+ missing registration ship looking like a design choice, and phase 3's
43
+ coverage gate would be the first thing to notice. This is the one string
44
+ the producer owns, and it exists to make a gap visible. */
45
+ var UNREGISTERED = 'This command has no entry yet — please report it';
46
+
47
+ function guidanceFor(snapshot) {
48
+ var s = snapshot || {};
49
+
50
+ // An armed command in a child surface always wins — you cannot abandon a
51
+ // multi-click sequence to read about a button the cursor crossed.
52
+ if (s.child && s.child.armed) return commandGuidance(s.child);
53
+
54
+ // A focused/queried control wins over the idle readout, but never over a
55
+ // blocked gate the user is actively looking at.
56
+ if (s.focus) return controlGuidance(s.focus, s.workflow);
57
+ return workflowGuidance(s.workflow);
58
+ }
59
+
60
+ /* PHASE 2: step text comes from the REGISTRY, not from a table in here.
61
+ The phase-0 scaffolding table is gone: a second list of step prose living
62
+ beside the producer is exactly the drift this design exists to prevent, and
63
+ it could only ever describe commands the shell happened to know about.
64
+
65
+ `steps` is authored once, next to the surface that owns the command
66
+ (commands-steel.js), and the child reports which index it is on. */
67
+
68
+ function commandGuidance(child) {
69
+ var id = child.armed;
70
+ var meta = window.Commands ? window.Commands.get(id) : null;
71
+
72
+ // No definition — the surface armed something that never registered, or its
73
+ // registrations did not load here. Say so plainly rather than inventing a
74
+ // step: a wrong instruction is worse than an admitted gap, and this reads as
75
+ // a bug report to whoever sees it.
76
+ if (!meta) return { tone: 'armed', chip: id, parts: [UNREGISTERED], ask: id, unregistered: true };
77
+
78
+ var steps = meta.steps || [];
79
+ var chip = meta.label;
80
+ var parts = [];
81
+
82
+ if (steps.length) {
83
+ var i = typeof child.step === 'number' && child.step >= 0 ? Math.min(child.step, steps.length - 1) : 0;
84
+ // A one-step command has no sequence to count through, so counting at it
85
+ // is noise — "step 1 of 1" tells the user nothing they cannot see.
86
+ if (steps.length > 1) chip = meta.label + ' · step ' + (i + 1) + ' of ' + steps.length;
87
+ parts.push(steps[i]);
88
+ } else {
89
+ parts.push(meta.label + ' is armed');
90
+ }
91
+
92
+ // Appended once here rather than repeated on every registration: how you get
93
+ // out of an armed command is the producer's business, not each command's.
94
+ parts.push('Esc to cancel');
95
+
96
+ return { tone: 'armed', chip: chip, parts: parts, ask: meta.label, commandId: id };
97
+ }
98
+
99
+ function workflowGuidance(wf) {
100
+ if (!wf || !wf.name) {
101
+ return {
102
+ tone: 'idle',
103
+ chip: 'No workflow',
104
+ parts: ['Open a workflow to see where it stands'],
105
+ ask: null,
106
+ };
107
+ }
108
+
109
+ var parts = [];
110
+ var tone = 'idle';
111
+ var chip = wf.statusLabel || 'Ready';
112
+
113
+ if (wf.runState === 'drift') {
114
+ tone = 'blocked';
115
+ chip = 'Run blocked';
116
+ parts.push(wf.name);
117
+ parts.push('changed since the last Compile, so its approved lock is out of date');
118
+ parts.push('Compile to re-enable Run');
119
+ } else if (wf.runState === 'uncompiled') {
120
+ tone = 'blocked';
121
+ chip = 'Not set up';
122
+ parts.push(wf.name);
123
+ parts.push('has no approved lock yet, so Run is off');
124
+ parts.push('Compile to freeze one');
125
+ } else {
126
+ parts.push(wf.name);
127
+ if (wf.totalInputs) {
128
+ parts.push(
129
+ wf.inputsSet === wf.totalInputs
130
+ ? 'all inputs set'
131
+ : wf.inputsSet + ' of ' + wf.totalInputs + ' inputs set'
132
+ );
133
+ }
134
+ parts.push('in sync');
135
+ parts.push(nextStep(wf));
136
+ }
137
+
138
+ return { tone: tone, chip: chip, parts: parts, ask: wf.name };
139
+ }
140
+
141
+ function nextStep(wf) {
142
+ if (wf.totalInputs && wf.inputsSet < wf.totalInputs) return 'Next: set the remaining inputs';
143
+ return 'Next: Run';
144
+ }
145
+
146
+ /* A control's entry. Returns null-ish guidance when every fact it could show
147
+ is already visible on screen — the No-Echo rule, enforced here rather than
148
+ left to the caller. */
149
+ function controlGuidance(focus, wf) {
150
+ var facts = [];
151
+
152
+ if (focus.acts) facts.push(focus.acts);
153
+ if (focus.group) facts.push(focus.group);
154
+ if (focus.key) facts.push(focus.key);
155
+
156
+ if (focus.disabled) {
157
+ facts.push(focus.disabledReason || 'Not available right now');
158
+ } else if (facts.length) {
159
+ facts.push('Available now');
160
+ }
161
+
162
+ // No derived fact → nothing worth saying beyond what the screen shows.
163
+ if (!facts.length) {
164
+ if (focus.tip) return { tone: 'idle', chip: focus.label, parts: [focus.tip], ask: focus.label };
165
+ return { tone: 'silent', chip: null, parts: [], ask: null, fallback: workflowGuidance(wf) };
166
+ }
167
+
168
+ return {
169
+ tone: focus.disabled ? 'blocked' : 'idle',
170
+ chip: focus.label,
171
+ parts: facts,
172
+ ask: focus.label,
173
+ };
174
+ }
175
+
176
+ /* ── derivation: a control → the focus half of a snapshot ─────────────────
177
+ Metadata (data-acts / data-group / data-key) is authored beside the
178
+ control; everything else is read live. */
179
+
180
+ function accessibleName(el) {
181
+ var aria = el.getAttribute('aria-label');
182
+ if (aria && aria.trim()) return aria.trim();
183
+ var text = (el.textContent || '').replace(/\s+/g, ' ').trim();
184
+ if (text) return text;
185
+ var tip = el.getAttribute('data-tip');
186
+ if (tip) return tip.split('\n')[0].split('—')[0].trim();
187
+ return el.id || 'This control';
188
+ }
189
+
190
+ function groupOf(el) {
191
+ var owner = el.closest('[data-group]');
192
+ if (owner) return owner.getAttribute('data-group');
193
+ if (el.closest('header')) return 'In the header';
194
+ if (el.closest('footer')) return 'In the footer';
195
+ if (el.closest('#chat-panel')) return 'In the Narrative panel';
196
+ if (el.closest('.canvas')) return 'On the workflow canvas';
197
+ if (el.closest('.inspect')) return 'In the Inspect panel';
198
+ return null;
199
+ }
200
+
201
+ /* ── command templates (PHASE 0b) ─────────────────────────────────────────
202
+ Runtime-generated rows are MANY INSTANCES OF ONE CAPABILITY. Registering
203
+ each instance would make the registry churn with project data and make the
204
+ checked-in id inventory unstable — the objection raised in review.
205
+
206
+ So the registry holds TEMPLATES only, and the DOM carries a parameterized
207
+ id: data-command-id="workflow.rename#my-app"
208
+ └ template ──┘ └ instance key ┘
209
+
210
+ A template is registered once, beside the code that generates the rows.
211
+ Instances register nothing: they are resolved by splitting on '#'. That
212
+ makes teardown free — instances die with the DOM that held them, and the
213
+ template's lifetime is the document's. */
214
+
215
+ /* Storage and resolution belong to commands.js — the single authority on what
216
+ a capability is. instructor.js only READS it, so there is exactly one place
217
+ a definition can live. */
218
+ function resolveCommand(el) {
219
+ return window.Commands ? window.Commands.resolve(el) : null;
220
+ }
221
+
222
+ function focusFor(el) {
223
+ if (!el || el === document.body) return null;
224
+ var target = el.closest('button, [role="button"], a[href], input, select, textarea');
225
+ if (!target) return null;
226
+
227
+ var tip = target.getAttribute('data-tip') || '';
228
+ var disabled = !!(target.disabled || target.getAttribute('aria-disabled') === 'true');
229
+ var cmd = resolveCommand(target);
230
+
231
+ // A registered template supplies the facts; the instance key supplies the
232
+ // subject, so one authored entry serves every generated row.
233
+ if (cmd && cmd.meta) {
234
+ return {
235
+ label: cmd.meta.label || accessibleName(target),
236
+ acts: cmd.instance && cmd.meta.actsOn
237
+ ? cmd.meta.actsOn.replace('{instance}', cmd.instance)
238
+ : cmd.meta.actsOn || null,
239
+ group: cmd.meta.group || groupOf(target),
240
+ key: cmd.meta.key || target.getAttribute('data-key'),
241
+ tip: tip ? tip.split('\n')[0] : '',
242
+ disabled: disabled,
243
+ disabledReason: target.getAttribute('data-blocked-reason'),
244
+ commandId: cmd.id,
245
+ instance: cmd.instance,
246
+ };
247
+ }
248
+
249
+ return {
250
+ label: accessibleName(target),
251
+ acts: target.getAttribute('data-acts'),
252
+ group: groupOf(target),
253
+ key: target.getAttribute('data-key'),
254
+ tip: tip ? tip.split('\n')[0] : '',
255
+ disabled: disabled,
256
+ disabledReason: target.getAttribute('data-blocked-reason'),
257
+ commandId: cmd ? cmd.id : null,
258
+ instance: cmd ? cmd.instance : null,
259
+ };
260
+ }
261
+
262
+ /* ── rendering ────────────────────────────────────────────────────────────
263
+ The only place that touches the DOM. Paints exactly what the producer
264
+ returned; authors nothing. */
265
+
266
+ var $band, $chip, $parts, $ask, $toggle;
267
+ var snapshot = { surface: 'shell', workflow: null, focus: null, child: null };
268
+ var collapsed = false;
269
+ var enabled = true;
270
+
271
+ function seg(cls, text) {
272
+ var el = document.createElement('span');
273
+ el.className = cls;
274
+ el.textContent = text;
275
+ return el;
276
+ }
277
+
278
+ function paint() {
279
+ if (!$band) return;
280
+
281
+ var g = guidanceFor(snapshot);
282
+ if (g.tone === 'silent' && g.fallback) g = g.fallback;
283
+
284
+ $band.className = 'instructor tone-' + g.tone;
285
+ if (collapsed) $band.classList.add('collapsed');
286
+
287
+ $chip.textContent = g.chip || '';
288
+ $chip.hidden = !g.chip;
289
+
290
+ $parts.textContent = '';
291
+ g.parts.forEach(function (part, i) {
292
+ if (i) $parts.appendChild(seg('ix-sep', '·'));
293
+ $parts.appendChild(seg(i === 0 ? 'ix-val' : 'ix-seg', part));
294
+ });
295
+
296
+ $ask.hidden = !g.ask;
297
+ if (g.ask) $ask.dataset.subject = g.ask;
298
+ }
299
+
300
+ function setCollapsed(next) {
301
+ collapsed = !!next;
302
+ try { localStorage.setItem(COLLAPSE_KEY, collapsed ? '1' : '0'); } catch (e) { /* private mode */ }
303
+ $toggle.setAttribute('aria-expanded', String(!collapsed));
304
+ $toggle.dataset.tip = collapsed ? 'Show the Instructor' : 'Hide the Instructor';
305
+ paint();
306
+ }
307
+
308
+ /* ── on/off ───────────────────────────────────────────────────────────────
309
+ Collapsing keeps a rail; turning the Instructor OFF takes the row out of
310
+ the .app grid so the space is genuinely reclaimed. Both the class and the
311
+ element's own hide are needed: the class is what defines the grid row, and
312
+ without hiding the element too it would be auto-placed into an implicit
313
+ one — the reserved space this setting exists to remove. */
314
+
315
+ function applyEnabled() {
316
+ var app = document.getElementById('app');
317
+ if (app) app.classList.toggle('has-instructor', enabled);
318
+ if ($band) $band.hidden = !enabled;
319
+
320
+ var item = document.getElementById('menu-instructor-toggle');
321
+ if (item) item.setAttribute('aria-checked', String(enabled));
322
+
323
+ // Restoring must not need a reload: repaint from the state we kept while off.
324
+ if (enabled) paint();
325
+ }
326
+
327
+ function setEnabled(next) {
328
+ enabled = !!next;
329
+ try { localStorage.setItem(ENABLED_KEY, enabled ? '1' : '0'); } catch (e) { /* private mode */ }
330
+ /* Turning the Instructor off while its sheet is open would hide the band and
331
+ leave the dialog on screen over an inert app — reachable today, because the
332
+ ≡ menu is still clickable from inside the sheet's own backdrop click-out.
333
+ Close it first, which also releases inertness and restores focus. */
334
+ if (!enabled) closeSheet();
335
+ applyEnabled();
336
+ }
337
+
338
+ /* ── `?` — explain what has focus, or what the pointer is over ────────────
339
+ Scoped off while typing. This is a prompt-native product; a bare-key
340
+ binding must never eat a literal "?" the user meant to type. */
341
+
342
+ var lastHovered = null;
343
+ var lastHoveredAt = 0;
344
+
345
+ function isTyping(el) {
346
+ if (!el) return false;
347
+ if (el.isContentEditable) return true;
348
+ var tag = el.tagName;
349
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
350
+ }
351
+
352
+ /* Which target does the user mean — the focused control, or the one under the
353
+ pointer? Both are defensible and phase 0b measured both being wrong:
354
+
355
+ • Focus-first explained "Search workflows" while the pointer sat on a
356
+ row's Delete action, because every searchable popover parks focus in
357
+ its filter box.
358
+ • Hover-first would explain whatever the mouse was last parked over,
359
+ which is meaningless for someone tabbing through with the keyboard.
360
+
361
+ The rule: a RECENT pointer movement means the user is pointing at what they
362
+ mean; otherwise they are navigating by keyboard and focus wins. */
363
+ var HOVER_INTENT_MS = 3000;
364
+
365
+ function explainCurrent() {
366
+ // The band is the only thing that renders an explanation, so with the
367
+ // Instructor off `?` and F1 must do nothing at all — and must not swallow
368
+ // the keystroke either (explainCurrent's return value is what decides
369
+ // whether the handler calls preventDefault).
370
+ if (!enabled) return false;
371
+
372
+ var active = document.activeElement;
373
+ var hasActive = active && active !== document.body;
374
+ var pointerIsFresh = lastHovered && (Date.now() - lastHoveredAt) < HOVER_INTENT_MS;
375
+
376
+ var el = hasActive ? active : lastHovered;
377
+ if (pointerIsFresh && lastHovered !== active && focusFor(lastHovered)) {
378
+ el = lastHovered;
379
+ }
380
+
381
+ var f = focusFor(el);
382
+ if (!setFocusEntry(f, activeSurface())) return false;
383
+ if (collapsed) setCollapsed(false);
384
+ paint();
385
+ return true;
386
+ }
387
+
388
+ /* The ONE way an on-demand entry gets into the band.
389
+ *
390
+ * It stamps where the entry came from, because the entry OUTLIVES the thing it
391
+ * describes otherwise. Escape used to be the only thing that cleared it, so
392
+ * asking about a control in a child surface, closing that surface and switching
393
+ * workflow left the band still reading "Save filter · In the Drawing Filter
394
+ * header · Not available right now" over a canvas with no filter on it — and
395
+ * because guidanceFor checks `focus` BEFORE the workflow readout, it did not
396
+ * merely linger, it suppressed the correct line underneath.
397
+ *
398
+ * That is the same defect the reporter contract was built to close (a band
399
+ * narrating a torn-down surface); the teardown cleared `snapshot.child` and
400
+ * nobody cleared this. Worse, "Not available right now" is read off the real
401
+ * element at capture time, so it silently became a fact about a dead document.
402
+ */
403
+ function setFocusEntry(f, origin) {
404
+ if (!f) return false;
405
+ /* The ORIGIN IS PASSED IN, never guessed from activeSurface(). The two differ:
406
+ the contract-editor overlay covers the shell without unmounting it, so while a
407
+ child is open a shell button is still found and still focusable — and guessing
408
+ would file that entry under the child, then throw it away when the child
409
+ closed even though the button is right there. Callers know the truth:
410
+ activate() knows which document it found the element in, and the registry
411
+ fallback has `cmd.surface`. Defaults to the shell only for a caller that has
412
+ nothing better, which is explain()'s hover/focus path — where a child overlay
413
+ means the pointer cannot be on a shell control anyway. */
414
+ f.originSurface = origin || 'shell';
415
+ snapshot.focus = f;
416
+ return true;
417
+ }
418
+
419
+ function clearFocusEntry() {
420
+ if (!snapshot.focus) return;
421
+ snapshot.focus = null;
422
+ paint();
423
+ }
424
+
425
+ /* ── the `?` command sheet ────────────────────────────────────────────────
426
+ `?`/F1 explain the ONE control you are on. This is the other half: every
427
+ command the registry knows, searchable. It opens on the same key when there
428
+ is no control to explain — asking for help while pointing at nothing is a
429
+ reasonable way to say "show me everything" — and from the strip's "see all".
430
+
431
+ Rows are DERIVED, never authored: label, what it acts on, its keyboard
432
+ route, its tier. Nothing here restates the label (No Echo). */
433
+
434
+ var $sheet, $sheetList, $sheetFilter, $sheetSub;
435
+ var sheetOpen = false;
436
+ var returnFocusTo = null; // where focus came from, so Escape can give it back
437
+ var sheetRows = [];
438
+ var activeRow = -1;
439
+
440
+ function sheetEntries() {
441
+ if (!window.Commands) return [];
442
+ return window.Commands.all().slice().sort(function (a, b) {
443
+ // What is on screen comes first. Nothing is hidden — the sheet is also how
444
+ // you find out what FloLess can do somewhere else, and its zero-result copy
445
+ // calls a miss "a gap worth reporting", which would be a lie if the
446
+ // catalogue were quietly trimmed to the current screen.
447
+ var sa = onScreen(a) ? 0 : 1, sb = onScreen(b) ? 0 : 1;
448
+ if (sa !== sb) return sa - sb;
449
+ var ga = a.group || 'Elsewhere', gb = b.group || 'Elsewhere';
450
+ if (ga !== gb) {
451
+ var ra = groupRank(ga), rb = groupRank(gb);
452
+ if (ra !== rb) return ra - rb;
453
+ return ga < gb ? -1 : 1;
454
+ }
455
+ return a.label < b.label ? -1 : a.label > b.label ? 1 : 0;
456
+ });
457
+ }
458
+
459
+ /* What a row says BESIDES its label. An entry with nothing to add says
460
+ nothing — silence beats an echo, and a row that reads "Compile — compiles"
461
+ would cost the whole surface its credibility. */
462
+ function factsFor(cmd) {
463
+ var facts = [];
464
+ /* actsOn may carry the {instance} placeholder one authored entry uses to
465
+ serve every generated row. The sheet lists TEMPLATES, so there is no
466
+ instance to fill it with — and shipping the literal braces to a user is
467
+ the kind of leak that costs a documentation surface its credibility. */
468
+ if (cmd.actsOn) facts.push(cmd.actsOn.replace(/\{instance\}/g, 'the one you pick'));
469
+ if (cmd.risk && cmd.risk.indexOf('destructive') !== -1) facts.push('cannot be undone');
470
+ if (cmd.risk && cmd.risk.indexOf('costs-money') !== -1) facts.push('costs money');
471
+ if (cmd.persistence === 'external') facts.push('reaches outside FloLess');
472
+ return facts.join(' · ');
473
+ }
474
+
475
+ /* The risk pill, in plain English rather than the vocabulary's own words. Only
476
+ T2 gets one: T3 is roughly two-thirds of the list, and badging the majority
477
+ is its own kind of noise. */
478
+ function tagFor(cmd) {
479
+ var risk = cmd.risk || [];
480
+ if (risk.indexOf('destructive') !== -1) return { text: 'Irreversible', tone: 'destructive' };
481
+ if (risk.indexOf('costs-money') !== -1) return { text: 'Costs money', tone: 'costly' };
482
+ if (cmd.persistence === 'external') return { text: 'Leaves FloLess', tone: 'costly' };
483
+ if (cmd.persistence === 'approved') return { text: 'Changes the lock', tone: 'costly' };
484
+ return null;
485
+ }
486
+
487
+ /* What a search reads. The step text is included so "click the member end"
488
+ finds Add member — the sentences ARE how a user remembers a tool. The
489
+ internal vocabulary (id, persistence, interaction, guidance) is NOT: those
490
+ are our words, and matching them would surface hits a user cannot explain to
491
+ themselves. Risk flags are in, so "destructive" finds what it should. */
492
+ function matches(cmd, q) {
493
+ if (!q) return true;
494
+ var hay = [cmd.label, cmd.actsOn, cmd.group, cmd.key, cmd.why]
495
+ .concat(cmd.steps || [])
496
+ .concat(cmd.risk || [])
497
+ .join(' ').toLowerCase();
498
+ return hay.indexOf(q) !== -1;
499
+ }
500
+
501
+ /* Groups in the order the user meets them on screen, not alphabetically —
502
+ "where am I, what is near me" is the model the band's own hover explanations
503
+ already use. Anything unlisted sorts after, alphabetically.
504
+
505
+ This is the WITHIN-SURFACE order. Which surface comes first is decided at
506
+ render time from what is actually on screen (see onScreen/sheetEntries) —
507
+ a static array cannot express that, because "active" is runtime state. */
508
+ var GROUP_ORDER = [
509
+ // the shell
510
+ 'In the header', 'In the workflow picker', 'In the project picker',
511
+ 'In the project workspace', 'On the workflow canvas',
512
+ 'In the Narrative panel', 'In the node Inspect panel', 'In the Instructor strip',
513
+ 'In the ≡ menu', 'In the footer',
514
+ 'In the contract editor', 'In the report viewer', 'In the guide',
515
+ 'In the agent library', 'In the requests list', 'In the Routines dialog',
516
+ 'In the Report an issue dialog', 'In the Build an agent dialog', 'In the Bake dialog',
517
+ 'In the FloLess dialogs',
518
+ /* the steel editor — read top-left down, then the menus, then the dialogs.
519
+ The ⋯ menu is six groups rather than one because it is six accordion
520
+ sections on screen: a single 'In the ⋯ menu' would have been about thirty
521
+ rows under one heading, which is a scroll rather than a list. */
522
+ 'In the steel editor header', 'On the steel canvas', 'In the Copy panel', 'In the Copy array panel', 'On the 2D zoom bar',
523
+ 'In the 3D toolbar', 'In the 3D side panel', 'On the snap bar',
524
+ 'In the grid panel', 'In the Inspect panel',
525
+ 'In the Properties popup', 'In the snap override menu', 'In the dimension value popup', 'In the selection filter',
526
+ 'In the ⋯ menu',
527
+ 'In the ⋯ menu — Snapping', 'In the ⋯ menu — Display', 'In the ⋯ menu — Detailing',
528
+ 'In the ⋯ menu — Model checks', 'In the ⋯ menu — Coordinate system', 'In the ⋯ menu — Session',
529
+ 'In the steel editor dialogs', 'In the Generate views dialog', 'In the Details dialog', 'In the RFI dialog',
530
+ 'In the Connections dialog', 'In the reference-model dialogs', 'In the connection-import dialog',
531
+ 'In the confidence report', 'In the Ask AI dialog', 'In the Favourites dialog',
532
+ // the drawing filter
533
+ 'In the Drawing Filter header', 'In the Drawing Filter panel', 'On the Drawing Filter canvas',
534
+ // the vector editor, and its 3D viewer
535
+ 'In the Trace header', 'In the Trace panel', 'On the Trace canvas',
536
+ 'In the Trace — 3D header', 'On the Trace — 3D view',
537
+ ];
538
+ function groupRank(g) {
539
+ var i = GROUP_ORDER.indexOf(g);
540
+ return i === -1 ? GROUP_ORDER.length : i;
541
+ }
542
+
543
+ /* Which surface the user is looking at. A child reporter names itself; with no
544
+ child live, the shell is what is on screen.
545
+
546
+ Only ONE surface is ever visible: the contract-editor overlay that hosts
547
+ every child is `position: fixed; inset: 0` (app.css), so an open child hides
548
+ the shell's own header, picker and canvas entirely. That is why an on-screen
549
+ test is `surface === live` and not "shell plus the live child". */
550
+ function activeSurface() {
551
+ return (snapshot.child && snapshot.child.surface) || 'shell';
552
+ }
553
+ function onScreen(cmd) {
554
+ /* A command registered before `surface` existed would have none. Treating
555
+ that as on-screen keeps it visible rather than silently exiling it, and
556
+ verify-command-registry is what stops one being added. */
557
+ return !cmd.surface || cmd.surface === activeSurface();
558
+ }
559
+
560
+ function renderSheet() {
561
+ var q = ($sheetFilter.value || '').trim().toLowerCase();
562
+ var all = sheetEntries();
563
+ var hits = all.filter(function (c) { return matches(c, q); });
564
+
565
+ $sheetList.textContent = '';
566
+ sheetRows = [];
567
+ activeRow = -1;
568
+
569
+ if (!hits.length) {
570
+ var empty = document.createElement('div');
571
+ empty.className = 'cmd-sheet-empty';
572
+ // A zero-result search names a coverage gap, so it says so rather than
573
+ // shrugging — this is the one place a user can tell us what is missing.
574
+ empty.appendChild(document.createTextNode('Nothing matches '));
575
+ var b = document.createElement('b');
576
+ b.textContent = '“' + ($sheetFilter.value || '').trim() + '”';
577
+ empty.appendChild(b);
578
+ empty.appendChild(document.createTextNode('. If FloLess does this and it is not listed, that is a gap worth reporting.'));
579
+ $sheetList.appendChild(empty);
580
+ $sheetSub.textContent = 'No matches of ' + all.length;
581
+ return;
582
+ }
583
+
584
+ var lastGroup = null;
585
+ var dividedYet = false;
586
+ hits.forEach(function (cmd) {
587
+ /* One divider, at the first command that is not on this screen. The sort
588
+ has already put every on-screen command ahead of every other, so a
589
+ single boundary is all there is. */
590
+ if (!dividedYet && !onScreen(cmd)) {
591
+ dividedYet = true;
592
+ lastGroup = null; // the first group below the rule still needs its heading
593
+ var sep = document.createElement('div');
594
+ sep.className = 'cmd-elsewhere';
595
+ /* role=presentation: ARIA permits only option/group as owned children of a
596
+ listbox, and the per-row sr-only span is already how "where does this live"
597
+ is announced. Without it an AT can surface this text out of order, between
598
+ options it does not belong to. */
599
+ sep.setAttribute('role', 'presentation');
600
+ sep.textContent = 'Elsewhere in FloLess';
601
+ $sheetList.appendChild(sep);
602
+ }
603
+ var group = cmd.group || 'Elsewhere';
604
+ if (group !== lastGroup) {
605
+ lastGroup = group;
606
+ var h = document.createElement('div');
607
+ h.className = 'cmd-group';
608
+ h.setAttribute('role', 'presentation'); // same reason as the divider below
609
+ h.textContent = group;
610
+ $sheetList.appendChild(h);
611
+ }
612
+
613
+ var row = document.createElement('button');
614
+ row.type = 'button';
615
+ row.className = 'cmd-row';
616
+ row.id = 'cmd-row-' + cmd.id; // the aria-activedescendant target
617
+ row.setAttribute('role', 'option');
618
+ row.setAttribute('aria-selected', 'false');
619
+ row.dataset.commandId = cmd.id;
620
+
621
+ var label = document.createElement('span');
622
+ label.className = 'cmd-row-label';
623
+ label.textContent = cmd.label;
624
+ row.appendChild(label);
625
+
626
+ /* Where this command lives, for screen readers only. Arrow-key navigation
627
+ moves aria-activedescendant between rows, and a reader announces just the
628
+ focused option — never the .cmd-group heading or the divider beside it. So
629
+ a sighted user can see "this one is somewhere else" and a screen-reader
630
+ user could not. Folded into every row rather than only the ones below the
631
+ rule, because the orientation gap is the same for the existing groups. */
632
+ if (cmd.group) {
633
+ var where = document.createElement('span');
634
+ where.className = 'sr-only';
635
+ where.textContent = ' — ' + cmd.group;
636
+ row.appendChild(where);
637
+ }
638
+
639
+ var facts = factsFor(cmd);
640
+ if (facts) {
641
+ var f = document.createElement('span');
642
+ f.className = 'cmd-row-facts';
643
+ f.textContent = facts;
644
+ row.appendChild(f);
645
+ }
646
+
647
+ // T1: how many steps, in the muted mono register the app already uses for
648
+ // row metadata. Not a badge — it is information, not a warning.
649
+ if (cmd.tier === 'T1' && cmd.steps && cmd.steps.length > 1) {
650
+ var t = document.createElement('span');
651
+ t.className = 'cmd-row-tier';
652
+ t.textContent = cmd.steps.length + ' steps';
653
+ row.appendChild(t);
654
+ }
655
+
656
+ var tag = tagFor(cmd);
657
+ if (tag) {
658
+ var g = document.createElement('span');
659
+ g.className = 'cmd-row-tag';
660
+ g.dataset.tone = tag.tone;
661
+ g.textContent = tag.text;
662
+ row.appendChild(g);
663
+ }
664
+
665
+ if (cmd.key) {
666
+ var k = document.createElement('span');
667
+ k.className = 'cmd-row-key';
668
+ k.textContent = cmd.key.replace(/^Also:\s*/, '');
669
+ row.appendChild(k);
670
+ }
671
+
672
+ row.addEventListener('click', function () { activate(cmd); });
673
+ $sheetList.appendChild(row);
674
+ sheetRows.push(row);
675
+ });
676
+
677
+ $sheetSub.textContent = q
678
+ ? hits.length + ' of ' + all.length + ' commands'
679
+ : all.length + ' commands — this screen first';
680
+ }
681
+
682
+ /* Choosing a row takes you TO the control, when one is on screen. A list that
683
+ only described things would make the user find them again by hand. */
684
+ function activate(cmd) {
685
+ /* Look for the control OUTSIDE the sheet. The rows carry data-command-id
686
+ themselves (that is how a row knows what it is), so a naive query matches
687
+ the row you just clicked — and for any command with no live control on this
688
+ surface, such as every steel.* one while the editor is in an iframe, the
689
+ row is the ONLY match. The result was focusing a row inside a dialog that
690
+ had just been hidden. Visibility is checked too: a control in a closed
691
+ panel is found by a selector but cannot be focused. */
692
+ /* Concatenated, not escaped, and that is safe for a specific reason worth
693
+ stating: `cmd.id` can only be a registered id, and commands.js refuses to
694
+ register anything outside lowercase dotted-kebab — so it cannot contain a
695
+ quote to close the string or a backslash to start an escape.
696
+
697
+ The INSTANCE key is the half that comes from data (a member mark, a level
698
+ elevation like 16'-6"), and it deliberately never appears here: the second
699
+ arm matches on the `id#` PREFIX and lets the attribute selector's own
700
+ quoting cover whatever follows. So an instance containing a quote is a
701
+ problem only where it is WRITTEN INTO markup, never where it is read back.
702
+ Keep it that way — building a selector from a raw instance is the shape
703
+ that would break. */
704
+ var sel = '[data-command-id="' + cmd.id + '"], [data-command-id^="' + cmd.id + '#"]';
705
+ var live = null;
706
+ /* Which document the control was found in — carried so the entry can be stamped
707
+ with where the control LIVES rather than with whatever surface happened to be
708
+ on screen. A shell button stays alive (and focusable) under the child overlay,
709
+ so those two are genuinely different answers. */
710
+ var liveOrigin = 'shell';
711
+ Array.prototype.forEach.call(document.querySelectorAll(sel), function (el) {
712
+ if (live || (el.closest && el.closest('#command-sheet'))) return;
713
+ if (el.offsetParent || (el.getClientRects && el.getClientRects().length)) live = el;
714
+ });
715
+
716
+ /* Then the live child surface, if one is up. Searching only this document used
717
+ to be survivable because the unreachable commands sat at the BOTTOM of the
718
+ list — but the on-screen-first sort now hoists exactly those to the top
719
+ whenever a child is open, which would turn a documented tail case into the
720
+ first thing the user meets. The frame is same-origin and the shell already
721
+ holds a reference to it, so this is a lookup, not a new channel. */
722
+ /* `snapshot.child` is the guard, not just a null-check: it is the SAME report the
723
+ sort ordered by, so the frame searched here is always the surface whose commands
724
+ were promoted. Between a new frame's ready and its first report, activeReporterWindow
725
+ has moved on while snapshot.child is still null — ordering falls back to the shell,
726
+ and so must this. */
727
+ if (!live && activeReporterWindow && snapshot.child) {
728
+ try {
729
+ var doc = activeReporterWindow.document;
730
+ Array.prototype.forEach.call(doc.querySelectorAll(sel), function (el) {
731
+ // Same exclusion as above. No child renders a sheet today, but the rows are
732
+ // the one place a data-command-id describes a LIST ENTRY rather than a control,
733
+ // and half a rule is how that distinction gets lost.
734
+ if (live || (el.closest && el.closest('#command-sheet'))) return;
735
+ if (el.offsetParent || (el.getClientRects && el.getClientRects().length)) {
736
+ live = el;
737
+ liveOrigin = snapshot.child.surface || 'shell';
738
+ }
739
+ });
740
+ } catch (e) { /* torn down mid-lookup, or cross-origin one day */ }
741
+ }
742
+
743
+ closeSheet();
744
+ if (live && live.focus) {
745
+ if (live.scrollIntoView) live.scrollIntoView({ block: 'center' });
746
+ live.focus();
747
+ /* FALLS THROUGH when the control cannot be described, rather than returning.
748
+ focusFor() resolves upward through
749
+ `closest('button, [role="button"], a[href], input, select, textarea')`, and
750
+ three registered commands carry their id on a <label> whose <input> is a
751
+ DESCENDANT — filter.match-on and vector.show-kind — so the walk finds
752
+ nothing and it returns null. (That shape is deliberate: the id sits on the
753
+ label because that is what a screen reader names the control from.)
754
+
755
+ Returning here on a null entry would have left the PREVIOUS entry standing,
756
+ since setFocusEntry declines rather than assigning — reintroducing exactly
757
+ the stale-narration bug this commit exists to fix, one level down. Falling
758
+ through instead means the registry describes the command, which is a better
759
+ answer than the blank the old `snapshot.focus = focusFor(live)` produced. */
760
+ if (setFocusEntry(focusFor(live), liveOrigin)) {
761
+ paint();
762
+ return;
763
+ }
764
+ }
765
+
766
+ /* No control on screen — which is the NORMAL case for most of the list: every
767
+ menu.* command (the ≡ menu is display:none until opened), every steel.*
768
+ one (they live in an iframe), and anything registered without a
769
+ data-command-id in markup. Closing and doing nothing would make the
770
+ footer's "Enter — go to it" a promise the sheet breaks ~35 times out of 53.
771
+ So it puts the command's own entry in the band instead: the user still
772
+ learns what it does and where it lives, which is what they asked for. */
773
+ setFocusEntry({
774
+ label: cmd.label,
775
+ acts: cmd.actsOn ? cmd.actsOn.replace(/\{instance\}/g, 'the one you pick') : null,
776
+ group: cmd.group,
777
+ key: cmd.key,
778
+ tip: cmd.why || '',
779
+ disabled: false,
780
+ disabledReason: null,
781
+ commandId: cmd.id,
782
+ instance: null,
783
+ }, cmd.surface || 'shell');
784
+ paint();
785
+ }
786
+
787
+ function setActiveRow(next) {
788
+ if (!sheetRows.length) return;
789
+ if (activeRow >= 0 && sheetRows[activeRow]) {
790
+ sheetRows[activeRow].classList.remove('active');
791
+ sheetRows[activeRow].setAttribute('aria-selected', 'false');
792
+ }
793
+ activeRow = (next + sheetRows.length) % sheetRows.length;
794
+ var row = sheetRows[activeRow];
795
+ row.classList.add('active');
796
+ row.setAttribute('aria-selected', 'true');
797
+ // Focus stays in the filter box while the arrows move a highlight, so the
798
+ // only way a screen reader learns what is selected is activedescendant.
799
+ $sheetFilter.setAttribute('aria-activedescendant', row.id);
800
+ if (row.scrollIntoView) row.scrollIntoView({ block: 'nearest' });
801
+ }
802
+
803
+ /* Inertness. `inert` removes a subtree from the tab order, from pointer input
804
+ AND from the accessibility tree in one attribute — the aria-hidden +
805
+ pointer-events pair this app used before `inert` existed leaves the
806
+ background reachable by keyboard.
807
+
808
+ EVERY body child except the sheet, not just #app: #toast-container is a body
809
+ sibling too, and a toast carries a focusable close button, so inerting only
810
+ #app would let Tab walk out of the dialog into a toast. */
811
+ /* Restoring, not clearing. An earlier version set `inert = false` on every body
812
+ sibling when closing, which would have un-inerted anything that was ALREADY
813
+ inert before the sheet opened — this sheet is currently the only thing in the
814
+ app using `inert`, so it is latent rather than live, but "the second user of
815
+ inert silently breaks the first" is a bad thing to leave lying around. */
816
+ var inertBefore = null;
817
+
818
+ function setBackgroundInert(on) {
819
+ if (on) {
820
+ inertBefore = [];
821
+ Array.prototype.forEach.call(document.body.children, function (el) {
822
+ if (el === $sheet) return;
823
+ inertBefore.push([el, el.inert]);
824
+ el.inert = true;
825
+ });
826
+ return;
827
+ }
828
+ if (!inertBefore) return;
829
+ inertBefore.forEach(function (pair) { pair[0].inert = pair[1]; });
830
+ inertBefore = null;
831
+ }
832
+
833
+ function openSheet() {
834
+ if (!$sheet || sheetOpen || !enabled) return false;
835
+ /* Never stack on another dialog. Every .modal-backdrop here sits at the same
836
+ z-index (app.css records the bugs that caused), so a second one would be
837
+ ordered by DOM position rather than by what the user opened last. Declining
838
+ is the honest behaviour — `?` while a dialog is open is not a request to
839
+ bury it. */
840
+ if (document.querySelector('.modal-backdrop.show')) return false;
841
+
842
+ returnFocusTo = document.activeElement;
843
+ sheetOpen = true;
844
+ $sheet.hidden = false;
845
+ $sheet.classList.add('show');
846
+ setBackgroundInert(true);
847
+
848
+ /* If building the list throws, the background is already inert — and an app
849
+ nobody can focus is a far worse failure than a missing help sheet. So the
850
+ open unwinds itself rather than leaving the page dead to the keyboard. */
851
+ try {
852
+ $sheetFilter.value = '';
853
+ renderSheet();
854
+ $sheetFilter.focus();
855
+ } catch (e) {
856
+ closeSheet();
857
+ throw e; // still a bug worth seeing in the console, just not a fatal one
858
+ }
859
+ return true;
860
+ }
861
+
862
+ function closeSheet() {
863
+ if (!sheetOpen) return;
864
+ sheetOpen = false;
865
+ $sheet.classList.remove('show');
866
+ $sheet.hidden = true;
867
+ setBackgroundInert(false);
868
+ // Focus goes back where it came from. Dropping it on <body> is how a keyboard
869
+ // user gets stranded at the top of the document with no idea what happened.
870
+ if (returnFocusTo && returnFocusTo.focus && document.contains(returnFocusTo)) returnFocusTo.focus();
871
+ returnFocusTo = null;
872
+ }
873
+
874
+ function mountSheet() {
875
+ $sheet = document.getElementById('command-sheet');
876
+ if (!$sheet) return;
877
+ $sheetList = document.getElementById('cmd-sheet-list');
878
+ $sheetFilter = document.getElementById('cmd-sheet-filter');
879
+ $sheetSub = document.getElementById('cmd-sheet-sub');
880
+
881
+ document.getElementById('cmd-sheet-close').addEventListener('click', closeSheet);
882
+ var seeAll = document.getElementById('ix-all');
883
+ if (seeAll) seeAll.addEventListener('click', openSheet);
884
+
885
+ // Clicking the backdrop closes; clicking the dialog must not.
886
+ $sheet.addEventListener('mousedown', function (e) { if (e.target === $sheet) closeSheet(); });
887
+
888
+ $sheetFilter.addEventListener('input', renderSheet);
889
+
890
+ $sheet.addEventListener('keydown', function (e) {
891
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeSheet(); return; }
892
+ if (e.key === 'ArrowDown') { e.preventDefault(); setActiveRow(activeRow + 1); return; }
893
+ if (e.key === 'ArrowUp') { e.preventDefault(); setActiveRow(activeRow - 1); return; }
894
+ if (e.key === 'Enter' && activeRow >= 0 && sheetRows[activeRow]) {
895
+ e.preventDefault();
896
+ sheetRows[activeRow].click();
897
+ return;
898
+ }
899
+ /* Tab trapping. `inert` on the regions behind is what makes this short:
900
+ the only focusable things left are inside the dialog, so the trap only
901
+ has to wrap the two ends. */
902
+ if (e.key === 'Tab') {
903
+ var focusable = $sheet.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');
904
+ if (!focusable.length) return;
905
+ var first = focusable[0], last = focusable[focusable.length - 1];
906
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
907
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
908
+ }
909
+ });
910
+ }
911
+
912
+ /* ── public surface ───────────────────────────────────────────────────────
913
+ aware.js pushes workflow state in; nothing reads back out. */
914
+
915
+ var Instructor = {
916
+ guidanceFor: guidanceFor, // exported for tests — pure
917
+ setWorkflow: function (wf) {
918
+ var was = (snapshot.workflow && snapshot.workflow.name) || null;
919
+ var now = (wf && wf.name) || null;
920
+ snapshot.workflow = wf || null;
921
+ /* Only on a real CHANGE OF WORKFLOW, never on a status repaint. aware.js
922
+ calls this from paintRunState, which fires on every run-state tick — so
923
+ clearing unconditionally would yank an entry out from under someone the
924
+ moment a run progressed. Comparing the name is what makes it "you moved
925
+ on" rather than "something ticked".
926
+
927
+ `was` must be non-null too: the FIRST paint of the session goes null → a
928
+ name, which is the app arriving rather than the user leaving anything.
929
+ Someone who pressed `?` in that window (the band mounts on
930
+ DOMContentLoaded, before aware.js has painted run state) would otherwise
931
+ watch their answer vanish as the page finished loading.
932
+
933
+ Known limit, deliberately not chased: two workflows sharing a display
934
+ name read as "no change". aware.js sends only `name`, so telling them
935
+ apart would mean widening the payload for a case whose whole cost is one
936
+ stale entry the user can dismiss with Escape. */
937
+ if (snapshot.focus && was && was !== now) { snapshot.focus = null; }
938
+ paint();
939
+ },
940
+ explain: explainCurrent,
941
+ clear: clearFocusEntry,
942
+ childSnapshot: function () { return snapshot.child; },
943
+ isEnabled: function () { return enabled; },
944
+ setEnabled: setEnabled,
945
+ toggleEnabled: function () { setEnabled(!enabled); return enabled; },
946
+
947
+ /* Thin pass-throughs to commands.js, kept so callers and tests have one
948
+ import surface. The data lives there, not here. */
949
+ registerTemplate: function (id, meta) { return window.Commands && window.Commands.define(id, meta); },
950
+ templateIds: function () { return window.Commands ? window.Commands.ids() : []; },
951
+ resolve: function (el) { return resolveCommand(el); },
952
+ inventory: function (root) { return window.Commands ? window.Commands.inventory(root) : null; },
953
+ };
954
+
955
+ /* ── the bidirectional reporter seam ──────────────────────────────────────
956
+ A child surface (steel-editor.html and friends, same-origin iframes)
957
+ publishes a typed snapshot; the shell produces guidance and hands the
958
+ payload back. The child never derives guidance and never imports the
959
+ producer — that is what stops a second narrator appearing. */
960
+
961
+ var activeReporterWindow = null;
962
+
963
+ window.__instructorReady = function (childWin) {
964
+ /* Drop the outgoing frame's snapshot in the SAME step as adopting the new
965
+ reporter, so `activeReporterWindow` and `snapshot.child` always describe the
966
+ same document. In practice the old frame's pagehide has already cleared it —
967
+ but that is an ordering guarantee, and everything reading these two together
968
+ (the sheet's surface ordering, activate()'s child lookup and the origin it
969
+ stamps) would silently attribute the NEW frame's controls to the OLD surface
970
+ if it ever did not hold. One assignment is cheaper than depending on it.
971
+ Nothing is lost: the new reporter's first report is one macrotask away. */
972
+ if (childWin !== activeReporterWindow) snapshot.child = null;
973
+ activeReporterWindow = childWin;
974
+ };
975
+
976
+ window.__instructorReport = function (childSnap, childWin) {
977
+ // A stale frame must never narrate. Ignore anything that is no longer the
978
+ // live reporter, or whose document has been torn down / replaced.
979
+ if (activeReporterWindow && childWin !== activeReporterWindow) return;
980
+ try {
981
+ if (!childWin || childWin.closed) return;
982
+ if (!childWin.document || childWin.location.href === 'about:blank') return;
983
+ } catch (e) { return; }
984
+
985
+ snapshot.child = childSnap || null;
986
+ paint();
987
+
988
+ // shell → child: hand back what the producer made.
989
+ try {
990
+ var payload = guidanceFor(snapshot);
991
+ if (childWin.__instructor && typeof childWin.__instructor.receiveGuidance === 'function') {
992
+ childWin.__instructor.receiveGuidance(payload);
993
+ }
994
+ } catch (e) { /* frame went away mid-publish */ }
995
+ };
996
+
997
+ /* `?` / F1 pressed inside a child frame. A keydown in an iframe never reaches
998
+ this document, so a child forwards the key here rather than rendering a
999
+ second sheet of its own — one producer, one sheet, one list showing every
1000
+ command instead of two showing half each. Returns whether it was handled,
1001
+ so the child knows whether to preventDefault. */
1002
+ window.__instructorKey = function (key) {
1003
+ if (!enabled) return false;
1004
+ if (key !== '?' && key !== 'F1') return false;
1005
+ // A child's armed command already owns the band, so explaining a control the
1006
+ // shell has focus on would be the wrong answer — go straight to the list.
1007
+ return openSheet();
1008
+ };
1009
+
1010
+ // A frame that unloads stops being the reporter, so its last snapshot cannot
1011
+ // keep painting a surface the user has left.
1012
+ window.__instructorReporterGone = function (childWin) {
1013
+ if (childWin === activeReporterWindow) {
1014
+ // Read BEFORE clearing: this is the surface that just died, and the entry is
1015
+ // dropped only if it came from THAT one. "Anything not the shell" would also
1016
+ // throw away an answer about a different child, which cannot happen today but
1017
+ // is a rule that stops being true the moment two frames can be up at once.
1018
+ var gone = (snapshot.child && snapshot.child.surface) || null;
1019
+ activeReporterWindow = null;
1020
+ snapshot.child = null;
1021
+ /* An on-demand entry captured while that surface was up describes a control
1022
+ that has just gone with it — including a `disabled` flag read off the real
1023
+ element, which would otherwise keep asserting "Not available right now"
1024
+ about a document that no longer exists. Clearing `child` alone was not
1025
+ enough, because guidanceFor consults `focus` FIRST: the stale entry did
1026
+ not merely linger, it hid the workflow readout underneath it.
1027
+ Entries captured on the shell are left alone — nothing about them died, and
1028
+ a shell button stays live under the overlay, so this really is a different
1029
+ set from "captured while a child happened to be open".
1030
+
1031
+ Clearing SILENTLY, with no "what you were reading is gone" note, because the
1032
+ user pressed Close and the cause is already plain — the strip's own No-Echo
1033
+ rule (see controlGuidance) says not to state what the screen makes obvious.
1034
+ The accepted trade-off: a teardown the user did NOT initiate (an external
1035
+ write invalidating the surface, a forced reload) reads the same way, and
1036
+ nothing here can tell the two apart. Named rather than fixed — a
1037
+ "that vanished" notice would be new UI for a rare case. */
1038
+ if (snapshot.focus && gone && snapshot.focus.originSurface === gone) {
1039
+ snapshot.focus = null;
1040
+ }
1041
+ paint();
1042
+ }
1043
+ };
1044
+
1045
+ function mount() {
1046
+ $band = document.getElementById('instructor');
1047
+ if (!$band) return;
1048
+ $chip = $band.querySelector('.ix-chip');
1049
+ $parts = $band.querySelector('.ix-parts');
1050
+ $ask = $band.querySelector('.ix-ask');
1051
+ $toggle = $band.querySelector('.ix-toggle');
1052
+
1053
+ // Default ON: only the literal '0' turns it off, so a brand-new user (no key
1054
+ // at all) and a user whose storage is unreadable both get the Instructor.
1055
+ try { enabled = localStorage.getItem(ENABLED_KEY) !== '0'; } catch (e) { enabled = true; }
1056
+
1057
+ try { collapsed = localStorage.getItem(COLLAPSE_KEY) === '1'; } catch (e) { collapsed = false; }
1058
+ setCollapsed(collapsed);
1059
+ applyEnabled();
1060
+
1061
+ $toggle.addEventListener('click', function () { setCollapsed(!collapsed); });
1062
+
1063
+ $ask.addEventListener('click', function () {
1064
+ var subject = $ask.dataset.subject || '';
1065
+ var box = document.getElementById('chat-input') || document.querySelector('textarea');
1066
+ var prompt = 'Explain "' + subject + '" in FloLess — what it does and when I would use it.';
1067
+ if (box) {
1068
+ box.value = prompt;
1069
+ box.focus();
1070
+ } else if (navigator.clipboard) {
1071
+ navigator.clipboard.writeText(prompt);
1072
+ }
1073
+ });
1074
+
1075
+ document.addEventListener('mouseover', function (e) {
1076
+ var t = e.target instanceof Element ? e.target : null;
1077
+ if (t) { lastHovered = t; lastHoveredAt = Date.now(); }
1078
+ }, true);
1079
+
1080
+ document.addEventListener('keydown', function (e) {
1081
+ // `?` is the everyday route, but it MUST yield to typing — this is a
1082
+ // prompt-native product and a literal "?" in a search box wins.
1083
+ if (e.key === '?' && !e.ctrlKey && !e.metaKey && !e.altKey) {
1084
+ if (isTyping(e.target) || isTyping(document.activeElement)) return;
1085
+ // Explain what you are on; with nothing to explain, show everything.
1086
+ // Asking for help while pointing at nothing in particular is a
1087
+ // reasonable way to say "what CAN I do here?".
1088
+ if (explainCurrent() || openSheet()) e.preventDefault();
1089
+ return;
1090
+ }
1091
+
1092
+ // PHASE 0b finding: yielding to typing makes `?` unreachable inside every
1093
+ // searchable popover — including the workflow picker, which is exactly
1094
+ // where the generated rows live. F1 is unbound app-wide and is safe to
1095
+ // press while a text field has focus, so it is the second route.
1096
+ if (e.key === 'F1' && !e.ctrlKey && !e.metaKey && !e.altKey) {
1097
+ if (explainCurrent() || openSheet()) e.preventDefault();
1098
+ }
1099
+ });
1100
+
1101
+ // Escape drops the on-demand entry and returns to the project readout. The
1102
+ // sheet handles its own Escape and stops it here, so one press never both
1103
+ // closes the sheet and clears the entry behind it.
1104
+ document.addEventListener('keydown', function (e) {
1105
+ if (e.key === 'Escape' && !sheetOpen && snapshot.focus) clearFocusEntry();
1106
+ });
1107
+
1108
+ mountSheet();
1109
+ paint();
1110
+ }
1111
+
1112
+ if (document.readyState === 'loading') {
1113
+ document.addEventListener('DOMContentLoaded', mount);
1114
+ } else {
1115
+ mount();
1116
+ }
1117
+
1118
+ window.Instructor = Instructor;
1119
+ })();