ui-router-devtools 0.0.1-alpha.0 → 0.1.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.
Files changed (223) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +161 -0
  3. package/dist/console.d.ts +5 -0
  4. package/dist/console.d.ts.map +1 -0
  5. package/dist/console.js +47 -0
  6. package/dist/console.js.map +1 -0
  7. package/dist/define.d.ts +8 -0
  8. package/dist/define.d.ts.map +1 -0
  9. package/dist/define.js +4 -0
  10. package/dist/define.js.map +1 -0
  11. package/dist/edges.d.ts +25 -0
  12. package/dist/edges.d.ts.map +1 -0
  13. package/dist/edges.js +28 -0
  14. package/dist/edges.js.map +1 -0
  15. package/dist/element/chips.d.ts +17 -0
  16. package/dist/element/chips.d.ts.map +1 -0
  17. package/dist/element/chips.js +134 -0
  18. package/dist/element/chips.js.map +1 -0
  19. package/dist/element/glyphs.d.ts +34 -0
  20. package/dist/element/glyphs.d.ts.map +1 -0
  21. package/dist/element/glyphs.js +107 -0
  22. package/dist/element/glyphs.js.map +1 -0
  23. package/dist/element/inspector.d.ts +7 -0
  24. package/dist/element/inspector.d.ts.map +1 -0
  25. package/dist/element/inspector.js +183 -0
  26. package/dist/element/inspector.js.map +1 -0
  27. package/dist/element/links.d.ts +4 -0
  28. package/dist/element/links.d.ts.map +1 -0
  29. package/dist/element/links.js +87 -0
  30. package/dist/element/links.js.map +1 -0
  31. package/dist/element/log.d.ts +12 -0
  32. package/dist/element/log.d.ts.map +1 -0
  33. package/dist/element/log.js +272 -0
  34. package/dist/element/log.js.map +1 -0
  35. package/dist/element/map.d.ts +5 -0
  36. package/dist/element/map.d.ts.map +1 -0
  37. package/dist/element/map.js +5 -0
  38. package/dist/element/map.js.map +1 -0
  39. package/dist/element/mapview.d.ts +17 -0
  40. package/dist/element/mapview.d.ts.map +1 -0
  41. package/dist/element/mapview.js +158 -0
  42. package/dist/element/mapview.js.map +1 -0
  43. package/dist/element/measure.d.ts +3 -0
  44. package/dist/element/measure.d.ts.map +1 -0
  45. package/dist/element/measure.js +9 -0
  46. package/dist/element/measure.js.map +1 -0
  47. package/dist/element/nested.d.ts +45 -0
  48. package/dist/element/nested.d.ts.map +1 -0
  49. package/dist/element/nested.js +686 -0
  50. package/dist/element/nested.js.map +1 -0
  51. package/dist/element/pack.d.ts +75 -0
  52. package/dist/element/pack.d.ts.map +1 -0
  53. package/dist/element/pack.js +281 -0
  54. package/dist/element/pack.js.map +1 -0
  55. package/dist/element/panel.d.ts +159 -0
  56. package/dist/element/panel.d.ts.map +1 -0
  57. package/dist/element/panel.js +1542 -0
  58. package/dist/element/panel.js.map +1 -0
  59. package/dist/element/popover.d.ts +12 -0
  60. package/dist/element/popover.d.ts.map +1 -0
  61. package/dist/element/popover.js +38 -0
  62. package/dist/element/popover.js.map +1 -0
  63. package/dist/element/route.d.ts +75 -0
  64. package/dist/element/route.d.ts.map +1 -0
  65. package/dist/element/route.js +883 -0
  66. package/dist/element/route.js.map +1 -0
  67. package/dist/element/scrubber.d.ts +4 -0
  68. package/dist/element/scrubber.d.ts.map +1 -0
  69. package/dist/element/scrubber.js +67 -0
  70. package/dist/element/scrubber.js.map +1 -0
  71. package/dist/element/styles.d.ts +3 -0
  72. package/dist/element/styles.d.ts.map +1 -0
  73. package/dist/element/styles.js +2084 -0
  74. package/dist/element/styles.js.map +1 -0
  75. package/dist/element/timeline-styles.d.ts +3 -0
  76. package/dist/element/timeline-styles.d.ts.map +1 -0
  77. package/dist/element/timeline-styles.js +286 -0
  78. package/dist/element/timeline-styles.js.map +1 -0
  79. package/dist/element/timeline.d.ts +9 -0
  80. package/dist/element/timeline.d.ts.map +1 -0
  81. package/dist/element/timeline.js +225 -0
  82. package/dist/element/timeline.js.map +1 -0
  83. package/dist/element/tree.d.ts +24 -0
  84. package/dist/element/tree.d.ts.map +1 -0
  85. package/dist/element/tree.js +149 -0
  86. package/dist/element/tree.js.map +1 -0
  87. package/dist/element/viewmap-styles.d.ts +3 -0
  88. package/dist/element/viewmap-styles.d.ts.map +1 -0
  89. package/dist/element/viewmap-styles.js +282 -0
  90. package/dist/element/viewmap-styles.js.map +1 -0
  91. package/dist/element/viewmap.d.ts +39 -0
  92. package/dist/element/viewmap.d.ts.map +1 -0
  93. package/dist/element/viewmap.js +406 -0
  94. package/dist/element/viewmap.js.map +1 -0
  95. package/dist/element/viewport.d.ts +31 -0
  96. package/dist/element/viewport.d.ts.map +1 -0
  97. package/dist/element/viewport.js +37 -0
  98. package/dist/element/viewport.js.map +1 -0
  99. package/dist/element/waterfall.d.ts +85 -0
  100. package/dist/element/waterfall.d.ts.map +1 -0
  101. package/dist/element/waterfall.js +284 -0
  102. package/dist/element/waterfall.js.map +1 -0
  103. package/dist/fold.d.ts +27 -0
  104. package/dist/fold.d.ts.map +1 -0
  105. package/dist/fold.js +104 -0
  106. package/dist/fold.js.map +1 -0
  107. package/dist/index.d.ts +6 -0
  108. package/dist/index.d.ts.map +1 -0
  109. package/dist/index.js +6 -0
  110. package/dist/index.js.map +1 -0
  111. package/dist/lit-ui-router.d.ts +24 -0
  112. package/dist/lit-ui-router.d.ts.map +1 -0
  113. package/dist/lit-ui-router.js +102 -0
  114. package/dist/lit-ui-router.js.map +1 -0
  115. package/dist/notation.d.ts +28 -0
  116. package/dist/notation.d.ts.map +1 -0
  117. package/dist/notation.js +105 -0
  118. package/dist/notation.js.map +1 -0
  119. package/dist/performance.d.ts +5 -0
  120. package/dist/performance.d.ts.map +1 -0
  121. package/dist/performance.js +66 -0
  122. package/dist/performance.js.map +1 -0
  123. package/dist/plugin.d.ts +32 -0
  124. package/dist/plugin.d.ts.map +1 -0
  125. package/dist/plugin.js +21 -0
  126. package/dist/plugin.js.map +1 -0
  127. package/dist/recorder.d.ts +30 -0
  128. package/dist/recorder.d.ts.map +1 -0
  129. package/dist/recorder.js +117 -0
  130. package/dist/recorder.js.map +1 -0
  131. package/dist/schema.d.ts +2 -0
  132. package/dist/schema.d.ts.map +1 -0
  133. package/dist/schema.js +2 -0
  134. package/dist/schema.js.map +1 -0
  135. package/dist/session-schema.d.ts +31 -0
  136. package/dist/session-schema.d.ts.map +1 -0
  137. package/dist/session-schema.js +314 -0
  138. package/dist/session-schema.js.map +1 -0
  139. package/dist/session.schema.json +1172 -0
  140. package/dist/shared/event-schema.d.ts +225 -0
  141. package/dist/shared/event-schema.d.ts.map +1 -0
  142. package/dist/shared/event-schema.js +2 -0
  143. package/dist/shared/event-schema.js.map +1 -0
  144. package/dist/shared/redaction.d.ts +19 -0
  145. package/dist/shared/redaction.d.ts.map +1 -0
  146. package/dist/shared/redaction.js +56 -0
  147. package/dist/shared/redaction.js.map +1 -0
  148. package/dist/shared/resolve-timing.d.ts +6 -0
  149. package/dist/shared/resolve-timing.d.ts.map +1 -0
  150. package/dist/shared/resolve-timing.js +61 -0
  151. package/dist/shared/resolve-timing.js.map +1 -0
  152. package/dist/shared/router-events.d.ts +10 -0
  153. package/dist/shared/router-events.d.ts.map +1 -0
  154. package/dist/shared/router-events.js +296 -0
  155. package/dist/shared/router-events.js.map +1 -0
  156. package/dist/shared/thrown.d.ts +5 -0
  157. package/dist/shared/thrown.d.ts.map +1 -0
  158. package/dist/shared/thrown.js +12 -0
  159. package/dist/shared/thrown.js.map +1 -0
  160. package/dist/shared/transition-source.d.ts +4 -0
  161. package/dist/shared/transition-source.d.ts.map +1 -0
  162. package/dist/shared/transition-source.js +2 -0
  163. package/dist/shared/transition-source.js.map +1 -0
  164. package/dist/shared/views.d.ts +10 -0
  165. package/dist/shared/views.d.ts.map +1 -0
  166. package/dist/shared/views.js +67 -0
  167. package/dist/shared/views.js.map +1 -0
  168. package/dist/spans.d.ts +15 -0
  169. package/dist/spans.d.ts.map +1 -0
  170. package/dist/spans.js +24 -0
  171. package/dist/spans.js.map +1 -0
  172. package/dist/testing.d.ts +32 -0
  173. package/dist/testing.d.ts.map +1 -0
  174. package/dist/testing.js +28 -0
  175. package/dist/testing.js.map +1 -0
  176. package/dist/ui-router-devtools.d.ts +36 -0
  177. package/dist/ui-router-devtools.d.ts.map +1 -0
  178. package/dist/ui-router-devtools.js +3 -0
  179. package/dist/ui-router-devtools.js.map +1 -0
  180. package/dist/views.d.ts +44 -0
  181. package/dist/views.d.ts.map +1 -0
  182. package/dist/views.js +43 -0
  183. package/dist/views.js.map +1 -0
  184. package/package.json +112 -2
  185. package/src/console.ts +104 -0
  186. package/src/define.ts +12 -0
  187. package/src/edges.ts +64 -0
  188. package/src/element/chips.ts +187 -0
  189. package/src/element/glyphs.ts +218 -0
  190. package/src/element/inspector.ts +315 -0
  191. package/src/element/links.ts +136 -0
  192. package/src/element/log.ts +410 -0
  193. package/src/element/map.ts +22 -0
  194. package/src/element/mapview.ts +224 -0
  195. package/src/element/measure.ts +13 -0
  196. package/src/element/nested.ts +1124 -0
  197. package/src/element/pack.ts +526 -0
  198. package/src/element/panel.ts +2378 -0
  199. package/src/element/popover.ts +64 -0
  200. package/src/element/route.ts +1481 -0
  201. package/src/element/scrubber.ts +103 -0
  202. package/src/element/styles.ts +2084 -0
  203. package/src/element/timeline-styles.ts +287 -0
  204. package/src/element/timeline.ts +392 -0
  205. package/src/element/tree.ts +271 -0
  206. package/src/element/viewmap-styles.ts +283 -0
  207. package/src/element/viewmap.ts +733 -0
  208. package/src/element/viewport.ts +112 -0
  209. package/src/element/waterfall.ts +585 -0
  210. package/src/fold.ts +151 -0
  211. package/src/index.ts +40 -0
  212. package/src/lit-ui-router.ts +194 -0
  213. package/src/notation.ts +181 -0
  214. package/src/performance.ts +142 -0
  215. package/src/plugin.ts +57 -0
  216. package/src/recorder.ts +228 -0
  217. package/src/schema.ts +32 -0
  218. package/src/session-schema.ts +362 -0
  219. package/src/spans.ts +53 -0
  220. package/src/testing.ts +74 -0
  221. package/src/types/import-meta-env.d.ts +9 -0
  222. package/src/ui-router-devtools.ts +39 -0
  223. package/src/views.ts +116 -0
@@ -0,0 +1,2378 @@
1
+ import {
2
+ adoptStyles,
3
+ html,
4
+ LitElement,
5
+ nothing,
6
+ type CSSResult,
7
+ type CSSResultGroup,
8
+ type PropertyDeclarations,
9
+ type PropertyValues,
10
+ type TemplateResult,
11
+ } from 'lit';
12
+ import type { UIRouter } from '@uirouter/core';
13
+ import { record, type Recorder } from '../recorder.ts';
14
+ import {
15
+ ancestorsOf,
16
+ apply,
17
+ bareName,
18
+ durationOf,
19
+ emptyModel,
20
+ fold,
21
+ originOf,
22
+ type Model,
23
+ type Tx,
24
+ } from '../fold.ts';
25
+ import { ms, resultLine, seq } from '../notation.ts';
26
+ import {
27
+ defaultRedaction,
28
+ redactionOf,
29
+ redactSession,
30
+ } from '@repo/router-events/redaction';
31
+ import {
32
+ SCHEMA_VERSION,
33
+ type Params,
34
+ type Redaction,
35
+ type Session,
36
+ type SpanRecord,
37
+ type StateInfo,
38
+ type ViewInfo,
39
+ } from '../schema.ts';
40
+ import { spansDuring, upsertSpan } from '../spans.ts';
41
+ import type { ViewLocator } from '../views.ts';
42
+ import type { WaterfallInput } from './waterfall.ts';
43
+ import {
44
+ closeGlyph,
45
+ depthClass,
46
+ maxGlyph,
47
+ minGlyph,
48
+ statusGlyph,
49
+ statusLabel,
50
+ took,
51
+ type Role,
52
+ type Status,
53
+ } from './glyphs.ts';
54
+ import { styles } from './styles.ts';
55
+ import { renderOutline } from './tree.ts';
56
+ import type { NestedLayout } from './nested.ts';
57
+ import type { Metrics, Rung, Size } from './pack.ts';
58
+ import type { Rect } from './route.ts';
59
+ import { placeBeside } from './popover.ts';
60
+ import type { Room, View } from './viewport.ts';
61
+ import { renderScrubber } from './scrubber.ts';
62
+ import { renderLog } from './log.ts';
63
+ import {
64
+ renderRouterCard,
65
+ renderStateInspector,
66
+ renderTxInspector,
67
+ } from './inspector.ts';
68
+
69
+ export interface Row {
70
+ state: StateInfo;
71
+ depth: number;
72
+ hasChildren: boolean;
73
+ setsize: number;
74
+ posinset: number;
75
+ }
76
+
77
+ type Inspect = 'none' | 'router' | 'state' | 'tx' | 'view';
78
+
79
+ type MapLayout = 'nested' | 'tree';
80
+
81
+ type MapModule = typeof import('./map.ts');
82
+
83
+ type TimelineModule = typeof import('./timeline.ts');
84
+
85
+ type ViewMapModule = typeof import('./viewmap.ts');
86
+
87
+ type StateView = 'outline' | 'map' | 'timeline' | 'views';
88
+
89
+ type SessionReader = typeof import('../session-schema.ts');
90
+
91
+ // Kept outside the recorder's ring buffer, so not counted as recorded events.
92
+ const SNAPSHOTS: ReadonlySet<string> = new Set([
93
+ 'config',
94
+ 'states',
95
+ 'current',
96
+ 'views',
97
+ ]);
98
+
99
+ interface SessionFacts {
100
+ routerId: string;
101
+ /** Recorded events, snapshots aside. */
102
+ events: number;
103
+ dropped: number;
104
+ }
105
+
106
+ interface Notice {
107
+ text: string;
108
+ fault: boolean;
109
+ }
110
+
111
+ const MAP_FAILED = 'The Map did not load. Switch views to retry.';
112
+
113
+ const TIMELINE_FAILED = 'The Timeline did not load. Switch views to retry.';
114
+
115
+ const VIEWS_FAILED = 'The Views did not load. Switch views to retry.';
116
+
117
+ const HEADINGS: Record<StateView, string> = {
118
+ outline: 'States',
119
+ map: 'States',
120
+ timeline: 'Timeline',
121
+ views: 'Views',
122
+ };
123
+
124
+ /** Below this inline size the nested layout is the Outline with borders, so it is not offered. */
125
+ const NESTED_MIN_WIDTH = 560;
126
+
127
+ /** How long boxes take to move to their new places; `nested.ts` delays edges by as much. */
128
+ const SETTLE = 200;
129
+
130
+ /** The room the dock's inspector popover takes beside the diagram: its inline size and a module either side. */
131
+ const ASIDE = 320;
132
+
133
+ const MARGIN = 12;
134
+
135
+ /** How far a press travels before it is a drag; `mapview.ts` pans past as much. */
136
+ const DRAG = 4;
137
+
138
+ const EASE_OUT = 'cubic-bezier(0.23, 1, 0.32, 1)';
139
+
140
+ const FLIP = 'uird-flip';
141
+
142
+ const RESCALE = 'uird-rescale';
143
+
144
+ const LAYOUT_KEY = 'ui-router-devtools:map-layout';
145
+
146
+ // Storage can be blocked or throw; the preference is a convenience, so a failure is silent.
147
+ const storedLayout = (): MapLayout => {
148
+ try {
149
+ return localStorage.getItem(LAYOUT_KEY) === 'tree' ? 'tree' : 'nested';
150
+ } catch {
151
+ return 'nested';
152
+ }
153
+ };
154
+
155
+ const storeLayout = (layout: MapLayout): void => {
156
+ try {
157
+ localStorage.setItem(LAYOUT_KEY, layout);
158
+ } catch {
159
+ // the choice still holds for this page
160
+ }
161
+ };
162
+
163
+ const VIEWS_KEY = 'ui-router-devtools:map-views';
164
+
165
+ const storedViews = (): boolean => {
166
+ try {
167
+ return localStorage.getItem(VIEWS_KEY) !== 'off';
168
+ } catch {
169
+ return true;
170
+ }
171
+ };
172
+
173
+ const storeViews = (shown: boolean): void => {
174
+ try {
175
+ localStorage.setItem(VIEWS_KEY, shown ? 'on' : 'off');
176
+ } catch {
177
+ // the choice still holds for this page
178
+ }
179
+ };
180
+
181
+ const rectOf = (element: Element, origin: DOMRect): Rect => {
182
+ const rect = element.getBoundingClientRect();
183
+
184
+ return {
185
+ x: Math.round(rect.x - origin.x),
186
+ y: Math.round(rect.y - origin.y),
187
+ width: Math.round(rect.width),
188
+ height: Math.round(rect.height),
189
+ };
190
+ };
191
+
192
+ // Where the popover may stand over the dock: clear of the header strip and the transitions strip.
193
+ const popBounds = (origin: Size): Rect => ({
194
+ x: 8,
195
+ y: 34,
196
+ width: origin.width - 16,
197
+ height: origin.height - 70,
198
+ });
199
+
200
+ // The Map's root and every element that stands for a state, parents first.
201
+ const MOVERS = ':is(.nested, .map), [data-name]';
202
+
203
+ const moverKey = (element: HTMLElement): string => element.dataset.name ?? '';
204
+
205
+ // The key the Map's room is measured under, beside its movers; no state has a name with a space.
206
+ const ROOM = ' room';
207
+
208
+ // A change of type size is one object changing size: the diagram scales from its old outline and its boxes ride it.
209
+ const rescale = (
210
+ root: HTMLElement,
211
+ was: DOMRect,
212
+ shift: { x: number; y: number },
213
+ ): void => {
214
+ const now = root.getBoundingClientRect();
215
+ const from = `translate(${was.x + shift.x - now.x}px, ${was.y + shift.y - now.y}px) scale(${was.width / now.width}, ${was.height / now.height})`;
216
+
217
+ root.animate(
218
+ [
219
+ { transformOrigin: '0 0', transform: from },
220
+ { transformOrigin: '0 0', transform: 'none' },
221
+ ],
222
+ { id: RESCALE, duration: SETTLE, easing: EASE_OUT },
223
+ );
224
+ };
225
+
226
+ // Whether two outlines have the same proportions, within a tenth.
227
+ const alike = (a: DOMRect, b: DOMRect): boolean =>
228
+ Math.abs(Math.log((a.width * b.height) / (a.height * b.width || 1))) < 0.1;
229
+
230
+ // While a box changes size its header keeps its final width, so no name is elided mid-flight, and what the box does not hold yet stays out of sight.
231
+ const holdInside = (box: HTMLElement, rtl: boolean): (() => void) => {
232
+ const head = box.querySelector<HTMLElement>(':scope > .head');
233
+ const width = `${head?.offsetWidth ?? 0}px`;
234
+ const timing = { id: FLIP, duration: SETTLE };
235
+
236
+ // The clip leaves room for the selection outline, and at the inline start for the default-child marker.
237
+ const clipPath = rtl
238
+ ? 'inset(-4px -24px -4px -4px)'
239
+ : 'inset(-4px -4px -4px -24px)';
240
+
241
+ // The header is measured at rest, before the box's own animation narrows or widens it.
242
+ return () => {
243
+ head?.animate([{ minWidth: width }, { minWidth: width }], timing);
244
+ box.animate([{ clipPath }, { clipPath }], timing);
245
+ };
246
+ };
247
+
248
+ const sizeOf = (rect: DOMRect) => ({
249
+ width: `${rect.width}px`,
250
+ height: `${rect.height}px`,
251
+ });
252
+
253
+ // Only a box changes size: the root would re-centre mid-flight, and a tree node is its label.
254
+ const ease = (
255
+ element: HTMLElement,
256
+ was: DOMRect,
257
+ now: DOMRect,
258
+ { x, y, rtl }: { x: number; y: number; rtl: boolean },
259
+ ): void => {
260
+ const grows =
261
+ element.matches('.box') &&
262
+ (Math.abs(was.width - now.width) >= 1 ||
263
+ Math.abs(was.height - now.height) >= 1);
264
+
265
+ if (!grows && Math.abs(x) < 1 && Math.abs(y) < 1) return;
266
+
267
+ const hold = grows ? holdInside(element, rtl) : undefined;
268
+ const from: Keyframe = { transform: `translate(${x}px, ${y}px)` };
269
+ const to: Keyframe = { transform: 'none' };
270
+
271
+ if (grows) {
272
+ Object.assign(from, sizeOf(was));
273
+ Object.assign(to, sizeOf(now));
274
+ }
275
+
276
+ element.animate([from, to], {
277
+ id: FLIP,
278
+ duration: SETTLE,
279
+ easing: EASE_OUT,
280
+ });
281
+ hold?.();
282
+ };
283
+
284
+ const elide = (name: string): string => {
285
+ if (name.length <= 28) return name;
286
+
287
+ return `…${name.split('.').slice(-2).join('.')}`;
288
+ };
289
+
290
+ // The element behind `<ui-router-devtools>`; `_` members are for the render modules beside it, never public.
291
+ export class DevtoolsPanel extends LitElement {
292
+ static styles: CSSResultGroup = styles;
293
+
294
+ static properties: PropertyDeclarations = {
295
+ router: { attribute: false },
296
+ history: { type: Number },
297
+ timeResolves: { type: Boolean, attribute: 'time-resolves' },
298
+ redaction: { attribute: false },
299
+ viewLocator: { attribute: false },
300
+ _live: { state: true },
301
+ _imported: { state: true },
302
+ _tab: { state: true },
303
+ _view: { state: true },
304
+ _layoutPref: { state: true },
305
+ _mapViews: { state: true },
306
+ _pathFocus: { state: true },
307
+ _max: { state: true },
308
+ _mapSize: { state: true },
309
+ _mapOpen: { state: true },
310
+ _mapFailed: { state: true },
311
+ _mapPan: { state: true },
312
+ _mapZoom: { state: true },
313
+ _selectedTx: { state: true },
314
+ _previewTx: { state: true },
315
+ _selectedState: { state: true },
316
+ _inspect: { state: true },
317
+ _focusState: { state: true },
318
+ _collapsed: { state: true },
319
+ _announcement: { state: true },
320
+ _copied: { state: true },
321
+ _now: { state: true },
322
+ _keepValues: { state: true },
323
+ _keepMessages: { state: true },
324
+ _notice: { state: true },
325
+ _timelineFailed: { state: true },
326
+ _timelineFocus: { state: true },
327
+ _timelineSelected: { state: true },
328
+ _timelineCollapsed: { state: true },
329
+ _spanCount: { state: true },
330
+ _viewsFailed: { state: true },
331
+ _viewFocus: { state: true },
332
+ _viewSelected: { state: true },
333
+ };
334
+
335
+ declare router: UIRouter | undefined;
336
+ declare history: number;
337
+ /** Time resolves by wrapping their `resolveFn`; read when the router attaches. */
338
+ declare timeResolves: boolean;
339
+ declare redaction: Redaction;
340
+ /** Finds a view's element on the page, for the Views; a renderer's subpath supplies it. */
341
+ declare viewLocator: ViewLocator | undefined;
342
+ declare _live: Model;
343
+ declare _imported: { session: Session; model: Model } | null;
344
+ declare _tab: 'tree' | 'log';
345
+ declare _view: StateView;
346
+ declare _layoutPref: MapLayout;
347
+ // The viewer's choice to draw the view path under the Map.
348
+ declare _mapViews: boolean;
349
+ // The view path's item that takes Tab, by its key.
350
+ declare _pathFocus: string | null;
351
+ declare _max: boolean;
352
+ declare _mapSize: Size;
353
+ declare _mapOpen: ReadonlyMap<string, boolean>;
354
+ // The Map's chunk failed to load; choosing the Map view again retries it.
355
+ declare _mapFailed: boolean;
356
+ // Where the Map was panned to, and the type step it was zoomed to; `null` is the fitted view.
357
+ declare _mapPan: View | null;
358
+ declare _mapZoom: number | null;
359
+ declare _selectedTx: number | null;
360
+ declare _previewTx: number | null;
361
+ declare _selectedState: string | null;
362
+ declare _inspect: Inspect;
363
+ declare _focusState: string | null;
364
+ /** The nested Map box the last first click landed on, for the double-click that click may start. */
365
+ _pressed: string | null = null;
366
+ declare _collapsed: ReadonlySet<string>;
367
+ declare _announcement: string;
368
+ // Which inspector copy button shows its check; it clears after a moment.
369
+ declare _copied: string | null;
370
+ declare _now: number;
371
+ // Export's toggles, reset from `redaction` whenever it is set.
372
+ declare _keepValues: boolean;
373
+ declare _keepMessages: boolean;
374
+ declare _notice: Notice | null;
375
+ // The Timeline's chunk failed to load; choosing the Timeline again retries it.
376
+ declare _timelineFailed: boolean;
377
+ // The Timeline row with the roving tab stop, the one whose details show, and the rows closed by hand.
378
+ declare _timelineFocus: string | null;
379
+ declare _timelineSelected: string | null;
380
+ declare _timelineCollapsed: ReadonlySet<string>;
381
+ // Bumped by every span added, so the Timeline redraws.
382
+ declare _spanCount: number;
383
+ // The Views' chunk failed to load; choosing the Views again retries it.
384
+ declare _viewsFailed: boolean;
385
+ // The view with the roving tab stop, and the one whose details show, by the renderer's view id.
386
+ declare _viewFocus: number | null;
387
+ declare _viewSelected: number | null;
388
+
389
+ _mapWidths: Map<string, number> = new Map();
390
+ _moveFocus = false;
391
+ _copiedTimer: ReturnType<typeof setTimeout> | undefined;
392
+ // The validator loads on first import, so a panel that never imports does not pay for it; a spec swaps it to fail the load.
393
+ _importReader = (): Promise<SessionReader> => import('../session-schema.ts');
394
+ // Loads the Map's chunk; a spec swaps it to fail the load.
395
+ _importMap = (): Promise<MapModule> => import('./map.ts');
396
+ // Loads the Timeline's chunk; a spec swaps it to fail the load.
397
+ _importTimeline = (): Promise<TimelineModule> => import('./timeline.ts');
398
+ // The Timeline's waterfall and its render, loaded on first use of the Timeline view.
399
+ _timeline: TimelineModule | undefined;
400
+ #timelineLoading = false;
401
+ // Loads the Views' chunk; a spec swaps it to fail the load.
402
+ _importViews = (): Promise<ViewMapModule> => import('./viewmap.ts');
403
+ _viewMap: ViewMapModule | undefined;
404
+ #viewsLoading = false;
405
+ // The state whose view path a view was selected from, which the path keeps drawing while the view is selected.
406
+ #pathFrom: string | null = null;
407
+ // The states the selection was last checked against; a registration or a lazy load replaces the list.
408
+ #statesSeen: Model['states'] | undefined;
409
+ // The view path's item that had focus before an update, kept while a re-render that removed it leaves none.
410
+ #pathFocused: Element | null = null;
411
+ // The view under the pointer, and the one the locator last marked on the page.
412
+ #pointedView: number | null = null;
413
+ #markedView: ViewInfo | null = null;
414
+ readonly #adopted = new Set<CSSResult>();
415
+ // Spans from a tracer, by span id, oldest first.
416
+ #spans = new Map<string, SpanRecord>();
417
+ // The fit ladder's last rung, for its hysteresis.
418
+ _rung: Rung | undefined;
419
+ // The Map's layouts and edge router, loaded on first use of the Map tab.
420
+ _map: MapModule | undefined;
421
+ #mapLoading = false;
422
+ // What the Map last drew, and where its states were before a change to it.
423
+ #geometry: readonly unknown[] = [];
424
+ #before: Map<string, DOMRect> | null = null;
425
+ // The layout last drawn, and whether the view was last moved by hand, which is not animated.
426
+ #layout: NestedLayout | null = null;
427
+ #direct = false;
428
+ readonly #onWheel = {
429
+ handleEvent: (event: WheelEvent) => this._map?.wheelPan(this, event),
430
+ passive: false,
431
+ };
432
+ // The Map's type step, and whether the last change to the Map changed it.
433
+ #step: Metrics | undefined;
434
+ #resized = false;
435
+ #resize: ResizeObserver | undefined;
436
+ #observed: Element | null = null;
437
+ #recorder: Recorder | undefined;
438
+ #attached: UIRouter | undefined;
439
+ #unsubscribe: (() => void) | undefined;
440
+ #ticker: ReturnType<typeof setInterval> | undefined;
441
+ // The scrubber and newest tick last scrolled to, so a render that adds no transition leaves the strip be.
442
+ #newestTick: { ticks: Element; id: number | undefined } | undefined;
443
+ // Where the last press on the Map began, so a click that ends a drag is told from one that does not.
444
+ #press: { x: number; y: number } | undefined;
445
+
446
+ constructor() {
447
+ super();
448
+ this.history = 500;
449
+ this.timeResolves = false;
450
+ this.redaction = defaultRedaction();
451
+ this._live = emptyModel();
452
+ this._imported = null;
453
+ this._tab = 'tree';
454
+ this._view = 'outline';
455
+ this._layoutPref = storedLayout();
456
+ this._mapViews = storedViews();
457
+ this._pathFocus = null;
458
+ this._max = false;
459
+ this._mapSize = { width: 0, height: 0 };
460
+ this._mapFailed = false;
461
+ this._mapOpen = new Map();
462
+ this._mapPan = null;
463
+ this._mapZoom = null;
464
+ this._inspect = 'none';
465
+ this.#resetSelection();
466
+ this._collapsed = new Set();
467
+ this._announcement = '';
468
+ this._copied = null;
469
+ this._now = performance.now();
470
+ this._notice = null;
471
+ this._timelineFailed = false;
472
+ this._timelineCollapsed = new Set();
473
+ this._spanCount = 0;
474
+ this._viewsFailed = false;
475
+ }
476
+
477
+ // The recorder behind the panel, for reporters that should share it.
478
+ get recorder(): Recorder | undefined {
479
+ return this.#recorder;
480
+ }
481
+
482
+ /** Spans from a tracer, for the Timeline; setting it replaces them all. */
483
+ get spans(): readonly SpanRecord[] {
484
+ return [...this.#spans.values()];
485
+ }
486
+
487
+ set spans(spans: readonly SpanRecord[]) {
488
+ this.#spans = new Map();
489
+
490
+ for (const span of spans) upsertSpan(this.#spans, span);
491
+ this._spanCount += 1;
492
+ }
493
+
494
+ /** Adds a span, or replaces the one with its `spanId`, so a started span is sent again when it ends. */
495
+ addSpan(span: SpanRecord): void {
496
+ upsertSpan(this.#spans, span);
497
+ this._spanCount += 1;
498
+ }
499
+
500
+ // The spans the Timeline joins: an imported session's own, else the ones given to the panel.
501
+ _spanList(): readonly SpanRecord[] {
502
+ return this._imported ? (this._imported.session.spans ?? []) : this.spans;
503
+ }
504
+
505
+ // The epoch time of the event clock's zero.
506
+ get _timeOrigin(): number {
507
+ return this._imported?.session.timeOrigin ?? performance.timeOrigin;
508
+ }
509
+
510
+ _timelineInput(): Omit<WaterfallInput, 'tx'> {
511
+ const model = this._model;
512
+
513
+ return {
514
+ txs: model.txs,
515
+ states: model.states,
516
+ clock: this._clock,
517
+ timeResolves: this._imported?.session.timeResolves ?? this.timeResolves,
518
+ spans: this._spanList(),
519
+ timeOrigin: this._timeOrigin,
520
+ };
521
+ }
522
+
523
+ get _model(): Model {
524
+ return this._imported?.model ?? this._live;
525
+ }
526
+
527
+ // An imported session's clock stops at its export, so a transition running then ends there.
528
+ get _clock(): number {
529
+ return this._imported?.session.t ?? this._now;
530
+ }
531
+
532
+ connectedCallback(): void {
533
+ super.connectedCallback();
534
+
535
+ // Firefox and WebKit keep the media rules a shared sheet matched while no adopter was connected; resetting its media re-evaluates them.
536
+ for (const sheet of this.shadowRoot?.adoptedStyleSheets ?? [])
537
+ sheet.media.mediaText = String(sheet.media);
538
+
539
+ if (this.router && !this.#recorder) this.#attach(this.router);
540
+
541
+ // Removal from the document closes every popover; a reconnected element shows its pill again.
542
+ if (this.hasUpdated) this.#pill?.showPopover();
543
+ }
544
+
545
+ disconnectedCallback(): void {
546
+ super.disconnectedCallback();
547
+ this.#mark(null);
548
+ this.#detach();
549
+ this.#resize?.disconnect();
550
+ this.#observed = null;
551
+ }
552
+
553
+ protected willUpdate(changed: PropertyValues<this>): void {
554
+ if (changed.has('redaction')) {
555
+ this._keepValues = this.redaction.params === 'all';
556
+ this._keepMessages = this.redaction.messages;
557
+ }
558
+
559
+ if (changed.has('router') && this.#attached !== this.router) {
560
+ this.#detach();
561
+ this._live = emptyModel();
562
+ this.#resetSelection();
563
+
564
+ if (this.router && this.isConnected) this.#attach(this.router);
565
+ }
566
+
567
+ this.#followGoneStates();
568
+ this.#forgetGoneViews();
569
+ this.#dropStrandedView();
570
+ this.#loadViews(changed);
571
+ this.#followMap(changed);
572
+ this.#syncTicker();
573
+ }
574
+
575
+ // Durations of a live transition tick while it runs, and on the Timeline so do the spans still running.
576
+ #syncTicker() {
577
+ const running =
578
+ Boolean(this.#recorder) &&
579
+ !this._imported &&
580
+ (this._live.txs.some((tx) => !tx.result) ||
581
+ (this._view === 'timeline' &&
582
+ this.spans.some((span) => span.endTime === undefined)));
583
+
584
+ if (running && !this.#ticker)
585
+ this.#ticker = setInterval(() => (this._now = performance.now()), 100);
586
+
587
+ if (!running && this.#ticker) {
588
+ clearInterval(this.#ticker);
589
+ this.#ticker = undefined;
590
+ }
591
+ }
592
+
593
+ // The Map, the Timeline and the Views load on first use; a failed load retries when the view, or the view path, is chosen again.
594
+ #loadViews(changed: PropertyValues<this>) {
595
+ const retry = changed.has('_view') || changed.has('_mapViews');
596
+
597
+ const due = (
598
+ shown: boolean,
599
+ loaded: boolean,
600
+ loading: boolean,
601
+ failed: boolean,
602
+ ) => shown && !loaded && !loading && (!failed || retry);
603
+
604
+ if (
605
+ due(
606
+ this._view === 'map',
607
+ Boolean(this._map),
608
+ this.#mapLoading,
609
+ this._mapFailed,
610
+ )
611
+ )
612
+ this.#loadMap();
613
+
614
+ if (
615
+ due(
616
+ this._view === 'timeline',
617
+ Boolean(this._timeline),
618
+ this.#timelineLoading,
619
+ this._timelineFailed,
620
+ )
621
+ )
622
+ this.#loadTimeline();
623
+
624
+ // The Map draws the view path under it, so it loads the views too.
625
+ const views =
626
+ this._view === 'views' ||
627
+ (this._view === 'map' && this._mapViews && this.#holdsViews());
628
+
629
+ if (
630
+ due(views, Boolean(this._viewMap), this.#viewsLoading, this._viewsFailed)
631
+ )
632
+ this.#loadViewMap();
633
+ }
634
+
635
+ #loadViewMap() {
636
+ this.#viewsLoading = true;
637
+ this._viewsFailed = false;
638
+
639
+ if (this._announcement === VIEWS_FAILED) this._announcement = '';
640
+
641
+ void this._importViews().then(
642
+ (views) => {
643
+ this._viewMap = views;
644
+ this.#viewsLoading = false;
645
+ this.#adopt(views.viewMapStyles);
646
+ this.requestUpdate();
647
+ },
648
+ () => {
649
+ this._viewsFailed = true;
650
+ this.#viewsLoading = false;
651
+ this._announcement = VIEWS_FAILED;
652
+ },
653
+ );
654
+ }
655
+
656
+ #loadMap() {
657
+ this.#mapLoading = true;
658
+ this._mapFailed = false;
659
+
660
+ if (this._announcement === MAP_FAILED) this._announcement = '';
661
+
662
+ void this._importMap().then(
663
+ (map) => {
664
+ this._map = map;
665
+ this.#mapLoading = false;
666
+ this.requestUpdate();
667
+ },
668
+ () => {
669
+ this._mapFailed = true;
670
+ this.#mapLoading = false;
671
+ this._announcement = MAP_FAILED;
672
+ },
673
+ );
674
+ }
675
+
676
+ #loadTimeline() {
677
+ this.#timelineLoading = true;
678
+ this._timelineFailed = false;
679
+
680
+ if (this._announcement === TIMELINE_FAILED) this._announcement = '';
681
+
682
+ void this._importTimeline().then(
683
+ (timeline) => {
684
+ this._timeline = timeline;
685
+ this.#timelineLoading = false;
686
+ this.#adopt(timeline.timelineStyles);
687
+ this.requestUpdate();
688
+ },
689
+ () => {
690
+ this._timelineFailed = true;
691
+ this.#timelineLoading = false;
692
+ this._announcement = TIMELINE_FAILED;
693
+ },
694
+ );
695
+ }
696
+
697
+ // A chunk's own rules join the panel's and those of chunks loaded before it; lit falls back to style elements where sheets cannot be adopted.
698
+ #adopt(styles: CSSResult) {
699
+ this.#adopted.add(styles);
700
+ // SAFETY: a LitElement renders into its open shadow root unless createRenderRoot is overridden, and this one's is not
701
+ adoptStyles(this.renderRoot as ShadowRoot, [
702
+ ...DevtoolsPanel.elementStyles,
703
+ ...this.#adopted,
704
+ ]);
705
+ }
706
+
707
+ // A panned view follows its layout: a zoom holds the middle of the room still, and a re-pack the focused box.
708
+ #followMap(changed: PropertyValues<this>) {
709
+ const nested = this._view === 'map' ? this._nested() : null;
710
+ const last = this.#layout;
711
+ const pan = this._mapPan;
712
+
713
+ this.#layout = nested;
714
+
715
+ if (!nested || !this._map) return;
716
+
717
+ if (pan && last && last !== nested)
718
+ this._mapPan = changed.has('_mapZoom')
719
+ ? this._map.zoomView(
720
+ pan,
721
+ last.placed,
722
+ nested.placed,
723
+ this._room(nested),
724
+ )
725
+ : this.#anchored(pan, last, nested);
726
+
727
+ // Focus moved by the keyboard or from the inspector brings its box into view.
728
+ if (this._moveFocus && this._focusState)
729
+ this._reveal(nested, this._focusState);
730
+ }
731
+
732
+ #anchored(pan: View, last: NestedLayout, nested: NestedLayout): View {
733
+ const name = this._focusState ?? this._selectedState ?? '';
734
+ const was = last.rects.get(name);
735
+ const now = nested.rects.get(name);
736
+
737
+ return was && now
738
+ ? { x: pan.x + was.x - now.x, y: pan.y + was.y - now.y }
739
+ : pan;
740
+ }
741
+
742
+ // A re-pack can move the focused box to another row, which rebuilds it; focus then returns to the same state.
743
+ protected update(changed: PropertyValues<this>): void {
744
+ const focused = this.shadowRoot?.activeElement;
745
+
746
+ if (focused?.matches('.box > .head')) this._moveFocus = true;
747
+
748
+ // A path drawn between snapshots can have no items; focus its removal dropped is still the path's.
749
+ const dropped =
750
+ !focused &&
751
+ document.activeElement === document.body &&
752
+ this.#pathFocused?.isConnected === false;
753
+
754
+ if (!dropped) this.#pathFocused = focused?.closest('.vp') ? focused : null;
755
+
756
+ this.#before = this.#mapMoved() ? this.#measureMovers() : null;
757
+ super.update(changed);
758
+ }
759
+
760
+ // The Map's drawing changes with its view, its layout and the panel's size; anything else leaves boxes where they are.
761
+ #mapMoved(): boolean {
762
+ const nested = this._view === 'map' ? this._nested() : null;
763
+ const geometry = this.#drawnGeometry(nested);
764
+ const direct = this.#direct;
765
+
766
+ const moved =
767
+ geometry.length !== this.#geometry.length ||
768
+ geometry.some((part, index) => part !== this.#geometry[index]);
769
+
770
+ const drawn = this.#geometry.length > 0;
771
+
772
+ this.#direct = false;
773
+ this.#geometry = geometry;
774
+ this.#resized = Boolean(
775
+ this.#step && nested && this.#step !== nested.metrics,
776
+ );
777
+ this.#step = nested?.metrics;
778
+
779
+ return (
780
+ moved &&
781
+ drawn &&
782
+ !direct &&
783
+ geometry.length > 0 &&
784
+ !matchMedia('(prefers-reduced-motion: reduce)').matches
785
+ );
786
+ }
787
+
788
+ #drawnGeometry(nested: NestedLayout | null): readonly unknown[] {
789
+ if (this._view !== 'map') return [];
790
+
791
+ const view = nested && this._viewOf(nested);
792
+
793
+ return [nested?.placed ?? this._layoutPref, this._max, view?.x, view?.y];
794
+ }
795
+
796
+ get #movers(): HTMLElement[] {
797
+ return [
798
+ ...(this.renderRoot
799
+ .querySelector('.map-scroll')
800
+ ?.querySelectorAll<HTMLElement>(MOVERS) ?? []),
801
+ ];
802
+ }
803
+
804
+ // Where each state is drawn now, mid-flight included, so an interrupted move starts from what the eye sees.
805
+ #measureMovers(): Map<string, DOMRect> {
806
+ const room = this.renderRoot.querySelector('.map-scroll');
807
+
808
+ return new Map([
809
+ ...this.#movers.map(
810
+ (element) =>
811
+ [moverKey(element), element.getBoundingClientRect()] as const,
812
+ ),
813
+ ...(room ? [[ROOM, room.getBoundingClientRect()] as const] : []),
814
+ ]);
815
+ }
816
+
817
+ // How far the middle of the Map's room has moved on the page since `before` was read: the panel changes size at once, and the diagram is followed from where it sat in the room.
818
+ #roomShift(before: ReadonlyMap<string, DOMRect>): { x: number; y: number } {
819
+ const was = before.get(ROOM);
820
+
821
+ const now = this.renderRoot
822
+ .querySelector('.map-scroll')
823
+ ?.getBoundingClientRect();
824
+
825
+ return was && now
826
+ ? {
827
+ x: now.x + now.width / 2 - was.x - was.width / 2,
828
+ y: now.y + now.height / 2 - was.y - was.height / 2,
829
+ }
830
+ : { x: 0, y: 0 };
831
+ }
832
+
833
+ // Ends the moves in flight and, when the type size changed, starts the one that scales the whole diagram.
834
+ #rescaled(
835
+ root: HTMLElement | undefined,
836
+ outline: DOMRect | undefined,
837
+ shift: { x: number; y: number },
838
+ ) {
839
+ // The panel's own resize re-packs once more while the diagram is still changing size; that stays one move.
840
+ const rescaling =
841
+ this.#resized ||
842
+ root?.getAnimations().some((animation) => animation.id === RESCALE);
843
+
844
+ for (const element of this.renderRoot.querySelectorAll('.map-scroll *'))
845
+ for (const animation of element.getAnimations())
846
+ if (animation.id === FLIP || animation.id === RESCALE)
847
+ animation.cancel();
848
+
849
+ if (!rescaling || !root?.matches('.nested') || !outline?.width)
850
+ return false;
851
+
852
+ // One object changing size keeps its proportions; a step that also rearranges the boxes moves them one by one.
853
+ if (!alike(outline, root.getBoundingClientRect())) return false;
854
+
855
+ rescale(root, outline, shift);
856
+
857
+ return true;
858
+ }
859
+
860
+ // FLIP: each state's element starts where and as large as the state was and eases to its new place and size; a child moves relative to its parent.
861
+ #flip(before: ReadonlyMap<string, DOMRect>) {
862
+ const movers = this.#movers;
863
+ const room = this.#roomShift(before);
864
+
865
+ if (this.#rescaled(movers[0], before.get(''), room)) return;
866
+
867
+ // A box hangs from its parent's inline-start edge, so that is the edge a shift is measured at.
868
+ const rtl = getComputedStyle(this).direction === 'rtl';
869
+ const edge = (rect: DOMRect) => (rtl ? rect.right : rect.x);
870
+ const shifts = new Map<Element, { x: number; y: number }>();
871
+
872
+ // Every box is read before any is animated, since a parent's animation would move what its children report.
873
+ const plans = movers.map((element) => {
874
+ const read = before.get(moverKey(element));
875
+ const now = element.getBoundingClientRect();
876
+
877
+ const was =
878
+ read &&
879
+ new DOMRect(read.x + room.x, read.y + room.y, read.width, read.height);
880
+
881
+ const carried = shifts.get(
882
+ element.parentElement?.closest(MOVERS) ?? element,
883
+ ) ?? { x: 0, y: 0 };
884
+
885
+ // A state that was not drawn rides with its parent and fades in.
886
+ const shift = was
887
+ ? { x: edge(was) - edge(now), y: was.y - now.y }
888
+ : carried;
889
+
890
+ shifts.set(element, shift);
891
+
892
+ return {
893
+ element,
894
+ was: was ?? now,
895
+ now,
896
+ by: { x: shift.x - carried.x, y: shift.y - carried.y, rtl },
897
+ };
898
+ });
899
+
900
+ for (const { element, was, now, by } of plans) ease(element, was, now, by);
901
+ }
902
+
903
+ protected firstUpdated(): void {
904
+ if (this.isConnected) this.#pill?.showPopover();
905
+ }
906
+
907
+ protected updated(): void {
908
+ this.#observeMap();
909
+ this.#markPointed();
910
+
911
+ if (this._view === 'views') this._viewMap?.measureViewMap(this);
912
+ this.#measureMap();
913
+ this.#placePopover();
914
+ this.#showTick();
915
+
916
+ if (this.#before) this.#flip(this.#before);
917
+ this.#before = null;
918
+
919
+ this.#keepPathFocus();
920
+
921
+ if (!this._moveFocus) return;
922
+ this._moveFocus = false;
923
+ this.renderRoot
924
+ .querySelector<HTMLElement>('[role="treeitem"][tabindex="0"]')
925
+ ?.focus();
926
+ }
927
+
928
+ // Focus in the view path stays there when a re-render replaces its items, on the path's tab stop.
929
+ #keepPathFocus() {
930
+ if (!this.#pathFocused) return;
931
+
932
+ if (!this._pathShown()) {
933
+ this.#pathFocused = null;
934
+
935
+ return;
936
+ }
937
+
938
+ const stop =
939
+ this.renderRoot.querySelector<HTMLElement>('.vp [tabindex="0"]');
940
+
941
+ if (!stop) return;
942
+
943
+ this.#pathFocused = stop;
944
+
945
+ if (this.shadowRoot?.activeElement !== stop) stop.focus();
946
+ }
947
+
948
+ // The nested Map packs for the Map viewport, and the Views for the area beside their details, so that content box is observed.
949
+ #observeMap() {
950
+ const scroller = this.renderRoot.querySelector('.map-scroll, .vm-main');
951
+
952
+ if (scroller === this.#observed) return;
953
+
954
+ this.#resize ??= new ResizeObserver(([entry]) => {
955
+ const width = Math.floor(entry.contentRect.width);
956
+ const height = Math.floor(entry.contentRect.height);
957
+
958
+ if (width !== this._mapSize.width || height !== this._mapSize.height)
959
+ this._mapSize = { width, height };
960
+ });
961
+ this.#resize.disconnect();
962
+ this.#observed = scroller;
963
+
964
+ if (scroller) this.#resize.observe(scroller);
965
+ }
966
+
967
+ // The popover sits beside the selection, on the side that covers least of the drawn edges and the boxes they end at.
968
+ #placePopover() {
969
+ const panel = this.#panel;
970
+ const popover = this.renderRoot.querySelector('.inspector-pane');
971
+
972
+ if (!panel || !popover || this._view !== 'map' || this._max) return;
973
+
974
+ const origin = panel.getBoundingClientRect();
975
+
976
+ const place =
977
+ this._inspect === 'view'
978
+ ? this.#viewPlace(popover.getBoundingClientRect(), origin)
979
+ : this.#anchoredPlace(popover, origin);
980
+
981
+ if (!place) return;
982
+
983
+ panel.style.setProperty('--uird-pop-x', `${place.x}px`);
984
+ panel.style.setProperty('--uird-pop-y', `${place.y}px`);
985
+ }
986
+
987
+ #anchoredPlace(popover: Element, origin: DOMRect) {
988
+ const root = this.renderRoot.querySelector<HTMLElement>('.nested');
989
+ const nested = root && this._nested();
990
+
991
+ const marked = [
992
+ ...this.renderRoot.querySelectorAll('.map-node.anchor, .brand.anchor'),
993
+ ].at(-1);
994
+
995
+ // The diagram's place in the panel as drawn, its viewport's translation included.
996
+ const drawn = root?.getBoundingClientRect();
997
+
998
+ const at = drawn
999
+ ? { x: drawn.x - origin.x, y: drawn.y - origin.y }
1000
+ : { x: 0, y: 0 };
1001
+
1002
+ const inPanel = <R extends Rect>(rect: R): R => ({
1003
+ ...rect,
1004
+ x: rect.x + at.x,
1005
+ y: rect.y + at.y,
1006
+ });
1007
+
1008
+ const box = nested && this._map?.anchorRect(this, nested);
1009
+ const anchor = box ? inPanel(box) : marked && rectOf(marked, origin);
1010
+
1011
+ if (!anchor) return undefined;
1012
+
1013
+ return this.#popoverPlace(
1014
+ anchor,
1015
+ popover.getBoundingClientRect(),
1016
+ origin,
1017
+ nested && box ? { nested, at } : undefined,
1018
+ );
1019
+ }
1020
+
1021
+ // A view is selected from the path under the Map, and its popover stands beside its item, off the other items.
1022
+ #viewPlace(size: Size, origin: DOMRect) {
1023
+ const item = this.renderRoot.querySelector('.vp-chip[aria-pressed="true"]');
1024
+
1025
+ if (!item) return undefined;
1026
+
1027
+ const anchor = rectOf(item, origin);
1028
+
1029
+ return placeBeside(anchor, size, popBounds(origin), [
1030
+ { ...anchor, weight: 1000 },
1031
+ ...this.#chips(origin),
1032
+ ]);
1033
+ }
1034
+
1035
+ // The view path's items, which a popover keeps off where it can.
1036
+ #chips(origin: DOMRect) {
1037
+ return [...this.renderRoot.querySelectorAll('.vp-chip')].map((chip) => ({
1038
+ ...rectOf(chip, origin),
1039
+ weight: 1,
1040
+ }));
1041
+ }
1042
+
1043
+ // The popover's own column, at the end of the dock.
1044
+ #besidePlace(size: Size, origin: Size) {
1045
+ const rtl = getComputedStyle(this).direction === 'rtl';
1046
+
1047
+ return { x: rtl ? MARGIN : origin.width - MARGIN - size.width, y: 38 };
1048
+ }
1049
+
1050
+ // Beside the diagram the popover has a column of its own; over it, it takes the place that covers least.
1051
+ #popoverPlace(
1052
+ anchor: Rect,
1053
+ size: Size,
1054
+ origin: DOMRect,
1055
+ map?: { nested: NestedLayout; at: { x: number; y: number } },
1056
+ ) {
1057
+ const bounds = popBounds(origin);
1058
+
1059
+ if (!map) return placeBeside(anchor, size, bounds);
1060
+
1061
+ if (this._beside(map.nested)) return this.#besidePlace(size, origin);
1062
+
1063
+ const clear = this._map?.keepClear(this, map.nested) ?? [];
1064
+
1065
+ return placeBeside(anchor, size, bounds, [
1066
+ { ...anchor, weight: 1000 },
1067
+ ...clear.map((rect) => ({
1068
+ ...rect,
1069
+ x: rect.x + map.at.x,
1070
+ y: rect.y + map.at.y,
1071
+ })),
1072
+ ...this.#chips(origin),
1073
+ ]);
1074
+ }
1075
+
1076
+ // The scrubber keeps the selected transition in view, else scrolls to a newest one that is new.
1077
+ #showTick() {
1078
+ const ticks = this.renderRoot.querySelector<HTMLElement>('.ticks');
1079
+ const tick = ticks?.querySelector<HTMLElement>('.tick.on');
1080
+
1081
+ if (!ticks) return;
1082
+
1083
+ if (!tick) {
1084
+ const id = this._model.txs.at(-1)?.id;
1085
+ const seen = this.#newestTick;
1086
+
1087
+ // A hidden strip cannot scroll, so its newest tick stays unseen until it shows.
1088
+ if (!ticks.clientWidth || (seen?.ticks === ticks && seen.id === id))
1089
+ return;
1090
+
1091
+ this.#newestTick = { ticks, id };
1092
+ ticks.scrollLeft =
1093
+ ticks.scrollWidth * (ticks.matches(':dir(rtl)') ? -1 : 1);
1094
+
1095
+ return;
1096
+ }
1097
+
1098
+ const box = ticks.getBoundingClientRect();
1099
+ const rect = tick.getBoundingClientRect();
1100
+
1101
+ if (rect.left < box.left) ticks.scrollLeft -= box.left - rect.left;
1102
+ else if (rect.right > box.right) ticks.scrollLeft += rect.right - box.right;
1103
+ }
1104
+
1105
+ // Map columns and edge starts follow rendered label widths; a changed width re-renders once.
1106
+ #measureMap() {
1107
+ let changed = false;
1108
+
1109
+ for (const node of this.renderRoot.querySelectorAll<HTMLElement>(
1110
+ '.map-node',
1111
+ )) {
1112
+ const name = node.dataset.name!;
1113
+ const width = Math.ceil(node.getBoundingClientRect().width);
1114
+
1115
+ if (width && this._mapWidths.get(name) !== width) {
1116
+ this._mapWidths.set(name, width);
1117
+ changed = true;
1118
+ }
1119
+ }
1120
+
1121
+ if (changed) this.requestUpdate();
1122
+ }
1123
+
1124
+ get #pill() {
1125
+ return this.renderRoot.querySelector<HTMLElement>('.pill');
1126
+ }
1127
+
1128
+ get #panel() {
1129
+ return this.renderRoot.querySelector<HTMLElement>('.panel');
1130
+ }
1131
+
1132
+ // A selected or focused state the registry no longer has gives way to the state a lazy load put in its place, `name`
1133
+ // for `name.**`; with none in its place, the selection clears and the inspector with it.
1134
+ #followGoneStates() {
1135
+ const { states } = this._model;
1136
+
1137
+ if (states === this.#statesSeen) return;
1138
+
1139
+ this.#statesSeen = states;
1140
+
1141
+ const names = new Set(states.map((state) => state.name));
1142
+
1143
+ const follow = (name: string | null) => {
1144
+ if (name === null || names.has(name)) return name;
1145
+
1146
+ const loaded = bareName(name);
1147
+
1148
+ return names.has(loaded) ? loaded : null;
1149
+ };
1150
+
1151
+ this._focusState = follow(this._focusState);
1152
+ this.#pathFrom = follow(this.#pathFrom);
1153
+
1154
+ const selected = follow(this._selectedState);
1155
+
1156
+ if (selected === this._selectedState) return;
1157
+
1158
+ this._selectedState = selected;
1159
+
1160
+ if (selected === null && this._inspect === 'state') this._inspect = 'none';
1161
+ }
1162
+
1163
+ #resetSelection() {
1164
+ this._selectedTx = null;
1165
+ this._previewTx = null;
1166
+ this._selectedState = null;
1167
+ this._focusState = null;
1168
+ this._timelineFocus = null;
1169
+ this._timelineSelected = null;
1170
+ this._viewFocus = null;
1171
+ this._viewSelected = null;
1172
+
1173
+ if (this._inspect !== 'router') this._inspect = 'none';
1174
+ }
1175
+
1176
+ #attach(router: UIRouter) {
1177
+ this.#attached = router;
1178
+
1179
+ const recorder = record(router, {
1180
+ limit: this.history * 40,
1181
+ timeResolves: this.timeResolves,
1182
+ });
1183
+
1184
+ this.#recorder = recorder;
1185
+ this._live = fold(recorder.session({ params: 'all' }).events);
1186
+ this.#unsubscribe = recorder.subscribe((event) => {
1187
+ const next = apply(this._live, event);
1188
+ this._live =
1189
+ next.txs.length > this.history
1190
+ ? { ...next, txs: next.txs.slice(-this.history) }
1191
+ : next;
1192
+
1193
+ if (event.type === 'result' || event.type === 'invalid')
1194
+ this.#announce(event.type === 'result' ? event.id : -event.seq);
1195
+ });
1196
+ }
1197
+
1198
+ #detach() {
1199
+ this.#unsubscribe?.();
1200
+ this.#recorder?.stop();
1201
+ this.#recorder = undefined;
1202
+ this.#attached = undefined;
1203
+ this.#unsubscribe = undefined;
1204
+ clearInterval(this.#ticker);
1205
+ this.#ticker = undefined;
1206
+ }
1207
+
1208
+ _tx(id: number | null | undefined): Tx | undefined {
1209
+ return id == null ? undefined : this._model.txs.find((tx) => tx.id === id);
1210
+ }
1211
+
1212
+ _origin(tx: Tx): Tx | undefined {
1213
+ return originOf(this._model.txs, tx);
1214
+ }
1215
+
1216
+ _duration(tx: Tx): number {
1217
+ return durationOf(this._model.txs, tx, this._clock);
1218
+ }
1219
+
1220
+ #announce(id: number) {
1221
+ if (this._imported) return;
1222
+ const tx = this._live.txs.find((t) => t.id === id);
1223
+ const outcome = tx?.result?.outcome;
1224
+
1225
+ if (!tx || !outcome || !['success', 'error', 'invalid'].includes(outcome))
1226
+ return;
1227
+ this._announcement =
1228
+ outcome === 'success'
1229
+ ? `Transition ${tx.id} succeeded: ${tx.to}, ${ms(this._duration(tx))}`
1230
+ : `${tx.id < 0 ? 'Target' : `Transition ${tx.id}`} failed: ${tx.to}. ${resultLine(tx)}`;
1231
+ }
1232
+
1233
+ #open() {
1234
+ this.#pill?.hidePopover();
1235
+ this.#panel?.showPopover();
1236
+ this.#markPointed();
1237
+ void this.updateComplete.then(() =>
1238
+ this.renderRoot.querySelector<HTMLElement>('.close')?.focus(),
1239
+ );
1240
+ }
1241
+
1242
+ #close() {
1243
+ this.#panel?.hidePopover();
1244
+ this.#markPointed();
1245
+ this.#pill?.showPopover();
1246
+ this.#pill?.focus();
1247
+ }
1248
+
1249
+ // The Map holds one selection at a time, so a state or transition takes the place of a view selected from its path.
1250
+ #dropView() {
1251
+ if (this._inspect === 'view') this._viewSelected = null;
1252
+ }
1253
+
1254
+ _selectTx(id: number | null): void {
1255
+ this.#dropView();
1256
+ this._selectedTx = id;
1257
+ this._inspect = id === null ? 'none' : 'tx';
1258
+ }
1259
+
1260
+ // A click toggles; the second click of a double-click keeps the state selected.
1261
+ _selectState(name: string, keep = false): void {
1262
+ this.#dropView();
1263
+ this._selectedState = keep || this._selectedState !== name ? name : null;
1264
+ this._focusState = name;
1265
+ this._inspect = this._selectedState ? 'state' : 'none';
1266
+ }
1267
+
1268
+ // The Go button and a double-click share this rule.
1269
+ _canGo(state: StateInfo): boolean {
1270
+ return (
1271
+ !this._imported &&
1272
+ !state.abstract &&
1273
+ // A lazy placeholder's params are its own, not those of the state it loads.
1274
+ (state.future || state.params.every((p) => p.optional)) &&
1275
+ !!this.router
1276
+ );
1277
+ }
1278
+
1279
+ _go(state: StateInfo): void {
1280
+ if (this._canGo(state))
1281
+ void this.router?.stateService.go(bareName(state.name)).catch(() => {});
1282
+ }
1283
+
1284
+ // The second press of a double-click would select the word under it; a drag still selects text.
1285
+ _keepText(event: MouseEvent): void {
1286
+ if (event.detail > 1) event.preventDefault();
1287
+ }
1288
+
1289
+ // A double-click selects the state and goes to it when it can be gone to.
1290
+ _goState(name: string): void {
1291
+ const state = this._model.states.find((s) => s.name === name);
1292
+
1293
+ this._selectState(name, true);
1294
+
1295
+ if (state) this._go(state);
1296
+ }
1297
+
1298
+ // Selects a state named in the inspector and moves focus to its row or box.
1299
+ _revealState(name: string): void {
1300
+ const hidden = new Set(ancestorsOf(this._model.states, name));
1301
+
1302
+ this.#dropView();
1303
+ this._selectedState = name;
1304
+ this._focusState = name;
1305
+ this._inspect = 'state';
1306
+ this._collapsed = new Set(
1307
+ [...this._collapsed].filter((state) => !hidden.has(state)),
1308
+ );
1309
+ this._mapOpen = new Map(
1310
+ [...this._mapOpen].filter(([state]) => !hidden.has(state)),
1311
+ );
1312
+ this._moveFocus = true;
1313
+ }
1314
+
1315
+ _selectView(id: number | null): void {
1316
+ const map = this._view === 'map';
1317
+
1318
+ const again =
1319
+ id === this._viewSelected && (!map || this._inspect === 'view');
1320
+
1321
+ this._viewSelected = again ? null : id;
1322
+
1323
+ if (id !== null) this._viewFocus = id;
1324
+
1325
+ if (!map) return;
1326
+
1327
+ if (this._inspect !== 'view') this.#pathFrom = this._pathState();
1328
+
1329
+ // On the Map a view is shown in the panel's inspector, in place of a state or transition.
1330
+ this._selectedState = null;
1331
+ this._selectedTx = null;
1332
+ this._inspect = this._viewSelected === null ? 'none' : 'view';
1333
+ }
1334
+
1335
+ _pointView(id: number | null): void {
1336
+ this.#pointedView = id;
1337
+ this.#markPointed();
1338
+ }
1339
+
1340
+ // Selects a state named in a view's details: on the Map, else in the Outline.
1341
+ _showState(name: string): void {
1342
+ if (this._view !== 'map') this._view = 'outline';
1343
+ this._revealState(name);
1344
+ }
1345
+
1346
+ // The locator marks the view under the pointer, else the selected one, while views of the live router are drawn.
1347
+ #markPointed() {
1348
+ const tab = this._view === 'views';
1349
+ const beside = this._view === 'map' && this._pathShown();
1350
+
1351
+ const shown =
1352
+ (tab || beside) &&
1353
+ !this._imported &&
1354
+ Boolean(this.#panel?.matches(':popover-open'));
1355
+
1356
+ const chosen = tab || this._inspect === 'view' ? this._viewSelected : null;
1357
+ const id = shown ? (this.#pointedView ?? chosen) : null;
1358
+ const view = this.#viewOf(id);
1359
+
1360
+ // A new snapshot is a new object, so the mark follows a view that changed or left.
1361
+ if (view !== this.#markedView) this.#mark(view);
1362
+ }
1363
+
1364
+ #viewOf(id: number | null): ViewInfo | null {
1365
+ return this._model.views?.views.find((view) => view.id === id) ?? null;
1366
+ }
1367
+
1368
+ #mark(view: ViewInfo | null) {
1369
+ this.#markedView = view;
1370
+ this.viewLocator?.highlight(view);
1371
+ }
1372
+
1373
+ // A view that left the snapshot is no longer selected or pointed at.
1374
+ #forgetGoneViews() {
1375
+ if (this.#viewOf(this._viewSelected) === null) {
1376
+ this._viewSelected = null;
1377
+
1378
+ if (this._inspect === 'view') this._inspect = 'none';
1379
+ }
1380
+
1381
+ if (this.#viewOf(this.#pointedView) === null) this.#pointedView = null;
1382
+ }
1383
+
1384
+ // A view is inspected on the Map only from its path; once the path goes, so do the inspection and the page's outline.
1385
+ #dropStrandedView() {
1386
+ if (this._inspect !== 'view') return;
1387
+
1388
+ if (this._view === 'map' && this._pathShown()) return;
1389
+
1390
+ // The Views tab keeps its selection for its own details.
1391
+ if (this._view !== 'views') this._viewSelected = null;
1392
+ this._inspect = 'none';
1393
+ }
1394
+
1395
+ // The states tied to the view selected on the Map, and how: the one whose content created it, and the one that fills it.
1396
+ _linkedStates(): ReadonlyMap<string, string> {
1397
+ const view = this._inspect === 'view' && this.#viewOf(this._viewSelected);
1398
+
1399
+ if (!view) return new Map();
1400
+
1401
+ const ties: [string, string][] = [
1402
+ [view.context, 'created the selected view'],
1403
+ [view.fill?.state ?? '', 'fills the selected view'],
1404
+ ];
1405
+
1406
+ return new Map(ties.filter(([name]) => name));
1407
+ }
1408
+
1409
+ _clearSelection(): void {
1410
+ this.#dropView();
1411
+ this._selectedState = null;
1412
+ this._selectedTx = null;
1413
+ this._inspect = 'none';
1414
+ }
1415
+
1416
+ // Clears the selection; focus inside the inspector, which then hides, goes back to where the selection was made.
1417
+ _dismiss(): void {
1418
+ const from = this.#selectionSources();
1419
+
1420
+ const held = this.shadowRoot?.activeElement?.closest(
1421
+ '.inspector-pane, .router-pane',
1422
+ );
1423
+
1424
+ this._clearSelection();
1425
+
1426
+ if (!held) return;
1427
+
1428
+ void this.updateComplete.then(() =>
1429
+ from
1430
+ .find((element) => element?.isConnected && element.checkVisibility())
1431
+ ?.focus(),
1432
+ );
1433
+ }
1434
+
1435
+ // Where the current selection was made, most specific first, then the Map or Outline's tab stop.
1436
+ #selectionSources(): (HTMLElement | null)[] {
1437
+ const find = (selector: string) =>
1438
+ this.renderRoot.querySelector<HTMLElement>(selector);
1439
+
1440
+ const tx = this._inspect === 'tx';
1441
+
1442
+ return [
1443
+ this._inspect === 'router' ? find('.brand') : null,
1444
+ tx ? find('.ticks') : null,
1445
+ tx ? find('.log .tx.selected > .line') : null,
1446
+ this._inspect === 'state' ? find('.map-node.selected') : null,
1447
+ this._inspect === 'view' ? find('.vp-chip[aria-pressed="true"]') : null,
1448
+ find('[role="treeitem"][tabindex="0"]'),
1449
+ find('.map-node'),
1450
+ // The narrowest panel shows only its tabs.
1451
+ find('.tabs [aria-selected="true"]'),
1452
+ ];
1453
+ }
1454
+
1455
+ // Escape anywhere in the panel clears a selection, once whatever had focus has passed it up.
1456
+ #onKey(event: KeyboardEvent) {
1457
+ // SAFETY: the listener is on the panel, whose event targets are its own elements
1458
+ const target = event.target as Element;
1459
+
1460
+ if (
1461
+ event.key !== 'Escape' ||
1462
+ event.defaultPrevented ||
1463
+ this._inspect === 'none' ||
1464
+ target.closest('input, textarea, select, [contenteditable]')
1465
+ )
1466
+ return;
1467
+
1468
+ event.preventDefault();
1469
+ this._dismiss();
1470
+ }
1471
+
1472
+ // A click on the Map's empty room clears the selection; one on anything drawn, or that ends a drag, does not.
1473
+ #onMapClick(event: MouseEvent) {
1474
+ const press = this.#press;
1475
+ // SAFETY: the listener is on the Map viewport, whose event targets are its own elements
1476
+ const target = event.target as Element;
1477
+
1478
+ this.#press = undefined;
1479
+
1480
+ if (
1481
+ this._inspect === 'none' ||
1482
+ !target.matches('.map-scroll, .nested, .map') ||
1483
+ (press &&
1484
+ Math.hypot(event.clientX - press.x, event.clientY - press.y) >= DRAG)
1485
+ )
1486
+ return;
1487
+
1488
+ this._dismiss();
1489
+ }
1490
+
1491
+ // The state the inspector popover sits beside: the selected state, or a selected transition's target.
1492
+ get _anchorState(): string | null {
1493
+ if (this._inspect === 'state') return this._selectedState;
1494
+
1495
+ return this._inspect === 'tx'
1496
+ ? (this._tx(this._selectedTx)?.to ?? null)
1497
+ : null;
1498
+ }
1499
+
1500
+ // Whether the dock has room for the inspector popover beside the diagram. It follows the diagram's size, never the selection.
1501
+ _beside(nested: NestedLayout): boolean {
1502
+ return !this._max && this._mapSize.width - nested.placed.width >= ASIDE;
1503
+ }
1504
+
1505
+ // The room kept at the diagram's end so the popover's column is empty before anything is selected, and nothing moves when it is.
1506
+ _reserve(nested: NestedLayout): number {
1507
+ if (!this._beside(nested)) return 0;
1508
+
1509
+ const spare = this._mapSize.width - nested.placed.width;
1510
+
1511
+ // Centred while a column is free either side; past that the diagram gives up its end margin first.
1512
+ return Math.max(0, Math.min(ASIDE, ASIDE * 2 - spare));
1513
+ }
1514
+
1515
+ // The room the Map is shown in, for the view of a layout.
1516
+ _room(nested: NestedLayout): Room {
1517
+ return {
1518
+ ...this._mapSize,
1519
+ reserve: this._reserve(nested),
1520
+ // A dock without the column has the popover over the diagram, which can then be pulled out from under it.
1521
+ slack: this._max || this._beside(nested) ? 0 : ASIDE,
1522
+ foot: this._map?.MINI_FOOT ?? 0,
1523
+ rtl: nested.rtl,
1524
+ };
1525
+ }
1526
+
1527
+ // Where the diagram sits: where it was panned to, else fitted, and when it overflows with the current state in the middle.
1528
+ _viewOf(nested: NestedLayout): View {
1529
+ const map = this._map;
1530
+ const room = this._room(nested);
1531
+ const size = nested.placed;
1532
+
1533
+ if (!map) return { x: 0, y: 0 };
1534
+
1535
+ if (this._mapPan) return map.clampView(this._mapPan, size, room);
1536
+
1537
+ const current = nested.rects.get(this._model.current.name);
1538
+
1539
+ return current && map.overflows(size, room)
1540
+ ? map.centreView(current, size, room)
1541
+ : map.fitView(size, room);
1542
+ }
1543
+
1544
+ _pans(nested: NestedLayout): boolean {
1545
+ return Boolean(this._map?.overflows(nested.placed, this._mapSize));
1546
+ }
1547
+
1548
+ // Moves the view and says whether it moved; a drag or the wheel moves it at once, anything else eases.
1549
+ _panTo(nested: NestedLayout, view: View, eased: boolean): boolean {
1550
+ const now = this._viewOf(nested);
1551
+
1552
+ const next =
1553
+ this._map?.clampView(view, nested.placed, this._room(nested)) ?? now;
1554
+
1555
+ if (next.x === now.x && next.y === now.y) return false;
1556
+
1557
+ this.#direct = !eased;
1558
+ this._mapPan = next;
1559
+
1560
+ return true;
1561
+ }
1562
+
1563
+ _reveal(nested: NestedLayout, name: string): void {
1564
+ const rect = nested.rects.get(name);
1565
+
1566
+ if (!rect || !this._map) return;
1567
+
1568
+ const view = this._map.revealView(
1569
+ this._viewOf(nested),
1570
+ rect,
1571
+ nested.placed,
1572
+ this._room(nested),
1573
+ );
1574
+
1575
+ this._panTo(nested, view, true);
1576
+ }
1577
+
1578
+ _zoomBy(nested: NestedLayout, steps: number): void {
1579
+ const last = (this._map?.ZOOMS.length ?? 1) - 1;
1580
+ const step = Math.min(last, Math.max(0, nested.step + steps));
1581
+
1582
+ if (step !== nested.step) this._mapZoom = step;
1583
+ }
1584
+
1585
+ _fit(): void {
1586
+ this._mapPan = null;
1587
+ this._mapZoom = null;
1588
+ }
1589
+
1590
+ _depthClass(name: string): string {
1591
+ return depthClass(ancestorsOf(this._model.states, name).length + 1);
1592
+ }
1593
+
1594
+ // What colour says: a state's identity, except while a transition is in focus, when it says what that transition does.
1595
+ get #mode(): 'tx' | 'state' | 'rest' {
1596
+ if (this._focusTx) return 'tx';
1597
+
1598
+ return this._inspect === 'state' ? 'state' : 'rest';
1599
+ }
1600
+
1601
+ // The nested layout, when it is loaded, chosen and offered at this width.
1602
+ _nested(): NestedLayout | null {
1603
+ if (
1604
+ !this._map ||
1605
+ this._view !== 'map' ||
1606
+ this._layoutPref !== 'nested' ||
1607
+ this._mapSize.width < NESTED_MIN_WIDTH
1608
+ )
1609
+ return null;
1610
+
1611
+ return this._map.layoutNested(this);
1612
+ }
1613
+
1614
+ // Whether the view path is drawn under the Map: wanted, loaded, and for a session that holds views.
1615
+ _pathShown(): boolean {
1616
+ return (
1617
+ this._view === 'map' &&
1618
+ this._mapViews &&
1619
+ Boolean(this._viewMap) &&
1620
+ this.#holdsViews()
1621
+ );
1622
+ }
1623
+
1624
+ // The state whose view path is drawn: the selected state, the one a selected view was picked from, else the active one.
1625
+ _pathState(): string {
1626
+ if (this._inspect === 'state' && this._selectedState !== null)
1627
+ return this._selectedState;
1628
+
1629
+ if (this._inspect === 'view' && this.#pathFrom !== null)
1630
+ return this.#pathFrom;
1631
+
1632
+ return this._model.current.name;
1633
+ }
1634
+
1635
+ #chooseLayout(layout: MapLayout) {
1636
+ this._layoutPref = layout;
1637
+ storeLayout(layout);
1638
+ }
1639
+
1640
+ #chooseViews(shown: boolean) {
1641
+ this._mapViews = shown;
1642
+ storeViews(shown);
1643
+ }
1644
+
1645
+ // Session export and import
1646
+
1647
+ session(redaction?: Partial<Redaction>): Session | undefined {
1648
+ const session = this._imported?.session ?? this.#liveSession();
1649
+
1650
+ return (
1651
+ session &&
1652
+ redactSession(session, redactionOf({ ...this.redaction, ...redaction }))
1653
+ );
1654
+ }
1655
+
1656
+ // The recorder's session, with the spans that ran during its transitions when the panel was given any.
1657
+ #liveSession(): Session | undefined {
1658
+ const session = this.#recorder?.session({ params: 'all' });
1659
+
1660
+ if (!session || !this.#spans.size) return session;
1661
+
1662
+ const spans = spansDuring(
1663
+ this.spans,
1664
+ fold(session.events).txs,
1665
+ session.timeOrigin,
1666
+ session.t,
1667
+ );
1668
+
1669
+ return spans.length ? { ...session, spans } : session;
1670
+ }
1671
+
1672
+ importSession(session: Session): void {
1673
+ if (session.v !== SCHEMA_VERSION)
1674
+ throw new Error(
1675
+ `Unsupported session version ${String(session.v)}; expected ${String(SCHEMA_VERSION)}`,
1676
+ );
1677
+ this._imported = { session, model: fold(session.events) };
1678
+ this.#resetSelection();
1679
+ this._announcement = `Imported session ${session.routerId}, ${this._imported.model.txs.length} transitions. Live updates paused.`;
1680
+ }
1681
+
1682
+ // What the session holds beyond the folded model: its event count and what it lost.
1683
+ _sessionFacts(): SessionFacts {
1684
+ const imported = this._imported?.session;
1685
+
1686
+ if (imported)
1687
+ return {
1688
+ routerId: imported.routerId,
1689
+ events: imported.events.filter((event) => !SNAPSHOTS.has(event.type))
1690
+ .length,
1691
+ dropped: imported.dropped,
1692
+ };
1693
+
1694
+ const recorder = this.#recorder;
1695
+
1696
+ return {
1697
+ routerId: recorder?.routerId ?? '',
1698
+ events: recorder?.events.length ?? 0,
1699
+ dropped: recorder?.dropped ?? 0,
1700
+ };
1701
+ }
1702
+
1703
+ #goLive() {
1704
+ this._imported = null;
1705
+ this._notice = null;
1706
+ this.#resetSelection();
1707
+ this._announcement = 'Showing the live router.';
1708
+ }
1709
+
1710
+ // The toggle decides both ways; off falls back to the configured allowlist, or to none when that is 'all'.
1711
+ _exportSession(): Session | undefined {
1712
+ const configured = this.redaction.params;
1713
+
1714
+ return this.session({
1715
+ params: this._keepValues ? 'all' : configured === 'all' ? [] : configured,
1716
+ messages: this._keepMessages,
1717
+ });
1718
+ }
1719
+
1720
+ #export() {
1721
+ const session = this._exportSession();
1722
+
1723
+ if (!session) return;
1724
+
1725
+ const blob = new Blob([JSON.stringify(session, null, 1)], {
1726
+ type: 'application/json',
1727
+ });
1728
+
1729
+ const link = document.createElement('a');
1730
+ link.href = URL.createObjectURL(blob);
1731
+ link.download = `ui-router-session-${session.routerId}-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
1732
+ link.click();
1733
+ setTimeout(() => URL.revokeObjectURL(link.href));
1734
+ }
1735
+
1736
+ #fail(text: string) {
1737
+ this._notice = { text, fault: true };
1738
+ this._announcement = text;
1739
+ }
1740
+
1741
+ async #readFile(file: File | undefined) {
1742
+ if (!file) return;
1743
+ this._notice = null;
1744
+
1745
+ let json: unknown;
1746
+
1747
+ try {
1748
+ json = JSON.parse(await file.text());
1749
+ } catch {
1750
+ this.#fail(`Import failed: ${file.name} is not JSON.`);
1751
+
1752
+ return;
1753
+ }
1754
+
1755
+ let reader: SessionReader;
1756
+
1757
+ try {
1758
+ reader = await this._importReader();
1759
+ } catch {
1760
+ this.#fail('Import failed: the session reader did not load. Try again.');
1761
+
1762
+ return;
1763
+ }
1764
+
1765
+ const read = reader.readSession(json);
1766
+
1767
+ if (!read.ok) {
1768
+ this.#fail(`Import failed: ${read.error}`);
1769
+
1770
+ return;
1771
+ }
1772
+
1773
+ this.importSession(read.session);
1774
+
1775
+ const skipped = [
1776
+ ...(read.skipped
1777
+ ? [
1778
+ `${read.skipped} ${read.skipped === 1 ? 'event' : 'events'} of a kind this version does not read`,
1779
+ ]
1780
+ : []),
1781
+ ...(read.skippedSpans
1782
+ ? [
1783
+ `${read.skippedSpans} ${read.skippedSpans === 1 ? 'span' : 'spans'} that did not read`,
1784
+ ]
1785
+ : []),
1786
+ ];
1787
+
1788
+ if (skipped.length)
1789
+ this._notice = { text: `${skipped.join(' and ')} skipped`, fault: false };
1790
+ }
1791
+
1792
+ #onDrop(event: DragEvent) {
1793
+ event.preventDefault();
1794
+ void this.#readFile(event.dataTransfer?.files[0]);
1795
+ }
1796
+
1797
+ // Derived model
1798
+
1799
+ get _runningTx(): Tx | undefined {
1800
+ return this._model.txs.findLast((tx) => !tx.result);
1801
+ }
1802
+
1803
+ get _focusTx(): Tx | undefined {
1804
+ return (
1805
+ this._tx(this._previewTx) ?? this._tx(this._selectedTx) ?? this._runningTx
1806
+ );
1807
+ }
1808
+
1809
+ #erroredState(tx: Tx): string | null {
1810
+ if (tx.result?.outcome !== 'error') return null;
1811
+
1812
+ return tx.resolves.find((r) => !r.ok)?.state ?? tx.to;
1813
+ }
1814
+
1815
+ _role(state: StateInfo): Role {
1816
+ const tx = this._focusTx;
1817
+
1818
+ if (tx) {
1819
+ if (this.#erroredState(tx) === state.name) return 'errored';
1820
+
1821
+ if (tx.entering.includes(state.name)) return 'entering';
1822
+
1823
+ if (tx.exiting.includes(state.name)) return 'exiting';
1824
+
1825
+ if (tx.retained.includes(state.name)) return 'retained';
1826
+ }
1827
+
1828
+ const { states, current } = this._model;
1829
+
1830
+ if (state.name === current.name) return 'current';
1831
+
1832
+ if (ancestorsOf(states, current.name).includes(state.name))
1833
+ return 'ancestor';
1834
+
1835
+ return state.future ? 'future' : 'inactive';
1836
+ }
1837
+
1838
+ _children(): Map<string | null, StateInfo[]> {
1839
+ const known = new Set(this._model.states.map((s) => s.name));
1840
+ const children = new Map<string | null, StateInfo[]>();
1841
+
1842
+ for (const state of this._model.states) {
1843
+ const parent =
1844
+ state.parent && known.has(state.parent) ? state.parent : null;
1845
+
1846
+ children.set(parent, [...(children.get(parent) ?? []), state]);
1847
+ }
1848
+
1849
+ return children;
1850
+ }
1851
+
1852
+ _rows(): Row[] {
1853
+ const children = this._children();
1854
+ const rows: Row[] = [];
1855
+
1856
+ const walk = (parent: string | null, depth: number) => {
1857
+ const kids = children.get(parent) ?? [];
1858
+ kids.forEach((state, index) => {
1859
+ const hasChildren = (children.get(state.name) ?? []).length > 0;
1860
+ rows.push({
1861
+ state,
1862
+ depth,
1863
+ hasChildren,
1864
+ setsize: kids.length,
1865
+ posinset: index + 1,
1866
+ });
1867
+
1868
+ if (hasChildren && !this._collapsed.has(state.name))
1869
+ walk(state.name, depth + 1);
1870
+ });
1871
+ };
1872
+
1873
+ walk(null, 1);
1874
+
1875
+ return rows;
1876
+ }
1877
+
1878
+ _paramBase(tx: Tx): Params {
1879
+ const first = (this._origin(tx) ?? tx).id;
1880
+
1881
+ return (
1882
+ this._model.txs.findLast(
1883
+ (t) => t.id >= 0 && t.id < first && t.result?.outcome === 'success',
1884
+ )?.toParams ?? tx.fromParams
1885
+ );
1886
+ }
1887
+
1888
+ // Render
1889
+
1890
+ render(): TemplateResult {
1891
+ const inspected =
1892
+ this._inspect === 'tx' ? this._tx(this._selectedTx) : undefined;
1893
+
1894
+ const imported = Boolean(this._imported);
1895
+
1896
+ return html`
1897
+ ${this.#renderPill()}
1898
+ <div
1899
+ class="panel"
1900
+ popover="manual"
1901
+ role="region"
1902
+ aria-label="Router devtools"
1903
+ data-tab=${this._tab}
1904
+ data-view=${this._view}
1905
+ data-inspect=${this._inspect}
1906
+ data-mode=${this.#mode}
1907
+ ?data-max=${this._max}
1908
+ ?data-imported=${imported}
1909
+ @dragover=${(e: DragEvent) => e.preventDefault()}
1910
+ @drop=${this.#onDrop}
1911
+ @keydown=${this.#onKey}
1912
+ >
1913
+ ${this.#renderTitle()}
1914
+ <div class="body">
1915
+ <section
1916
+ class="pane tree-pane"
1917
+ id="pane-tree"
1918
+ role="tabpanel"
1919
+ aria-labelledby="h-states"
1920
+ >
1921
+ ${this.#sectionHead('1', HEADINGS[this._view], 'h-states')}
1922
+ <div class="pane-switch">${this.#renderSwitch()}</div>
1923
+ ${this.#renderStates()}
1924
+ </section>
1925
+ ${this._view === 'outline' ? nothing : renderScrubber(this)}
1926
+ <section
1927
+ class="pane log-pane"
1928
+ id="pane-log"
1929
+ role="tabpanel"
1930
+ aria-labelledby="h-log"
1931
+ >
1932
+ ${this.#sectionHead('2', 'Transitions', 'h-log')}
1933
+ <div class="scroll">${renderLog(this)}</div>
1934
+ </section>
1935
+ <section class="pane inspector-pane" aria-labelledby="h-insp">
1936
+ ${this.#sectionHead('3', 'Inspector', 'h-insp', inspected ? seq(inspected.id) || 'Invalid target' : this.#inspectorAside())}${
1937
+ this._inspect === 'none'
1938
+ ? nothing
1939
+ : html`<button
1940
+ class="icon dismiss"
1941
+ aria-label="Close inspector"
1942
+ title="Close (Esc)"
1943
+ @click=${() => this._dismiss()}
1944
+ >
1945
+ ${closeGlyph}
1946
+ </button>`
1947
+ }
1948
+ <div
1949
+ class="scroll"
1950
+ tabindex="0"
1951
+ role="group"
1952
+ aria-labelledby="h-insp"
1953
+ >
1954
+ ${this.#renderInspector(inspected)}
1955
+ </div>
1956
+ </section>
1957
+ <section
1958
+ class="pane router-pane"
1959
+ id="pane-router"
1960
+ role="tabpanel"
1961
+ aria-labelledby="h-router"
1962
+ >
1963
+ ${this.#sectionHead('3', 'Router', 'h-router')}
1964
+ <div
1965
+ class="scroll"
1966
+ tabindex="0"
1967
+ role="group"
1968
+ aria-labelledby="h-router"
1969
+ >
1970
+ ${renderRouterCard(this, true)}
1971
+ </div>
1972
+ </section>
1973
+ </div>
1974
+ </div>
1975
+ <input
1976
+ class="file visually-hidden"
1977
+ type="file"
1978
+ accept=".json,application/json"
1979
+ tabindex="-1"
1980
+ aria-hidden="true"
1981
+ @change=${(e: Event) => {
1982
+ // SAFETY: the listener is on this <input>
1983
+ const input = e.currentTarget as HTMLInputElement;
1984
+ void this.#readFile(input.files?.[0]).then(() => (input.value = ''));
1985
+ }}
1986
+ />
1987
+ <div class="visually-hidden" role="status" aria-live="polite">
1988
+ ${this._announcement}
1989
+ </div>
1990
+ `;
1991
+ }
1992
+
1993
+ #renderStates() {
1994
+ if (this._view === 'outline')
1995
+ return html`<div class="scroll outline-scroll">
1996
+ ${renderOutline(this)}
1997
+ </div>`;
1998
+
1999
+ if (this._view === 'timeline')
2000
+ return html`<div class="scroll timeline-scroll">
2001
+ ${
2002
+ this._timeline
2003
+ ? this._timeline.renderTimeline(this)
2004
+ : this._timelineFailed
2005
+ ? html`<p class="empty">${TIMELINE_FAILED}</p>`
2006
+ : nothing
2007
+ }
2008
+ </div>`;
2009
+
2010
+ if (this._view === 'views')
2011
+ return html`<div class="scroll views-scroll">
2012
+ ${
2013
+ this._viewMap
2014
+ ? this._viewMap.renderViewMap(this)
2015
+ : this._viewsFailed
2016
+ ? html`<p class="empty">${VIEWS_FAILED}</p>`
2017
+ : nothing
2018
+ }
2019
+ </div>`;
2020
+
2021
+ const nested = this._nested();
2022
+ const map = this._map;
2023
+
2024
+ /* oxlint-disable lit-a11y/click-events-have-key-events -- Escape anywhere in the panel clears the selection too */
2025
+ return html`<div
2026
+ class="scroll map-scroll"
2027
+ ?data-pan=${nested && this._pans(nested)}
2028
+ @pointerdown=${(event: PointerEvent) => {
2029
+ this.#press = { x: event.clientX, y: event.clientY };
2030
+ map?.startPan(this, event);
2031
+ }}
2032
+ @click=${this.#onMapClick}
2033
+ @wheel=${this.#onWheel}
2034
+ >
2035
+ ${map ? (nested ? map.renderNested(this, nested) : map.renderMap(this)) : this.#mapNotice()}
2036
+ </div>
2037
+ ${
2038
+ // SAFETY: the path is drawn only once the views' module has loaded
2039
+ this._pathShown() ? this._viewMap!.renderPath(this) : nothing
2040
+ }`;
2041
+ /* oxlint-enable lit-a11y/click-events-have-key-events */
2042
+ }
2043
+
2044
+ #mapNotice() {
2045
+ return this._mapFailed ? html`<p class="empty">${MAP_FAILED}</p>` : nothing;
2046
+ }
2047
+
2048
+ // Outline or Map, and on the Map the nested boxes or the node-link tree.
2049
+ #renderSwitch() {
2050
+ const map = this._view === 'map';
2051
+ const layout = this._nested();
2052
+ const nested = Boolean(layout);
2053
+ const narrow = this._mapSize.width < NESTED_MIN_WIDTH;
2054
+ const why = `Nested boxes need ${NESTED_MIN_WIDTH}px of width`;
2055
+
2056
+ return html`<div class="switch" role="group" aria-label="State view">
2057
+ ${(['outline', 'map', 'timeline', 'views'] as const).map(
2058
+ (view) =>
2059
+ html`<button
2060
+ aria-pressed=${this._view === view}
2061
+ @click=${() => (this._view = view)}
2062
+ >
2063
+ ${view}
2064
+ </button>`,
2065
+ )}
2066
+ </div>
2067
+ ${
2068
+ map
2069
+ ? html`<div class="switch" role="group" aria-label="Map layout">
2070
+ <button
2071
+ aria-pressed=${nested}
2072
+ ?disabled=${narrow}
2073
+ title=${narrow ? why : 'Child states inside their parent'}
2074
+ @click=${() => this.#chooseLayout('nested')}
2075
+ >
2076
+ Nested
2077
+ </button>
2078
+ <button
2079
+ aria-pressed=${!nested}
2080
+ title="Node-link tree"
2081
+ @click=${() => this.#chooseLayout('tree')}
2082
+ >
2083
+ Tree
2084
+ </button>
2085
+ </div>
2086
+ ${layout ? this.#renderViewTools(layout) : nothing}
2087
+ ${this.#holdsViews() ? this.#renderViewsToggle() : nothing}`
2088
+ : nothing
2089
+ }`;
2090
+ }
2091
+
2092
+ // Draws the view path under the Map; the viewer's choice is kept, and pressed means wanted, so the press and the click agree while the module loads.
2093
+ #renderViewsToggle() {
2094
+ const failed = this._mapViews && this._viewsFailed;
2095
+
2096
+ return html`<div class="switch" role="group" aria-label="Under the Map">
2097
+ <button
2098
+ aria-pressed=${this._mapViews && !failed}
2099
+ ?disabled=${failed}
2100
+ title=${failed ? VIEWS_FAILED : this._mapViews ? 'Hide the view path under the Map' : 'Show the view path under the Map'}
2101
+ @click=${() => this.#chooseViews(!this._mapViews)}
2102
+ >
2103
+ View path
2104
+ </button>
2105
+ </div>`;
2106
+ }
2107
+
2108
+ // Whether the session's views snapshot holds any view; an empty one is no snapshot to the path.
2109
+ #holdsViews(): boolean {
2110
+ return Boolean(this._model.views?.views.length);
2111
+ }
2112
+
2113
+ // The view of the Map: its type step, and the way back to the fitted view.
2114
+ #renderViewTools(layout: NestedLayout) {
2115
+ const last = (this._map?.ZOOMS.length ?? 1) - 1;
2116
+ const fitted = this._mapPan === null && this._mapZoom === null;
2117
+
2118
+ return html`<div
2119
+ class="switch view-tools"
2120
+ role="group"
2121
+ aria-label="Map view"
2122
+ >
2123
+ <button
2124
+ class="step"
2125
+ aria-label="Zoom out"
2126
+ title="Smaller type (−)"
2127
+ ?disabled=${layout.step <= 0}
2128
+ @click=${() => this._zoomBy(layout, -1)}
2129
+ >
2130
+ −
2131
+ </button>
2132
+ <button
2133
+ class="step"
2134
+ aria-label="Zoom in"
2135
+ title="Larger type (+)"
2136
+ ?disabled=${layout.step >= last}
2137
+ @click=${() => this._zoomBy(layout, 1)}
2138
+ >
2139
+ +
2140
+ </button>
2141
+ <button
2142
+ title="Fit the map to the panel (0)"
2143
+ ?disabled=${fitted}
2144
+ @click=${() => this._fit()}
2145
+ >
2146
+ Fit
2147
+ </button>
2148
+ </div>`;
2149
+ }
2150
+
2151
+ #inspectorAside(): string | undefined {
2152
+ if (this._inspect === 'state') return undefined;
2153
+
2154
+ if (this._inspect === 'view') return 'View';
2155
+
2156
+ return this._inspect === 'none' || this._inspect === 'router'
2157
+ ? 'Router'
2158
+ : undefined;
2159
+ }
2160
+
2161
+ #renderInspector(inspected: Tx | undefined) {
2162
+ if (inspected) return renderTxInspector(this, inspected);
2163
+
2164
+ if (this._inspect === 'state') return renderStateInspector(this);
2165
+
2166
+ // SAFETY: a view is selected on the Map only from its path, which the views' module draws
2167
+ if (this._inspect === 'view')
2168
+ return this._viewMap!.renderViewInspector(this);
2169
+
2170
+ return renderRouterCard(this);
2171
+ }
2172
+
2173
+ #sectionHead(n: string, title: string, id: string, aside?: string) {
2174
+ return html`<h2 class="section" id=${id}>
2175
+ <span class="num">${n}</span
2176
+ ><span class="title">${title}</span
2177
+ >${aside ? html`<span class="aside">${aside}</span>` : nothing}
2178
+ </h2>`;
2179
+ }
2180
+
2181
+ #summary() {
2182
+ const running = this._runningTx;
2183
+
2184
+ const last = this._model.txs.findLast(
2185
+ (tx) => tx.result?.outcome !== 'ignored',
2186
+ );
2187
+
2188
+ const status: Status = running
2189
+ ? 'running'
2190
+ : (last?.result?.outcome ?? 'success');
2191
+
2192
+ const tx = running ?? last;
2193
+
2194
+ const name =
2195
+ running?.to ??
2196
+ (last && last.result?.outcome !== 'success'
2197
+ ? last.to
2198
+ : this._model.current.name);
2199
+
2200
+ return {
2201
+ status,
2202
+ name: name || '(root)',
2203
+ took: tx && tx.id >= 0 ? took(this._duration(tx)) : nothing,
2204
+ };
2205
+ }
2206
+
2207
+ #renderPill() {
2208
+ const { status, name, took } = this.#summary();
2209
+
2210
+ return html`<button
2211
+ class="pill status-${status}"
2212
+ popover="manual"
2213
+ @click=${this.#open}
2214
+ >
2215
+ ${statusGlyph(status)}<span class="visually-hidden"
2216
+ >Router ${statusLabel[status]}:</span
2217
+ ><span class="pill-name">${elide(name)}</span
2218
+ >${took === nothing ? nothing : html`<span class="num">${took}</span>`}${
2219
+ this._imported ? html`<span class="tag">Imported</span>` : nothing
2220
+ }
2221
+ </button>`;
2222
+ }
2223
+
2224
+ #toggleRouter() {
2225
+ this.#dropView();
2226
+ this._inspect = this._inspect === 'router' ? 'none' : 'router';
2227
+ this._selectedTx = null;
2228
+ this._selectedState = null;
2229
+ }
2230
+
2231
+ #showTab(tab: 'tree' | 'log' | 'router') {
2232
+ if (tab === 'router') {
2233
+ this._inspect = 'router';
2234
+
2235
+ return;
2236
+ }
2237
+
2238
+ this._tab = tab;
2239
+
2240
+ if (this._inspect === 'router') this._inspect = 'none';
2241
+ }
2242
+
2243
+ #renderTabs() {
2244
+ const router = this._inspect === 'router';
2245
+
2246
+ const tabs = [
2247
+ ['tree', '1', 'States', 'pane-tree', !router && this._tab === 'tree'],
2248
+ ['log', '2', 'Transitions', 'pane-log', !router && this._tab === 'log'],
2249
+ ['router', '3', 'Router', 'pane-router', router],
2250
+ ] as const;
2251
+
2252
+ return html`<div class="tabs" role="tablist" aria-label="Devtools views">
2253
+ ${tabs.map(
2254
+ ([tab, n, label, id, selected]) =>
2255
+ html`<button
2256
+ role="tab"
2257
+ aria-selected=${selected}
2258
+ aria-controls=${id}
2259
+ @click=${() => this.#showTab(tab)}
2260
+ >
2261
+ <span class="num">${n}</span><span class="label">${label}</span>
2262
+ </button>`,
2263
+ )}
2264
+ </div>`;
2265
+ }
2266
+
2267
+ // What Export keeps; each toggle starts from `redaction`.
2268
+ _exportToggles(): TemplateResult {
2269
+ return html`<div class="switch" role="group" aria-label="Export keeps">
2270
+ <button
2271
+ aria-pressed=${this._keepValues}
2272
+ title=${this._keepValues ? 'Export keeps param values' : 'Export redacts param values; keys stay'}
2273
+ @click=${() => (this._keepValues = !this._keepValues)}
2274
+ >
2275
+ Param values
2276
+ </button>
2277
+ <button
2278
+ aria-pressed=${this._keepMessages}
2279
+ title=${this._keepMessages ? 'Export keeps error messages' : 'Export drops error messages'}
2280
+ @click=${() => (this._keepMessages = !this._keepMessages)}
2281
+ >
2282
+ Messages
2283
+ </button>
2284
+ </div>`;
2285
+ }
2286
+
2287
+ _sessionButtons(): TemplateResult {
2288
+ return html`<button
2289
+ @click=${this.#export}
2290
+ aria-label="Export session as JSON"
2291
+ >
2292
+ Export</button
2293
+ >${
2294
+ this._imported
2295
+ ? html`<button
2296
+ @click=${this.#goLive}
2297
+ aria-label="Live: return to the live router"
2298
+ >
2299
+ Live
2300
+ </button>`
2301
+ : html`<button
2302
+ @click=${() => this.renderRoot.querySelector<HTMLInputElement>('.file')?.click()}
2303
+ aria-label="Import session from JSON"
2304
+ >
2305
+ Import
2306
+ </button>`
2307
+ }`;
2308
+ }
2309
+
2310
+ #renderTitle() {
2311
+ const count = (outcome: string) =>
2312
+ this._model.txs.filter((tx) => tx.result?.outcome === outcome).length;
2313
+
2314
+ const counts = [
2315
+ ['success', count('success'), 'succeeded'],
2316
+ ['error', count('error') + count('invalid'), 'failed'],
2317
+ ['redirected', count('redirected'), 'redirected'],
2318
+ ] as const;
2319
+
2320
+ const imported = this._imported;
2321
+
2322
+ return html`<div class="titlestrip">
2323
+ <button
2324
+ class="brand ${this._inspect === 'router' || this._inspect === 'tx' ? 'anchor' : ''}"
2325
+ aria-pressed=${this._inspect === 'router'}
2326
+ title="Router configuration"
2327
+ @click=${this.#toggleRouter}
2328
+ >
2329
+ Router
2330
+ </button>
2331
+ <div class="strip-switch">${this.#renderSwitch()}</div>
2332
+ ${this.#renderTabs()}
2333
+ ${imported ? html`<span class="imported tag" title=${imported.session.routerId}>Imported</span>` : nothing}
2334
+ <span class="spacer"
2335
+ >${
2336
+ this._notice
2337
+ ? html`<span
2338
+ class="notice ${this._notice.fault ? 'fault' : ''}"
2339
+ title=${this._notice.text}
2340
+ >${this._notice.text}</span
2341
+ >`
2342
+ : nothing
2343
+ }</span
2344
+ >
2345
+ <span class="counts">
2346
+ ${counts.map(
2347
+ ([status, n, label]) =>
2348
+ html`<span
2349
+ class="count status-${status} ${n ? '' : 'zero'}"
2350
+ title="${n} ${label}"
2351
+ >${statusGlyph(status)}<span class="num">${n}</span
2352
+ ><span class="visually-hidden">${label}</span></span
2353
+ >`,
2354
+ )}
2355
+ </span>
2356
+ <span class="session">${this._sessionButtons()}</span>
2357
+ <button
2358
+ class="icon max"
2359
+ aria-pressed=${this._max}
2360
+ aria-label="Maximise devtools"
2361
+ title=${this._max ? 'Restore the dock' : 'Maximise'}
2362
+ @click=${() => {
2363
+ this._max = !this._max;
2364
+ this._fit();
2365
+ }}
2366
+ >
2367
+ ${this._max ? minGlyph : maxGlyph}
2368
+ </button>
2369
+ <button
2370
+ class="icon close"
2371
+ aria-label="Collapse devtools"
2372
+ @click=${this.#close}
2373
+ >
2374
+ ${closeGlyph}
2375
+ </button>
2376
+ </div>`;
2377
+ }
2378
+ }