@zsherman/charts 0.0.0-stage → 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 (180) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +373 -0
  3. package/README.md +13 -2
  4. package/THIRD_PARTY_NOTICES.md +33 -0
  5. package/dist/dom/bar-list/bar-list.js +386 -0
  6. package/dist/dom/bar-list/bar-list.styles.js +171 -0
  7. package/dist/dom/bar-list/index.js +1 -0
  8. package/dist/dom/chart/chart.js +716 -0
  9. package/dist/dom/chart/chart.styles.js +165 -0
  10. package/dist/dom/chart/index.js +1 -0
  11. package/dist/dom/chart-grid/chart-grid.js +67 -0
  12. package/dist/dom/chart-grid/index.js +1 -0
  13. package/dist/dom/donut/donut.js +565 -0
  14. package/dist/dom/donut/donut.styles.js +111 -0
  15. package/dist/dom/donut/index.js +1 -0
  16. package/dist/dom/heat-graph/calendar.js +118 -0
  17. package/dist/dom/heat-graph/heat-graph.js +423 -0
  18. package/dist/dom/heat-graph/heat-graph.styles.js +168 -0
  19. package/dist/dom/heat-graph/index.js +1 -0
  20. package/dist/dom/heat-matrix/heat-matrix.js +346 -0
  21. package/dist/dom/heat-matrix/heat-matrix.styles.js +155 -0
  22. package/dist/dom/heat-matrix/index.js +1 -0
  23. package/dist/dom/heat-matrix/model.js +41 -0
  24. package/dist/dom/index.js +13 -0
  25. package/dist/dom/internal/colors.js +44 -0
  26. package/dist/dom/internal/floating-tip.js +83 -0
  27. package/dist/dom/internal/format.js +43 -0
  28. package/dist/dom/internal/grid-context.js +5 -0
  29. package/dist/dom/internal/hidden.styles.js +16 -0
  30. package/dist/dom/internal/legend.js +112 -0
  31. package/dist/dom/internal/legend.styles.js +108 -0
  32. package/dist/dom/internal/markers.js +101 -0
  33. package/dist/dom/internal/options.js +300 -0
  34. package/dist/dom/internal/place.js +27 -0
  35. package/dist/dom/internal/scheme-watch.js +73 -0
  36. package/dist/dom/internal/share.js +28 -0
  37. package/dist/dom/internal/types.js +0 -0
  38. package/dist/dom/row-chart/index.js +1 -0
  39. package/dist/dom/row-chart/model.js +59 -0
  40. package/dist/dom/row-chart/row-chart.js +691 -0
  41. package/dist/dom/row-chart/row-chart.styles.js +242 -0
  42. package/dist/dom/segmented-bar/index.js +1 -0
  43. package/dist/dom/segmented-bar/segmented-bar.js +280 -0
  44. package/dist/dom/segmented-bar/segmented-bar.styles.js +88 -0
  45. package/dist/dom/sparkline/index.js +1 -0
  46. package/dist/dom/sparkline/sparkline.js +145 -0
  47. package/dist/dom/stacked-histogram/histogram.js +137 -0
  48. package/dist/dom/stacked-histogram/index.js +1 -0
  49. package/dist/dom/stacked-histogram/stacked-histogram.js +761 -0
  50. package/dist/dom/stacked-histogram/stacked-histogram.styles.js +211 -0
  51. package/dist/dom/state-timeline/index.js +1 -0
  52. package/dist/dom/state-timeline/model.js +166 -0
  53. package/dist/dom/state-timeline/state-timeline.js +729 -0
  54. package/dist/dom/state-timeline/state-timeline.styles.js +171 -0
  55. package/dist/dom/status-history/index.js +1 -0
  56. package/dist/dom/status-history/status-history.js +542 -0
  57. package/dist/dom/status-history/status-history.styles.js +171 -0
  58. package/dist/solid/bar-list/bar-list.jsx +139 -0
  59. package/dist/solid/bar-list/bar-list.styles.jsx +171 -0
  60. package/dist/solid/bar-list/index.jsx +1 -0
  61. package/dist/solid/chart/chart.jsx +454 -0
  62. package/dist/solid/chart/chart.styles.jsx +165 -0
  63. package/dist/solid/chart/index.jsx +1 -0
  64. package/dist/solid/chart-grid/chart-grid.jsx +46 -0
  65. package/dist/solid/chart-grid/index.jsx +1 -0
  66. package/dist/solid/donut/donut.jsx +291 -0
  67. package/dist/solid/donut/donut.styles.jsx +111 -0
  68. package/dist/solid/donut/index.jsx +1 -0
  69. package/dist/solid/heat-graph/calendar.jsx +118 -0
  70. package/dist/solid/heat-graph/heat-graph.jsx +228 -0
  71. package/dist/solid/heat-graph/heat-graph.styles.jsx +168 -0
  72. package/dist/solid/heat-graph/index.jsx +1 -0
  73. package/dist/solid/heat-matrix/heat-matrix.jsx +165 -0
  74. package/dist/solid/heat-matrix/heat-matrix.styles.jsx +155 -0
  75. package/dist/solid/heat-matrix/index.jsx +1 -0
  76. package/dist/solid/heat-matrix/model.jsx +41 -0
  77. package/dist/solid/index.jsx +13 -0
  78. package/dist/solid/internal/colors.jsx +44 -0
  79. package/dist/solid/internal/floating-tip.jsx +68 -0
  80. package/dist/solid/internal/format.jsx +43 -0
  81. package/dist/solid/internal/grid-context.jsx +5 -0
  82. package/dist/solid/internal/hidden.styles.jsx +16 -0
  83. package/dist/solid/internal/legend.jsx +35 -0
  84. package/dist/solid/internal/legend.styles.jsx +108 -0
  85. package/dist/solid/internal/markers.jsx +101 -0
  86. package/dist/solid/internal/options.jsx +300 -0
  87. package/dist/solid/internal/place.jsx +27 -0
  88. package/dist/solid/internal/scheme-watch.jsx +73 -0
  89. package/dist/solid/internal/share.jsx +28 -0
  90. package/dist/solid/internal/types.jsx +0 -0
  91. package/dist/solid/row-chart/index.jsx +1 -0
  92. package/dist/solid/row-chart/model.jsx +59 -0
  93. package/dist/solid/row-chart/row-chart.jsx +312 -0
  94. package/dist/solid/row-chart/row-chart.styles.jsx +242 -0
  95. package/dist/solid/segmented-bar/index.jsx +1 -0
  96. package/dist/solid/segmented-bar/segmented-bar.jsx +125 -0
  97. package/dist/solid/segmented-bar/segmented-bar.styles.jsx +88 -0
  98. package/dist/solid/sparkline/index.jsx +1 -0
  99. package/dist/solid/sparkline/sparkline.jsx +88 -0
  100. package/dist/solid/stacked-histogram/histogram.jsx +137 -0
  101. package/dist/solid/stacked-histogram/index.jsx +1 -0
  102. package/dist/solid/stacked-histogram/stacked-histogram.jsx +381 -0
  103. package/dist/solid/stacked-histogram/stacked-histogram.styles.jsx +211 -0
  104. package/dist/solid/state-timeline/index.jsx +1 -0
  105. package/dist/solid/state-timeline/model.jsx +166 -0
  106. package/dist/solid/state-timeline/state-timeline.jsx +387 -0
  107. package/dist/solid/state-timeline/state-timeline.styles.jsx +171 -0
  108. package/dist/solid/status-history/index.jsx +1 -0
  109. package/dist/solid/status-history/status-history.jsx +279 -0
  110. package/dist/solid/status-history/status-history.styles.jsx +171 -0
  111. package/dist/styles.css +1 -0
  112. package/dist/types/bar-list/bar-list.d.ts +91 -0
  113. package/dist/types/bar-list/bar-list.styles.d.ts +148 -0
  114. package/dist/types/bar-list/index.d.ts +3 -0
  115. package/dist/types/chart/chart.d.ts +98 -0
  116. package/dist/types/chart/chart.styles.d.ts +145 -0
  117. package/dist/types/chart/index.d.ts +3 -0
  118. package/dist/types/chart-grid/chart-grid.d.ts +35 -0
  119. package/dist/types/chart-grid/index.d.ts +2 -0
  120. package/dist/types/donut/donut.d.ts +124 -0
  121. package/dist/types/donut/donut.styles.d.ts +96 -0
  122. package/dist/types/donut/index.d.ts +3 -0
  123. package/dist/types/heat-graph/calendar.d.ts +61 -0
  124. package/dist/types/heat-graph/heat-graph.d.ts +82 -0
  125. package/dist/types/heat-graph/heat-graph.styles.d.ts +141 -0
  126. package/dist/types/heat-graph/index.d.ts +4 -0
  127. package/dist/types/heat-matrix/heat-matrix.d.ts +65 -0
  128. package/dist/types/heat-matrix/heat-matrix.styles.d.ts +135 -0
  129. package/dist/types/heat-matrix/index.d.ts +3 -0
  130. package/dist/types/heat-matrix/model.d.ts +15 -0
  131. package/dist/types/index.d.ts +12 -0
  132. package/dist/types/internal/colors.d.ts +22 -0
  133. package/dist/types/internal/floating-tip.d.ts +15 -0
  134. package/dist/types/internal/format.d.ts +7 -0
  135. package/dist/types/internal/grid-context.d.ts +9 -0
  136. package/dist/types/internal/hidden.styles.d.ts +15 -0
  137. package/dist/types/internal/legend.d.ts +18 -0
  138. package/dist/types/internal/legend.styles.d.ts +96 -0
  139. package/dist/types/internal/markers.d.ts +16 -0
  140. package/dist/types/internal/options.d.ts +59 -0
  141. package/dist/types/internal/place.d.ts +20 -0
  142. package/dist/types/internal/scheme-watch.d.ts +12 -0
  143. package/dist/types/internal/share.d.ts +19 -0
  144. package/dist/types/internal/types.d.ts +163 -0
  145. package/dist/types/row-chart/index.d.ts +4 -0
  146. package/dist/types/row-chart/model.d.ts +50 -0
  147. package/dist/types/row-chart/row-chart.d.ts +148 -0
  148. package/dist/types/row-chart/row-chart.styles.d.ts +216 -0
  149. package/dist/types/segmented-bar/index.d.ts +3 -0
  150. package/dist/types/segmented-bar/segmented-bar.d.ts +65 -0
  151. package/dist/types/segmented-bar/segmented-bar.styles.d.ts +75 -0
  152. package/dist/types/sparkline/index.d.ts +3 -0
  153. package/dist/types/sparkline/sparkline.d.ts +38 -0
  154. package/dist/types/stacked-histogram/histogram.d.ts +48 -0
  155. package/dist/types/stacked-histogram/index.d.ts +4 -0
  156. package/dist/types/stacked-histogram/stacked-histogram.d.ts +73 -0
  157. package/dist/types/stacked-histogram/stacked-histogram.styles.d.ts +187 -0
  158. package/dist/types/state-timeline/index.d.ts +3 -0
  159. package/dist/types/state-timeline/model.d.ts +63 -0
  160. package/dist/types/state-timeline/state-timeline.d.ts +108 -0
  161. package/dist/types/state-timeline/state-timeline.styles.d.ts +151 -0
  162. package/dist/types/status-history/index.d.ts +3 -0
  163. package/dist/types/status-history/status-history.d.ts +72 -0
  164. package/dist/types/status-history/status-history.styles.d.ts +150 -0
  165. package/docs/api.json +1346 -0
  166. package/docs/bar-list.md +190 -0
  167. package/docs/chart-grid.md +77 -0
  168. package/docs/chart.md +355 -0
  169. package/docs/donut.md +182 -0
  170. package/docs/heat-graph.md +121 -0
  171. package/docs/heat-matrix.md +108 -0
  172. package/docs/llms.txt +68 -0
  173. package/docs/row-chart.md +193 -0
  174. package/docs/search-index.json +291 -0
  175. package/docs/segmented-bar.md +128 -0
  176. package/docs/sparkline.md +82 -0
  177. package/docs/stacked-histogram.md +123 -0
  178. package/docs/state-timeline.md +141 -0
  179. package/docs/status-history.md +121 -0
  180. package/package.json +104 -4
@@ -0,0 +1,166 @@
1
+ // src/state-timeline/model.ts
2
+ /** The smallest positive step between neighbouring samples across rows (a minute, if there's none). */
3
+ function inferStep(rows) {
4
+ let step = Infinity;
5
+ for (const row of rows) for (let i = 1; i < row.length; i++) {
6
+ const d = row[i].time - row[i - 1].time;
7
+ if (d > 0 && d < step) step = d;
8
+ }
9
+ return Number.isFinite(step) ? step : 6e4;
10
+ }
11
+ /**
12
+ * A row's samples, sorted, each lasting until the next one or `step`, whichever comes first (a reading
13
+ * that's late by more than its step leaves a gap); then runs of one state merged into segments. `null`
14
+ * states draw nothing.
15
+ */
16
+ function buildRow(data, step) {
17
+ const sorted = [...data].filter((s) => Number.isFinite(s.time)).sort((a, b) => a.time - b.time);
18
+ const samples = sorted.map((s, i) => {
19
+ const next = sorted[i + 1]?.time;
20
+ return {
21
+ ...s,
22
+ end: next === void 0 ? s.time + step : Math.min(next, s.time + step)
23
+ };
24
+ });
25
+ const segments = [];
26
+ samples.forEach((s, i) => {
27
+ if (s.state == null) return;
28
+ const open = segments.at(-1);
29
+ if (open && open.state === s.state && open.last === i - 1 && open.end === s.time) {
30
+ open.end = s.end;
31
+ open.last = i;
32
+ } else segments.push({
33
+ state: s.state,
34
+ start: s.time,
35
+ end: s.end,
36
+ first: i,
37
+ last: i
38
+ });
39
+ });
40
+ return {
41
+ samples,
42
+ segments
43
+ };
44
+ }
45
+ /** Each state's share of `[start, end)` in a row, and the share with no data. Segments are clipped. */
46
+ function shares(segments, start, end) {
47
+ const span = end - start;
48
+ const byState = /* @__PURE__ */ new Map();
49
+ let covered = 0;
50
+ if (span <= 0) return {
51
+ byState,
52
+ missing: 0
53
+ };
54
+ for (const s of segments) {
55
+ const d = Math.max(0, Math.min(end, s.end) - Math.max(start, s.start));
56
+ if (d <= 0) continue;
57
+ covered += d;
58
+ byState.set(s.state, (byState.get(s.state) ?? 0) + d / span);
59
+ }
60
+ return {
61
+ byState,
62
+ missing: Math.max(0, 1 - covered / span)
63
+ };
64
+ }
65
+ /** The sample whose span holds `time`, or `undefined` in a gap. */
66
+ function sampleAt(samples, time) {
67
+ let lo = 0;
68
+ let hi = samples.length - 1;
69
+ while (lo <= hi) {
70
+ const mid = lo + hi >> 1;
71
+ const s = samples[mid];
72
+ if (time < s.time) hi = mid - 1;
73
+ else if (time >= s.end) lo = mid + 1;
74
+ else return s;
75
+ }
76
+ }
77
+ /** The segment that holds `time`, or `undefined`. */
78
+ function segmentAt(segments, time) {
79
+ return sampleAt(segments.map((s) => ({
80
+ ...s,
81
+ time: s.start
82
+ })), time);
83
+ }
84
+ const SECOND = 1e3;
85
+ const MINUTE = 60 * SECOND;
86
+ const HOUR = 60 * MINUTE;
87
+ const DAY = 24 * HOUR;
88
+ const STEPS = [
89
+ SECOND,
90
+ 5 * SECOND,
91
+ 10 * SECOND,
92
+ 15 * SECOND,
93
+ 30 * SECOND,
94
+ MINUTE,
95
+ 2 * MINUTE,
96
+ 5 * MINUTE,
97
+ 10 * MINUTE,
98
+ 15 * MINUTE,
99
+ 30 * MINUTE,
100
+ HOUR,
101
+ 2 * HOUR,
102
+ 3 * HOUR,
103
+ 6 * HOUR,
104
+ 12 * HOUR,
105
+ DAY,
106
+ 2 * DAY,
107
+ 7 * DAY,
108
+ 14 * DAY,
109
+ 30 * DAY
110
+ ];
111
+ /**
112
+ * Round ticks across `[start, end]`: the smallest round step that gives at most `count` of them, at
113
+ * multiples of the step in the given UTC offset (minutes east of UTC), so an hour step lands on the hour.
114
+ */
115
+ function ticks(start, end, count, offsetMinutes = 0) {
116
+ const span = end - start;
117
+ if (!(span > 0) || count < 1) return {
118
+ step: span,
119
+ at: []
120
+ };
121
+ const step = STEPS.find((s) => span / s <= count) ?? Math.ceil(span / count / DAY) * DAY;
122
+ const shift = offsetMinutes * MINUTE;
123
+ const first = Math.ceil((start + shift) / step) * step - shift;
124
+ const at = [];
125
+ for (let t = first; t <= end; t += step) at.push(t);
126
+ return {
127
+ step,
128
+ at
129
+ };
130
+ }
131
+ /** The time zone's offset from UTC at `time`, in minutes east (Intl's `longOffset`: "GMT+05:30"). */
132
+ function zoneOffset(time, timeZone) {
133
+ if (!timeZone) return -new Date(time).getTimezoneOffset();
134
+ try {
135
+ const m = (new Intl.DateTimeFormat("en-US", {
136
+ timeZone,
137
+ timeZoneName: "longOffset"
138
+ }).formatToParts(new Date(time)).find((p) => p.type === "timeZoneName")?.value)?.match(/GMT([+-])(\d{2}):?(\d{2})?/);
139
+ if (!m) return 0;
140
+ const minutes = Number(m[2]) * 60 + Number(m[3] ?? 0);
141
+ return m[1] === "-" ? -minutes : minutes;
142
+ } catch {
143
+ return 0;
144
+ }
145
+ }
146
+ /**
147
+ * One SVG path per state for a row: a rectangle per segment in a 1000-wide, 1-high box. A segment shorter
148
+ * than `min` (in box units: about a pixel) is widened to it, so a short failure stays visible.
149
+ */
150
+ function paths(segments, start, end, min) {
151
+ const span = end - start;
152
+ const out = /* @__PURE__ */ new Map();
153
+ if (span <= 0) return /* @__PURE__ */ new Map();
154
+ for (const s of segments) {
155
+ const a = Math.max(start, s.start);
156
+ const b = Math.min(end, s.end);
157
+ if (b <= a) continue;
158
+ const x = (a - start) / span * 1e3;
159
+ const w = Math.max(min, (b - a) / span * 1e3);
160
+ const list = out.get(s.state) ?? [];
161
+ list.push(`M${x.toFixed(2)} 0h${w.toFixed(2)}v1h${(-w).toFixed(2)}z`);
162
+ out.set(s.state, list);
163
+ }
164
+ return new Map([...out].map(([k, v]) => [k, v.join("")]));
165
+ }
166
+ export { buildRow, inferStep, paths, sampleAt, segmentAt, shares, ticks, zoneOffset };
@@ -0,0 +1,387 @@
1
+ import { cssColor, toneColor } from "../internal/colors.jsx";
2
+ import { FloatingTip } from "../internal/floating-tip.jsx";
3
+ import { numberFormat } from "../internal/format.jsx";
4
+ import { hidden } from "../internal/hidden.styles.jsx";
5
+ import { shareFormat } from "../internal/share.jsx";
6
+ import { buildRow, inferStep, paths, sampleAt, segmentAt, shares, ticks, zoneOffset } from "./model.jsx";
7
+ import { styles } from "./state-timeline.styles.jsx";
8
+ import * as stylex from "@stylexjs/stylex";
9
+ import { useLocale, useMessages } from "@zsherman/kit/locale-provider";
10
+ import { For, Show, createMemo, createSignal, createUniqueId, omit, onSettled } from "solid-js";
11
+ // src/state-timeline/state-timeline.tsx
12
+ const DEFAULT_LABELS = {
13
+ keyboardHint: "Use the up and down arrow keys to choose a row, and the left and right arrow keys to move between its states.",
14
+ noData: "No data",
15
+ legend: (label) => `${label}: states`,
16
+ empty: "No data"
17
+ };
18
+ const toMs = (t) => t instanceof Date ? t.getTime() : typeof t === "number" ? t : Date.parse(t);
19
+ /**
20
+ * Many rows on one time axis, each a lane of colored states: route health, service status, host states
21
+ * over hours. Runs of one state are merged into one segment, so hundreds of readings per row stay light;
22
+ * a short failure is never thinner than a pixel. A cursor runs through every lane, with a tooltip for the
23
+ * row under the pointer; the arrow keys walk rows and segments. Plain SVG and DOM, so it renders on the
24
+ * server; each row is named with its share of time per state.
25
+ *
26
+ * @example
27
+ * <StateTimeline
28
+ * label="Route loss, last 12 hours"
29
+ * states={[{ key: "ok", label: "No loss", tone: "success" }, { key: "loss", label: "Loss", tone: "danger" }]}
30
+ * rows={[{ label: "eu → us", data: [{ time: t0, state: "ok" }, { time: t1, state: "loss" }] }]}
31
+ * />
32
+ */
33
+ function StateTimeline(props) {
34
+ const rest = omit(props, "label", "states", "rows", "step", "range", "rowHeight", "rowGap", "ticks", "timeZone", "formatTime", "formatValue", "legend", "tooltip", "labels", "class");
35
+ const id = createUniqueId();
36
+ const locale = useLocale();
37
+ const messages = useMessages("stateTimeline");
38
+ const text = (k) => props.labels?.[k] ?? messages()?.[k] ?? DEFAULT_LABELS[k];
39
+ let plot;
40
+ let list;
41
+ let axis;
42
+ const [width, setWidth] = createSignal(800);
43
+ const [active, setActive] = createSignal(null);
44
+ const [readout, setReadout] = createSignal("");
45
+ const tooltipOn = () => props.tooltip !== false;
46
+ /** Each state's color and order. */
47
+ const states = createMemo(() => {
48
+ let next = 0;
49
+ return new Map(props.states.map((s, i) => [s.key, {
50
+ ...s,
51
+ order: i,
52
+ css: s.color ? cssColor(s.color, 0) : s.tone ? toneColor(s.tone) : cssColor(void 0, next++)
53
+ }]));
54
+ });
55
+ const model = createMemo(() => {
56
+ const raw = props.rows.map((r) => r.data.map((s) => ({
57
+ time: toMs(s.time),
58
+ state: s.state,
59
+ value: s.value,
60
+ note: s.note
61
+ })));
62
+ const step = props.step && props.step > 0 ? props.step : inferStep(raw);
63
+ const rows = raw.map((d) => buildRow(d, step));
64
+ let start = Infinity;
65
+ let end = -Infinity;
66
+ for (const r of rows) if (r.samples.length) {
67
+ start = Math.min(start, r.samples[0].time);
68
+ end = Math.max(end, r.samples.at(-1).end);
69
+ }
70
+ if (props.range) {
71
+ start = toMs(props.range[0]);
72
+ end = toMs(props.range[1]);
73
+ }
74
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) {
75
+ start = 0;
76
+ end = 1;
77
+ }
78
+ for (const r of rows) r.segments = r.segments.filter((s) => s.end > start && s.start < end).map((s) => ({
79
+ ...s,
80
+ start: Math.max(start, s.start),
81
+ end: Math.min(end, s.end)
82
+ }));
83
+ return {
84
+ step,
85
+ rows,
86
+ start,
87
+ end
88
+ };
89
+ });
90
+ const formats = createMemo(() => {
91
+ const { start, end, step } = model();
92
+ const span = end - start;
93
+ const zone = props.timeZone;
94
+ const days = span >= 864e5;
95
+ const tickFormat = new Intl.DateTimeFormat(locale(), {
96
+ timeZone: zone,
97
+ ...ticks(start, end, props.ticks ?? 8).step >= 864e5 ? {
98
+ month: "short",
99
+ day: "numeric"
100
+ } : {
101
+ hour: "numeric",
102
+ minute: "2-digit"
103
+ }
104
+ });
105
+ const timeFormat = new Intl.DateTimeFormat(locale(), {
106
+ timeZone: zone,
107
+ ...days ? {
108
+ month: "short",
109
+ day: "numeric"
110
+ } : {},
111
+ hour: "numeric",
112
+ minute: "2-digit",
113
+ ...step < 6e4 ? { second: "2-digit" } : {}
114
+ });
115
+ const unit = (u) => new Intl.NumberFormat(locale(), {
116
+ style: "unit",
117
+ unit: u,
118
+ unitDisplay: "short",
119
+ maximumFractionDigits: 0
120
+ });
121
+ const units = {
122
+ second: unit("second"),
123
+ minute: unit("minute"),
124
+ hour: unit("hour"),
125
+ day: unit("day")
126
+ };
127
+ return {
128
+ tick: (t) => tickFormat.format(new Date(t)),
129
+ time: (t) => props.formatTime ? props.formatTime(new Date(t)) : timeFormat.format(new Date(t)),
130
+ duration: (ms) => {
131
+ const s = Math.round(ms / 1e3);
132
+ if (s < 60) return units.second.format(s);
133
+ const m = Math.round(s / 60);
134
+ if (m < 60) return units.minute.format(m);
135
+ const h = Math.floor(m / 60);
136
+ if (h < 48) return m % 60 ? `${units.hour.format(h)} ${units.minute.format(m % 60)}` : units.hour.format(h);
137
+ return units.day.format(Math.round(h / 24));
138
+ },
139
+ value: props.formatValue ?? numberFormat(locale())
140
+ };
141
+ });
142
+ const axisTicks = createMemo(() => {
143
+ const { start, end } = model();
144
+ const span = end - start;
145
+ const { at } = ticks(start, end, props.ticks ?? 8, zoneOffset(start, props.timeZone));
146
+ return at.map((t) => ({
147
+ left: (t - start) / span * 100,
148
+ text: formats().tick(t)
149
+ }));
150
+ });
151
+ /** Each row's lane (a path per state, calm first) and its name with the share of time per state. */
152
+ const lanes = createMemo(() => {
153
+ const { rows, start, end } = model();
154
+ const byKey = states();
155
+ const min = 1e3 / Math.max(1, width());
156
+ const share = shareFormat(locale());
157
+ return props.rows.map((row, i) => {
158
+ const r = rows[i];
159
+ const drawn = [...paths(r.segments, start, end, min)].map(([state, d]) => ({
160
+ d,
161
+ state: byKey.get(state)
162
+ })).filter((p) => p.state).sort((a, b) => a.state.order - b.state.order).map((p) => ({
163
+ d: p.d,
164
+ color: p.state.css
165
+ }));
166
+ const parts = shares(r.segments, start, end);
167
+ const words = props.states.filter((s) => (parts.byState.get(s.key) ?? 0) > 0).map((s) => `${s.label} ${share(parts.byState.get(s.key))}`);
168
+ if (parts.missing > 5e-4) words.push(`${text("noData")} ${share(parts.missing)}`);
169
+ return {
170
+ label: row.label,
171
+ drawn,
172
+ name: `${row.label}: ${words.join(", ")}`
173
+ };
174
+ });
175
+ });
176
+ let observer;
177
+ onSettled(() => {
178
+ observer = new ResizeObserver(() => {
179
+ if (axis?.isConnected) setWidth(axis.clientWidth || 800);
180
+ });
181
+ if (axis) observer.observe(axis);
182
+ return () => observer?.disconnect();
183
+ });
184
+ /** A time's x in the plot's pixels. */
185
+ const xOf = (time) => {
186
+ const { start, end } = model();
187
+ const a = axis.getBoundingClientRect();
188
+ return a.left - plot.getBoundingClientRect().left + (time - start) / (end - start) * a.width;
189
+ };
190
+ const rowMid = (row) => {
191
+ const li = list.children[row];
192
+ if (!li) return 0;
193
+ const box = li.getBoundingClientRect();
194
+ return box.top - plot.getBoundingClientRect().top + box.height / 2;
195
+ };
196
+ function hover(event) {
197
+ if (!tooltipOn() || event.pointerType === "touch") return;
198
+ const li = event.target.closest("[data-index]");
199
+ const a = axis.getBoundingClientRect();
200
+ const frac = (event.clientX - a.left) / a.width;
201
+ if (!li || frac < 0 || frac > 1) {
202
+ if (document.activeElement !== plot) setActive(null);
203
+ return;
204
+ }
205
+ const { start, end } = model();
206
+ const row = Number(li.dataset["index"]);
207
+ setActive({
208
+ row,
209
+ time: start + frac * (end - start),
210
+ left: event.clientX - plot.getBoundingClientRect().left,
211
+ top: rowMid(row)
212
+ });
213
+ }
214
+ /** Put the cursor on a row at a time (the keyboard's), and read it out. */
215
+ function activate(row, time) {
216
+ setActive({
217
+ row,
218
+ time,
219
+ left: xOf(time),
220
+ top: rowMid(row)
221
+ });
222
+ const p = pointAt(row, time);
223
+ setReadout(p ? `${p.row}: ${p.state ?? text("noData")}${p.value ? `, ${p.value}` : ""}, ${p.from} – ${p.to}` : "");
224
+ }
225
+ function onKeyDown(event) {
226
+ const { rows, start } = model();
227
+ if (!tooltipOn() || rows.length === 0) return;
228
+ const current = active();
229
+ const row = current?.row ?? 0;
230
+ const time = current?.time ?? start;
231
+ const segments = rows[row].segments;
232
+ const at = segments.findIndex((s) => time >= s.start && time < s.end);
233
+ const after = segments.findIndex((s) => s.start > time);
234
+ const middle = (i) => (segments[i].start + segments[i].end) / 2;
235
+ switch (event.key) {
236
+ case "ArrowDown":
237
+ case "ArrowUp": {
238
+ const next = current ? Math.max(0, Math.min(rows.length - 1, row + (event.key === "ArrowDown" ? 1 : -1))) : 0;
239
+ event.preventDefault();
240
+ activate(next, time);
241
+ return;
242
+ }
243
+ case "ArrowRight": {
244
+ const i = at >= 0 ? at + 1 : after;
245
+ event.preventDefault();
246
+ if (i >= 0 && i < segments.length) activate(row, middle(i));
247
+ else if (!current) activate(row, time);
248
+ return;
249
+ }
250
+ case "ArrowLeft": {
251
+ const i = at >= 0 ? at - 1 : (after >= 0 ? after : segments.length) - 1;
252
+ event.preventDefault();
253
+ if (i >= 0) activate(row, middle(i));
254
+ return;
255
+ }
256
+ case "Home":
257
+ event.preventDefault();
258
+ if (segments.length) activate(row, middle(0));
259
+ return;
260
+ case "End":
261
+ event.preventDefault();
262
+ if (segments.length) activate(row, middle(segments.length - 1));
263
+ return;
264
+ case "Escape":
265
+ if (!current) return;
266
+ event.preventDefault();
267
+ setActive(null);
268
+ setReadout("");
269
+ return;
270
+ }
271
+ }
272
+ /** What's at a row and time, in words: the tooltip's and the readout's. */
273
+ function pointAt(row, time) {
274
+ const r = model().rows[row];
275
+ if (!r) return void 0;
276
+ const f = formats();
277
+ const sample = sampleAt(r.samples, time);
278
+ const segment = segmentAt(r.segments, time);
279
+ const state = segment ? states().get(segment.state) : void 0;
280
+ return {
281
+ row: props.rows[row]?.label ?? "",
282
+ time: f.time(time),
283
+ state: state?.label,
284
+ color: state?.css,
285
+ value: sample?.value != null ? f.value(sample.value) : void 0,
286
+ note: sample?.note,
287
+ from: segment ? f.time(segment.start) : "",
288
+ to: segment ? f.time(segment.end) : "",
289
+ duration: segment ? f.duration(segment.end - segment.start) : ""
290
+ };
291
+ }
292
+ const point = createMemo(() => {
293
+ const a = active();
294
+ return a ? pointAt(a.row, a.time) : void 0;
295
+ });
296
+ const focusable = () => tooltipOn() && props.rows.length > 0;
297
+ return <div {...rest} data-slot="state-timeline" class={[stylex.props(styles.root).className, props.class]} style={{
298
+ "--st-row": `${props.rowHeight ?? 14}px`,
299
+ "--st-gap": `${props.rowGap ?? 4}px`
300
+ }}>
301
+ <Show when={props.legend !== false}>
302
+ <ul data-slot="state-timeline-legend" aria-label={text("legend")(props.label)} {...stylex.attrs(styles.legend)}>
303
+ <For each={props.states}>
304
+ {(s) => <li {...stylex.attrs(styles.legendItem)}>
305
+ <span aria-hidden="true" {...stylex.attrs(styles.swatch)} style={{ "--swatch": states().get(s.key)?.css }} />
306
+ {s.label}
307
+ </li>}
308
+ </For>
309
+ </ul>
310
+ </Show>
311
+ <Show when={props.rows.length} fallback={<p data-slot="state-timeline-empty" {...stylex.attrs(styles.empty)}>
312
+ {text("empty")}
313
+ </p>}>
314
+ <div ref={(el) => plot = el} role="group" aria-label={props.label} aria-describedby={focusable() ? `${id}-keys` : void 0} tabindex={focusable() ? 0 : void 0} data-slot="state-timeline-plot" onKeyDown={onKeyDown} onPointerMove={hover} onPointerLeave={() => {
315
+ if (document.activeElement !== plot) setActive(null);
316
+ }} onBlur={() => {
317
+ setActive(null);
318
+ setReadout("");
319
+ }} {...stylex.attrs(styles.plot)}>
320
+ <ul ref={(el) => list = el} data-slot="state-timeline-rows" {...stylex.attrs(styles.rows)}>
321
+ <For each={lanes()} keyed={false}>
322
+ {(lane, index) => <li data-slot="state-timeline-row" data-index={index} {...stylex.attrs(styles.row)}>
323
+ <span {...stylex.attrs(hidden.visually)}>{lane().name}</span>
324
+ <span aria-hidden="true" title={lane().label} data-slot="state-timeline-label" data-active={active()?.row === index ? "" : void 0} {...stylex.attrs(styles.label)}>
325
+ {lane().label}
326
+ </span>
327
+ <svg aria-hidden="true" data-slot="state-timeline-lane" viewBox="0 0 1000 1" preserveAspectRatio="none" {...stylex.attrs(styles.track)}>
328
+ <For each={lane().drawn} keyed={false}>
329
+ {(p) => <path d={p().d} style={{ fill: p().color }} />}
330
+ </For>
331
+ </svg>
332
+ </li>}
333
+ </For>
334
+ </ul>
335
+ <div ref={(el) => {
336
+ axis = el;
337
+ observer?.observe(el);
338
+ }} aria-hidden="true" data-slot="state-timeline-axis" {...stylex.attrs(styles.axis)}>
339
+ <For each={axisTicks()} keyed={false}>
340
+ {(t) => <span {...stylex.attrs(styles.tick)} style={{
341
+ left: `${t().left}%`,
342
+ translate: t().left < 4 ? "0 0" : t().left > 96 ? "-100% 0" : "-50% 0"
343
+ }}>
344
+ {t().text}
345
+ </span>}
346
+ </For>
347
+ </div>
348
+ <Show when={active()}>
349
+ {(a) => <span aria-hidden="true" data-slot="state-timeline-cursor" {...stylex.attrs(styles.cursor)} style={{
350
+ left: `${a().left}px`,
351
+ height: `${list.offsetHeight}px`
352
+ }} />}
353
+ </Show>
354
+ <Show when={tooltipOn() ? point() : void 0}>
355
+ {(p) => <FloatingTip data-slot="state-timeline-tooltip" aria-hidden="true" origin={() => plot} left={active()?.left ?? 0} top={active()?.top ?? 0} before={(active()?.left ?? 0) > plot.clientWidth / 2} xstyle={styles.tooltip}>
356
+ <div {...stylex.attrs(styles.tooltipHeading)}>{p().row}</div>
357
+ <div {...stylex.attrs(styles.tooltipMuted)}>{p().time}</div>
358
+ <div {...stylex.attrs(styles.tooltipState)}>
359
+ <Show when={p().color}>
360
+ <span aria-hidden="true" {...stylex.attrs(styles.swatch)} style={{ "--swatch": p().color }} />
361
+ </Show>
362
+ <span>{p().state ?? text("noData")}</span>
363
+ <Show when={p().value}>
364
+ <span {...stylex.attrs(styles.tooltipValue)}>{p().value}</span>
365
+ </Show>
366
+ </div>
367
+ <Show when={p().from}>
368
+ <div {...stylex.attrs(styles.tooltipMuted)}>
369
+ {p().from} – {p().to} · {p().duration}
370
+ </div>
371
+ </Show>
372
+ <Show when={p().note}>
373
+ <div>{p().note}</div>
374
+ </Show>
375
+ </FloatingTip>}
376
+ </Show>
377
+ </div>
378
+ </Show>
379
+ <span id={`${id}-keys`} {...stylex.attrs(hidden.visually)}>
380
+ {text("keyboardHint")}
381
+ </span>
382
+ <span data-slot="state-timeline-readout" aria-live="polite" {...stylex.attrs(hidden.visually)}>
383
+ {readout()}
384
+ </span>
385
+ </div>;
386
+ }
387
+ export { StateTimeline };