@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.2

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.
package/client.js CHANGED
@@ -23,624 +23,649 @@
23
23
  *
24
24
  * Bundled for the DSH client loader; no rendering, no slots.
25
25
  */
26
- window.__ModuleLoader__.load({
27
- id: '@thready-web/dsh-bot-plugin',
28
- factory: (require) => {
29
- var module = { exports: {} };
30
- var exports = module.exports;
31
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
32
-
33
- /** Hash segment naming a Session. */
34
- const SEG_SESSION = 's';
35
- /** Hash segment naming a main panel. */
36
- const SEG_PANEL = 'p';
37
- /** Hash segment naming how many overlays are stacked above the view. */
38
- const SEG_OVERLAY = 'o';
39
- /** How long after a history event echoes are folded into `replaceState`. */
40
- const SETTLE_MS = 1500;
41
- /**
42
- * How long a deep link keeps reasserting itself while the app boots. The
43
- * workspace restores its persisted Session asynchronously once both the
44
- * Workspace and Session catalogs are ready, which over a slow link can
45
- * take a few seconds.
46
- */
47
- const BOOT_MS = 8000;
48
- /** Attempts allowed per deep-link segment before it is abandoned. */
49
- const BOOT_TRIES = 3;
50
- /** The core's own modal dialogs: a portal on `body`, topmost last. */
51
- const DIALOG_SELECTOR = '[role="dialog"][aria-modal="true"]';
52
- /** Overlay depth is capped so a runaway stack cannot fill the address bar. */
53
- const MAX_OVERLAY = 9;
54
- /** A batch of DOM mutations settles this long before the overlay is measured. */
55
- const SCAN_DEBOUNCE_MS = 80;
56
- /** Fallback poll for overlay changes no mutation reports (column expansion). */
57
- const SCAN_INTERVAL_MS = 350;
58
- /** One overlay close gets this long to commit before the next step. */
59
- const CLOSE_STEP_MS = 40;
60
- /** Close steps allowed for one Back press. */
61
- const CLOSE_TRIES = 12;
62
- /** Our own `history.back()` gets this long to land before it is given up on. */
63
- const BACK_MS = 1200;
64
- /** Key of the marker this plugin keeps in `history.state`. */
65
- const STATE_KEY = '__dshUiRouter';
66
-
67
- /**
68
- * @param value - value to escape.
69
- * @returns the escaped segment.
70
- */
71
- function encodeSegment(value) {
72
- try {
73
- return encodeURIComponent(value);
74
- } catch (_error) {
75
- return value;
76
- }
77
- }
78
-
79
- /**
80
- * @param value - escaped segment.
81
- * @returns the decoded segment.
82
- */
83
- function decodeSegment(value) {
84
- try {
85
- return decodeURIComponent(value);
86
- } catch (_error) {
87
- return value;
88
- }
89
- }
90
-
91
- /**
92
- * Read a route out of a location hash.
93
- * @param hash - `location.hash`, with or without the leading `#`.
94
- * @returns the session id (undefined when absent), the panel id (null when
95
- * absent) and the overlay depth (0 when absent).
96
- */
97
- function parseHash(hash) {
98
- const route = { sessionId: void 0, panelId: null, overlay: 0 };
99
- if (typeof hash !== 'string' || hash.length === 0) return route;
100
- const parts = hash
101
- .replace(/^#/, '')
102
- .split('/')
103
- .filter((segment) => segment.length > 0)
104
- .map(decodeSegment);
105
- for (let index = 0; index + 1 < parts.length; index += 2) {
106
- const key = parts[index];
107
- const value = parts[index + 1];
108
- if (key === SEG_SESSION && value.length > 0) route.sessionId = value;
109
- else if (key === SEG_PANEL && value.length > 0) route.panelId = value;
110
- else if (key === SEG_OVERLAY) {
111
- const depth = Number.parseInt(value, 10);
112
- if (Number.isFinite(depth) && depth > 0) route.overlay = Math.min(depth, MAX_OVERLAY);
113
- }
114
- }
115
- return route;
116
- }
117
-
118
- /**
119
- * @param route - session id, panel id and overlay depth.
120
- * @returns the hash for that route, empty when nothing is addressable.
121
- */
122
- function formatHash(route) {
123
- const segments = [];
124
- if (typeof route.sessionId === 'string' && route.sessionId.length > 0) segments.push(SEG_SESSION, encodeSegment(route.sessionId));
125
- if (typeof route.panelId === 'string' && route.panelId.length > 0) segments.push(SEG_PANEL, encodeSegment(route.panelId));
126
- if (typeof route.overlay === 'number' && route.overlay > 0) segments.push(SEG_OVERLAY, String(Math.min(route.overlay, MAX_OVERLAY)));
127
- return segments.length === 0 ? '' : '#/' + segments.join('/');
128
- }
129
-
130
- /** Services required from the client runtime. */
131
- exports.inject = ['layout', 'uiWorkspace'];
132
-
133
- /**
134
- * Mirror the active Session, main panel and overlay stack into the URL and
135
- * drive them from it.
136
- * @param ctx - client plugin context.
137
- */
138
- function apply(ctx) {
139
- if (typeof window === 'undefined' || window.location === void 0 || window.history === void 0) return;
140
- const location = window.location;
141
- const history = window.history;
142
-
143
- const layout = ctx.layout;
144
- const workspace = ctx.uiWorkspace;
145
- const panelInfo = layout.panelInfo;
146
- const selection = workspace.selection;
147
- const sessionList = workspace.sessions.list;
148
-
149
- /** The route the page was opened with; consumed one item at a time. */
150
- const boot = parseHash(location.hash);
151
- let bootSession = boot.sessionId;
152
- let bootPanel = boot.panelId;
153
- const bootUntil = Date.now() + BOOT_MS;
154
- let sessionTries = 0;
155
- let panelTries = 0;
156
- /** False until the boot route has been applied (or given up on). */
157
- let live = false;
158
- /** Echoes until this timestamp rewrite the URL in place. */
159
- let settleUntil = Date.now() + SETTLE_MS;
160
- /** A deferred `sync` is pending. */
161
- let queued = false;
162
- /** Overlay depth the current history entry is believed to describe. */
163
- let publishedOverlay = boot.overlay;
164
- /** Non-zero while our own `history.back()` is in flight. */
165
- let backAt = 0;
166
- /** Overlay depth a Back press asked for, while the closes run. */
167
- let settleTarget = null;
168
- /** Pending debounced overlay scan. */
169
- let scanTimer = 0;
170
-
171
- /** @returns the current app route. */
172
- const readRoute = () => ({
173
- sessionId: selection.getSnapshot().sessionId,
174
- panelId: panelInfo.getSnapshot().activePanelId
175
- });
176
-
177
- const currentUrl = () => location.pathname + location.search + location.hash;
178
-
179
- /**
180
- * @param route - target route.
181
- * @returns the absolute URL for it, keeping path and query.
182
- */
183
- const urlFor = (route) => location.pathname + location.search + formatHash(route);
184
-
185
- /** @returns the right-column service, or undefined when it is not mounted. */
186
- const sidebarRight = () => {
187
- if (typeof ctx.get !== 'function') return void 0;
188
- try {
189
- return ctx.get('sidebarRight');
190
- } catch (_error) {
191
- return void 0;
192
- }
193
- };
194
-
195
- /** @returns the marker this plugin left on the current history entry. */
196
- const entryTag = () => {
197
- let state;
198
- try {
199
- state = history.state;
200
- } catch (_error) {
201
- return void 0;
202
- }
203
- if (state === null || typeof state !== 'object') return void 0;
204
- const tag = state[STATE_KEY];
205
- return tag !== null && typeof tag === 'object' ? tag : void 0;
206
- };
207
-
208
- /**
209
- * @param tag - marker to record.
210
- * @returns the state object to write, keeping whatever the page already stored.
211
- */
212
- const withTag = (tag) => {
213
- let state;
214
- try {
215
- state = history.state;
216
- } catch (_error) {
217
- state = null;
218
- }
219
- const base = state !== null && typeof state === 'object' ? { ...state } : {};
220
- base[STATE_KEY] = tag;
221
- return base;
222
- };
223
-
224
- /**
225
- * Write the route into the address bar.
226
- * @param route - route to publish.
227
- * @param mode - `push` for a new entry, `replace` to rewrite in place.
228
- * @param kind - why the entry exists: `overlay` for one this plugin opened
229
- * for an overlay, `route` for a Session / panel move or a rewrite.
230
- */
231
- const publish = (route, mode, kind) => {
232
- publishedOverlay = route.overlay;
233
- const url = urlFor(route);
234
- if (url === currentUrl()) return;
235
- const state = withTag({ kind, depth: route.overlay });
236
- try {
237
- if (mode === 'replace') history.replaceState(state, '', url);
238
- else history.pushState(state, '', url);
239
- } catch (_error) {
240
- /* History may be unavailable in a sandboxed frame; the app still works. */
241
- }
242
- };
243
-
244
- /** @returns the dialogs the core currently shows, topmost last. */
245
- const visibleDialogs = () => {
246
- if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return [];
247
- let nodes;
248
- try {
249
- nodes = document.querySelectorAll(DIALOG_SELECTOR);
250
- } catch (_error) {
251
- return [];
252
- }
253
- const open = [];
254
- for (let index = 0; index < nodes.length; index += 1) {
255
- const node = nodes[index];
256
- if (node === null || node === void 0) continue;
257
- // A dialog kept mounted while hidden is not an overlay.
258
- if (typeof node.getClientRects === 'function' && node.getClientRects().length === 0) continue;
259
- open.push(node);
260
- }
261
- return open;
262
- };
263
-
264
- /** @returns whether the right column is showing its panel. */
265
- const sidebarExpanded = () => {
266
- const sidebar = sidebarRight();
267
- if (sidebar === void 0 || typeof sidebar.isExpanded !== 'function') return false;
268
- try {
269
- return sidebar.isExpanded() === true;
270
- } catch (_error) {
271
- return false;
272
- }
273
- };
274
-
275
- /**
276
- * Count what is stacked above the plain view: every modal dialog, plus
277
- * the right column (the file / code preview lives there) when expanded.
278
- * @returns the overlay depth, 0 for a bare view.
279
- */
280
- const overlayDepth = () => Math.min(visibleDialogs().length + (sidebarExpanded() ? 1 : 0), MAX_OVERLAY);
281
-
282
- /**
283
- * Send the core's own Escape handling to the topmost modal, which is what
284
- * its dialog stack listens for.
285
- * @returns whether an event could be dispatched.
286
- */
287
- const pressEscape = () => {
288
- if (typeof document === 'undefined' || typeof document.dispatchEvent !== 'function') return false;
289
- const ctor =
290
- typeof window.KeyboardEvent === 'function'
291
- ? window.KeyboardEvent
292
- : typeof KeyboardEvent === 'function'
293
- ? KeyboardEvent
294
- : void 0;
295
- if (ctor === void 0) return false;
296
- let event;
297
- try {
298
- event = new ctor('keydown', {
299
- key: 'Escape',
300
- code: 'Escape',
301
- keyCode: 27,
302
- which: 27,
303
- bubbles: true,
304
- cancelable: true
305
- });
306
- } catch (_error) {
307
- return false;
308
- }
309
- try {
310
- document.dispatchEvent(event);
311
- return true;
312
- } catch (_error) {
313
- return false;
314
- }
315
- };
316
-
317
- /**
318
- * Ask the dialog's own close affordances, for a modal that ignores Escape.
319
- * @param dialog - the topmost dialog.
320
- * @returns whether something was clicked.
321
- */
322
- const clickDialogClose = (dialog) => {
323
- if (typeof dialog.querySelector !== 'function') return false;
324
- const candidates = ['button[aria-label]', '.mask'];
325
- for (const selector of candidates) {
326
- let node;
327
- try {
328
- node = dialog.querySelector(selector);
329
- } catch (_error) {
330
- continue;
331
- }
332
- if (node !== null && node !== void 0 && typeof node.click === 'function') {
333
- try {
334
- node.click();
335
- return true;
336
- } catch (_error) {
337
- /* Keep to the next affordance. */
338
- }
339
- }
340
- }
341
- return false;
342
- };
343
-
344
- /**
345
- * Close whatever is on top: the last modal first, then the right column.
346
- * @param control - true to use the dialog's own close control instead of
347
- * sending Escape, for a modal that does not take the key.
348
- * @returns whether a close was requested.
349
- */
350
- const closeTopOverlay = (control) => {
351
- const dialogs = visibleDialogs();
352
- if (dialogs.length > 0) {
353
- if (!control && pressEscape()) return true;
354
- return clickDialogClose(dialogs[dialogs.length - 1]);
355
- }
356
- if (sidebarExpanded()) {
357
- const sidebar = sidebarRight();
358
- try {
359
- sidebar.toggleExpanded();
360
- return true;
361
- } catch (_error) {
362
- return false;
363
- }
364
- }
365
- return false;
366
- };
367
-
368
- /**
369
- * @param sessionId - candidate Session id.
370
- * @returns whether the catalog already knows that Session.
371
- */
372
- const knownSession = (sessionId) => {
373
- const snapshot = sessionList.getSnapshot();
374
- return snapshot !== void 0 && snapshot.byId !== void 0 && snapshot.byId[sessionId] !== void 0;
375
- };
376
-
377
- /** @returns whether the Session catalog has finished its first load. */
378
- const catalogReady = () => {
379
- const snapshot = sessionList.getSnapshot();
380
- return snapshot !== void 0 && snapshot.phase === 'ready';
381
- };
382
-
383
- /**
384
- * Apply one pending piece of the boot route. A segment is only dropped
385
- * once the app actually shows it, because the workspace restore runs
386
- * after this plugin mounts and may briefly override both.
387
- * @returns true while the route still waits for data or for the app to
388
- * follow the change it just triggered.
389
- */
390
- const adopt = () => {
391
- if (Date.now() > bootUntil) {
392
- bootSession = void 0;
393
- bootPanel = null;
394
- return false;
395
- }
396
- const route = readRoute();
397
- if (bootSession !== void 0) {
398
- if (route.sessionId === bootSession) bootSession = void 0;
399
- else if (!knownSession(bootSession)) {
400
- if (!catalogReady()) return true;
401
- bootSession = void 0;
402
- } else if (sessionTries < BOOT_TRIES) {
403
- sessionTries += 1;
404
- try {
405
- workspace.openSession(bootSession);
406
- } catch (error) {
407
- console.warn('ui-router: cannot open the Session named by the URL', error);
408
- bootSession = void 0;
409
- }
410
- return true;
411
- } else bootSession = void 0;
412
- }
413
- if (bootPanel !== null) {
414
- if (route.panelId === bootPanel) bootPanel = null;
415
- else if (!layout.hasMainPanel(bootPanel)) bootPanel = null;
416
- else if (panelTries < BOOT_TRIES) {
417
- panelTries += 1;
418
- try {
419
- layout.selectPanel(bootPanel);
420
- } catch (error) {
421
- console.warn('ui-router: cannot open the panel named by the URL', error);
422
- bootPanel = null;
423
- }
424
- return true;
425
- } else bootPanel = null;
426
- }
427
- return false;
428
- };
429
-
430
- /**
431
- * Publish the current route and overlay depth, or finish adopting the
432
- * boot route first.
433
- */
434
- const sync = () => {
435
- if (settleTarget !== null) return;
436
- if (backAt !== 0) {
437
- if (Date.now() - backAt <= BACK_MS) return;
438
- backAt = 0;
439
- }
440
- const overlay = overlayDepth();
441
- if (!live) {
442
- if (adopt()) return;
443
- live = true;
444
- publish({ ...readRoute(), overlay }, 'replace', 'route');
445
- return;
446
- }
447
- const route = { ...readRoute(), overlay };
448
- const fresh = Date.now() >= settleUntil;
449
- if (overlay > publishedOverlay) {
450
- // An overlay appearing is always the user's doing, so it always gets
451
- // its own entry, even right after a history move.
452
- publish(route, 'push', 'overlay');
453
- return;
454
- }
455
- if (overlay < publishedOverlay) {
456
- const tag = entryTag();
457
- // The current entry exists only for the overlay that just closed, so
458
- // stepping back removes it instead of leaving a dead entry behind.
459
- if (fresh && overlay === publishedOverlay - 1 && tag !== void 0 && tag.kind === 'overlay' && tag.depth === publishedOverlay) {
460
- backAt = Date.now();
461
- try {
462
- history.back();
463
- return;
464
- } catch (_error) {
465
- backAt = 0;
466
- }
467
- }
468
- publish(route, 'replace', 'route');
469
- return;
470
- }
471
- publish(route, fresh ? 'push' : 'replace', 'route');
472
- };
473
-
474
- /**
475
- * Defer `sync` to the next microtask: the workspace keeps writing state
476
- * after the listener returns (`replaceMain` closes the panel once the
477
- * Session is selected), so reacting inside the notification would race
478
- * with the very change that triggered it.
479
- */
480
- const queue = () => {
481
- if (queued) return;
482
- queued = true;
483
- queueMicrotask(() => {
484
- queued = false;
485
- sync();
486
- });
487
- };
488
-
489
- /**
490
- * Measure the overlay stack after a batch of DOM mutations.
491
- */
492
- const scheduleScan = () => {
493
- if (scanTimer !== 0) return;
494
- scanTimer = setTimeout(() => {
495
- scanTimer = 0;
496
- sync();
497
- }, SCAN_DEBOUNCE_MS);
498
- if (typeof scanTimer === 'object' && scanTimer !== null && typeof scanTimer.unref === 'function') scanTimer.unref();
499
- };
500
-
501
- /**
502
- * Close overlays until only `target` are left, then let the address bar
503
- * drive the rest of the navigation. Closes commit asynchronously, so this
504
- * walks one step per turn instead of closing everything at once.
505
- * @param target - overlay depth the Back press asked for.
506
- */
507
- const closeToDepth = (target) => {
508
- settleTarget = target;
509
- let tries = 0;
510
- const step = () => {
511
- if (overlayDepth() <= target || tries >= CLOSE_TRIES) {
512
- settleTarget = null;
513
- applyHash(true);
514
- return;
515
- }
516
- tries += 1;
517
- // Alternate the key and the dialog's own control, so a modal that
518
- // ignores Escape still closes.
519
- if (!closeTopOverlay(tries % 2 === 0)) {
520
- settleTarget = null;
521
- applyHash(true);
522
- return;
523
- }
524
- setTimeout(step, CLOSE_STEP_MS);
525
- };
526
- // Off the event path: the history handlers may run mid-commit.
527
- setTimeout(step, 0);
528
- };
529
-
530
- /**
531
- * Bring the app to the route the address bar now names.
532
- * @param forced - true when the overlay stack is already settled, so a
533
- * lower depth must not start another close sequence.
534
- */
535
- const applyHash = (forced) => {
536
- // A history move of our own, or the user's, has now landed.
537
- backAt = 0;
538
- if (!forced && settleTarget !== null) return;
539
- const target = parseHash(location.hash);
540
- const depth = overlayDepth();
541
- if (forced !== true && target.overlay < depth) {
542
- closeToDepth(target.overlay);
543
- return;
544
- }
545
- publishedOverlay = target.overlay;
546
- settleUntil = Date.now() + SETTLE_MS;
547
- // A deliberate history move supersedes whatever the page was opened with.
548
- bootSession = void 0;
549
- bootPanel = null;
550
- live = true;
551
- const route = readRoute();
552
- if (target.sessionId !== void 0 && target.sessionId !== route.sessionId && knownSession(target.sessionId)) {
553
- try {
554
- workspace.openSession(target.sessionId);
555
- } catch (error) {
556
- console.warn('ui-router: cannot open the Session named by the URL', error);
557
- }
558
- }
559
- // The panel goes last: opening a Session reveals the conversation and
560
- // would close a panel selected before it.
561
- const shown = readRoute();
562
- if (target.panelId !== shown.panelId) {
563
- if (target.panelId === null) layout.selectPanel(null);
564
- else if (layout.hasMainPanel(target.panelId)) layout.selectPanel(target.panelId);
565
- }
566
- // Correct the address bar when part of the target was not reachable.
567
- queue();
568
- };
569
-
570
- /** `popstate` / `hashchange`: the event object is not an argument here. */
571
- const onHistory = () => applyHash(false);
572
-
573
- ctx.effect(() => {
574
- const disposers = [panelInfo.subscribe(queue), selection.subscribe(queue), sessionList.subscribe(queue)];
575
- // The right column reports its own tab moves; expansion has no
576
- // observable, so the fallback poll below covers that half.
577
- const sidebar = sidebarRight();
578
- if (sidebar !== void 0) {
579
- for (const source of [sidebar.openTabs, sidebar.mounted]) {
580
- if (source === void 0 || typeof source.subscribe !== 'function') continue;
581
- try {
582
- disposers.push(source.subscribe(scheduleScan));
583
- } catch (_error) {
584
- /* A store already torn down by the runtime. */
585
- }
586
- }
587
- }
588
- window.addEventListener('popstate', onHistory);
589
- window.addEventListener('hashchange', onHistory);
590
-
591
- // Dialogs are portals appended to `body`, so watching its direct
592
- // children catches them without paying for every streamed token.
593
- const Observer =
594
- typeof window.MutationObserver === 'function'
595
- ? window.MutationObserver
596
- : typeof MutationObserver === 'function'
597
- ? MutationObserver
598
- : void 0;
599
- let observer;
600
- if (Observer !== void 0 && typeof document !== 'undefined' && document.body !== null && document.body !== void 0) {
601
- try {
602
- observer = new Observer(scheduleScan);
603
- observer.observe(document.body, { childList: true });
604
- } catch (_error) {
605
- observer = void 0;
606
- }
607
- }
608
-
609
- const poll = setInterval(() => {
610
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;
611
- sync();
612
- }, SCAN_INTERVAL_MS);
613
- if (typeof poll.unref === 'function') poll.unref();
614
-
615
- return () => {
616
- window.removeEventListener('popstate', onHistory);
617
- window.removeEventListener('hashchange', onHistory);
618
- clearInterval(poll);
619
- if (scanTimer !== 0) {
620
- clearTimeout(scanTimer);
621
- scanTimer = 0;
622
- }
623
- if (observer !== void 0) {
624
- try {
625
- observer.disconnect();
626
- } catch (_error) {
627
- /* Already disconnected. */
628
- }
629
- }
630
- for (const dispose of disposers) {
631
- try {
632
- dispose();
633
- } catch (_error) {
634
- /* A store already torn down by the runtime. */
635
- }
636
- }
637
- };
638
- }, 'ui-router: history');
639
-
640
- queue();
641
- }
642
-
643
- exports.apply = apply;
644
- return module.exports;
645
- }
646
- });
26
+ /** @type {Window & { __ModuleLoader__: { load: (spec: { id: string, factory: (require: (id: string) => unknown) => unknown }) => void } }} */
27
+ const hostWindow =
28
+ /** @type {Window & { __ModuleLoader__: { load: (spec: { id: string, factory: (require: (id: string) => unknown) => unknown }) => void } }} */ (
29
+ /** @type {unknown} */ (window)
30
+ )
31
+ hostWindow.__ModuleLoader__.load({
32
+ id: '@thready-web/dsh-bot-plugin',
33
+ factory: (/** @type {(id: string) => unknown} */ require) => {
34
+ /** @type {{ exports: { inject?: string[], apply?: (ctx: { layout?: any, uiWorkspace?: any, get?: (name: string) => any, effect: (setup: () => (() => void) | void, label?: string) => void }) => void } }} */
35
+ var module = { exports: {} }
36
+ var exports = module.exports
37
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
38
+
39
+ /** Hash segment naming a Session. */
40
+ const SEG_SESSION = 's'
41
+ /** Hash segment naming a main panel. */
42
+ const SEG_PANEL = 'p'
43
+ /** Hash segment naming how many overlays are stacked above the view. */
44
+ const SEG_OVERLAY = 'o'
45
+ /** How long after a history event echoes are folded into `replaceState`. */
46
+ const SETTLE_MS = 1500
47
+ /**
48
+ * How long a deep link keeps reasserting itself while the app boots. The
49
+ * workspace restores its persisted Session asynchronously once both the
50
+ * Workspace and Session catalogs are ready, which over a slow link can
51
+ * take a few seconds.
52
+ */
53
+ const BOOT_MS = 8000
54
+ /** Attempts allowed per deep-link segment before it is abandoned. */
55
+ const BOOT_TRIES = 3
56
+ /** The core's own modal dialogs: a portal on `body`, topmost last. */
57
+ const DIALOG_SELECTOR = '[role="dialog"][aria-modal="true"]'
58
+ /** Overlay depth is capped so a runaway stack cannot fill the address bar. */
59
+ const MAX_OVERLAY = 9
60
+ /** A batch of DOM mutations settles this long before the overlay is measured. */
61
+ const SCAN_DEBOUNCE_MS = 80
62
+ /** Fallback poll for overlay changes no mutation reports (column expansion). */
63
+ const SCAN_INTERVAL_MS = 350
64
+ /** One overlay close gets this long to commit before the next step. */
65
+ const CLOSE_STEP_MS = 40
66
+ /** Close steps allowed for one Back press. */
67
+ const CLOSE_TRIES = 12
68
+ /** Our own `history.back()` gets this long to land before it is given up on. */
69
+ const BACK_MS = 1200
70
+ /** Key of the marker this plugin keeps in `history.state`. */
71
+ const STATE_KEY = '__dshUiRouter'
72
+
73
+ /**
74
+ * @param {string} value - value to escape.
75
+ * @returns the escaped segment.
76
+ */
77
+ function encodeSegment(value) {
78
+ try {
79
+ return encodeURIComponent(value)
80
+ } catch (_error) {
81
+ return value
82
+ }
83
+ }
84
+
85
+ /**
86
+ * @param {string} value - escaped segment.
87
+ * @returns the decoded segment.
88
+ */
89
+ function decodeSegment(value) {
90
+ try {
91
+ return decodeURIComponent(value)
92
+ } catch (_error) {
93
+ return value
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Read a route out of a location hash.
99
+ * @param {string} hash - `location.hash`, with or without the leading `#`.
100
+ * @returns the session id (undefined when absent), the panel id (null when
101
+ * absent) and the overlay depth (0 when absent).
102
+ */
103
+ function parseHash(hash) {
104
+ /** @type {{ sessionId?: string, panelId: string | null, overlay: number }} */
105
+ const route = { sessionId: undefined, panelId: null, overlay: 0 }
106
+ if (typeof hash !== 'string' || hash.length === 0) return route
107
+ const parts = hash
108
+ .replace(/^#/, '')
109
+ .split('/')
110
+ .filter(segment => segment.length > 0)
111
+ .map(decodeSegment)
112
+ for (let index = 0; index + 1 < parts.length; index += 2) {
113
+ const key = parts[index]
114
+ const value = parts[index + 1]
115
+ if (key === SEG_SESSION && value.length > 0) route.sessionId = value
116
+ else if (key === SEG_PANEL && value.length > 0) route.panelId = value
117
+ else if (key === SEG_OVERLAY) {
118
+ const depth = Number.parseInt(value, 10)
119
+ if (Number.isFinite(depth) && depth > 0) route.overlay = Math.min(depth, MAX_OVERLAY)
120
+ }
121
+ }
122
+ return route
123
+ }
124
+
125
+ /**
126
+ * @param {{ sessionId?: string, panelId?: string | null, overlay?: number }} route - session id, panel id and overlay depth.
127
+ * @returns the hash for that route, empty when nothing is addressable.
128
+ */
129
+ function formatHash(route) {
130
+ const segments = []
131
+ if (typeof route.sessionId === 'string' && route.sessionId.length > 0)
132
+ segments.push(SEG_SESSION, encodeSegment(route.sessionId))
133
+ if (typeof route.panelId === 'string' && route.panelId.length > 0)
134
+ segments.push(SEG_PANEL, encodeSegment(route.panelId))
135
+ if (typeof route.overlay === 'number' && route.overlay > 0)
136
+ segments.push(SEG_OVERLAY, String(Math.min(route.overlay, MAX_OVERLAY)))
137
+ return segments.length === 0 ? '' : '#/' + segments.join('/')
138
+ }
139
+
140
+ /** Services required from the client runtime. */
141
+ exports.inject = ['layout', 'uiWorkspace']
142
+
143
+ /**
144
+ * Mirror the active Session, main panel and overlay stack into the URL and
145
+ * drive them from it.
146
+ * @param {{ layout?: any, uiWorkspace?: any, get?: (name: string) => any, effect: (setup: () => (() => void) | void, label?: string) => void }} ctx - client plugin context.
147
+ */
148
+ function apply(ctx) {
149
+ if (typeof window === 'undefined' || window.location === void 0 || window.history === void 0) return
150
+ const location = window.location
151
+ const history = window.history
152
+
153
+ const layout = ctx.layout
154
+ const workspace = ctx.uiWorkspace
155
+ const panelInfo = layout.panelInfo
156
+ const selection = workspace.selection
157
+ const sessionList = workspace.sessions.list
158
+
159
+ /** The route the page was opened with; consumed one item at a time. */
160
+ const boot = parseHash(location.hash)
161
+ let bootSession = boot.sessionId
162
+ let bootPanel = boot.panelId
163
+ const bootUntil = Date.now() + BOOT_MS
164
+ let sessionTries = 0
165
+ let panelTries = 0
166
+ /** False until the boot route has been applied (or given up on). */
167
+ let live = false
168
+ /** Echoes until this timestamp rewrite the URL in place. */
169
+ let settleUntil = Date.now() + SETTLE_MS
170
+ /** A deferred `sync` is pending. */
171
+ let queued = false
172
+ /** Overlay depth the current history entry is believed to describe. */
173
+ let publishedOverlay = boot.overlay
174
+ /** Non-zero while our own `history.back()` is in flight. */
175
+ let backAt = 0
176
+ /** Overlay depth a Back press asked for, while the closes run. */
177
+ /** @type {number | null} */
178
+ let settleTarget = null
179
+ /** Pending debounced overlay scan. */
180
+ let scanTimer = 0
181
+
182
+ /** @returns the current app route. */
183
+ const readRoute = () => ({
184
+ sessionId: selection.getSnapshot().sessionId,
185
+ panelId: panelInfo.getSnapshot().activePanelId,
186
+ })
187
+
188
+ const currentUrl = () => location.pathname + location.search + location.hash
189
+
190
+ /**
191
+ * @param {{ sessionId?: string, panelId?: string | null, overlay?: number }} route - target route.
192
+ * @returns the absolute URL for it, keeping path and query.
193
+ */
194
+ const urlFor = route => location.pathname + location.search + formatHash(route)
195
+
196
+ /** @returns the right-column service, or undefined when it is not mounted. */
197
+ const sidebarRight = () => {
198
+ if (typeof ctx.get !== 'function') return void 0
199
+ try {
200
+ return ctx.get('sidebarRight')
201
+ } catch (_error) {
202
+ return void 0
203
+ }
204
+ }
205
+
206
+ /** @returns the marker this plugin left on the current history entry. */
207
+ const entryTag = () => {
208
+ let state
209
+ try {
210
+ state = history.state
211
+ } catch (_error) {
212
+ return void 0
213
+ }
214
+ if (state === null || typeof state !== 'object') return void 0
215
+ const tag = state[STATE_KEY]
216
+ return tag !== null && typeof tag === 'object' ? tag : void 0
217
+ }
218
+
219
+ /**
220
+ * @param {Record<string, unknown>} tag - marker to record.
221
+ * @returns the state object to write, keeping whatever the page already stored.
222
+ */
223
+ const withTag = tag => {
224
+ let state
225
+ try {
226
+ state = history.state
227
+ } catch (_error) {
228
+ state = null
229
+ }
230
+ const base = state !== null && typeof state === 'object' ? { ...state } : {}
231
+ base[STATE_KEY] = tag
232
+ return base
233
+ }
234
+
235
+ /**
236
+ * Write the route into the address bar.
237
+ * @param {{ sessionId?: string, panelId?: string | null, overlay?: number }} route - route to publish.
238
+ * @param {string} mode - `push` for a new entry, `replace` to rewrite in place.
239
+ * @param {string} kind - why the entry exists: `overlay` for one this plugin opened
240
+ * for an overlay, `route` for a Session / panel move or a rewrite.
241
+ */
242
+ const publish = (route, mode, kind) => {
243
+ publishedOverlay = route.overlay ?? 0
244
+ const url = urlFor(route)
245
+ if (url === currentUrl()) return
246
+ const state = withTag({ kind, depth: route.overlay })
247
+ try {
248
+ if (mode === 'replace') history.replaceState(state, '', url)
249
+ else history.pushState(state, '', url)
250
+ } catch (_error) {
251
+ /* History may be unavailable in a sandboxed frame; the app still works. */
252
+ }
253
+ }
254
+
255
+ /** @returns the dialogs the core currently shows, topmost last. */
256
+ const visibleDialogs = () => {
257
+ if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') return []
258
+ let nodes
259
+ try {
260
+ nodes = document.querySelectorAll(DIALOG_SELECTOR)
261
+ } catch (_error) {
262
+ return []
263
+ }
264
+ const open = []
265
+ for (let index = 0; index < nodes.length; index += 1) {
266
+ const node = nodes[index]
267
+ if (node === null || node === void 0) continue
268
+ // A dialog kept mounted while hidden is not an overlay.
269
+ if (typeof node.getClientRects === 'function' && node.getClientRects().length === 0) continue
270
+ open.push(node)
271
+ }
272
+ return open
273
+ }
274
+
275
+ /** @returns whether the right column is showing its panel. */
276
+ const sidebarExpanded = () => {
277
+ const sidebar = sidebarRight()
278
+ if (sidebar === void 0 || typeof sidebar.isExpanded !== 'function') return false
279
+ try {
280
+ return sidebar.isExpanded() === true
281
+ } catch (_error) {
282
+ return false
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Count what is stacked above the plain view: every modal dialog, plus
288
+ * the right column (the file / code preview lives there) when expanded.
289
+ * @returns the overlay depth, 0 for a bare view.
290
+ */
291
+ const overlayDepth = () => Math.min(visibleDialogs().length + (sidebarExpanded() ? 1 : 0), MAX_OVERLAY)
292
+
293
+ /**
294
+ * Send the core's own Escape handling to the topmost modal, which is what
295
+ * its dialog stack listens for.
296
+ * @returns whether an event could be dispatched.
297
+ */
298
+ const pressEscape = () => {
299
+ if (typeof document === 'undefined' || typeof document.dispatchEvent !== 'function') return false
300
+ const ctor =
301
+ typeof window.KeyboardEvent === 'function'
302
+ ? window.KeyboardEvent
303
+ : typeof KeyboardEvent === 'function'
304
+ ? KeyboardEvent
305
+ : void 0
306
+ if (ctor === void 0) return false
307
+ let event
308
+ try {
309
+ event = new ctor('keydown', {
310
+ key: 'Escape',
311
+ code: 'Escape',
312
+ keyCode: 27,
313
+ which: 27,
314
+ bubbles: true,
315
+ cancelable: true,
316
+ })
317
+ } catch (_error) {
318
+ return false
319
+ }
320
+ try {
321
+ document.dispatchEvent(event)
322
+ return true
323
+ } catch (_error) {
324
+ return false
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Ask the dialog's own close affordances, for a modal that ignores Escape.
330
+ * @param {Element} dialog - the topmost dialog.
331
+ * @returns whether something was clicked.
332
+ */
333
+ const clickDialogClose = dialog => {
334
+ if (typeof dialog.querySelector !== 'function') return false
335
+ const candidates = ['button[aria-label]', '.mask']
336
+ for (const selector of candidates) {
337
+ let node
338
+ try {
339
+ node = dialog.querySelector(selector)
340
+ } catch (_error) {
341
+ continue
342
+ }
343
+ if (node !== null && node !== void 0 && 'click' in node && typeof node.click === 'function') {
344
+ try {
345
+ node.click()
346
+ return true
347
+ } catch (_error) {
348
+ /* Keep to the next affordance. */
349
+ }
350
+ }
351
+ }
352
+ return false
353
+ }
354
+
355
+ /**
356
+ * Close whatever is on top: the last modal first, then the right column.
357
+ * @param {boolean} control - true to use the dialog's own close control instead of
358
+ * sending Escape, for a modal that does not take the key.
359
+ * @returns whether a close was requested.
360
+ */
361
+ const closeTopOverlay = control => {
362
+ const dialogs = visibleDialogs()
363
+ if (dialogs.length > 0) {
364
+ if (!control && pressEscape()) return true
365
+ return clickDialogClose(dialogs[dialogs.length - 1])
366
+ }
367
+ if (sidebarExpanded()) {
368
+ const sidebar = sidebarRight()
369
+ try {
370
+ sidebar.toggleExpanded()
371
+ return true
372
+ } catch (_error) {
373
+ return false
374
+ }
375
+ }
376
+ return false
377
+ }
378
+
379
+ /**
380
+ * @param {string} sessionId - candidate Session id.
381
+ * @returns whether the catalog already knows that Session.
382
+ */
383
+ const knownSession = sessionId => {
384
+ const snapshot = sessionList.getSnapshot()
385
+ return snapshot !== void 0 && snapshot.byId !== void 0 && snapshot.byId[sessionId] !== void 0
386
+ }
387
+
388
+ /** @returns whether the Session catalog has finished its first load. */
389
+ const catalogReady = () => {
390
+ const snapshot = sessionList.getSnapshot()
391
+ return snapshot !== void 0 && snapshot.phase === 'ready'
392
+ }
393
+
394
+ /**
395
+ * Apply one pending piece of the boot route. A segment is only dropped
396
+ * once the app actually shows it, because the workspace restore runs
397
+ * after this plugin mounts and may briefly override both.
398
+ * @returns true while the route still waits for data or for the app to
399
+ * follow the change it just triggered.
400
+ */
401
+ const adopt = () => {
402
+ if (Date.now() > bootUntil) {
403
+ bootSession = void 0
404
+ bootPanel = null
405
+ return false
406
+ }
407
+ const route = readRoute()
408
+ if (bootSession !== void 0) {
409
+ if (route.sessionId === bootSession) bootSession = void 0
410
+ else if (!knownSession(bootSession)) {
411
+ if (!catalogReady()) return true
412
+ bootSession = void 0
413
+ } else if (sessionTries < BOOT_TRIES) {
414
+ sessionTries += 1
415
+ try {
416
+ workspace.openSession(bootSession)
417
+ } catch (error) {
418
+ console.warn('ui-router: cannot open the Session named by the URL', error)
419
+ bootSession = void 0
420
+ }
421
+ return true
422
+ } else bootSession = void 0
423
+ }
424
+ if (bootPanel !== null) {
425
+ if (route.panelId === bootPanel) bootPanel = null
426
+ else if (!layout.hasMainPanel(bootPanel)) bootPanel = null
427
+ else if (panelTries < BOOT_TRIES) {
428
+ panelTries += 1
429
+ try {
430
+ layout.selectPanel(bootPanel)
431
+ } catch (error) {
432
+ console.warn('ui-router: cannot open the panel named by the URL', error)
433
+ bootPanel = null
434
+ }
435
+ return true
436
+ } else bootPanel = null
437
+ }
438
+ return false
439
+ }
440
+
441
+ /**
442
+ * Publish the current route and overlay depth, or finish adopting the
443
+ * boot route first.
444
+ */
445
+ const sync = () => {
446
+ if (settleTarget !== null) return
447
+ if (backAt !== 0) {
448
+ if (Date.now() - backAt <= BACK_MS) return
449
+ backAt = 0
450
+ }
451
+ const overlay = overlayDepth()
452
+ if (!live) {
453
+ if (adopt()) return
454
+ live = true
455
+ publish({ ...readRoute(), overlay }, 'replace', 'route')
456
+ return
457
+ }
458
+ const route = { ...readRoute(), overlay }
459
+ const fresh = Date.now() >= settleUntil
460
+ if (overlay > publishedOverlay) {
461
+ // An overlay appearing is always the user's doing, so it always gets
462
+ // its own entry, even right after a history move.
463
+ publish(route, 'push', 'overlay')
464
+ return
465
+ }
466
+ if (overlay < publishedOverlay) {
467
+ const tag = entryTag()
468
+ // The current entry exists only for the overlay that just closed, so
469
+ // stepping back removes it instead of leaving a dead entry behind.
470
+ if (
471
+ fresh &&
472
+ overlay === publishedOverlay - 1 &&
473
+ tag !== void 0 &&
474
+ tag.kind === 'overlay' &&
475
+ tag.depth === publishedOverlay
476
+ ) {
477
+ backAt = Date.now()
478
+ try {
479
+ history.back()
480
+ return
481
+ } catch (_error) {
482
+ backAt = 0
483
+ }
484
+ }
485
+ publish(route, 'replace', 'route')
486
+ return
487
+ }
488
+ publish(route, fresh ? 'push' : 'replace', 'route')
489
+ }
490
+
491
+ /**
492
+ * Defer `sync` to the next microtask: the workspace keeps writing state
493
+ * after the listener returns (`replaceMain` closes the panel once the
494
+ * Session is selected), so reacting inside the notification would race
495
+ * with the very change that triggered it.
496
+ */
497
+ const queue = () => {
498
+ if (queued) return
499
+ queued = true
500
+ queueMicrotask(() => {
501
+ queued = false
502
+ sync()
503
+ })
504
+ }
505
+
506
+ /**
507
+ * Measure the overlay stack after a batch of DOM mutations.
508
+ */
509
+ const scheduleScan = () => {
510
+ if (scanTimer !== 0) return
511
+ scanTimer = setTimeout(() => {
512
+ scanTimer = 0
513
+ sync()
514
+ }, SCAN_DEBOUNCE_MS)
515
+ const nodeTimer = /** @type {{ unref?: () => void }} */ (/** @type {unknown} */ (scanTimer))
516
+ if (typeof nodeTimer.unref === 'function') nodeTimer.unref()
517
+ }
518
+
519
+ /**
520
+ * Close overlays until only `target` are left, then let the address bar
521
+ * drive the rest of the navigation. Closes commit asynchronously, so this
522
+ * walks one step per turn instead of closing everything at once.
523
+ * @param {number} target - overlay depth the Back press asked for.
524
+ */
525
+ const closeToDepth = target => {
526
+ settleTarget = target
527
+ let tries = 0
528
+ const step = () => {
529
+ if (overlayDepth() <= target || tries >= CLOSE_TRIES) {
530
+ settleTarget = null
531
+ applyHash(true)
532
+ return
533
+ }
534
+ tries += 1
535
+ // Alternate the key and the dialog's own control, so a modal that
536
+ // ignores Escape still closes.
537
+ if (!closeTopOverlay(tries % 2 === 0)) {
538
+ settleTarget = null
539
+ applyHash(true)
540
+ return
541
+ }
542
+ setTimeout(step, CLOSE_STEP_MS)
543
+ }
544
+ // Off the event path: the history handlers may run mid-commit.
545
+ setTimeout(step, 0)
546
+ }
547
+
548
+ /**
549
+ * Bring the app to the route the address bar now names.
550
+ * @param {boolean} forced - true when the overlay stack is already settled, so a
551
+ * lower depth must not start another close sequence.
552
+ */
553
+ const applyHash = forced => {
554
+ // A history move of our own, or the user's, has now landed.
555
+ backAt = 0
556
+ if (!forced && settleTarget !== null) return
557
+ const target = parseHash(location.hash)
558
+ const depth = overlayDepth()
559
+ if (forced !== true && target.overlay < depth) {
560
+ closeToDepth(target.overlay)
561
+ return
562
+ }
563
+ publishedOverlay = target.overlay
564
+ settleUntil = Date.now() + SETTLE_MS
565
+ // A deliberate history move supersedes whatever the page was opened with.
566
+ bootSession = void 0
567
+ bootPanel = null
568
+ live = true
569
+ const route = readRoute()
570
+ if (target.sessionId !== void 0 && target.sessionId !== route.sessionId && knownSession(target.sessionId)) {
571
+ try {
572
+ workspace.openSession(target.sessionId)
573
+ } catch (error) {
574
+ console.warn('ui-router: cannot open the Session named by the URL', error)
575
+ }
576
+ }
577
+ // The panel goes last: opening a Session reveals the conversation and
578
+ // would close a panel selected before it.
579
+ const shown = readRoute()
580
+ if (target.panelId !== shown.panelId) {
581
+ if (target.panelId === null) layout.selectPanel(null)
582
+ else if (layout.hasMainPanel(target.panelId)) layout.selectPanel(target.panelId)
583
+ }
584
+ // Correct the address bar when part of the target was not reachable.
585
+ queue()
586
+ }
587
+
588
+ /** `popstate` / `hashchange`: the event object is not an argument here. */
589
+ const onHistory = () => applyHash(false)
590
+
591
+ ctx.effect(() => {
592
+ const disposers = [panelInfo.subscribe(queue), selection.subscribe(queue), sessionList.subscribe(queue)]
593
+ // The right column reports its own tab moves; expansion has no
594
+ // observable, so the fallback poll below covers that half.
595
+ const sidebar = sidebarRight()
596
+ if (sidebar !== void 0) {
597
+ for (const source of [sidebar.openTabs, sidebar.mounted]) {
598
+ if (source === void 0 || typeof source.subscribe !== 'function') continue
599
+ try {
600
+ disposers.push(source.subscribe(scheduleScan))
601
+ } catch (_error) {
602
+ /* A store already torn down by the runtime. */
603
+ }
604
+ }
605
+ }
606
+ window.addEventListener('popstate', onHistory)
607
+ window.addEventListener('hashchange', onHistory)
608
+
609
+ // Dialogs are portals appended to `body`, so watching its direct
610
+ // children catches them without paying for every streamed token.
611
+ const Observer =
612
+ typeof window.MutationObserver === 'function'
613
+ ? window.MutationObserver
614
+ : typeof MutationObserver === 'function'
615
+ ? MutationObserver
616
+ : void 0
617
+ /** @type {MutationObserver | undefined} */
618
+ let observer
619
+ if (
620
+ Observer !== void 0 &&
621
+ typeof document !== 'undefined' &&
622
+ document.body !== null &&
623
+ document.body !== void 0
624
+ ) {
625
+ try {
626
+ observer = new Observer(scheduleScan)
627
+ observer.observe(document.body, { childList: true })
628
+ } catch (_error) {
629
+ observer = void 0
630
+ }
631
+ }
632
+
633
+ const poll = setInterval(() => {
634
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
635
+ sync()
636
+ }, SCAN_INTERVAL_MS)
637
+ const nodePoll = /** @type {{ unref?: () => void }} */ (/** @type {unknown} */ (poll))
638
+ if (typeof nodePoll.unref === 'function') nodePoll.unref()
639
+
640
+ return () => {
641
+ window.removeEventListener('popstate', onHistory)
642
+ window.removeEventListener('hashchange', onHistory)
643
+ clearInterval(poll)
644
+ if (scanTimer !== 0) {
645
+ clearTimeout(scanTimer)
646
+ scanTimer = 0
647
+ }
648
+ if (observer !== void 0) {
649
+ try {
650
+ observer.disconnect()
651
+ } catch (_error) {
652
+ /* Already disconnected. */
653
+ }
654
+ }
655
+ for (const dispose of disposers) {
656
+ try {
657
+ dispose()
658
+ } catch (_error) {
659
+ /* A store already torn down by the runtime. */
660
+ }
661
+ }
662
+ }
663
+ }, 'ui-router: history')
664
+
665
+ queue()
666
+ }
667
+
668
+ exports.apply = apply
669
+ return module.exports
670
+ },
671
+ })