@johnoscott/isometric-engine 0.0.0-stage → 0.10.1

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 (310) hide show
  1. package/EDITOR-GUIDE.md +355 -0
  2. package/LICENSE +21 -0
  3. package/LICENSES/ajv.txt +22 -0
  4. package/LICENSES/lucide-static.txt +43 -0
  5. package/LICENSES/yaml.txt +13 -0
  6. package/README.md +62 -2
  7. package/assets/app.css +269 -0
  8. package/assets/default-theme.yaml +99 -0
  9. package/assets/icons.svg +1 -0
  10. package/assets/marks.css +39 -0
  11. package/assets/skin.css +181 -0
  12. package/iso-editor.d.ts +4 -0
  13. package/iso-editor.js +550 -0
  14. package/iso-render.d.ts +3 -0
  15. package/iso-render.js +388 -0
  16. package/iso-systems.d.ts +4 -0
  17. package/iso-systems.js +389 -0
  18. package/js/iso-core/compile-schema.js +22 -0
  19. package/js/iso-core/depth.js +55 -0
  20. package/js/iso-core/errors.js +65 -0
  21. package/js/iso-core/glyphs.js +100 -0
  22. package/js/iso-core/index.js +55 -0
  23. package/js/iso-core/kernel.js +158 -0
  24. package/js/iso-core/metrics.json +1 -0
  25. package/js/iso-core/package.json +6 -0
  26. package/js/iso-core/parse.js +79 -0
  27. package/js/iso-core/schema-errors.js +170 -0
  28. package/js/iso-core/shims/crypto.js +125 -0
  29. package/js/iso-core/shims/path.js +49 -0
  30. package/js/iso-core/svg-dom.js +144 -0
  31. package/js/iso-core/theme.js +48 -0
  32. package/js/iso-core/vdom.js +48 -0
  33. package/js/iso-editor/adapter.js +0 -0
  34. package/js/iso-editor/clipboard.js +152 -0
  35. package/js/iso-editor/commands.js +173 -0
  36. package/js/iso-editor/complete.js +55 -0
  37. package/js/iso-editor/doc.js +182 -0
  38. package/js/iso-editor/index.js +105 -0
  39. package/js/iso-editor/model.js +210 -0
  40. package/js/iso-editor/outline.js +111 -0
  41. package/js/iso-editor/package.json +6 -0
  42. package/js/iso-editor/path.js +19 -0
  43. package/js/iso-editor/providers.js +96 -0
  44. package/js/iso-editor/schema-nav.js +117 -0
  45. package/js/iso-editor/splice.js +443 -0
  46. package/js/iso-editor/storage-keys.js +6 -0
  47. package/js/iso-editor/ui/actions.js +116 -0
  48. package/js/iso-editor/ui/canvas-layer.js +0 -0
  49. package/js/iso-editor/ui/canvas.js +1403 -0
  50. package/js/iso-editor/ui/clip.js +133 -0
  51. package/js/iso-editor/ui/dialog.js +26 -0
  52. package/js/iso-editor/ui/flat-canvas.js +54 -0
  53. package/js/iso-editor/ui/icons.js +15 -0
  54. package/js/iso-editor/ui/keys.js +26 -0
  55. package/js/iso-editor/ui/later.js +28 -0
  56. package/js/iso-editor/ui/layer.js +11 -0
  57. package/js/iso-editor/ui/menu.js +105 -0
  58. package/js/iso-editor/ui/monaco-entry.js +2 -0
  59. package/js/iso-editor/ui/mount-kit.js +0 -0
  60. package/js/iso-editor/ui/mount.js +767 -0
  61. package/js/iso-editor/ui/pane.js +0 -0
  62. package/js/iso-editor/ui/part.js +0 -0
  63. package/js/iso-editor/ui/plain-icons.js +34 -0
  64. package/js/iso-editor/ui/props.js +314 -0
  65. package/js/iso-editor/ui/scope-css.js +81 -0
  66. package/js/iso-editor/ui/setup.js +149 -0
  67. package/js/iso-editor/ui/text.js +323 -0
  68. package/js/iso-editor/ui/tree.js +728 -0
  69. package/js/iso-editor/validate.js +33 -0
  70. package/js/iso-editor/window/protocol.js +8 -0
  71. package/js/iso-objects/assemble.js +43 -0
  72. package/js/iso-objects/assets.js +88 -0
  73. package/js/iso-objects/board.js +162 -0
  74. package/js/iso-objects/compile.js +60 -0
  75. package/js/iso-objects/css.js +154 -0
  76. package/js/iso-objects/flat.js +696 -0
  77. package/js/iso-objects/focus.js +16 -0
  78. package/js/iso-objects/geometry.js +76 -0
  79. package/js/iso-objects/index.js +93 -0
  80. package/js/iso-objects/kinds.js +12 -0
  81. package/js/iso-objects/labels.js +325 -0
  82. package/js/iso-objects/package.json +6 -0
  83. package/js/iso-objects/place.js +347 -0
  84. package/js/iso-objects/route.js +461 -0
  85. package/js/iso-objects/scene.js +350 -0
  86. package/js/iso-objects/steps.js +246 -0
  87. package/js/iso-objects/types.js +0 -0
  88. package/js/iso-systems/catalog.js +42 -0
  89. package/js/iso-systems/compile.js +34 -0
  90. package/js/iso-systems/css.js +8 -0
  91. package/js/iso-systems/index.js +16 -0
  92. package/js/iso-systems/nodes.js +124 -0
  93. package/js/iso-systems/package.json +6 -0
  94. package/js/iso-systems/schema.json +311 -0
  95. package/js/iso-systems/validate.js +35 -0
  96. package/js/iso-viewer/bundle.js +20 -0
  97. package/js/iso-viewer/card-motion.js +228 -0
  98. package/js/iso-viewer/dom.js +14 -0
  99. package/js/iso-viewer/dual-view.js +212 -0
  100. package/js/iso-viewer/flat-view.js +124 -0
  101. package/js/iso-viewer/history.js +990 -0
  102. package/js/iso-viewer/index.js +98 -0
  103. package/js/iso-viewer/morph.js +192 -0
  104. package/js/iso-viewer/overlay.js +199 -0
  105. package/js/iso-viewer/package.json +6 -0
  106. package/js/iso-viewer/page.js +138 -0
  107. package/js/iso-viewer/player.js +409 -0
  108. package/js/iso-viewer/still.js +81 -0
  109. package/js/iso-viewer/timeline-contract.js +14 -0
  110. package/js/iso-viewer/timeline-engine.js +475 -0
  111. package/js/iso-viewer/timeline-export.js +36 -0
  112. package/js/iso-viewer/timeline-scale.js +116 -0
  113. package/js/iso-viewer/timeline-scope.js +58 -0
  114. package/js/iso-viewer/timeline-search.js +216 -0
  115. package/js/iso-viewer/timeline-time.js +55 -0
  116. package/js/iso-viewer/view-css.js +68 -0
  117. package/js/iso-viewer/viewport.js +177 -0
  118. package/package.json +511 -4
  119. package/src/iso-core/compile-schema.ts +23 -0
  120. package/src/iso-core/depth.ts +56 -0
  121. package/src/iso-core/errors.ts +73 -0
  122. package/src/iso-core/glyphs.ts +108 -0
  123. package/src/iso-core/index.ts +27 -0
  124. package/src/iso-core/kernel.ts +163 -0
  125. package/src/iso-core/metrics.json +1 -0
  126. package/src/iso-core/package.json +6 -0
  127. package/src/iso-core/parse.ts +91 -0
  128. package/src/iso-core/schema-errors.ts +163 -0
  129. package/src/iso-core/shims/crypto.ts +37 -0
  130. package/src/iso-core/shims/path.ts +24 -0
  131. package/src/iso-core/svg-dom.ts +103 -0
  132. package/src/iso-core/theme.ts +64 -0
  133. package/src/iso-core/vdom.ts +41 -0
  134. package/src/iso-editor/adapter.ts +147 -0
  135. package/src/iso-editor/clipboard.ts +163 -0
  136. package/src/iso-editor/commands.ts +191 -0
  137. package/src/iso-editor/complete.ts +73 -0
  138. package/src/iso-editor/doc.ts +207 -0
  139. package/src/iso-editor/index.ts +67 -0
  140. package/src/iso-editor/model.ts +234 -0
  141. package/src/iso-editor/outline.ts +126 -0
  142. package/src/iso-editor/package.json +6 -0
  143. package/src/iso-editor/path.ts +18 -0
  144. package/src/iso-editor/providers.ts +113 -0
  145. package/src/iso-editor/schema-nav.ts +129 -0
  146. package/src/iso-editor/splice.ts +477 -0
  147. package/src/iso-editor/storage-keys.ts +6 -0
  148. package/src/iso-editor/ui/actions.ts +119 -0
  149. package/src/iso-editor/ui/app.css +230 -0
  150. package/src/iso-editor/ui/canvas-layer.ts +56 -0
  151. package/src/iso-editor/ui/canvas.ts +1227 -0
  152. package/src/iso-editor/ui/clip.ts +97 -0
  153. package/src/iso-editor/ui/dialog.ts +25 -0
  154. package/src/iso-editor/ui/flat-canvas.ts +51 -0
  155. package/src/iso-editor/ui/icons.ts +21 -0
  156. package/src/iso-editor/ui/keys.ts +30 -0
  157. package/src/iso-editor/ui/later.ts +22 -0
  158. package/src/iso-editor/ui/layer.ts +7 -0
  159. package/src/iso-editor/ui/marks.css +39 -0
  160. package/src/iso-editor/ui/menu.ts +67 -0
  161. package/src/iso-editor/ui/monaco-entry.ts +6 -0
  162. package/src/iso-editor/ui/mount-kit.ts +35 -0
  163. package/src/iso-editor/ui/mount.ts +684 -0
  164. package/src/iso-editor/ui/pane.ts +45 -0
  165. package/src/iso-editor/ui/part.ts +45 -0
  166. package/src/iso-editor/ui/plain-icons.ts +83 -0
  167. package/src/iso-editor/ui/props.ts +347 -0
  168. package/src/iso-editor/ui/scope-css.ts +65 -0
  169. package/src/iso-editor/ui/setup.ts +153 -0
  170. package/src/iso-editor/ui/skin.css +181 -0
  171. package/src/iso-editor/ui/text.ts +262 -0
  172. package/src/iso-editor/ui/tree.ts +657 -0
  173. package/src/iso-editor/validate.ts +62 -0
  174. package/src/iso-editor/window/protocol.ts +33 -0
  175. package/src/iso-objects/assemble.ts +57 -0
  176. package/src/iso-objects/assets.ts +122 -0
  177. package/src/iso-objects/board.ts +169 -0
  178. package/src/iso-objects/compile.ts +76 -0
  179. package/src/iso-objects/css.ts +163 -0
  180. package/src/iso-objects/flat.ts +653 -0
  181. package/src/iso-objects/focus.ts +14 -0
  182. package/src/iso-objects/geometry.ts +86 -0
  183. package/src/iso-objects/index.ts +33 -0
  184. package/src/iso-objects/kinds.ts +56 -0
  185. package/src/iso-objects/labels.ts +310 -0
  186. package/src/iso-objects/package.json +6 -0
  187. package/src/iso-objects/place.ts +318 -0
  188. package/src/iso-objects/route.ts +444 -0
  189. package/src/iso-objects/scene.ts +376 -0
  190. package/src/iso-objects/steps.ts +234 -0
  191. package/src/iso-objects/types.ts +68 -0
  192. package/src/iso-systems/catalog.ts +31 -0
  193. package/src/iso-systems/compile.ts +39 -0
  194. package/src/iso-systems/css.ts +9 -0
  195. package/src/iso-systems/index.ts +12 -0
  196. package/src/iso-systems/nodes.ts +126 -0
  197. package/src/iso-systems/package.json +6 -0
  198. package/src/iso-systems/schema.json +311 -0
  199. package/src/iso-systems/validate.ts +34 -0
  200. package/src/iso-viewer/bundle.ts +15 -0
  201. package/src/iso-viewer/card-motion.ts +237 -0
  202. package/src/iso-viewer/dom.ts +13 -0
  203. package/src/iso-viewer/dual-view.ts +212 -0
  204. package/src/iso-viewer/flat-view.ts +127 -0
  205. package/src/iso-viewer/history.ts +781 -0
  206. package/src/iso-viewer/index.ts +40 -0
  207. package/src/iso-viewer/morph.ts +191 -0
  208. package/src/iso-viewer/overlay.ts +212 -0
  209. package/src/iso-viewer/package.json +6 -0
  210. package/src/iso-viewer/page.ts +150 -0
  211. package/src/iso-viewer/player.ts +321 -0
  212. package/src/iso-viewer/still.ts +74 -0
  213. package/src/iso-viewer/timeline-contract.ts +342 -0
  214. package/src/iso-viewer/timeline-engine.ts +420 -0
  215. package/src/iso-viewer/timeline-export.ts +31 -0
  216. package/src/iso-viewer/timeline-scale.ts +129 -0
  217. package/src/iso-viewer/timeline-scope.ts +56 -0
  218. package/src/iso-viewer/timeline-search.ts +198 -0
  219. package/src/iso-viewer/timeline-time.ts +54 -0
  220. package/src/iso-viewer/view-css.ts +59 -0
  221. package/src/iso-viewer/viewport.ts +142 -0
  222. package/types/iso-core/compile-schema.d.ts +11 -0
  223. package/types/iso-core/depth.d.ts +6 -0
  224. package/types/iso-core/errors.d.ts +24 -0
  225. package/types/iso-core/glyphs.d.ts +19 -0
  226. package/types/iso-core/index.d.ts +17 -0
  227. package/types/iso-core/kernel.d.ts +130 -0
  228. package/types/iso-core/metrics.json +1 -0
  229. package/types/iso-core/parse.d.ts +18 -0
  230. package/types/iso-core/schema-errors.d.ts +14 -0
  231. package/types/iso-core/shims/crypto.d.ts +9 -0
  232. package/types/iso-core/svg-dom.d.ts +15 -0
  233. package/types/iso-core/theme.d.ts +38 -0
  234. package/types/iso-core/vdom.d.ts +26 -0
  235. package/types/iso-editor/adapter.d.ts +178 -0
  236. package/types/iso-editor/clipboard.d.ts +23 -0
  237. package/types/iso-editor/commands.d.ts +32 -0
  238. package/types/iso-editor/complete.d.ts +25 -0
  239. package/types/iso-editor/doc.d.ts +50 -0
  240. package/types/iso-editor/index.d.ts +57 -0
  241. package/types/iso-editor/model.d.ts +96 -0
  242. package/types/iso-editor/outline.d.ts +28 -0
  243. package/types/iso-editor/path.d.ts +7 -0
  244. package/types/iso-editor/providers.d.ts +43 -0
  245. package/types/iso-editor/schema-nav.d.ts +34 -0
  246. package/types/iso-editor/splice.d.ts +53 -0
  247. package/types/iso-editor/storage-keys.d.ts +5 -0
  248. package/types/iso-editor/ui/actions.d.ts +23 -0
  249. package/types/iso-editor/ui/canvas-layer.d.ts +65 -0
  250. package/types/iso-editor/ui/canvas.d.ts +307 -0
  251. package/types/iso-editor/ui/clip.d.ts +14 -0
  252. package/types/iso-editor/ui/dialog.d.ts +7 -0
  253. package/types/iso-editor/ui/flat-canvas.d.ts +2 -0
  254. package/types/iso-editor/ui/icons.d.ts +5 -0
  255. package/types/iso-editor/ui/keys.d.ts +7 -0
  256. package/types/iso-editor/ui/later.d.ts +12 -0
  257. package/types/iso-editor/ui/layer.d.ts +2 -0
  258. package/types/iso-editor/ui/menu.d.ts +21 -0
  259. package/types/iso-editor/ui/mount-kit.d.ts +31 -0
  260. package/types/iso-editor/ui/mount.d.ts +146 -0
  261. package/types/iso-editor/ui/pane.d.ts +60 -0
  262. package/types/iso-editor/ui/part.d.ts +40 -0
  263. package/types/iso-editor/ui/plain-icons.d.ts +10 -0
  264. package/types/iso-editor/ui/props.d.ts +57 -0
  265. package/types/iso-editor/ui/scope-css.d.ts +5 -0
  266. package/types/iso-editor/ui/setup.d.ts +49 -0
  267. package/types/iso-editor/ui/text.d.ts +19 -0
  268. package/types/iso-editor/ui/tree.d.ts +100 -0
  269. package/types/iso-editor/validate.d.ts +36 -0
  270. package/types/iso-editor/window/protocol.d.ts +60 -0
  271. package/types/iso-objects/assemble.d.ts +35 -0
  272. package/types/iso-objects/assets.d.ts +49 -0
  273. package/types/iso-objects/board.d.ts +36 -0
  274. package/types/iso-objects/compile.d.ts +35 -0
  275. package/types/iso-objects/css.d.ts +16 -0
  276. package/types/iso-objects/flat.d.ts +130 -0
  277. package/types/iso-objects/focus.d.ts +1 -0
  278. package/types/iso-objects/geometry.d.ts +59 -0
  279. package/types/iso-objects/index.d.ts +26 -0
  280. package/types/iso-objects/kinds.d.ts +53 -0
  281. package/types/iso-objects/labels.d.ts +92 -0
  282. package/types/iso-objects/place.d.ts +25 -0
  283. package/types/iso-objects/route.d.ts +67 -0
  284. package/types/iso-objects/scene.d.ts +63 -0
  285. package/types/iso-objects/steps.d.ts +90 -0
  286. package/types/iso-objects/types.d.ts +140 -0
  287. package/types/iso-systems/catalog.d.ts +4 -0
  288. package/types/iso-systems/compile.d.ts +6 -0
  289. package/types/iso-systems/css.d.ts +3 -0
  290. package/types/iso-systems/index.d.ts +5 -0
  291. package/types/iso-systems/nodes.d.ts +3 -0
  292. package/types/iso-viewer/card-motion.d.ts +56 -0
  293. package/types/iso-viewer/dom.d.ts +1 -0
  294. package/types/iso-viewer/dual-view.d.ts +44 -0
  295. package/types/iso-viewer/flat-view.d.ts +25 -0
  296. package/types/iso-viewer/history.d.ts +91 -0
  297. package/types/iso-viewer/index.d.ts +31 -0
  298. package/types/iso-viewer/morph.d.ts +28 -0
  299. package/types/iso-viewer/overlay.d.ts +135 -0
  300. package/types/iso-viewer/page.d.ts +13 -0
  301. package/types/iso-viewer/still.d.ts +26 -0
  302. package/types/iso-viewer/timeline-contract.d.ts +345 -0
  303. package/types/iso-viewer/timeline-engine.d.ts +20 -0
  304. package/types/iso-viewer/timeline-export.d.ts +5 -0
  305. package/types/iso-viewer/timeline-scale.d.ts +44 -0
  306. package/types/iso-viewer/timeline-scope.d.ts +33 -0
  307. package/types/iso-viewer/timeline-search.d.ts +52 -0
  308. package/types/iso-viewer/timeline-time.d.ts +8 -0
  309. package/types/iso-viewer/view-css.d.ts +7 -0
  310. package/types/iso-viewer/viewport.d.ts +50 -0
@@ -0,0 +1,781 @@
1
+ // The timeline component (docs/timeline/README.md): a host's history, from a machine down to its smallest scope, over
2
+ // any TimelineSource<T> (a host's records, a recorded fixture, a simulation). The same flat 2D lanes, pan, zoom and
3
+ // playhead as a simulation's timeline panel, with
4
+ // - rows by scope and depth, breadcrumbs, and drilling in;
5
+ // - semantic zoom: single marks and spans when zoomed in, count bars and heat strips by bin when zoomed out, metric
6
+ // rows as small area charts (counters as sums, gauges as min/max bands), quick ranges;
7
+ // - time breaks: long empty stretches drawn as a narrow saw-tooth cut, labelled, expanded by a click;
8
+ // - the search language (the component parses; the query carries the parse), hits stepped with next and previous,
9
+ // facets, the view in the URL, saved views (the host stores them);
10
+ // - a brushed range's events in a table, exported as JSON or CSV; an event's detail with the domain's actions;
11
+ // - live at the right edge, paused when scrubbed into the past;
12
+ // - the playhead drives a canvas where a state was recorded (stateAt), and says so where none was.
13
+ // Nothing here talks to a server: every fetch is the source's, every link the host's. What the scopes, flags, links
14
+ // and actions mean is the domain's (its catalogue, and actions()).
15
+
16
+ import type { Bin, Catalog, Filters, MetricPoint, MetricRollup, Query, Result, Row, Scope, Severity, TimelineEvent, TimelineSource, View, SourceInfo, TimelineCatalog, TimelineTypes, AnyTimeline } from './timeline-contract.ts';
17
+ import { BIN_MS, SEVERITIES } from './timeline-contract.ts';
18
+ import { highlights, searchFor } from './timeline-search.ts';
19
+ import { crumbs, levelOf, prefixAt } from './timeline-scope.ts';
20
+ import { findGaps, gapKey, gapLabel, ticks, timeScale, type Gap, type TimeScale } from './timeline-scale.ts';
21
+ import { toCSV, toJSON } from './timeline-export.ts';
22
+ import { h } from './dom.ts';
23
+
24
+ export interface TimelineMountOptions<T extends TimelineTypes = AnyTimeline> {
25
+ source: TimelineSource<T>;
26
+ /** the domain's scopes, flags and search links */
27
+ catalog: TimelineCatalog;
28
+ /** classes on the component's root beside its own (the stylesheet it is styled by is scoped to one) */
29
+ rootClass?: string[];
30
+ /** where to start (else the URL's view, else the first host, 1 level down, the last day) */
31
+ view?: Partial<View>;
32
+ /** the owner's time zone (default: the viewer's) */
33
+ tz?: string;
34
+ /** light, dark, or the viewer's (default) */
35
+ theme?: 'light' | 'dark' | 'system';
36
+ /** keep the view in location.hash (#timeline=…) */
37
+ urlState?: boolean;
38
+ /** collapse long empty stretches into time breaks (default true; remembered per view) */
39
+ collapseGaps?: boolean;
40
+ /** animate a time break opening (default: unless the viewer prefers reduced motion) */
41
+ motion?: boolean;
42
+ /** an event's actions, in its detail: a label, and what it does (none: not shown) */
43
+ actions?(e: TimelineEvent<T>): [string, (() => void) | undefined][];
44
+ /** saved views: the host stores them */
45
+ saveView?(v: View): void | Promise<void>;
46
+ views?(): View[] | Promise<View[]>;
47
+ /** the playhead moved: the state recorded there, if any (draw it on a canvas) */
48
+ onPlayhead?(t: number, state: T['state'] | undefined): void;
49
+ /** a recorded state, in words for the canvas's note: when it was observed, and what it belongs to */
50
+ stamp?(state: T['state']): { at?: string; tag?: string };
51
+ onViewChange?(v: View): void;
52
+ /** an export: the host saves it (else the browser downloads it) */
53
+ onExport?(name: string, text: string, type: string): void;
54
+ }
55
+
56
+ const SVGNS = 'http://www.w3.org/2000/svg';
57
+ const ROW = 22, MROW = 38, AXIS = 26, LABELS = 210, CUT = 24;
58
+ const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
59
+ const QUICK = { '15m': 15 * MIN, '1h': HOUR, '1d': DAY, '1w': 7 * DAY } as const;
60
+ const SEV_RANK = (s: string) => (SEVERITIES as readonly string[]).indexOf(s);
61
+ /** the marks' shapes: never colour alone */
62
+ const SHAPE: Record<Severity, string> = { debug: 'dot', info: 'circle', notice: 'square', warning: 'triangle', error: 'diamond' };
63
+ type Mode = { kind: 'single' } | { kind: 'binned'; bin: Bin };
64
+ type Line<T extends TimelineTypes = AnyTimeline> = { kind: 'row'; row: Row<T> } | { kind: 'metric'; series: string; unit: string; type: 'counter' | 'gauge'; title: string };
65
+
66
+ const svgEl = (name: string, attrs: Record<string, string | number | undefined>, title?: string) => {
67
+ const e = document.createElementNS(SVGNS, name);
68
+ for (const [k, v] of Object.entries(attrs)) if (v !== undefined) e.setAttribute(k, String(v));
69
+ if (title) { const tt = document.createElementNS(SVGNS, 'title'); tt.textContent = title; e.append(tt); }
70
+ return e;
71
+ };
72
+ const fmtTime = (t: number, tz?: string) => {
73
+ try { return new Intl.DateTimeFormat(undefined, { timeZone: tz, dateStyle: 'medium', timeStyle: 'medium' }).format(t); } catch { return new Date(t).toISOString(); }
74
+ };
75
+ const fmtDur = (ms: number) => (ms < 1000 ? `${Math.round(ms)} ms` : ms < MIN ? `${(ms / 1000).toFixed(1)} s` : gapLabel(ms));
76
+ const fmtNum = (n: number, unit: string) => unit === 'bytes' ? (n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : n >= 1e6 ? `${(n / 1e6).toFixed(1)} MB` : n >= 1e3 ? `${(n / 1e3).toFixed(1)} kB` : `${Math.round(n)} B`) : `${Math.round(n * 10) / 10}${unit === 'count' ? '' : ` ${unit}`}`;
77
+
78
+ /** which zoom level a visible span reads at: single events up to a few hours, then minute, hour and day bins */
79
+ export function modeFor(span: number, px: number): Mode {
80
+ if (span <= 3 * HOUR) return { kind: 'single' };
81
+ for (const b of ['1m', '1h', '1d'] as Bin[]) if (span / BIN_MS[b] <= px / 2) return { kind: 'binned', bin: b };
82
+ return { kind: 'binned', bin: '1d' };
83
+ }
84
+
85
+ /** the activity a result shows (for time breaks): marks, span ends, bins with events, metrics that moved */
86
+ export function activityOf<T extends TimelineTypes = AnyTimeline>(r: Result<T>, mode: Mode, series?: Map<string, 'counter' | 'gauge'>): [number, number][] {
87
+ const out: [number, number][] = [];
88
+ for (const e of r.events ?? []) { out.push([e.t, e.t]); if (e.dur !== undefined && !e.open) out.push([e.t + e.dur, e.t + e.dur]); }
89
+ for (const e of r.spans ?? []) { out.push([e.t, e.t]); if (e.dur !== undefined && !e.open) out.push([e.t + e.dur, e.t + e.dur]); }
90
+ const w = mode.kind === 'binned' ? BIN_MS[mode.bin] : MIN;
91
+ for (const b of r.bins ?? []) if (b.count) out.push([b.t, b.t + BIN_MS[b.bin]]);
92
+ const last = new Map<string, number>();
93
+ for (const m of r.metrics) {
94
+ const v = 'value' in m ? m.value : m.sum, k = `${m.series}|${m.scope}`;
95
+ const moved = (series?.get(m.series) ?? 'counter') === 'counter' ? v !== 0 : last.get(k) !== v;
96
+ last.set(k, v);
97
+ if (moved) out.push([m.t, m.t + w]);
98
+ }
99
+ return out;
100
+ }
101
+
102
+ export function mountTimeline<T extends TimelineTypes = AnyTimeline>(el: HTMLElement, o: TimelineMountOptions<T>) {
103
+ const tz = o.tz ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
104
+ const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
105
+ const motion = o.motion ?? !reduced;
106
+ // a stylesheet scoped to a root class: the component sits in one
107
+ el.classList.add(...(o.rootClass ?? []), 'tlx');
108
+ const { parseSearch, compileSearch } = searchFor(o.catalog);
109
+ const setTheme = (t: 'light' | 'dark' | 'system' = 'system') => { el.style.colorScheme = t === 'system' ? 'light dark' : t; if (t === 'system') delete el.dataset.theme; else el.dataset.theme = t; };
110
+ setTheme(o.theme);
111
+ el.setAttribute('role', 'region');
112
+ el.setAttribute('aria-label', 'Timeline');
113
+
114
+ // ---------- state ----------
115
+ let catalog: Catalog<T> | undefined;
116
+ let scope: Scope = '', depth = 1, q = '', filters: Filters = {}, live = false, collapse = o.collapseGaps ?? true;
117
+ let view = { t0: 0, t1: DAY };
118
+ let result: Result<T> | undefined, resultKey = '', loaded = { from: 0, to: 0, mode: { kind: 'single' } as Mode, key: '' };
119
+ let playhead: number | undefined, playState: T['state'] | undefined, selected: TimelineEvent<T> | undefined;
120
+ let brush: { from: number; to: number } | undefined;
121
+ let follow = true, frame = 0, fetching = 0, pending = false, unsub: (() => void) | undefined, warnings: string[] = [];
122
+ let hits: TimelineEvent<T>[] = [], hitAt = -1;
123
+ const expanded = new Set<string>(), weights = new Map<string, number>();
124
+ let gaps: Gap[] = [], scale: TimeScale = timeScale(0, DAY, 800);
125
+ const seriesInfo = new Map<string, { unit: string; type: 'counter' | 'gauge'; title: string; source: string }>();
126
+ let sensitive: string[] = [];
127
+
128
+ // ---------- the DOM ----------
129
+ const crumbsEl = h('nav', { class: 'tlx-crumbs', 'aria-label': 'Scope' });
130
+ const quick = h('div', { class: 'segmented tlx-quick', role: 'group', 'aria-label': 'Range' });
131
+ for (const k of ['15m', '1h', '1d', '1w', 'run'] as const) {
132
+ const b = h('button', { type: 'button', class: 'seg', 'data-v': k, title: k === 'run' ? 'The latest run' : `The last ${k}` }, k === 'run' ? 'this run' : k);
133
+ b.addEventListener('click', () => setQuick(k));
134
+ quick.append(b);
135
+ }
136
+ const liveBtn = h('button', { type: 'button', class: 'btn sm tlx-live', 'aria-pressed': 'false', title: 'Follow what happens now' }, 'Live');
137
+ const nowBtn = h('button', { type: 'button', class: 'btn sm quiet tlx-now', hidden: true, title: 'Back to the live edge' }, 'Back to now');
138
+ const fitBtn = h('button', { type: 'button', class: 'btn sm quiet tlx-fit', title: 'Everything in this scope' }, 'Fit');
139
+ const gapsBox = h('input', { type: 'checkbox', class: 'tlx-gaps' }) as HTMLInputElement;
140
+ gapsBox.checked = collapse;
141
+ let hideQuiet = true;
142
+ const quietBox = h('input', { type: 'checkbox', class: 'tlx-quiet' }) as HTMLInputElement;
143
+ quietBox.checked = hideQuiet;
144
+ const search = h('input', { type: 'search', class: 'input tlx-q', placeholder: 'Search: words, kind:…, source:…, severity:>=warning, -kind:…', 'aria-label': 'Search the timeline', spellcheck: 'false' }) as HTMLInputElement;
145
+ const hitsEl = h('span', { class: 'tlx-hits', role: 'status', 'aria-live': 'polite' });
146
+ const prevBtn = h('button', { type: 'button', class: 'btn sm quiet tlx-prev', title: 'Previous hit (⇧N)', 'aria-label': 'Previous hit' }, '‹');
147
+ const nextBtn = h('button', { type: 'button', class: 'btn sm quiet tlx-next', title: 'Next hit (N)', 'aria-label': 'Next hit' }, '›');
148
+ const facets = h('div', { class: 'tlx-facets', role: 'group', 'aria-label': 'Sources' });
149
+ const sevSel = h('select', { class: 'input tlx-sev', 'aria-label': 'Severity' },
150
+ h('option', { value: '' }, 'every severity'), ...SEVERITIES.slice(1).map(s => h('option', { value: s }, `${s} and above`))) as HTMLSelectElement;
151
+ const viewsSel = h('select', { class: 'input tlx-views', 'aria-label': 'Saved views', hidden: !o.views }, h('option', { value: '' }, 'Saved views…')) as HTMLSelectElement;
152
+ const saveBtn = h('button', { type: 'button', class: 'btn sm quiet tlx-save', hidden: !o.saveView, title: 'Save this view' }, 'Save view');
153
+ const warnEl = h('div', { class: 'tlx-warn', role: 'status', hidden: true });
154
+ const status = h('div', { class: 'tlx-status', role: 'status' });
155
+ const canvasNote = h('span', { class: 'tlx-canvas-note' });
156
+ const labels = h('div', { class: 'tlx-labels' });
157
+ const lanes = h('div', { class: 'tlx-lanes', tabindex: '0', role: 'application', 'aria-label': 'Timeline lanes: drag to pan, wheel to zoom, drag the axis to choose a range, click it to move the playhead. Keys: ← → pan, + − zoom, N next hit' });
158
+ const svg = svgEl('svg', { class: 'tlx-svg' }) as SVGSVGElement;
159
+ lanes.append(svg);
160
+ const scroller = h('div', { class: 'tlx-scroll' }, h('div', { class: 'tlx-grid' }, labels, lanes));
161
+ const table = h('section', { class: 'tlx-table', hidden: true, 'aria-label': 'The events in the chosen range' });
162
+ const detail = h('aside', { class: 'tlx-detail', hidden: true, 'aria-label': 'The event' });
163
+ el.replaceChildren(
164
+ h('div', { class: 'tlx-bar' }, crumbsEl, h('span', { class: 'spacer' }), quick, liveBtn, nowBtn, fitBtn, h('label', { class: 'tlx-gaps-label', title: 'Draw long empty stretches as narrow breaks' }, gapsBox, 'Collapse gaps'),
165
+ h('label', { class: 'tlx-gaps-label', title: 'Hide the rows with nothing in this range' }, quietBox, 'Hide quiet rows')),
166
+ h('div', { class: 'tlx-bar' }, search, hitsEl, prevBtn, nextBtn, sevSel, viewsSel, saveBtn),
167
+ facets, warnEl,
168
+ h('div', { class: 'tlx-body' }, scroller, detail),
169
+ h('div', { class: 'tlx-foot' }, status, h('span', { class: 'spacer' }), canvasNote),
170
+ table);
171
+
172
+ const width = () => Math.max(200, lanes.clientWidth || 800);
173
+ const lines = (): Line<T>[] => {
174
+ // the scope's own row first, then the rest in a natural order (bash~3 before bash~24); quiet ones hidden if asked
175
+ const collate = (a: Row<T>, b: Row<T>) => (a.own ? -1 : 0) - (b.own ? -1 : 0) || a.scope.localeCompare(b.scope, undefined, { numeric: true });
176
+ const shown = (result?.rows ?? []).filter(r => !hideQuiet || r.count > 0 || r.own || (result?.rows.length ?? 0) <= 1).sort(collate);
177
+ const rs: Line<T>[] = shown.map(row => ({ kind: 'row', row }));
178
+ const present = new Set(result?.metrics.map(m => m.series) ?? []);
179
+ for (const s of [...present].sort()) { const i = seriesInfo.get(s); rs.push({ kind: 'metric', series: s, unit: i?.unit ?? 'count', type: i?.type ?? 'counter', title: i?.title ?? s }); }
180
+ return rs;
181
+ };
182
+ /** a scope's label: the catalogue's, else its last segment's */
183
+ const labelOf = (s: Scope, fallback: string) => catalog?.names?.find(n => n.scope === s)?.label ?? fallback;
184
+ const lineH = (l: Line<T>) => (l.kind === 'metric' ? MROW : ROW);
185
+ const mode = () => modeFor(view.t1 - view.t0, width());
186
+ const nowT = () => catalog?.now ?? Date.now();
187
+
188
+ // ---------- the view, the URL, saved views ----------
189
+ function currentView(): View {
190
+ return { timeline: 1, type: 'view', name: '', scope, depth, range: { from: Math.round(view.t0), to: Math.round(view.t1) }, ...(q ? { q } : {}), ...(Object.keys(filters).length ? { filters } : {}), ...(live ? { live } : {}), ...(collapse ? {} : { collapseGaps: false }), ...(hideQuiet ? {} : { quietRows: true }) } as View;
191
+ }
192
+ function applyView(v: Partial<View> & { collapseGaps?: boolean; quietRows?: boolean }) {
193
+ if (v.scope !== undefined) scope = v.scope;
194
+ if (v.depth !== undefined) depth = v.depth;
195
+ q = v.q ?? ''; search.value = q;
196
+ filters = v.filters ?? {};
197
+ sevSel.value = filters.severity?.length ? filters.severity[0] : '';
198
+ collapse = v.collapseGaps ?? (o.collapseGaps ?? true); gapsBox.checked = collapse;
199
+ hideQuiet = !(v as { quietRows?: boolean }).quietRows; quietBox.checked = hideQuiet;
200
+ expanded.clear(); weights.clear();
201
+ const r = v.range;
202
+ if (r && 'last' in r) setQuick(r.last, false);
203
+ else if (r) view = { t0: r.from, t1: r.to };
204
+ setLive(!!v.live, false);
205
+ }
206
+ const writeUrl = () => {
207
+ const v = currentView();
208
+ o.onViewChange?.(v);
209
+ if (!o.urlState) return;
210
+ try { history.replaceState(null, '', `#timeline=${encodeURIComponent(JSON.stringify(v))}`); } catch { /* a frame that may not */ }
211
+ };
212
+ const readUrl = (): Partial<View> | undefined => {
213
+ if (!o.urlState) return undefined;
214
+ const m = /#timeline=(.+)$/.exec(location.hash);
215
+ if (!m) return undefined;
216
+ try { return JSON.parse(decodeURIComponent(m[1])); } catch { return undefined; }
217
+ };
218
+
219
+ // ---------- fetching ----------
220
+ function query(from: number, to: number, md: Mode, extra: Partial<Query<T>> = {}): Query<T> {
221
+ const c = compileSearch(q, nowT(), from, to);
222
+ warnings = c.warnings;
223
+ // metrics follow what is shown: none while searching (a search is of events), and only the faceted sources'
224
+ const series = q ? [] : filters.source ? [...seriesInfo].filter(([, i]) => filters.source!.includes(i.source)).map(([n]) => n) : undefined;
225
+ return { timeline: 1, type: 'query', scope, depth, from: c.from, to: c.to, tz, ...(md.kind === 'binned' ? { bin: md.bin } : {}), ...(q ? { q, where: c.where as unknown as Query<T>['where'] } : {}), ...(Object.keys(filters).length ? { filters } : {}), ...(series ? { series } : {}), ...extra };
226
+ }
227
+ const keyOf = () => JSON.stringify([scope, depth, q, filters, mode()]);
228
+ /** fetch what the view needs: the visible range padded by half a span each side, again when it leaves that or the mode changes */
229
+ async function refresh(force = false) {
230
+ const md = mode(), key = keyOf(), span = view.t1 - view.t0;
231
+ if (!force && result && key === loaded.key && view.t0 >= loaded.from && view.t1 <= loaded.to) { later(); return; }
232
+ if (fetching) { pending = true; return; }
233
+ fetching++;
234
+ const from = view.t0 - span / 2, to = Math.min(view.t1 + span / 2, Math.max(view.t1, nowT() + span * 0.1));
235
+ try {
236
+ let r = await o.source.query(query(from, to, md, md.kind === 'single' ? { limit: 10000 } : {}));
237
+ // too many single events to draw: the minute bins instead
238
+ if (md.kind === 'single' && r.next) r = await o.source.query(query(from, to, { kind: 'binned', bin: '1m' }));
239
+ result = r; resultKey = key;
240
+ loaded = { from, to, mode: md, key };
241
+ } catch (err) {
242
+ status.textContent = `The history couldn't be read: ${String((err as Error)?.message ?? err)}`;
243
+ } finally {
244
+ fetching--;
245
+ }
246
+ later();
247
+ writeUrl();
248
+ if (pending) { pending = false; void refresh(); }
249
+ }
250
+
251
+ // ---------- the scale and time breaks ----------
252
+ function makeScale() {
253
+ const W = width(), md = mode();
254
+ gaps = [];
255
+ if (collapse && result) {
256
+ const types = new Map([...seriesInfo].map(([k, v]) => [k, v.type] as const));
257
+ gaps = findGaps(activityOf(result, md, types), view.t0, Math.min(view.t1, Math.max(view.t0, nowT())), { minFrac: 0.15, minMs: 10 * MIN });
258
+ if (md.kind === 'binned') gaps = gaps.filter(g => g.to - g.from >= 2 * BIN_MS[md.bin]);
259
+ gaps = gaps.filter(g => !(expanded.has(gapKey(g)) && (weights.get(gapKey(g)) ?? 1) >= 1));
260
+ }
261
+ scale = timeScale(view.t0, view.t1, W, gaps, { cut: CUT, weights });
262
+ }
263
+
264
+ // ---------- painting ----------
265
+ const later = () => { if (!frame) frame = requestAnimationFrame(paint); };
266
+ function paint() {
267
+ frame = 0;
268
+ makeScale();
269
+ const W = width(), L = lines(), md = loaded.mode;
270
+ const ys: number[] = []; let y = AXIS;
271
+ for (const l of L) { ys.push(y); y += lineH(l); }
272
+ const H = Math.max(y, AXIS + ROW);
273
+ svg.setAttribute('width', String(W)); svg.setAttribute('height', String(H)); svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
274
+ // only the rows in view are drawn (the scroller's window), with a margin
275
+ const top = scroller.scrollTop - 200, bottom = scroller.scrollTop + (scroller.clientHeight || 600) + 200;
276
+ const kids: Element[] = [];
277
+ const x = scale.x;
278
+ kids.push(svgEl('rect', { class: 'tlx-axis', x: 0, y: 0, width: W, height: AXIS }));
279
+ // what isn't kept: grey before the earliest time any shown source still holds (each source's own in the title),
280
+ // and the future after now
281
+ const kept = (result?.retention ?? []).map(r => ({ r, from: md.kind === 'binned' ? r.keptFrom.rollups[md.bin] ?? r.keptFrom.events : r.keptFrom.events, days: md.kind === 'binned' ? r.rollups[md.bin] : r.events }));
282
+ const held = kept.filter(k => k.from !== undefined) as { r: (typeof kept)[number]['r']; from: number; days: number | null }[];
283
+ if (held.length) {
284
+ const first = Math.min(...held.map(k => k.from));
285
+ if (first > view.t0) kids.push(svgEl('rect', { class: 'tlx-notkept', x: Math.max(0, x(view.t0)), y: AXIS, width: Math.max(0, x(first) - Math.max(0, x(view.t0))), height: H - AXIS },
286
+ `Nothing kept before ${fmtTime(first, tz)}: ${held.map(k => `${k.r.source} ${k.days === null ? 'kept until deleted' : `kept ${k.days} days`}`).join(', ')}`));
287
+ }
288
+ const now = nowT();
289
+ if (now < view.t1) kids.push(svgEl('rect', { class: 'tlx-future', x: x(now), y: AXIS, width: W - x(now), height: H - AXIS }));
290
+ for (const tk of ticks(scale, tz, 90)) {
291
+ kids.push(svgEl('line', { class: `tlx-tick${tk.major ? ' major' : ''}`, x1: tk.x, x2: tk.x, y1: AXIS - 6, y2: H }));
292
+ const lab = svgEl('text', { class: 'tlx-ticklabel', x: tk.x + 3, y: 16 }); lab.textContent = tk.label; kids.push(lab);
293
+ }
294
+ if (brush) kids.push(svgEl('rect', { class: 'tlx-brush', x: x(brush.from), y: 0, width: Math.max(1, x(brush.to) - x(brush.from)), height: H }));
295
+ // the lanes
296
+ const spans = md.kind === 'single' ? (result?.events ?? []).filter(e => e.dur !== undefined || e.open) : result?.spans ?? [];
297
+ const marks = md.kind === 'single' ? (result?.events ?? []).filter(e => e.dur === undefined && !e.open) : [];
298
+ const rowIndex = new Map<string, number>();
299
+ L.forEach((l, i) => { if (l.kind === 'row') rowIndex.set(l.row.scope, i); });
300
+ const rowOfScope = (s: Scope) => { const lvl = levelOf(scope) + depth; const r = levelOf(s) >= lvl ? prefixAt(s, lvl) : s; return rowIndex.get(r); };
301
+ const visible = (i: number) => ys[i] + lineH(L[i]) >= top && ys[i] <= bottom;
302
+ L.forEach((l, i) => { if (visible(i)) kids.push(svgEl('rect', { class: `tlx-lane${i % 2 ? ' odd' : ''}${l.kind === 'metric' ? ' metric' : ''}`, x: 0, y: ys[i], width: W, height: lineH(l) })); });
303
+ // binned: count bars (height by count, on a row's own scale) and a heat strip (the worst severity)
304
+ if (md.kind === 'binned') {
305
+ const max = new Map<number, number>();
306
+ for (const b of result?.bins ?? []) { const i = rowOfScope(b.scope); if (i !== undefined) max.set(i, Math.max(max.get(i) ?? 0, b.count)); }
307
+ for (const b of result?.bins ?? []) {
308
+ const i = rowOfScope(b.scope);
309
+ if (i === undefined || !visible(i)) continue;
310
+ const a = x(b.t), z = x(b.t + BIN_MS[b.bin]);
311
+ if (z < 0 || a > W) continue;
312
+ const worst = [...SEVERITIES].reverse().find(s => (b.severity[s] ?? 0) > 0) ?? 'info';
313
+ const hgt = Math.max(2, ((ROW - 8) * Math.sqrt(b.count)) / Math.sqrt(max.get(i) || 1));
314
+ kids.push(svgEl('rect', { class: 'tlx-countbar', x: a, y: ys[i] + ROW - 3 - hgt, width: Math.max(1, z - a - 0.5), height: hgt, 'data-t': b.t },
315
+ `${fmtTime(b.t, tz)}: ${b.count} event${b.count === 1 ? '' : 's'}${worst !== 'info' && worst !== 'debug' ? `, the worst ${worst}` : ''}`));
316
+ // the heat strip: warnings and errors only, under the bar (and a glyph's worth of height, not colour alone)
317
+ if (worst === 'warning' || worst === 'error') kids.push(svgEl('rect', { class: `tlx-heat sev-${worst}`, x: a, y: ys[i] + ROW - (worst === 'error' ? 4 : 3), width: Math.max(1, z - a - 0.5), height: worst === 'error' ? 3 : 2 }));
318
+ }
319
+ }
320
+ // spans (sessions, actions, runs): a bar, broken at a time break they last through
321
+ for (const e of spans) {
322
+ const i = rowOfScope(e.scope);
323
+ if (i === undefined || !visible(i)) continue;
324
+ const end = e.open ? now : e.t + (e.dur ?? 0);
325
+ const a = x(e.t), z = x(end);
326
+ if (z < -2 || a > W + 2) continue;
327
+ const cls = `tlx-span sev-${e.severity}${e.open ? ' open' : ''}${selected?.id === e.id ? ' selected' : ''}`;
328
+ const label = `${e.summary} · ${fmtTime(e.t, tz)}${e.open ? ', still going' : `, ${fmtDur(end - e.t)}`}`;
329
+ const sy = ys[i] + 5, sh = md.kind === 'binned' ? 4 : 8;
330
+ // the pieces between the cuts it crosses
331
+ let pa = a;
332
+ for (const c of scale.cuts) {
333
+ if (c.weight >= 1 || c.x1 <= a || c.x0 >= z) continue;
334
+ if (c.x0 > pa) kids.push(svgEl('rect', { class: cls, x: pa, y: sy, width: Math.max(1, c.x0 - pa), height: sh, rx: 2, 'data-id': e.id }, label));
335
+ kids.push(svgEl('path', { class: `${cls} through`, d: `M${c.x0} ${sy + sh / 2} H${c.x1}`, 'data-id': e.id }, `${label} (lasted through the break)`));
336
+ pa = c.x1;
337
+ }
338
+ if (z > pa) kids.push(svgEl('rect', { class: cls, x: Math.max(-2, pa), y: sy, width: Math.max(2, Math.min(W + 2, z) - Math.max(-2, pa)), height: sh, rx: 2, 'data-id': e.id }, label));
339
+ }
340
+ // marks: a shape per severity; dense ones within 3 px of the last on their row aren't drawn again
341
+ const lastX = new Map<number, number>();
342
+ for (const e of marks) {
343
+ const i = rowOfScope(e.scope);
344
+ if (i === undefined || !visible(i)) continue;
345
+ const px = x(e.t);
346
+ if (px < -6 || px > W + 6 || px - (lastX.get(i) ?? -Infinity) < 3) continue;
347
+ lastX.set(i, px);
348
+ const cy = ys[i] + ROW / 2 + 2, r = 4;
349
+ const shape = SHAPE[e.severity];
350
+ const d = shape === 'diamond' ? `M${px} ${cy - r - 1} l${r + 1} ${r + 1} l${-r - 1} ${r + 1} l${-r - 1} ${-r - 1} z` : shape === 'triangle' ? `M${px} ${cy - r - 1} l${r + 1} ${2 * r + 1} h${-2 * r - 2} z` : shape === 'square' ? `M${px - r + 0.5} ${cy - r + 0.5} h${2 * r - 1} v${2 * r - 1} h${-2 * r + 1} z` : '';
351
+ const title = `${fmtTime(e.t, tz)} · ${e.summary}`;
352
+ const cls = `tlx-mark sev-${e.severity}${selected?.id === e.id ? ' selected' : ''}${hitAt >= 0 && hits[hitAt]?.id === e.id ? ' hit' : ''}`;
353
+ kids.push(d ? svgEl('path', { class: cls, d, 'data-id': e.id }, title) : svgEl('circle', { class: cls, cx: px, cy, r: shape === 'dot' ? 2.5 : r, 'data-id': e.id }, title));
354
+ }
355
+ // metric rows: small area charts (counters as sums; gauges as a min/max band and the mean)
356
+ L.forEach((l, i) => {
357
+ if (l.kind !== 'metric' || !visible(i)) return;
358
+ const pts = new Map<number, { min: number; max: number; sum: number; count: number }>();
359
+ for (const m of result?.metrics ?? []) {
360
+ if (m.series !== l.series) continue;
361
+ const f = 'value' in m ? { min: m.value, max: m.value, sum: m.value, count: 1 } : { min: m.min, max: m.max, sum: m.sum, count: m.count };
362
+ const p = pts.get(m.t);
363
+ if (p) { p.min = Math.min(p.min, f.min); p.max = Math.max(p.max, f.max); p.sum += f.sum; p.count += f.count; } else pts.set(m.t, { ...f });
364
+ }
365
+ const series = [...pts].sort((a, b) => a[0] - b[0]);
366
+ if (!series.length) return;
367
+ const w = md.kind === 'binned' ? BIN_MS[md.bin] : MIN;
368
+ const val = (p: { sum: number; count: number }) => (l.type === 'gauge' ? p.sum / Math.max(1, p.count) : p.sum);
369
+ const peak = Math.max(1e-9, ...series.map(([, p]) => (l.type === 'gauge' ? p.max : val(p))));
370
+ const base = ys[i] + MROW - 4, hh = MROW - 10, yv = (v: number) => base - (v / peak) * hh;
371
+ if (l.type === 'gauge') {
372
+ const band = series.map(([t, p]) => `${x(t)},${yv(p.max)}`).join(' ') + ' ' + [...series].reverse().map(([t, p]) => `${x(t)},${yv(p.min)}`).join(' ');
373
+ kids.push(svgEl('polygon', { class: 'tlx-band', points: band }));
374
+ kids.push(svgEl('polyline', { class: 'tlx-line', points: series.map(([t, p]) => `${x(t + w / 2)},${yv(val(p))}`).join(' ') }));
375
+ } else {
376
+ // an area of steps, dropping to zero across gaps in the samples
377
+ let d = '', prevEnd = -Infinity;
378
+ for (const [t, p] of series) {
379
+ const a = x(t), z = x(t + w), v = yv(val(p));
380
+ d += t > prevEnd ? `M${a} ${base} V${v} H${z}` : ` V${v} H${z}`;
381
+ prevEnd = t + w;
382
+ const nxt = series.find(([t2]) => t2 > t);
383
+ if (!nxt || nxt[0] > prevEnd) d += ` V${base} Z`;
384
+ }
385
+ kids.push(svgEl('path', { class: 'tlx-area', d }));
386
+ }
387
+ const lab = svgEl('text', { class: 'tlx-peak', x: 4, y: ys[i] + 11 }); lab.textContent = `peak ${fmtNum(peak, l.unit)}${l.type === 'counter' ? ` per ${md.kind === 'binned' ? md.bin : '1m'}` : ''}`; kids.push(lab);
388
+ });
389
+ // the time breaks: a saw-tooth cut across the axis and every row, its length on it
390
+ for (const c of scale.cuts) {
391
+ if (c.weight >= 1) continue;
392
+ const teeth = (xx: number) => { let d = `M${xx} 0`; for (let yy = 0; yy < H; yy += 8) d += ` L${xx + (((yy / 8) % 2) ? -3 : 3)} ${yy + 8}`; return d; };
393
+ const g = svgEl('g', { class: 'tlx-cut', tabindex: 0, role: 'button', 'data-from': c.from, 'data-to': c.to, 'aria-label': `A break of ${gapLabel(c.to - c.from)} with nothing shown, from ${fmtTime(c.from, tz)} to ${fmtTime(c.to, tz)}: press to open it` },
394
+ `${gapLabel(c.to - c.from)} with nothing here: ${fmtTime(c.from, tz)} to ${fmtTime(c.to, tz)} (click to open)`);
395
+ g.append(svgEl('rect', { class: 'tlx-cut-bg', x: c.x0, y: 0, width: c.x1 - c.x0, height: H }));
396
+ g.append(svgEl('path', { class: 'tlx-cut-edge', d: teeth(c.x0 + 3) }), svgEl('path', { class: 'tlx-cut-edge', d: teeth(c.x1 - 3) }));
397
+ const t = svgEl('text', { class: 'tlx-cut-label', x: (c.x0 + c.x1) / 2, y: 15, 'text-anchor': 'middle' }); t.textContent = gapLabel(c.to - c.from);
398
+ g.append(t);
399
+ kids.push(g);
400
+ }
401
+ if (playhead !== undefined) {
402
+ const px = x(playhead);
403
+ kids.push(svgEl('line', { class: 'tlx-playhead', x1: px, x2: px, y1: 0, y2: H }));
404
+ kids.push(svgEl('path', { class: 'tlx-handle', d: `M${px - 6} 0 h12 v8 l-6 7 l-6 -7 z` }, `the playhead: ${fmtTime(playhead, tz)}`));
405
+ }
406
+ svg.replaceChildren(...kids);
407
+ // labels, beside their lanes
408
+ labels.replaceChildren(h('div', { class: 'tlx-labelhead', style: `height:${AXIS}px` }, mode().kind === 'single' ? 'single events' : `per ${mode().kind === 'binned' ? (mode() as { bin: Bin }).bin : ''}`),
409
+ ...L.map(l => {
410
+ if (l.kind === 'metric') return h('div', { class: 'tlx-rowlabel metric', style: `height:${MROW}px`, title: `${l.title} (${l.type === 'counter' ? 'sums' : 'min, max and mean'})` }, l.title);
411
+ const r = l.row;
412
+ const lab = h('div', { class: `tlx-rowlabel${r.own ? ' own' : ''}`, style: `height:${ROW}px`, 'data-scope': r.scope, title: `${r.scope || 'all hosts'} · ${r.count} event${r.count === 1 ? '' : 's'}` },
413
+ h('span', { class: 'tlx-kind' }, o.catalog.flags.find(f => (r as Record<string, unknown>)[f]) ?? r.kind), h('span', { class: 'tlx-name' }, r.own ? `${r.label} (itself)` : r.label), h('span', { class: 'tlx-count' }, String(r.count)));
414
+ if (!r.own && r.scope !== scope) {
415
+ const b = h('button', { type: 'button', class: 'tlx-drill', title: r.children ? `Into ${r.label}: its ${r.children} part${r.children === 1 ? '' : 's'}` : `Into ${r.label}`, 'aria-label': `Into ${r.label}` }, '›');
416
+ b.addEventListener('click', () => drill(r.scope));
417
+ lab.append(b);
418
+ }
419
+ return lab;
420
+ }));
421
+ labels.style.width = `${LABELS}px`;
422
+ paintChrome();
423
+ }
424
+
425
+ function paintChrome() {
426
+ crumbsEl.replaceChildren(...crumbs(scope).flatMap((c, i, all) => {
427
+ const b = h('button', { type: 'button', class: `tlx-crumb${i === all.length - 1 ? ' current' : ''}`, 'aria-current': i === all.length - 1 ? 'location' : undefined }, labelOf(c.scope, c.label));
428
+ b.addEventListener('click', () => { if (c.scope !== scope) { scope = c.scope; depth = 1; void refresh(true); } });
429
+ return i ? [h('span', { class: 'tlx-sep', 'aria-hidden': 'true' }, '/'), b] : [b];
430
+ }));
431
+ liveBtn.setAttribute('aria-pressed', String(live));
432
+ liveBtn.classList.toggle('on', live);
433
+ nowBtn.hidden = !live || follow;
434
+ const md = mode();
435
+ const total = result?.total ?? 0;
436
+ const kept = (result?.retention ?? []).filter(r => r.events !== null).map(r => `${r.source} kept ${r.events} d`);
437
+ status.textContent = `${fmtTime(view.t0, tz)} – ${fmtTime(view.t1, tz)} · ${md.kind === 'single' ? 'single events' : `bins of ${md.bin}`} · ${total} event${total === 1 ? '' : 's'}${gaps.length ? ` · ${gaps.length} break${gaps.length === 1 ? '' : 's'}` : ''}${kept.length ? ` · ${kept.slice(0, 3).join(', ')}` : ''}`;
438
+ warnEl.hidden = !warnings.length;
439
+ warnEl.textContent = warnings.join(' · ');
440
+ hitsEl.textContent = q ? (hits.length ? `${hitAt + 1 > 0 ? `${hitAt + 1} of ` : ''}${hits.length}${hits.length >= 2000 ? '+' : ''} hit${hits.length === 1 ? '' : 's'}` : `${total ? `${total} hit${total === 1 ? '' : 's'}` : 'no hits'}`) : '';
441
+ for (const b of quick.querySelectorAll<HTMLButtonElement>('.seg')) b.classList.remove('on');
442
+ canvasNote.textContent = playhead === undefined ? '' : playState ? (() => { const st = o.stamp?.(playState) ?? {}; return `Canvas: the state recorded at ${fmtTime(Date.parse(st.at ?? '') || playhead, tz)}${st.tag ? ` (${st.tag})` : ''}`; })() : 'No state recorded here';
443
+ canvasNote.classList.toggle('none', playhead !== undefined && !playState);
444
+ }
445
+
446
+ // ---------- facets ----------
447
+ function paintFacets() {
448
+ facets.replaceChildren();
449
+ for (const s of catalog?.sources ?? []) {
450
+ const on = !filters.source?.length || filters.source.includes(s.name);
451
+ const b = h('button', { type: 'button', class: `tlx-chip${on ? ' on' : ''}${s.status === 'not-yet' ? ' notyet' : ''}`, 'aria-pressed': String(on && s.status !== 'not-yet'), disabled: s.status === 'not-yet',
452
+ title: s.status === 'not-yet' ? `${s.title}: not kept yet` : `${s.title}${retentionText(s)}` }, s.name);
453
+ if (s.status !== 'not-yet') b.addEventListener('click', () => toggleSource(s.name));
454
+ facets.append(b);
455
+ }
456
+ }
457
+ const retentionText = (s: SourceInfo<T>) => { const r = catalog?.retention.find(x => x.source === s.name); return r ? ` (kept ${r.events === null ? 'until deleted' : `${r.events} days`})` : ''; };
458
+ function toggleSource(name: string) {
459
+ const all = (catalog?.sources ?? []).filter(s => s.status === 'kept').map(s => s.name);
460
+ let cur = filters.source?.length ? [...filters.source] : [...all];
461
+ cur = cur.includes(name) ? cur.filter(x => x !== name) : [...cur, name];
462
+ filters = { ...filters, ...(cur.length === all.length ? { source: undefined } : { source: cur }) };
463
+ if (!filters.source) delete filters.source;
464
+ paintFacets(); void refresh(true); void findHits();
465
+ }
466
+
467
+ // ---------- search and hits ----------
468
+ let typing = 0;
469
+ search.addEventListener('input', () => { clearTimeout(typing); typing = setTimeout(() => { q = search.value.trim(); hitAt = -1; void refresh(true); void findHits(); }, 250) as unknown as number; });
470
+ search.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); clearTimeout(typing); q = search.value.trim(); void refresh(true).then(() => findHits()).then(() => stepHit(e.shiftKey ? -1 : 1)); } });
471
+ async function findHits() {
472
+ if (!q) { hits = []; hitAt = -1; paintChrome(); return; }
473
+ const span = view.t1 - view.t0;
474
+ const r = await o.source.query(query(view.t0 - span * 4, Math.max(view.t1 + span * 4, nowT()), { kind: 'single' }, { limit: 2000 }));
475
+ hits = r.events ?? []; hitAt = Math.min(hitAt, hits.length - 1);
476
+ paintChrome();
477
+ }
478
+ function stepHit(dir: 1 | -1) {
479
+ if (!hits.length) return;
480
+ const center = (view.t0 + view.t1) / 2;
481
+ if (hitAt < 0) hitAt = dir > 0 ? Math.max(0, hits.findIndex(e => e.t >= center)) : Math.max(0, hits.length - 1 - [...hits].reverse().findIndex(e => e.t <= center));
482
+ else hitAt = (hitAt + dir + hits.length) % hits.length;
483
+ const e = hits[hitAt];
484
+ const span = Math.min(view.t1 - view.t0, 2 * HOUR);
485
+ view = { t0: e.t - span / 2, t1: e.t + span / 2 }; follow = false;
486
+ select(e);
487
+ void refresh();
488
+ }
489
+ prevBtn.addEventListener('click', () => stepHit(-1));
490
+ nextBtn.addEventListener('click', () => stepHit(1));
491
+ sevSel.addEventListener('change', () => {
492
+ const v = sevSel.value as Severity | '';
493
+ filters = { ...filters, ...(v ? { severity: SEVERITIES.filter(s => SEV_RANK(s) >= SEV_RANK(v)) } : {}) };
494
+ if (!v) delete filters.severity;
495
+ void refresh(true); void findHits();
496
+ });
497
+
498
+ // ---------- ranges, live, drilling ----------
499
+ async function setQuick(k: keyof typeof QUICK | 'run', go = true) {
500
+ const now = nowT();
501
+ if (k === 'run') {
502
+ const r = await o.source.query({ timeline: 1, type: 'query', scope, depth: 0, from: now - 30 * DAY, to: now + 1, filters: { kind: ['run'] }, limit: 10000 }).catch(() => undefined);
503
+ const run = r?.events?.[r.events.length - 1];
504
+ view = run ? { t0: run.t - (run.dur ?? HOUR) * 0.02, t1: (run.open ? now : run.t + (run.dur ?? HOUR)) + (run.dur ?? HOUR) * 0.04 } : { t0: now - DAY, t1: now + DAY * 0.02 };
505
+ } else view = { t0: now - QUICK[k], t1: now + QUICK[k] * 0.02 };
506
+ follow = true; expanded.clear(); weights.clear();
507
+ if (go) void refresh();
508
+ }
509
+ function setLive(on: boolean, go = true) {
510
+ live = on;
511
+ unsub?.(); unsub = undefined;
512
+ if (on && o.source.subscribe) {
513
+ let last = 0, wait = 0;
514
+ unsub = o.source.subscribe(query(nowT() - HOUR, nowT() + 365 * DAY, { kind: 'single' }), b => {
515
+ if (catalog) catalog.now = Math.max(catalog.now, b.now);
516
+ if (follow) { const span = view.t1 - view.t0; view = { t0: b.now - span * 0.98, t1: b.now + span * 0.02 }; }
517
+ // re-read at most twice a second (the host bins; a burst is one read)
518
+ const t = Date.now();
519
+ if (t - last > 500) { last = t; void refresh(true); } else if (!wait) wait = setTimeout(() => { wait = 0; last = Date.now(); void refresh(true); }, 500) as unknown as number;
520
+ });
521
+ follow = true;
522
+ }
523
+ if (go) { paintChrome(); writeUrl(); }
524
+ }
525
+ liveBtn.addEventListener('click', () => setLive(!live));
526
+ nowBtn.addEventListener('click', () => { follow = true; const span = view.t1 - view.t0, now = nowT(); view = { t0: now - span * 0.98, t1: now + span * 0.02 }; void refresh(); });
527
+ fitBtn.addEventListener('click', () => void fit());
528
+ gapsBox.addEventListener('change', () => { collapse = gapsBox.checked; expanded.clear(); weights.clear(); later(); writeUrl(); });
529
+ quietBox.addEventListener('change', () => { hideQuiet = quietBox.checked; later(); writeUrl(); });
530
+ /** into a scope: its parts as rows (a scope with none, a session: itself, one row) */
531
+ function drill(s: Scope) {
532
+ const row = result?.rows.find(r => r.scope === s);
533
+ scope = s; depth = row && row.children === 0 ? 0 : 1; brush = undefined; table.hidden = true;
534
+ void refresh(true);
535
+ }
536
+ async function fit() {
537
+ const now = nowT();
538
+ const r = await o.source.query({ timeline: 1, type: 'query', scope, depth: 0, from: now - 400 * DAY, to: now + 1, bin: '1d', tz }).catch(() => undefined);
539
+ const ts = (r?.bins ?? []).map(b => b.t);
540
+ const t0 = ts.length ? Math.min(...ts) : now - 7 * DAY;
541
+ view = { t0, t1: now + (now - t0) * 0.02 }; follow = true;
542
+ void refresh();
543
+ }
544
+
545
+ // ---------- the playhead and the canvas ----------
546
+ let stateReq = 0;
547
+ async function setPlayhead(t: number | undefined) {
548
+ playhead = t;
549
+ later();
550
+ if (t === undefined) { playState = undefined; return; }
551
+ const mine = ++stateReq;
552
+ const s = o.source.stateAt ? await o.source.stateAt(scope, t).catch(() => undefined) : undefined;
553
+ if (mine !== stateReq) return;
554
+ playState = s;
555
+ o.onPlayhead?.(t, s);
556
+ paintChrome();
557
+ }
558
+
559
+ // ---------- the brushed table and export ----------
560
+ async function showTable(from: number, to: number) {
561
+ brush = { from: Math.min(from, to), to: Math.max(from, to) };
562
+ later();
563
+ const page = await o.source.query(query(brush.from, brush.to, { kind: 'single' }, { limit: 500 }));
564
+ const p = parseSearch(q);
565
+ const mark = (s: string) => { const out: (string | Node)[] = []; let at = 0; for (const [a, b] of highlights(p, s)) { out.push(s.slice(at, a), h('mark', null, s.slice(a, b))); at = b; } out.push(s.slice(at)); return out; };
566
+ const rows = (page.events ?? []).map(e => {
567
+ const tr = h('tr', { 'data-id': e.id, tabindex: '0' }, h('td', null, fmtTime(e.t, tz)), h('td', null, e.dur !== undefined ? fmtDur(e.dur) : e.open ? 'still going' : ''), h('td', null, e.source), h('td', null, e.kind), h('td', { class: `sev-${e.severity}` }, e.severity), h('td', { class: 'tlx-sum' }, ...mark(e.summary)), h('td', { class: 'tlx-scope' }, e.scope));
568
+ tr.addEventListener('click', () => select(e));
569
+ tr.addEventListener('keydown', ev => { if (ev.key === 'Enter') select(e); });
570
+ return tr;
571
+ });
572
+ const close = h('button', { type: 'button', class: 'btn sm quiet', 'aria-label': 'Close the table' }, 'Close');
573
+ close.addEventListener('click', () => { brush = undefined; table.hidden = true; later(); });
574
+ const exp = (kind: 'json' | 'csv') => {
575
+ const b = h('button', { type: 'button', class: 'btn sm', 'data-export': kind }, kind.toUpperCase());
576
+ b.addEventListener('click', () => void exportRange(kind));
577
+ return b;
578
+ };
579
+ table.replaceChildren(
580
+ h('div', { class: 'tlx-table-head' }, h('strong', null, `${page.total} event${page.total === 1 ? '' : 's'}`), h('span', null, ` ${fmtTime(brush.from, tz)} – ${fmtTime(brush.to, tz)}${page.total > 500 ? ' (the first 500 shown; the export has them all)' : ''}`), h('span', { class: 'spacer' }), h('span', null, 'Export: '), exp('json'), exp('csv'), close),
581
+ h('div', { class: 'tlx-table-wrap' }, h('table', null, h('thead', null, h('tr', null, ...['When', 'Long', 'Source', 'Kind', 'Severity', 'What', 'Scope'].map(c => h('th', { scope: 'col' }, c)))), h('tbody', null, ...rows))));
582
+ table.hidden = false;
583
+ }
584
+ /** every event in the brushed range (all pages), sensitive attrs left out */
585
+ async function rangeEvents(): Promise<TimelineEvent<T>[]> {
586
+ if (!brush) return [];
587
+ const out: TimelineEvent<T>[] = [];
588
+ let cursor: string | undefined;
589
+ do {
590
+ const r = await o.source.query(query(brush.from, brush.to, { kind: 'single' }, { limit: 10000, ...(cursor ? { cursor } : {}) }));
591
+ out.push(...(r.events ?? [])); cursor = r.next;
592
+ } while (cursor && out.length < 200_000);
593
+ return out;
594
+ }
595
+ async function exportRange(kind: 'json' | 'csv') {
596
+ const es = await rangeEvents();
597
+ const text = kind === 'json' ? toJSON(es, sensitive) : toCSV(es, sensitive);
598
+ const name = `timeline-${new Date(brush!.from).toISOString().slice(0, 16).replace(/:/g, '')}.${kind}`;
599
+ const type = kind === 'json' ? 'application/json' : 'text/csv';
600
+ if (o.onExport) { o.onExport(name, text, type); return; }
601
+ // no host to save it: a download link with the text in it (never a blob: URL, which a host's asset rules forbid)
602
+ const a = h('a', { href: `data:${type};charset=utf-8,${encodeURIComponent(text)}`, download: name });
603
+ document.body.append(a); a.click(); a.remove();
604
+ }
605
+
606
+ // ---------- the detail panel ----------
607
+ function select(e: TimelineEvent<T> | undefined) {
608
+ selected = e;
609
+ later();
610
+ if (!e) { detail.hidden = true; return; }
611
+ const src = catalog?.sources.find(s => s.name === e.source);
612
+ const sens = new Set(src?.sensitive ?? []);
613
+ const p = parseSearch(q);
614
+ const mark = (s: string) => { const out: (string | Node)[] = []; let at = 0; for (const [a, b] of highlights(p, s)) { out.push(s.slice(at, a), h('mark', null, s.slice(a, b))); at = b; } out.push(s.slice(at)); return out; };
615
+ const link = (label: string, fn: (() => void) | undefined) => { if (!fn) return null; const b = h('button', { type: 'button', class: 'btn sm' }, label); b.addEventListener('click', fn); return b; };
616
+ const attrRows = Object.entries(e.attrs).map(([k, v]) => {
617
+ if (!sens.has(k)) return h('tr', null, h('th', { scope: 'row' }, k), h('td', null, ...mark(String(v))));
618
+ const show = h('button', { type: 'button', class: 'btn sm quiet', title: 'This can name a remote host, a folder or free text' }, 'Show');
619
+ const td = h('td', { class: 'tlx-sensitive' }, 'hidden ', show);
620
+ show.addEventListener('click', () => td.replaceChildren(String(v)));
621
+ return h('tr', null, h('th', { scope: 'row' }, k), td);
622
+ });
623
+ const close = h('button', { type: 'button', class: 'btn sm quiet tlx-close', 'aria-label': 'Close' }, '×');
624
+ close.addEventListener('click', () => select(undefined));
625
+ const scopeCrumbs = crumbs(e.scope).slice(1).map(c => { const b = h('button', { type: 'button', class: 'tlx-crumb' }, labelOf(c.scope, c.label)); b.addEventListener('click', () => drill(c.scope)); return b; });
626
+ detail.replaceChildren(
627
+ h('div', { class: 'tlx-detail-head' }, h('strong', null, e.kind), close),
628
+ h('p', { class: `tlx-sev sev-${e.severity}` }, `${e.severity} · ${src?.title ?? e.source}`),
629
+ h('p', { class: 'tlx-sum' }, ...mark(e.summary)),
630
+ h('p', null, fmtTime(e.t, tz), e.dur !== undefined ? ` · ${fmtDur(e.dur)}${e.open ? ' so far' : ''}` : e.open ? ' · still going' : ''),
631
+ h('p', { class: 'tlx-crumbs small' }, ...scopeCrumbs),
632
+ ...(attrRows.length ? [h('table', { class: 'tlx-attrs' }, h('tbody', null, ...attrRows))] : []),
633
+ h('div', { class: 'tlx-links' }, ...(o.actions?.(e) ?? []).map(([label, fn]) => link(label, fn))),
634
+ );
635
+ detail.hidden = false;
636
+ }
637
+
638
+ // ---------- time breaks: open one ----------
639
+ function openCut(from: number, to: number) {
640
+ const key = gapKey({ from, to });
641
+ const g = gaps.find(x => x.from === from && x.to === to);
642
+ if (!g) return;
643
+ expanded.add(key);
644
+ if (!motion) { weights.set(key, 1); later(); return; }
645
+ const t0 = performance.now();
646
+ const step = (now: number) => {
647
+ const k = Math.min(1, (now - t0) / 260);
648
+ weights.set(key, 1 - (1 - k) ** 3);
649
+ paint();
650
+ if (k < 1) requestAnimationFrame(step);
651
+ };
652
+ requestAnimationFrame(step);
653
+ }
654
+
655
+ // ---------- the pointer ----------
656
+ let drag: { kind: 'pan' | 'brush' | 'scrub'; x0: number; t0: number; v0: typeof view; moved: boolean } | undefined;
657
+ const pxOf = (e: PointerEvent | WheelEvent | MouseEvent) => e.clientX - svg.getBoundingClientRect().left;
658
+ svg.addEventListener('pointerdown', e => {
659
+ const px = pxOf(e), py = e.clientY - svg.getBoundingClientRect().top;
660
+ const cut = (e.target as Element).closest?.('.tlx-cut');
661
+ if (cut) { e.preventDefault(); openCut(Number(cut.getAttribute('data-from')), Number(cut.getAttribute('data-to'))); return; }
662
+ svg.setPointerCapture(e.pointerId);
663
+ const kind = py < AXIS ? 'brush' : e.shiftKey ? 'brush' : (e.target as Element).classList.contains('tlx-handle') ? 'scrub' : 'pan';
664
+ drag = { kind, x0: px, t0: scale.t(px), v0: view, moved: false };
665
+ e.preventDefault();
666
+ lanes.focus({ preventScroll: true });
667
+ });
668
+ svg.addEventListener('pointermove', e => {
669
+ if (!drag) return;
670
+ const px = pxOf(e);
671
+ if (Math.abs(px - drag.x0) > 3) drag.moved = true;
672
+ if (!drag.moved) return;
673
+ if (drag.kind === 'pan') {
674
+ // pan by time under the pointer (a cut moves as one piece)
675
+ const dt = (drag.x0 - px) * scale.msPerPx;
676
+ view = { t0: drag.v0.t0 + dt, t1: drag.v0.t1 + dt };
677
+ follow = false;
678
+ void refresh();
679
+ } else if (drag.kind === 'scrub') void setPlayhead(scale.t(px));
680
+ else { brush = { from: Math.min(drag.t0, scale.t(px)), to: Math.max(drag.t0, scale.t(px)) }; later(); }
681
+ });
682
+ svg.addEventListener('pointerup', e => {
683
+ const d = drag; drag = undefined;
684
+ if (!d) return;
685
+ const px = pxOf(e);
686
+ if (d.kind === 'brush' && d.moved) { void showTable(d.t0, scale.t(px)); return; }
687
+ if (d.kind === 'brush' && !d.moved) { void setPlayhead(scale.t(px)); return; }
688
+ if (d.kind === 'pan' && !d.moved) {
689
+ const id = (e.target as Element).closest?.('[data-id]')?.getAttribute('data-id');
690
+ const ev = id ? [...(result?.events ?? []), ...(result?.spans ?? [])].find(x => x.id === id) : undefined;
691
+ if (ev) { select(ev); void setPlayhead(ev.t); } else void setPlayhead(scale.t(px));
692
+ }
693
+ });
694
+ svg.addEventListener('keydown', e => {
695
+ const cut = (e.target as Element).closest?.('.tlx-cut');
696
+ if (cut && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); openCut(Number(cut.getAttribute('data-from')), Number(cut.getAttribute('data-to'))); }
697
+ });
698
+ svg.addEventListener('wheel', e => {
699
+ e.preventDefault();
700
+ const px = pxOf(e);
701
+ if (e.shiftKey || Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
702
+ const dt = (e.shiftKey ? e.deltaY : e.deltaX) * scale.msPerPx;
703
+ view = { t0: view.t0 + dt, t1: view.t1 + dt }; follow = false;
704
+ } else zoomAt(scale.t(px), Math.exp(e.deltaY * 0.0015), px / width());
705
+ void refresh();
706
+ }, { passive: false });
707
+ function zoomAt(at: number, f: number, frac = 0.5) {
708
+ const span = Math.min(400 * DAY, Math.max(10_000, (view.t1 - view.t0) * f));
709
+ view = { t0: at - frac * span, t1: at + (1 - frac) * span };
710
+ expanded.clear(); weights.clear();
711
+ if (f < 1) follow = live && view.t1 >= nowT();
712
+ }
713
+ lanes.addEventListener('keydown', e => {
714
+ const span = view.t1 - view.t0;
715
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { const dt = span * 0.15 * (e.key === 'ArrowLeft' ? -1 : 1); view = { t0: view.t0 + dt, t1: view.t1 + dt }; follow = false; }
716
+ else if (e.key === '+' || e.key === '=') zoomAt((view.t0 + view.t1) / 2, 0.6);
717
+ else if (e.key === '-' || e.key === '_') zoomAt((view.t0 + view.t1) / 2, 1 / 0.6);
718
+ else if (e.key === 'n' || e.key === 'N') { stepHit(e.shiftKey ? -1 : 1); e.preventDefault(); return; }
719
+ else if (e.key === 'Escape') { select(undefined); brush = undefined; table.hidden = true; }
720
+ else return;
721
+ e.preventDefault();
722
+ void refresh();
723
+ });
724
+ el.addEventListener('keydown', e => { if (e.key === '/' && document.activeElement !== search && !(e.target as HTMLElement).closest('input, select, textarea')) { e.preventDefault(); search.focus(); } });
725
+ scroller.addEventListener('scroll', () => later(), { passive: true });
726
+
727
+ // ---------- saved views ----------
728
+ saveBtn.addEventListener('click', async () => {
729
+ const name = `${crumbs(scope).slice(-1)[0].label}${q ? `: ${q}` : ''}`.slice(0, 80);
730
+ await o.saveView?.({ ...currentView(), name });
731
+ await loadViews();
732
+ });
733
+ let saved: View[] = [];
734
+ async function loadViews() {
735
+ if (!o.views) return;
736
+ saved = await o.views();
737
+ viewsSel.replaceChildren(h('option', { value: '' }, 'Saved views…'), ...saved.map((v, i) => h('option', { value: String(i) }, v.name)));
738
+ }
739
+ viewsSel.addEventListener('change', () => { const v = saved[Number(viewsSel.value)]; if (v) { applyView(v); paintFacets(); void refresh(true); } viewsSel.value = ''; });
740
+
741
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => later()) : undefined;
742
+ ro?.observe(lanes);
743
+
744
+ // ---------- start ----------
745
+ const ready = (async () => {
746
+ catalog = await o.source.catalog();
747
+ sensitive = catalog.sources.flatMap(s => (s.sensitive ?? []).map(a => `${s.name}.${a}`));
748
+ for (const s of catalog.sources) for (const x of s.series) seriesInfo.set(x.name, { unit: x.unit, type: x.type, title: x.title, source: s.name });
749
+ const firstHost = catalog.hosts.length === 1 ? `host:${catalog.hosts[0].replace(/[%/:\s]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}` : '';
750
+ scope = firstHost;
751
+ const now = catalog.now;
752
+ view = { t0: now - DAY, t1: now + DAY * 0.02 };
753
+ const v = readUrl() ?? o.view;
754
+ if (v) applyView(v);
755
+ paintFacets();
756
+ await loadViews();
757
+ await refresh(true);
758
+ if (q) await findHits();
759
+ })();
760
+
761
+ return {
762
+ el,
763
+ ready,
764
+ get view() { return currentView(); },
765
+ setView(v: Partial<View>) { applyView(v); paintFacets(); return refresh(true); },
766
+ setRange(t0: number, t1: number) { view = { t0, t1 }; follow = false; return refresh(); },
767
+ setPlayhead,
768
+ setLive,
769
+ setTheme,
770
+ refresh: () => refresh(true),
771
+ /** for tests and hosts: what is drawn, and the mapping */
772
+ internal: {
773
+ get result() { return result; }, get mode() { return mode(); }, get scale() { return scale; }, get gaps() { return gaps; },
774
+ get playState() { return playState; }, get hits() { return hits; }, get selected() { return selected; }, get follow() { return follow; },
775
+ openCut, showTable, rangeEvents, exportRange, select, stepHit, drill, findHits, paint, lines,
776
+ },
777
+ dispose() { unsub?.(); ro?.disconnect(); if (frame) cancelAnimationFrame(frame); el.replaceChildren(); },
778
+ };
779
+ }
780
+ export type TimelineHandle = ReturnType<typeof mountTimeline>;
781
+ export type { MetricPoint, MetricRollup, Row, Query, Result };