@adecore/charts 0.39.0 → 0.40.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.
package/src/series.tsx CHANGED
@@ -103,9 +103,13 @@ type Point = readonly [number, number] | null;
103
103
  const pointsOf = (chart: ChartContextValue, values: readonly (number | null)[]): Point[] =>
104
104
  values.map((value, index) => {
105
105
  const pixel = value === null ? null : chart.pixelOfY(value);
106
+
106
107
  return pixel === null ? null : [chart.centerOf(index), pixel];
107
108
  });
108
109
 
110
+ /* The pixel of zero, or of the lowest value when the axis starts above it. */
111
+ const groundOf = (chart: ChartContextValue): number => chart.pixelOfY(Math.max(chart.y.domain[0], 0)) ?? chart.plot.bottom;
112
+
109
113
  /* A value between two gaps is no line at all, so it gets a dot of its own. */
110
114
  const lonePoints = (points: readonly Point[]): number[] =>
111
115
  points.flatMap((point, index) => (point !== null && points[index - 1] == null && points[index + 1] == null ? [index] : []));
@@ -114,6 +118,7 @@ function useSeriesValues<Row>(part: string, value: ChartAccessor<Row, number | n
114
118
  const chart = useChartContext(part);
115
119
  const id = useId();
116
120
  useKeyCheck(value, chart.data, part);
121
+
117
122
  return [chart, id, (chart.data as Row[]).map((row, index) => numberOf(readValue(value, row, index)))];
118
123
  }
119
124
 
@@ -133,13 +138,16 @@ function LinePath({
133
138
  if (width === 0) {
134
139
  return null;
135
140
  }
141
+
136
142
  const path = line<Point>()
137
143
  .defined((point) => point !== null)
138
144
  .x((point) => point![0])
139
145
  .y((point) => point![1])
140
146
  .curve(CURVES[curve])(points);
147
+
141
148
  // Keyed by index: before the chart is measured every point stands at the same x.
142
149
  const marked = dots ? points.flatMap((point, index) => (point === null ? [] : [index])) : lonePoints(points);
150
+
143
151
  return (
144
152
  <>
145
153
  {path !== null && (
@@ -164,6 +172,7 @@ function LinePath({
164
172
  function tonesOf<Row>(chart: ChartContextValue, tone: ChartBarTone<Row> | undefined): [string | null, string[] | null] {
165
173
  const rows = chart.data as Row[];
166
174
  const rowColors = typeof tone === 'function' ? rows.map((row, index) => colorOf(tone(row, index))!) : null;
175
+
167
176
  return [typeof tone === 'function' ? (rowColors?.[0] ?? null) : colorOf(tone), rowColors];
168
177
  }
169
178
 
@@ -171,6 +180,7 @@ function tonesOf<Row>(chart: ChartContextValue, tone: ChartBarTone<Row> | undefi
171
180
  export function ChartLine<Row>({ value, label, tone, icon, curve = 'linear', dashed = false, dots = false, width = 2, className, ref }: ChartLineProps<Row>) {
172
181
  const [chart, id, values] = useSeriesValues('Chart.Line', value);
173
182
  const [color, rowColors] = tonesOf(chart, tone);
183
+
174
184
  useRegistration(chart.store, 'series', id, {
175
185
  kind: 'line',
176
186
  label,
@@ -183,16 +193,20 @@ export function ChartLine<Row>({ value, label, tone, icon, curve = 'linear', das
183
193
  icon: icon ?? null,
184
194
  valueLabels: false
185
195
  });
196
+
186
197
  if (chart.points) {
187
198
  return (
188
199
  <g ref={ref} className={clsx('pointer-events-none', className)}>
189
200
  {chart.pointGroups.map((run) => {
190
201
  const first = run.indexes[0]!;
202
+
191
203
  const placed = run.indexes.map((index) => {
192
204
  const pixel = values[index] === null ? null : chart.pixelOfY(values[index]!);
193
205
  const left = chart.positions[index]?.[0] ?? null;
206
+
194
207
  return pixel === null || left === null ? null : ([left, pixel] as const);
195
208
  });
209
+
196
210
  return (
197
211
  <g
198
212
  key={run.key}
@@ -206,6 +220,7 @@ export function ChartLine<Row>({ value, label, tone, icon, curve = 'linear', das
206
220
  </g>
207
221
  );
208
222
  }
223
+
209
224
  return (
210
225
  <g ref={ref} className={clsx('pointer-events-none', className)} style={{ color: chart.colors.get(id) ?? color ?? seriesColor(0) }}>
211
226
  <LinePath points={pointsOf(chart, values)} curve={curve} dashed={dashed} dots={dots} width={width} />
@@ -220,6 +235,7 @@ export function ChartLine<Row>({ value, label, tone, icon, curve = 'linear', das
220
235
  export function ChartPoint<Row>({ value, label, tone, icon, className, ref }: ChartPointProps<Row>) {
221
236
  const [chart, id, values] = useSeriesValues('Chart.Point', value);
222
237
  const [color, rowColors] = tonesOf(chart, tone);
238
+
223
239
  useRegistration(chart.store, 'series', id, {
224
240
  kind: 'point',
225
241
  label,
@@ -232,18 +248,23 @@ export function ChartPoint<Row>({ value, label, tone, icon, className, ref }: Ch
232
248
  icon: icon ?? null,
233
249
  valueLabels: false
234
250
  });
251
+
235
252
  const fallback = chart.colors.get(id) ?? seriesColor(0);
253
+
236
254
  return (
237
255
  <g ref={ref} className={clsx('pointer-events-none', className)}>
238
256
  {values.map((amount, index) => {
239
257
  const pixel = amount === null ? null : chart.pixelOfY(amount);
240
258
  const left = chart.points ? (chart.positions[index]?.[0] ?? null) : chart.centerOf(index);
259
+
241
260
  if (pixel === null || left === null || !Number.isFinite(left)) {
242
261
  return null;
243
262
  }
263
+
244
264
  const active = index === chart.activeIndex;
245
265
  const picked = chart.selected[index] === true;
246
266
  const fill = rowColors?.[index] ?? color ?? (chart.points ? chart.groupColorOf(index) : fallback);
267
+
247
268
  return (
248
269
  <g key={chart.keys?.[index] ?? index} opacity={chart.dimmed[index] === true ? DIMMED_POINT : 1}>
249
270
  <circle cx={left} cy={pixel} r={active || picked ? 5 : 4} strokeWidth={1} style={{ fill, stroke: chart.halo }} />
@@ -273,6 +294,7 @@ export function ChartArea<Row>({
273
294
  const [chart, id, values] = useSeriesValues('Chart.Area', value);
274
295
  const flat = stack || fillKind === 'flat';
275
296
  const gradient = `chart-area-${id.replace(/[^\w-]/g, '')}`;
297
+
276
298
  useRegistration(chart.store, 'series', id, {
277
299
  kind: 'area',
278
300
  label,
@@ -285,15 +307,18 @@ export function ChartArea<Row>({
285
307
  icon: icon ?? null,
286
308
  valueLabels: false
287
309
  });
310
+
288
311
  const stacked = chart.stacked.get(id);
289
312
  const tops = pointsOf(chart, stacked?.top ?? values);
290
- const ground = chart.pixelOfY(Math.max(chart.y.domain[0], 0)) ?? chart.plot.bottom;
313
+ const ground = groundOf(chart);
314
+
291
315
  const fill = area<number>()
292
316
  .defined((index) => tops[index] !== null)
293
317
  .x((index) => tops[index]![0])
294
318
  .y1((index) => tops[index]![1])
295
319
  .y0((index) => (stacked === undefined ? ground : (chart.pixelOfY(stacked.base[index]!) ?? ground)))
296
320
  .curve(CURVES[curve])(tops.map((_, index) => index));
321
+
297
322
  return (
298
323
  <g ref={ref} className={clsx('pointer-events-none', className)} style={{ color: chart.colors.get(id) ?? colorOf(tone) ?? seriesColor(0) }}>
299
324
  {flat ? null : (
@@ -313,6 +338,7 @@ export function ChartArea<Row>({
313
338
  /* A group of `Chart.Bar` that shares the width of a bucket, side by side or stacked. */
314
339
  export function ChartBars({ stack = false, children, className, ref }: ChartBarsProps) {
315
340
  const id = useId();
341
+
316
342
  return (
317
343
  <BarsContext value={{ id, stack }}>
318
344
  <g ref={ref} className={className}>
@@ -346,8 +372,9 @@ export function ChartBar<Row>({
346
372
  const labels = useRef<SVGGElement>(null);
347
373
  const [widths, setWidths] = useState<ReadonlyMap<string, number>>(() => new Map());
348
374
  const rows = chart.data as Row[];
349
- const rowColors = typeof tone === 'function' ? rows.map((row, index) => colorOf(tone(row, index))!) : null;
350
- const color = typeof tone === 'function' ? (rowColors?.[0] ?? null) : colorOf(tone);
375
+ const [color, rowColors] = tonesOf(chart, tone);
376
+ const labeled = valueLabels !== undefined && valueLabels !== false;
377
+
351
378
  useRegistration(chart.store, 'series', id, {
352
379
  kind: 'bar',
353
380
  label,
@@ -358,46 +385,58 @@ export function ChartBar<Row>({
358
385
  bars: bars?.id ?? null,
359
386
  curve: 'linear',
360
387
  icon: icon ?? null,
361
- valueLabels: valueLabels !== undefined && valueLabels !== false,
388
+ valueLabels: labeled,
362
389
  dimOpacity
363
390
  });
391
+
364
392
  // A time scale learns how long a bucket is from the distance between two rows, so one row alone has no slot.
365
393
  const noSlot = chart.xScale === 'time' && chart.data.length > 0 && chart.bucketAt(0) === null;
394
+
366
395
  useEffect(() => {
367
396
  if (noSlot) {
368
397
  warnOnce('Chart.Bar: a time scale with one row draws no columns without a `step` on the root.');
369
398
  }
370
399
  }, [noSlot]);
400
+
371
401
  const { slot, count } = chart.slots.get(id) ?? { slot: 0, count: 1 };
372
402
  const stacked = chart.stacked.get(id);
373
403
  const fallback = chart.colors.get(id) ?? seriesColor(0);
374
404
  const anySelected = chart.selected.some(Boolean);
405
+
375
406
  const groupOf = (index: number): { first: number; last: number } =>
376
407
  chart.band?.groups.find((run) => index >= run.first && index <= run.last) ?? { first: 0, last: values.length - 1 };
408
+
377
409
  const writeValue = typeof valueLabels === 'function' ? valueLabels : (amount: number): string => chart.formatY(amount);
410
+
378
411
  const drawn = values.flatMap((amount, index) => {
379
412
  const top = stacked?.top[index];
380
413
  const base = stacked?.base[index] ?? 0;
381
414
  const topPixel = top === null || top === undefined ? null : chart.pixelOfY(top);
382
415
  const basePixel = chart.pixelOfY(base) ?? chart.plot.bottom;
383
416
  const bucket = chart.bucketAt(index);
417
+
384
418
  if (amount === null || topPixel === null || bucket === null) {
385
419
  return [];
386
420
  }
421
+
387
422
  const column = columnsIn(bucket.left, bucket.width, count, columnWidth)[slot]!;
388
423
  const { y, height } = segmentOf(topPixel, basePixel, base === 0, amount, bars?.stack === true ? 0 : minHeight);
389
424
  const focused = index === chart.activeIndex || chart.selected[index] === true;
390
425
  const outOfFocus = chart.dimmed[index] === true || (anySelected && !focused);
391
426
  const run = groupOf(index);
392
427
  let alpha = focused ? 1 : (opacity?.(rows[index]!, index - run.first, run.last - run.first + 1) ?? 1);
428
+
393
429
  if (outOfFocus) {
394
430
  alpha *= dimOpacity;
395
431
  } else if (chart.activeIndex >= 0 && !focused) {
396
432
  alpha *= hoverOpacity;
397
433
  }
398
- const text = valueLabels === undefined || valueLabels === false ? '' : writeValue(amount, rows[index]!, index);
434
+
435
+ const text = labeled ? writeValue(amount, rows[index]!, index) : '';
436
+
399
437
  return [{ index, column, y, height, alpha, outOfFocus, text }];
400
438
  });
439
+
401
440
  const labelTops = placeValueLabels(
402
441
  drawn.map(({ column, y, text }) => ({ center: column.x + column.width / 2, top: y, width: widths.get(text) ?? guessLabelWidth(text, valueLabelSize) })),
403
442
  valueLabelSize
@@ -405,10 +444,13 @@ export function ChartBar<Row>({
405
444
 
406
445
  useBeforePaint(() => {
407
446
  const texts = [...(labels.current?.querySelectorAll('text') ?? [])];
447
+
408
448
  if (texts.length === 0 || typeof texts[0]!.getComputedTextLength !== 'function') {
409
449
  return;
410
450
  }
451
+
411
452
  const next = new Map(texts.map((node) => [node.textContent ?? '', Math.ceil(node.getComputedTextLength())]));
453
+
412
454
  if (next.size !== widths.size || [...next].some(([text, width]) => widths.get(text) !== width)) {
413
455
  setWidths(next);
414
456
  }
@@ -418,11 +460,12 @@ export function ChartBar<Row>({
418
460
  <g ref={ref} className={clsx('pointer-events-none', className)}>
419
461
  <g
420
462
  className={animate ? 'transition-[scale] duration-400 ease-out starting:scale-y-0 motion-reduce:transition-none' : undefined}
421
- style={animate ? { transformOrigin: `0px ${chart.pixelOfY(Math.max(chart.y.domain[0], 0)) ?? chart.plot.bottom}px` } : undefined}
463
+ style={animate ? { transformOrigin: `0px ${groundOf(chart)}px` } : undefined}
422
464
  >
423
465
  {drawn.map(({ index, column, y, height, alpha }) => {
424
466
  const corner = bars?.stack === true ? 0 : Math.min(radius, Math.floor(column.width / 4));
425
467
  const fill = rowColors?.[index] ?? color ?? fallback;
468
+
426
469
  return rounded === 'end' && corner > 0 ? (
427
470
  <path
428
471
  key={index}
@@ -436,11 +479,11 @@ export function ChartBar<Row>({
436
479
  })}
437
480
  </g>
438
481
  <g ref={labels}>
439
- {valueLabels !== undefined &&
440
- valueLabels !== false &&
482
+ {labeled &&
441
483
  drawn.map(({ index, column, y, outOfFocus, text }, i) => {
442
484
  const center = Math.round(column.x + column.width / 2);
443
485
  const baseline = labelTops[i]!;
486
+
444
487
  return (
445
488
  <g key={`label-${index}`} opacity={outOfFocus ? dimOpacity : 1} aria-hidden>
446
489
  {baseline < y - LABEL_LIFT - 2 && (
package/src/spark.ts CHANGED
@@ -12,22 +12,22 @@ export interface SparkColumn {
12
12
  readonly zero: boolean;
13
13
  }
14
14
 
15
- /*
16
- * The columns of a sparkline on whole pixels, 2px apart, rounded by half their width. A column is 4px tall at least,
17
- * so the smallest count still reads as a bar; a zero keeps a one-pixel baseline, so a quiet day still shows.
18
- */
15
+ /* The columns of a sparkline on whole pixels, 2px apart, rounded by half their width; a zero keeps a one-pixel baseline. */
19
16
  export function sparkColumns(values: readonly (number | null)[], width: number, height: number): SparkColumn[] {
20
17
  const high = Math.max(0, ...values.map((value) => value ?? 0));
21
18
  const step = values.length === 0 ? 0 : (width + GAP) / values.length;
19
+
22
20
  return values.flatMap((value, index) => {
23
21
  if (value === null) {
24
22
  return [];
25
23
  }
24
+
26
25
  const x = Math.round(index * step);
27
26
  const columnWidth = Math.max(1, Math.round((index + 1) * step) - x - GAP);
28
27
  const zero = value <= 0 || high === 0;
29
28
  const radius = zero ? 0 : columnWidth / 2;
30
29
  const columnHeight = zero ? 1 : Math.min(height, Math.max(MIN_HEIGHT, Math.round((value / high) * height)));
30
+
31
31
  return [{ x, y: height - columnHeight, width: columnWidth, height: columnHeight, radius, zero }];
32
32
  });
33
33
  }
package/src/store.ts CHANGED
@@ -96,6 +96,7 @@ const same = (one: unknown, other: unknown): boolean => {
96
96
  if (Array.isArray(one) && Array.isArray(other)) {
97
97
  return one.length === other.length && one.every((value, i) => Object.is(value, other[i]));
98
98
  }
99
+
99
100
  return Object.is(one, other);
100
101
  };
101
102
 
@@ -103,19 +104,12 @@ const sameEntry = (one: object | undefined, other: object): boolean =>
103
104
  one !== undefined && Object.entries(other).every(([key, value]) => same((one as Record<string, unknown>)[key], value));
104
105
 
105
106
  /*
106
- * What the parts tell the root: the series with their values, the axes with the room they need, the
107
- * markers and bands, and the formats of the axes. Each is a snapshot of its own that only changes
108
- * when what is in it does, so a part that registers the same values again changes nothing.
107
+ * What the parts tell the root. Each is a snapshot of its own that only changes when what is in it
108
+ * does, so a part that registers the same values again changes nothing.
109
109
  */
110
110
  export function createChartStore(): ChartStore {
111
111
  const listeners = new Set<() => void>();
112
- let series: ReadonlyMap<string, SeriesEntry> = new Map();
113
112
  let axes: AxisSizes = { end: null };
114
- let xAxes: ReadonlyMap<string, XAxisEntry> = new Map();
115
- let yAxes: ReadonlyMap<YAxisSide, YAxisEntry> = new Map();
116
- let markers: ReadonlyMap<string, MarkerEntry> = new Map();
117
- let rules: ReadonlyMap<string, RuleEntry> = new Map();
118
- let bands: ReadonlyMap<string, BandEntry> = new Map();
119
113
  let formats: ChartFormats = {};
120
114
 
121
115
  const emit = (): void => {
@@ -124,83 +118,65 @@ export function createChartStore(): ChartStore {
124
118
  }
125
119
  };
126
120
 
127
- const updated = <Key, Entry extends object>(map: ReadonlyMap<Key, Entry>, id: Key, entry: Entry | null): ReadonlyMap<Key, Entry> | null => {
128
- if (entry === null) {
129
- if (!map.has(id)) {
130
- return null;
121
+ const keyed = <Key, Entry extends object>() => {
122
+ let map: ReadonlyMap<Key, Entry> = new Map();
123
+
124
+ return {
125
+ get: (): ReadonlyMap<Key, Entry> => map,
126
+ set: (id: Key, entry: Entry | null): void => {
127
+ if (entry === null) {
128
+ if (!map.has(id)) {
129
+ return;
130
+ }
131
+
132
+ const next = new Map(map);
133
+ next.delete(id);
134
+ map = next;
135
+ } else if (sameEntry(map.get(id), entry)) {
136
+ return;
137
+ } else {
138
+ // A changed entry keeps its place, so a series keeps its color while its values change.
139
+ map = new Map(map).set(id, entry);
140
+ }
141
+
142
+ emit();
131
143
  }
132
- const next = new Map(map);
133
- next.delete(id);
134
- return next;
135
- }
136
- if (sameEntry(map.get(id), entry)) {
137
- return null;
138
- }
139
- // A changed entry keeps its place, so a series keeps its color while its values change.
140
- return new Map(map).set(id, entry);
144
+ };
141
145
  };
142
146
 
147
+ const series = keyed<string, SeriesEntry>();
148
+ const xAxes = keyed<string, XAxisEntry>();
149
+ const yAxes = keyed<YAxisSide, YAxisEntry>();
150
+ const markers = keyed<string, MarkerEntry>();
151
+ const rules = keyed<string, RuleEntry>();
152
+ const bands = keyed<string, BandEntry>();
153
+
143
154
  return {
144
155
  subscribe(listener) {
145
156
  listeners.add(listener);
157
+
146
158
  return () => listeners.delete(listener);
147
159
  },
148
- series: () => series,
160
+ series: series.get,
149
161
  axes: () => axes,
150
- xAxes: () => xAxes,
151
- yAxes: () => yAxes,
152
- markers: () => markers,
153
- rules: () => rules,
154
- bands: () => bands,
162
+ xAxes: xAxes.get,
163
+ yAxes: yAxes.get,
164
+ markers: markers.get,
165
+ rules: rules.get,
166
+ bands: bands.get,
155
167
  formats: () => formats,
156
- setSeries(id, entry) {
157
- const next = updated(series, id, entry);
158
- if (next !== null) {
159
- series = next;
160
- emit();
161
- }
162
- },
168
+ setSeries: series.set,
163
169
  setAxis(axis, size) {
164
170
  if (axes[axis] !== size) {
165
171
  axes = { ...axes, [axis]: size };
166
172
  emit();
167
173
  }
168
174
  },
169
- setXAxis(id, entry) {
170
- const next = updated(xAxes, id, entry);
171
- if (next !== null) {
172
- xAxes = next;
173
- emit();
174
- }
175
- },
176
- setYAxis(side, entry) {
177
- const next = updated(yAxes, side, entry);
178
- if (next !== null) {
179
- yAxes = next;
180
- emit();
181
- }
182
- },
183
- setRule(id, entry) {
184
- const next = updated(rules, id, entry);
185
- if (next !== null) {
186
- rules = next;
187
- emit();
188
- }
189
- },
190
- setMarker(id, entry) {
191
- const next = updated(markers, id, entry);
192
- if (next !== null) {
193
- markers = next;
194
- emit();
195
- }
196
- },
197
- setBand(id, entry) {
198
- const next = updated(bands, id, entry);
199
- if (next !== null) {
200
- bands = next;
201
- emit();
202
- }
203
- },
175
+ setXAxis: xAxes.set,
176
+ setYAxis: yAxes.set,
177
+ setRule: rules.set,
178
+ setMarker: markers.set,
179
+ setBand: bands.set,
204
180
  setFormat(axis, format) {
205
181
  if (formats[axis] !== format) {
206
182
  formats = { ...formats, [axis]: format };
@@ -13,6 +13,7 @@ export function timeLabelOf(span: number, step: number): TimeLabel {
13
13
  if (step >= DAY) {
14
14
  return 'day';
15
15
  }
16
+
16
17
  return span <= DAY ? 'clock' : 'dayClock';
17
18
  }
18
19
 
@@ -42,14 +42,24 @@ const byStart = <Span extends TimelineSpan>(first: Span, second: Span): number =
42
42
  export function timelineTree<Span extends TimelineSpan>(spans: readonly Span[]): TimelineTreeRow<Span>[] {
43
43
  const known = new Set(spans.map((span) => span.id));
44
44
  const children = new Map<string | null, Span[]>();
45
+
45
46
  for (const span of spans) {
46
47
  const parent = span.parent !== undefined && span.parent !== null && span.parent !== span.id && known.has(span.parent) ? span.parent : null;
47
- children.set(parent, [...(children.get(parent) ?? []), span]);
48
+ const siblings = children.get(parent);
49
+
50
+ if (siblings === undefined) {
51
+ children.set(parent, [span]);
52
+ } else {
53
+ siblings.push(span);
54
+ }
48
55
  }
56
+
49
57
  const rows: TimelineTreeRow<Span>[] = [];
50
58
  const placed = new Set<string>();
59
+
51
60
  const visit = (siblings: readonly Span[], ancestors: readonly string[]): void => {
52
61
  const sorted = siblings.filter((span) => !placed.has(span.id)).toSorted(byStart);
62
+
53
63
  sorted.forEach((span, index) => {
54
64
  placed.add(span.id);
55
65
  const own = (children.get(span.id) ?? []).filter((child) => !placed.has(child.id));
@@ -57,13 +67,16 @@ export function timelineTree<Span extends TimelineSpan>(spans: readonly Span[]):
57
67
  visit(own, [...ancestors, span.id]);
58
68
  });
59
69
  };
70
+
60
71
  visit(children.get(null) ?? [], []);
72
+
61
73
  // Spans of a parent cycle reach no root; each that is left starts a tree of its own.
62
74
  for (const span of spans.toSorted(byStart)) {
63
75
  if (!placed.has(span.id)) {
64
76
  visit([span], []);
65
77
  }
66
78
  }
79
+
67
80
  return rows;
68
81
  }
69
82
 
@@ -82,8 +95,10 @@ export function timelineExtent(spans: readonly TimelineSpan[], fixedEnd?: number
82
95
  if (spans.length === 0) {
83
96
  return { origin: 0, total: 1 };
84
97
  }
98
+
85
99
  const origin = Math.min(...spans.map((span) => span.start));
86
100
  const end = fixedEnd ?? Math.max(...spans.map((span) => span.start + span.duration));
101
+
87
102
  return { origin, total: Math.max(end - origin, 0.001) };
88
103
  }
89
104
 
@@ -95,14 +110,17 @@ export function durationTicks(total: number, count = 5): number[] {
95
110
  if (!(total > 0) || !(count > 0)) {
96
111
  return [0];
97
112
  }
113
+
98
114
  const raw = total / count;
99
115
  const power = 10 ** Math.floor(Math.log10(Math.max(raw, 0.001)));
100
116
  const step = [1, 2, 5, 10].map((factor) => factor * power).find((candidate) => candidate >= raw) ?? raw;
101
117
  const ticks: number[] = [];
118
+
102
119
  // Counted, not summed, so 0.1 + 0.2 never drifts past the end.
103
120
  for (let i = 0; i * step <= total + step * 1e-9; i++) {
104
121
  ticks.push(Number((i * step).toPrecision(12)));
105
122
  }
123
+
106
124
  return ticks;
107
125
  }
108
126
 
@@ -128,17 +146,20 @@ export function barOf(span: TimelineSpan, origin: number, total: number): Timeli
128
146
  const left = Math.min(percentOf(span.start, origin, total), 100 - MIN_WIDTH);
129
147
  // A span that runs past a fixed end is cut off there.
130
148
  const width = Math.max(MIN_WIDTH, Math.min((span.duration / total) * 100, 100 - left));
149
+
131
150
  return { left, width, label: width > INSIDE_FROM ? 'inside' : left + width > BEFORE_FROM ? 'before' : 'after' };
132
151
  }
133
152
 
134
153
  /* The time the spans of each kind take, the roots left out: a root covers the whole trace and would outweigh every kind. */
135
154
  export function kindTimes(rows: readonly TimelineTreeRow<TimelineSpan>[]): Map<string, number> {
136
155
  const times = new Map<string, number>();
156
+
137
157
  for (const { span, depth } of rows) {
138
158
  if (depth > 0 && span.kind !== undefined) {
139
159
  times.set(span.kind, (times.get(span.kind) ?? 0) + span.duration);
140
160
  }
141
161
  }
162
+
142
163
  return times;
143
164
  }
144
165
 
@@ -156,9 +177,11 @@ export function timelineMove(
156
177
  expanded: ReadonlySet<string>
157
178
  ): TimelineMove | undefined {
158
179
  const row = rows[current];
180
+
159
181
  if (row === undefined) {
160
182
  return undefined;
161
183
  }
184
+
162
185
  switch (key) {
163
186
  case 'ArrowDown':
164
187
  return { focus: Math.min(rows.length - 1, current + 1) };
@@ -172,13 +195,16 @@ export function timelineMove(
172
195
  if (row.children === 0) {
173
196
  return undefined;
174
197
  }
198
+
175
199
  return expanded.has(row.span.id) ? { focus: current + 1 } : { expand: row.span.id };
176
200
  case 'ArrowLeft': {
177
201
  if (row.children > 0 && expanded.has(row.span.id)) {
178
202
  return { collapse: row.span.id };
179
203
  }
204
+
180
205
  const parent = row.ancestors.at(-1);
181
206
  const index = parent === undefined ? -1 : rows.findIndex((candidate) => candidate.span.id === parent);
207
+
182
208
  return index < 0 ? undefined : { focus: index };
183
209
  }
184
210
  case 'Enter':