@floless/app 0.151.0 → 0.152.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.
@@ -11,6 +11,13 @@
11
11
  dialog lists "Ready to approve" cards, "Needs you" rows, the downloads
12
12
  line and the consequence footnote; after the click, the results replace
13
13
  the cards in a live region.
14
+
15
+ While a check runs (it can take minutes: each tool download is its own
16
+ wait, see aware-aeco/aware#671) the dialog shows the server's own account
17
+ of it: the steps, which one is active, what it is on and how long it has
18
+ been on it. It asks for that at most once a second (a slow answer skips a
19
+ tick) and only while the dialog is open and a check is running; those
20
+ answers are shown, never applied as the view.
14
21
  ────────────────────────────────────────────────────────────────────────── */
15
22
  (function () {
16
23
  'use strict';
@@ -22,6 +29,8 @@
22
29
  var $title = document.getElementById('tool-updates-title');
23
30
  var $body = document.getElementById('tool-updates-body');
24
31
  var $live = document.getElementById('tool-updates-live');
32
+ var $progress = document.getElementById('tool-updates-progress');
33
+ var $announce = document.getElementById('tool-updates-announce');
25
34
  var $foot = document.getElementById('tool-updates-foot');
26
35
  var $check = document.getElementById('tool-updates-check');
27
36
  var $cancel = document.getElementById('tool-updates-cancel');
@@ -57,8 +66,185 @@
57
66
  return true;
58
67
  }
59
68
  var busy = false;
69
+ var checking = false; // the Check for updates request is in flight
60
70
  var returnFocus = null;
61
71
 
72
+ // ── A running check, as the server describes it ───────────────────────────────────────────────────────────
73
+ // The clock is deliberately here although the headless-run styling avoids one (web/app.css, "Headless runs (#571
74
+ // slice 3)"): that run has no progress signal, so a duration there would carry no meaning. This one is the time on a
75
+ // real step, which lets a person tell waiting from stuck. The page subtracts the server's epoch from its own clock,
76
+ // which holds because the page and the server are on the same machine.
77
+ var CLOCK_AFTER_SECONDS = 10; // quick steps stay quiet; a slow one starts showing how long it has taken
78
+ var MARKS = { done: '✓', problem: '!' };
79
+ var progress = null; // the server's progress record ({steps, since}) for the check running now (null before its first answer)
80
+ var lostContact = false; // the last ask for them got no answer: the clock then says nothing it cannot back
81
+ var paintedSteps = null;
82
+ var announced = null;
83
+ var announcedProblems = {};
84
+ var watchTimer = null;
85
+ var polling = false;
86
+ var rereading = false; // the view re-read after a background check ended is on its way
87
+ var pollSentAt = 0;
88
+ var pollController = null;
89
+ var watchGeneration = 0; // bumped whenever watching stops: an answer to an older ask belongs to nothing now
90
+ var POLL_PATIENCE_MS = 6000;
91
+
92
+ function checkInFlight() { return checking || !!(view && view.checking); }
93
+ function checkRunning() { return $modal.classList.contains('show') && checkInFlight(); }
94
+
95
+ function elapsedText(seconds) {
96
+ var nb = '\u00a0'; // never wraps between the number and its unit
97
+ if (seconds < 60) return seconds + nb + 's';
98
+ var minutes = Math.floor(seconds / 60);
99
+ var rest = seconds % 60;
100
+ var pad = function (n) { return (n < 10 ? '0' : '') + n; };
101
+ if (minutes < 60) return minutes + nb + 'min' + nb + pad(rest) + nb + 's';
102
+ return Math.floor(minutes / 60) + nb + 'h' + nb + pad(minutes % 60) + nb + 'min';
103
+ }
104
+
105
+ function paintClock() {
106
+ var clock = $progress.querySelector('.tool-updates-step-clock');
107
+ if (!clock) return;
108
+ // Hidden without a start time from the server, and while the server is not answering.
109
+ var seconds = progress && typeof progress.since === 'number' && !lostContact ? Math.max(0, Math.floor((Date.now() - progress.since) / 1000)) : -1;
110
+ clock.hidden = seconds < CLOCK_AFTER_SECONDS;
111
+ if (!clock.hidden) clock.textContent = elapsedText(seconds);
112
+ }
113
+
114
+ // What a screen reader hears: a step that did not do all it set out to, once; and the active step, when it or the item
115
+ // it is on changes. Never the clock, never a repeat.
116
+ function announce(steps) {
117
+ var parts = [];
118
+ steps.forEach(function (step) {
119
+ if (step.state !== 'problem') return;
120
+ var line = step.label + ': ' + (step.detail || 'did not finish');
121
+ if (announcedProblems[step.label] === line) return;
122
+ announcedProblems[step.label] = line;
123
+ parts.push(line);
124
+ });
125
+ var active = steps.filter(function (step) { return step.state === 'active'; })[0];
126
+ var sentence = active ? active.label + (active.detail ? ': ' + active.detail : '') : '';
127
+ if (sentence !== announced) {
128
+ announced = sentence;
129
+ if (sentence) parts.push(sentence);
130
+ }
131
+ if (parts.length) $announce.textContent = parts.join('. ');
132
+ }
133
+
134
+ function paintProgress() {
135
+ var steps = progress && Array.isArray(progress.steps) ? progress.steps : [];
136
+ var signature = JSON.stringify(steps) + '|' + lostContact;
137
+ // Rebuilt only when what it shows changes; the clock beside the active step ticks in place.
138
+ if (signature !== paintedSteps || !$progress.firstChild) {
139
+ $progress.textContent = '';
140
+ $progress.appendChild(el('div', 'tool-updates-progress-head', 'Checking for updates…'));
141
+ if (lostContact) $progress.appendChild(el('div', 'tool-updates-progress-lost', 'Lost contact with FloLess. Still trying…'));
142
+ if (steps.length) {
143
+ var list = el('ol', 'tool-updates-steps');
144
+ list.setAttribute('role', 'list');
145
+ steps.forEach(function (step) {
146
+ var row = el('li', 'tool-updates-step');
147
+ row.setAttribute('data-state', step.state);
148
+ if (step.state === 'active') row.setAttribute('aria-current', 'step');
149
+ var mark = el('span', 'tool-updates-step-mark', MARKS[step.state] || '');
150
+ mark.setAttribute('aria-hidden', 'true');
151
+ row.appendChild(mark);
152
+ row.appendChild(el('span', 'tool-updates-step-label', step.label));
153
+ if (step.state === 'active') {
154
+ var clock = el('span', 'tool-updates-step-clock');
155
+ clock.hidden = true;
156
+ clock.setAttribute('aria-hidden', 'true');
157
+ clock.setAttribute('data-tip', 'Time on this item so far');
158
+ row.appendChild(clock);
159
+ }
160
+ if (step.detail) row.appendChild(el('span', 'tool-updates-step-detail', step.detail));
161
+ list.appendChild(row);
162
+ });
163
+ $progress.appendChild(list);
164
+ }
165
+ paintedSteps = signature;
166
+ }
167
+ announce(steps);
168
+ paintClock();
169
+ }
170
+
171
+ /** One ask at a time: an older answer can never arrive after, and undo, a newer one. */
172
+ async function pollProgress() {
173
+ if (polling) return;
174
+ polling = true;
175
+ pollSentAt = Date.now();
176
+ var generation = watchGeneration;
177
+ var controller = new AbortController();
178
+ pollController = controller;
179
+ var body = null;
180
+ var failed = false;
181
+ try { body = await call('/api/tool-updates/progress', 'GET', undefined, controller.signal); } catch (error) { failed = true; }
182
+ // A 200 that is not the answer (a truncated or foreign body) is no contact either.
183
+ if (!failed && (!body || body.ok !== true || typeof body.checking !== 'boolean')) failed = true;
184
+ if (pollController === controller) { pollController = null; polling = false; }
185
+ // An answer to an ask from before the dialog was closed (or the check ended) belongs to nothing now.
186
+ if (generation !== watchGeneration || !checkRunning()) return;
187
+ if (failed) {
188
+ markLost();
189
+ } else {
190
+ lostContact = false;
191
+ // Shown, never applied: this is not the view (the view's ticket order belongs to the requests above). A pass that
192
+ // is queued behind another has no steps yet: the old ones go with it rather than freeze with a running clock.
193
+ if (body.checking) {
194
+ progress = body.progress || null;
195
+ } else {
196
+ progress = null; // nothing is running: no steps, and no clock counting on one
197
+ // A check that ended without this page asking (a background one): the page reads the view and repaints, one read at a time.
198
+ if (!checking && !rereading) {
199
+ rereading = true;
200
+ var readDone = function () { rereading = false; };
201
+ refresh().then(readDone, readDone);
202
+ }
203
+ }
204
+ }
205
+ paintProgress();
206
+ }
207
+
208
+ /** The server is not answering: warn once per episode, whichever way the page found out. */
209
+ function markLost() {
210
+ if (!lostContact) console.warn('tool update progress unavailable');
211
+ lostContact = true;
212
+ }
213
+
214
+ function stopWatching() {
215
+ if (watchTimer) { clearInterval(watchTimer); watchTimer = null; }
216
+ watchGeneration += 1;
217
+ if (pollController) { pollController.abort(); pollController = null; }
218
+ polling = false;
219
+ progress = null;
220
+ lostContact = false;
221
+ paintedSteps = null;
222
+ announcedProblems = {};
223
+ $progress.textContent = '';
224
+ $announce.textContent = '';
225
+ }
226
+
227
+ /** Shows the panel exactly while a check runs in an open dialog, and asks the server how it is going. */
228
+ function syncProgress() {
229
+ var on = checkRunning();
230
+ $progress.hidden = !on;
231
+ if (on) $modal.setAttribute('data-checking', ''); else $modal.removeAttribute('data-checking');
232
+ if (!on) { stopWatching(); return; }
233
+ paintProgress();
234
+ if (watchTimer) return;
235
+ watchTimer = setInterval(function () {
236
+ // An ask that has not come back for a while is the server not answering, not a slow step: say so, give that ask
237
+ // up (it would otherwise hold every later one back for ever) and ask again on the next tick.
238
+ if (polling && Date.now() - pollSentAt > POLL_PATIENCE_MS) {
239
+ if (!lostContact) { markLost(); paintProgress(); }
240
+ if (pollController) pollController.abort();
241
+ }
242
+ paintClock();
243
+ void pollProgress();
244
+ }, 1000);
245
+ void pollProgress();
246
+ }
247
+
62
248
  function el(tag, cls, text) {
63
249
  var node = document.createElement(tag);
64
250
  if (cls) node.className = cls;
@@ -68,8 +254,8 @@
68
254
 
69
255
  function plural(n, one, many) { return n + ' ' + (n === 1 ? one : many); }
70
256
 
71
- async function call(path, method, payload) {
72
- var res = await fetch(path, { method: method || 'GET', headers: { 'content-type': 'application/json' }, body: payload });
257
+ async function call(path, method, payload, signal) {
258
+ var res = await fetch(path, { method: method || 'GET', headers: { 'content-type': 'application/json' }, body: payload, signal: signal });
73
259
  var body = await res.json().catch(function () { return { ok: false, error: 'FloLess received an unreadable answer (HTTP ' + res.status + ').' }; });
74
260
  if (!res.ok && body.ok !== true && !body.results) {
75
261
  var error = new Error(body.error || ('HTTP ' + res.status));
@@ -341,6 +527,7 @@
341
527
  function paint() {
342
528
  var keepFocus = focusKey();
343
529
  try { paintNow(); } finally { restoreFocus(keepFocus); }
530
+ syncProgress();
344
531
  }
345
532
 
346
533
  function paintNow() {
@@ -404,7 +591,8 @@
404
591
 
405
592
  function setBusy(on, label) {
406
593
  busy = on;
407
- $modal.setAttribute('aria-busy', on ? 'true' : 'false');
594
+ // Not while a check runs: a busy dialog can make a screen reader hold back the step announcements inside it.
595
+ $modal.setAttribute('aria-busy', on && !checking ? 'true' : 'false');
408
596
  [$check, $cancel, $approve].forEach(function (b) { b.disabled = on; });
409
597
  Array.prototype.forEach.call($body.querySelectorAll('[data-command-id="shell.tool-updates-forget-folder"]'), function (b) { b.disabled = on || !!forgetting; });
410
598
  if (on && label) $approve.textContent = label;
@@ -421,6 +609,7 @@
421
609
  if ($modal.classList.contains('show') && !busy) $live.textContent = 'FloLess could not check for tool updates just now. What is shown is from the last check.';
422
610
  }
423
611
  paintPill();
612
+ syncProgress();
424
613
  }
425
614
 
426
615
  function open(fromEl) {
@@ -429,6 +618,7 @@
429
618
  $live.textContent = '';
430
619
  paint();
431
620
  $modal.classList.add('show');
621
+ syncProgress();
432
622
  // Focus the title, not the primary: approving is consequential and Enter on open must not do it.
433
623
  setTimeout(function () { $title.focus(); }, 0);
434
624
  void refresh().then(function () { if ($modal.classList.contains('show') && !busy && !results) paint(); });
@@ -437,6 +627,7 @@
437
627
  function close() {
438
628
  if (busy) return;
439
629
  $modal.classList.remove('show');
630
+ syncProgress();
440
631
  if (results) { results = null; }
441
632
  if (returnFocus && document.contains(returnFocus)) returnFocus.focus();
442
633
  returnFocus = null;
@@ -460,8 +651,10 @@
460
651
  });
461
652
 
462
653
  $check.addEventListener('click', async function () {
654
+ checking = true;
463
655
  setBusy(true);
464
- $live.textContent = 'Checking for new tool versions…';
656
+ $live.textContent = ''; // the panel below says what is being checked; the live line is for what came of it
657
+ syncProgress();
465
658
  try {
466
659
  var ticket = nextTicket();
467
660
  var answer = await call('/api/tool-updates/check', 'POST');
@@ -474,6 +667,7 @@
474
667
  } catch (error) {
475
668
  $live.textContent = error.message;
476
669
  } finally {
670
+ checking = false;
477
671
  setBusy(false);
478
672
  paint();
479
673
  paintPill();
@@ -0,0 +1,197 @@
1
+ /* Saved-directory declarations change registration, never the folder's contents. */
2
+ (() => {
3
+ const modal = document.getElementById('workspace-root-modal');
4
+ if (!modal) return;
5
+ const instructorNote = document.getElementById('workspace-root-instructor-note');
6
+ window.flolessWorkspaceRootInstructorExplain = (guidance) => {
7
+ if (!instructorNote || !modal.classList.contains('show') || !Array.isArray(guidance?.parts)) return;
8
+ const chip = document.createElement('span'); chip.className = 'ix-chip'; chip.textContent = guidance.chip || '';
9
+ const parts = document.createElement('div'); parts.className = 'workspace-root-instructor-parts';
10
+ guidance.parts.forEach((part, index) => {
11
+ if (index) parts.append(document.createTextNode(' · '));
12
+ const segment = document.createElement('span'); segment.textContent = part; parts.append(segment);
13
+ });
14
+ instructorNote.replaceChildren(chip, parts); instructorNote.dataset.commandId = guidance.commandId || ''; instructorNote.hidden = false;
15
+ };
16
+ window.flolessWorkspaceRootInstructorClear = () => {
17
+ if (!instructorNote) return;
18
+ instructorNote.hidden = true; instructorNote.replaceChildren(); delete instructorNote.dataset.commandId;
19
+ };
20
+ const mount = document.createElement('section');
21
+ mount.className = 'workspace-root-management'; mount.tabIndex = -1;
22
+ modal.querySelector('#workspace-root-status').after(mount);
23
+ const heading = document.createElement('h3'); heading.textContent = 'Saved directories';
24
+ const status = document.createElement('div'); status.className = 'workspace-root-management-message'; status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
25
+ const alert = document.createElement('div'); alert.className = 'workspace-root-error'; alert.setAttribute('role', 'alert');
26
+ const content = document.createElement('div'); mount.append(heading, status, alert, content);
27
+ const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
28
+ let data = null, step = null, busy = false, message = '', problem = '', request = 0, reviewRequest = 0;
29
+ let sessionReady = null;
30
+ const existing = ['workspace-root-cancel', 'workspace-root-change', 'workspace-root-use'].map((id) => document.getElementById(id));
31
+ const disabledBefore = new Map();
32
+ const carriers = {
33
+ 'shell.workspace-root-stop-using': (row) => `data-command-id="shell.workspace-root-stop-using#${esc(row.rootId)}" data-command-instance-label="${esc(row.path)}"`,
34
+ 'shell.workspace-root-destination': (row) => `data-command-id="shell.workspace-root-destination#${esc(row.rootId)}" data-command-instance-label="${esc(row.path)}"`,
35
+ 'shell.workspace-root-choose-destination': 'data-command-id="shell.workspace-root-choose-destination"',
36
+ 'shell.workspace-root-confirm-retirement': (row) => `data-command-id="shell.workspace-root-confirm-retirement#${esc(row.rootId)}" data-command-instance-label="${esc(row.path)}"`,
37
+ 'shell.workspace-root-restore-registration': (row) => `data-command-id="shell.workspace-root-restore-registration#${esc(row.rootId)}" data-command-instance-label="${esc(row.path)}"`,
38
+ 'shell.workspace-root-confirm-restoration': (row) => `data-command-id="shell.workspace-root-confirm-restoration#${esc(row.rootId)}" data-command-instance-label="${esc(row.path)}"`,
39
+ 'shell.dialog-cancel#the directory registration': 'data-command-id="shell.dialog-cancel#the directory registration"',
40
+ };
41
+ async function api(path, body) {
42
+ if (!sessionReady) sessionReady = (async () => {
43
+ // Bootstrap once for this dialog. Renewing a cookie between review and recording
44
+ // would change the local decision's session identity.
45
+ const response = await fetch('/api/editor/session', { method: 'POST', credentials: 'same-origin' });
46
+ const result = await response.json().catch(() => null);
47
+ if (!response.ok && !(response.status === 403 && result?.error === 'editor_session_unavailable')) {
48
+ throw new Error('The local browser session could not be opened. Close this dialog and open it again.');
49
+ }
50
+ })();
51
+ await sessionReady;
52
+ const response = await fetch(path, { credentials: 'same-origin', headers: { 'content-type': 'application/json' },
53
+ ...(body === undefined ? {} : { method: 'POST', body: JSON.stringify(body) }) });
54
+ const result = await response.json();
55
+ if (!response.ok || result.ok === false) throw new Error(result.error || 'FloLess could not review this directory. Try again.');
56
+ return result;
57
+ }
58
+ function button(action, text, command, attrs = '', row = null) {
59
+ return `<button type="button" data-registration-action="${esc(action)}" ${typeof carriers[command] === 'function' ? carriers[command](row) : carriers[command]} ${attrs}${busy ? ' disabled data-blocked-reason="The directory choice is being recorded."' : ''}>${text}</button>`;
60
+ }
61
+ function render() {
62
+ const focused = document.activeElement?.closest('[data-registration-action]');
63
+ const focusKey = focused && content.contains(focused) ? { action: focused.dataset.registrationAction, rootId: focused.dataset.rootId } : null;
64
+ modal.classList.toggle('workspace-root-management-reviewing', !!step);
65
+ status.textContent = message; status.hidden = !message;
66
+ alert.textContent = problem; alert.hidden = !problem;
67
+ let html = '';
68
+ if (!data) html += '<p class="workspace-root-management-note">Checking saved directories…</p>';
69
+ else if (!step) {
70
+ html += '<div class="workspace-root-management-list">';
71
+ for (const row of data.roots) {
72
+ const different = !row.observation.available && row.observation.filesystemId && row.observation.markerId;
73
+ const state = row.retirement ? `Stopped · ${new Date(row.retirement.at).toLocaleDateString()}`
74
+ : row.rootId === data.activeRootId ? `In use${row.observation.available ? '' : ' · Unavailable'}`
75
+ : row.observation.available ? 'Available' : different ? 'Different folder at this path' : 'Unavailable';
76
+ html += `<div class="workspace-root-management-row"><div><code data-tip="${esc(row.path)}">${esc(row.path)}</code>` +
77
+ `<span class="workspace-root-management-state${!row.observation.available ? ' is-unavailable' : ''}">${esc(state)}</span></div>`;
78
+ if (row.retirement && row.observation.available) html += button('restore', 'Restore…', 'shell.workspace-root-restore-registration', `data-root-id="${esc(row.rootId)}" `, row);
79
+ else if (!row.retirement && !row.observation.available) html += button('retire', 'Stop using…', 'shell.workspace-root-stop-using', `data-root-id="${esc(row.rootId)}" `, row);
80
+ html += '</div>';
81
+ }
82
+ html += '</div><p class="workspace-root-management-note">Stopped directories keep their place reserved. FloLess does not look inside them for projects until you restore their registration.</p>';
83
+ } else {
84
+ html += `<h4>${step.action === 'restore' ? 'Restore this directory and switch?' : 'Stop using this directory?'}</h4>` +
85
+ `<code class="workspace-root-management-target" data-tip="${esc(step.row.path)}">${esc(step.row.path)}</code>` +
86
+ `<p class="workspace-root-management-note">${step.action === 'restore'
87
+ ? 'FloLess will verify the original folder, resume looking inside it for projects, and switch to it. Your files stay where they are, and the current directory stays registered.'
88
+ : 'Your files stay where they are. While stopped, FloLess will not look inside this directory for projects. Its place stays reserved. If the original folder comes back, you can restore its registration. If the Revit or Tekla Parser uses an approved model from a project in this directory, its next setup can leave that model out. Choose Cancel to keep this directory as it is.'}</p>`;
89
+ if (step.action === 'retire' && step.row.rootId === data.activeRootId) {
90
+ html += '<p class="workspace-root-management-note">Switch to:</p><div class="workspace-root-management-destinations">';
91
+ for (const row of data.roots.filter((row) => row.rootId !== step.row.rootId && !row.retirement && row.observation.available)) {
92
+ html += button('destination', `<code>${esc(row.path)}</code>`, 'shell.workspace-root-destination',
93
+ `class="workspace-root-management-choice" data-root-id="${esc(row.rootId)}" aria-pressed="${step.destinationRootId === row.rootId}" data-tip="${esc(row.path)}" `, row);
94
+ }
95
+ html += button('choose', 'Choose another folder…', 'shell.workspace-root-choose-destination') + '</div>';
96
+ if (step.destinationPath) html += `<p class="workspace-root-management-note">Selected: <code>${esc(step.destinationPath)}</code></p>`;
97
+ }
98
+ const label = step.action === 'restore' ? 'Restore and switch' : step.row.rootId === data.activeRootId ? 'Stop using it and switch' : 'Stop using this directory';
99
+ html += '<div class="workspace-root-management-actions modal-actions">' + button('back', 'Cancel', 'shell.dialog-cancel#the directory registration') +
100
+ (step.failed && (step.action === 'restore' || step.row.rootId !== data.activeRootId)
101
+ ? button(step.action, 'Review again', step.action === 'restore' ? 'shell.workspace-root-restore-registration' : 'shell.workspace-root-stop-using', `data-root-id="${esc(step.row.rootId)}" data-review-again `, step.row) : '') +
102
+ button('confirm', label, step.action === 'restore' ? 'shell.workspace-root-confirm-restoration' : 'shell.workspace-root-confirm-retirement',
103
+ `${step.action === 'restore' ? 'class="primary" ' : 'class="danger" '}${!step.previewId && !busy ? `disabled data-blocked-reason="${step.checking ? 'FloLess is checking this directory.' : step.failed && (step.action === 'restore' || step.row.rootId !== data.activeRootId) ? 'Choose Review again first.' : 'Choose where to switch first.'}" ` : ''}`, step.row) + '</div>';
104
+ }
105
+ content.innerHTML = html;
106
+ if (focusKey) [...content.querySelectorAll('[data-registration-action]')].find((control) => control.dataset.registrationAction === focusKey.action && control.dataset.rootId === focusKey.rootId)?.focus();
107
+ const carrier = document.activeElement?.closest('[data-command-id]');
108
+ if (carrier && modal.contains(carrier)) window.Instructor?.refreshCarrier(carrier);
109
+ }
110
+ async function refresh() {
111
+ const generation = ++request;
112
+ try { const result = await api('/api/workspace-root/registrations'); if (generation !== request) return; data = result; render(); }
113
+ catch (error) { if (generation !== request) return; problem = error.message; render(); }
114
+ }
115
+ function setBusy(value) {
116
+ busy = value;
117
+ if (value) {
118
+ mount.focus(); mount.setAttribute('aria-busy', 'true');
119
+ for (const control of existing) { disabledBefore.set(control, control.disabled); control.disabled = true; control.setAttribute('data-blocked-reason', 'The directory choice is being recorded.'); }
120
+ } else {
121
+ for (const control of existing) { control.disabled = disabledBefore.get(control) ?? control.disabled; control.removeAttribute('data-blocked-reason'); }
122
+ disabledBefore.clear(); mount.removeAttribute('aria-busy');
123
+ }
124
+ render();
125
+ }
126
+ function back() {
127
+ if (busy) return;
128
+ const rootId = step?.row.rootId;
129
+ step = null; message = ''; problem = ''; render(); mount.querySelector(`[data-root-id="${rootId}"]`)?.focus();
130
+ }
131
+ async function review(extra = {}) {
132
+ const current = step, generation = ++reviewRequest;
133
+ current.previewId = null; current.destinationRootId = undefined; current.destinationPath = undefined; current.checking = true; current.failed = false; render();
134
+ let result;
135
+ try { result = await api('/api/workspace-root/retirement-preview', { rootId: current.row.rootId, action: current.action, ...extra }); }
136
+ catch (error) { if (step !== current || generation !== reviewRequest) return; current.checking = false; throw error; }
137
+ if (step !== current || generation !== reviewRequest) return;
138
+ step.checking = false; step.previewId = result.previewId; step.destinationPath = result.preview?.destinationPath; step.destinationRootId = extra.destinationRootId;
139
+ render(); mount.querySelector('[data-registration-action="back"]')?.focus();
140
+ }
141
+ mount.addEventListener('click', async (event) => {
142
+ const control = event.target.closest('[data-registration-action]');
143
+ if (!control || busy) return;
144
+ const action = control.dataset.registrationAction; message = ''; problem = '';
145
+ try {
146
+ if (action === 'back') return back();
147
+ if (action === 'retire' || action === 'restore') {
148
+ step = { action, row: data.roots.find((row) => row.rootId === control.dataset.rootId) };
149
+ render(); mount.querySelector('[data-registration-action="back"]')?.focus();
150
+ if (action === 'restore' || step.row.rootId !== data.activeRootId) await review();
151
+ } else if (action === 'destination') await review({ destinationRootId: control.dataset.rootId });
152
+ else if (action === 'choose') {
153
+ const current = step, generation = ++reviewRequest;
154
+ current.previewId = null; current.destinationRootId = undefined; current.destinationPath = undefined; render();
155
+ const native = await api('/api/workspace-root/choose', {});
156
+ if (step !== current || generation !== reviewRequest || native.cancelled) return;
157
+ if (!native.selectionId) throw new Error('Choose a different working directory to switch to.');
158
+ await review({ selectionId: native.selectionId });
159
+ } else if (action === 'confirm' && step?.previewId) {
160
+ setBusy(true);
161
+ const result = await api('/api/workspace-root/retirement-confirm', { previewId: step.previewId });
162
+ step = null;
163
+ message = `Your choice was recorded from this FloLess window at ${new Date(result.recordedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}.`;
164
+ await window.flolessWorkspaceRoot?.refresh(); await refresh();
165
+ }
166
+ } catch (error) { problem = error.message; if (step) { step.previewId = null; step.failed = true; step.checking = false; } }
167
+ finally {
168
+ if (busy) setBusy(false); else render();
169
+ if (problem && step) {
170
+ (['destination', 'choose'].includes(action) ? mount.querySelector('[data-registration-action="choose"]') : mount.querySelector('[data-review-again]') || mount.querySelector('[data-registration-action="back"]'))?.focus();
171
+ } else if (action === 'confirm' && !step) existing[0]?.focus();
172
+ const carrier = document.activeElement?.closest('[data-command-id]');
173
+ if (carrier && modal.contains(carrier)) window.Instructor?.refreshCarrier(carrier);
174
+ }
175
+ });
176
+ modal.addEventListener('click', (event) => {
177
+ if (busy && (event.target === modal || existing.some((control) => control.contains(event.target)))) { event.preventDefault(); event.stopImmediatePropagation(); }
178
+ else if (step && (event.target === modal || event.target === existing[0])) { event.preventDefault(); event.stopImmediatePropagation(); back(); }
179
+ }, true);
180
+ document.addEventListener('keydown', (event) => {
181
+ if (!modal.classList.contains('show') || event.key !== 'Escape' || (!step && !busy)) return;
182
+ event.preventDefault(); event.stopImmediatePropagation(); if (!busy) back();
183
+ }, true);
184
+ let shown = modal.classList.contains('show');
185
+ new MutationObserver(() => {
186
+ const open = modal.classList.contains('show');
187
+ if (open && !shown) { sessionReady = null; step = null; message = ''; problem = ''; void refresh(); }
188
+ if (!open && shown) {
189
+ if (instructorNote && !instructorNote.hidden) window.Instructor?.clear();
190
+ window.flolessWorkspaceRootInstructorClear();
191
+ }
192
+ shown = open;
193
+ })
194
+ .observe(modal, { attributes: true, attributeFilter: ['class'] });
195
+ window.addEventListener('floless:workspace-root-state', () => { if (shown && !busy) void refresh(); });
196
+ render();
197
+ })();