@adecore/charts 0.38.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/overlays.tsx CHANGED
@@ -6,6 +6,7 @@ import { Button, Icon, Surface, useContentSize } from '@adecore/ui';
6
6
  import { useChartContext, type ChartContextValue } from './context.ts';
7
7
  import type { SeriesEntry } from './store.ts';
8
8
  import type { ChartNote, ChartX } from './types.ts';
9
+ import { tableClasses } from './values-table.ts';
9
10
 
10
11
  export interface ChartBucketValue {
11
12
  readonly label: string;
@@ -87,6 +88,7 @@ const bucketOf = <Row,>(chart: ChartContextValue, index: number): ChartBucket<Ro
87
88
  groupLabel: chart.groupLabels?.[index] ?? null,
88
89
  values: chart.readable.flatMap(([id, entry]) => {
89
90
  const value = entry.values[index];
91
+
90
92
  return value === null || value === undefined ? [] : [{ label: entry.label, color: colorAt(chart, id, entry, index), value }];
91
93
  }),
92
94
  notes: chart.notesAt(index)
@@ -101,6 +103,7 @@ function Swatch({ color, entry, size }: { color: string; entry: SeriesEntry; siz
101
103
  </span>
102
104
  );
103
105
  }
106
+
104
107
  return <span className={clsx('shrink-0', entry.kind === 'bar' ? 'size-2 rounded-xs' : 'h-0.5 w-3 rounded-full')} style={{ background: color }} />;
105
108
  }
106
109
 
@@ -121,41 +124,54 @@ export function ChartTooltip<Row>({ total = false, format, children, placement =
121
124
  const { t } = useTranslation('charts');
122
125
  const [measure, card] = useContentSize();
123
126
  const { activeIndex, elements } = chart;
127
+
124
128
  if (activeIndex < 0 || elements.tooltip === null || !chart.ownsCursor) {
125
129
  return null;
126
130
  }
131
+
127
132
  const bucket = bucketOf<Row>(chart, activeIndex);
128
133
  const write = format ?? chart.formatY;
129
134
  const position = chart.points ? chart.positions[activeIndex] : null;
130
135
  const pixel = chart.leftAxis + (position?.[0] ?? chart.centerOf(activeIndex)) - chart.scroll;
131
- // The card hangs on the side with the most room, so it never covers the cursor and never runs off.
132
- const right = pixel > chart.box / 2;
133
- let place: CSSProperties = right
134
- ? { right: Math.round(chart.box - pixel + OFFSET), maxWidth: Math.max(0, Math.round(pixel - OFFSET - EDGE)) }
135
- : { left: Math.round(pixel + OFFSET), maxWidth: Math.max(0, Math.round(chart.box - pixel - OFFSET - EDGE)) };
136
- place = { ...place, top: position === null || position === undefined ? chart.plot.top : Math.max(0, Math.round(position[1]) - OFFSET) };
137
- if (placement !== 'cursor') {
136
+ let place: CSSProperties;
137
+
138
+ if (placement === 'cursor') {
139
+ // The card hangs on the side with the most room, so it never covers the cursor and never runs off.
140
+ place = {
141
+ ...(pixel > chart.box / 2
142
+ ? { right: Math.round(chart.box - pixel + OFFSET), maxWidth: Math.max(0, Math.round(pixel - OFFSET - EDGE)) }
143
+ : { left: Math.round(pixel + OFFSET), maxWidth: Math.max(0, Math.round(chart.box - pixel - OFFSET - EDGE)) }),
144
+ top: position === null || position === undefined ? chart.plot.top : Math.max(0, Math.round(position[1]) - OFFSET)
145
+ };
146
+ } else {
138
147
  const plotLeft = chart.leftAxis + Math.max(0, chart.plot.left - chart.scroll);
139
148
  const plotRight = Math.min(chart.box - chart.rightAxis, chart.leftAxis + chart.plot.right - chart.scroll);
140
149
  const reach = (chart.bucketAt(activeIndex)?.width ?? 2 * POINT_ROOM) / 2;
141
150
  const [vertical, horizontal] = placement.split('-') as ['top' | 'bottom', 'left' | 'right'];
151
+
142
152
  const covers = (side: 'left' | 'right'): boolean => (side === 'left' ? pixel - reach < plotLeft + card.width : pixel + reach > plotRight - card.width);
153
+
143
154
  const side = covers(horizontal) && !covers(horizontal === 'left' ? 'right' : 'left') ? (horizontal === 'left' ? 'right' : 'left') : horizontal;
155
+
144
156
  place = {
145
157
  ...(side === 'left' ? { left: Math.round(plotLeft) } : { right: Math.round(chart.box - plotRight) }),
146
158
  top: vertical === 'top' ? Math.round(chart.plot.top) : Math.round(chart.plot.bottom - card.height),
147
159
  maxWidth: Math.max(0, Math.round(plotRight - plotLeft))
148
160
  };
149
161
  }
162
+
150
163
  const sum = bucket.values.reduce((all, entry) => all + entry.value, 0);
164
+
151
165
  // A point names its series and itself; its x is a value like the others, under the title of its axis.
152
166
  const heading = chart.points
153
167
  ? [bucket.groupLabel, chart.rowLabels?.[activeIndex]].filter(Boolean).join(' · ') || chart.formatX(bucket.x)
154
168
  : [bucket.groupLabel, chart.rowLabels?.[activeIndex] ?? chart.formatX(bucket.x)].filter(Boolean).join(' · ');
169
+
155
170
  return createPortal(
156
171
  <Surface
157
172
  ref={(node: HTMLDivElement | null) => {
158
173
  measure(node);
174
+
159
175
  if (typeof ref === 'function') {
160
176
  ref(node);
161
177
  } else if (ref) {
@@ -179,6 +195,7 @@ export function ChartTooltip<Row>({ total = false, format, children, placement =
179
195
  )}
180
196
  {chart.readable.map(([id, entry]) => {
181
197
  const value = entry.values[activeIndex];
198
+
182
199
  // A series without a value here still gets its row, so a gap reads as nothing measured.
183
200
  return (
184
201
  <p key={id} className="flex items-center gap-2 text-text-muted">
@@ -213,9 +230,11 @@ export function ChartTooltip<Row>({ total = false, format, children, placement =
213
230
  /* The series with their color, in the order of the children; on a point chart the series of its groups. */
214
231
  export function ChartLegend({ className, ref }: ChartLegendProps) {
215
232
  const chart = useChartContext('Chart.Legend');
233
+
216
234
  if (chart.elements.legend === null) {
217
235
  return null;
218
236
  }
237
+
219
238
  return createPortal(
220
239
  <ul ref={ref} className={clsx('flex flex-wrap gap-x-4 gap-y-1 text-xs text-text-muted', className)}>
221
240
  {chart.points && chart.groupKeys !== null
@@ -242,20 +261,26 @@ export function ChartTable({ toggle = true, open, defaultOpen = false, onOpenCha
242
261
  const { t } = useTranslation('charts');
243
262
  const [ownOpen, setOwnOpen] = useState(defaultOpen);
244
263
  const id = useId();
264
+
245
265
  if (chart.elements.table === null) {
246
266
  return null;
247
267
  }
268
+
248
269
  const shown = toggle && (open ?? ownOpen);
270
+
249
271
  const setShown = (next: boolean): void => {
250
272
  if (open === undefined) {
251
273
  setOwnOpen(next);
252
274
  }
275
+
253
276
  onOpenChange?.(next);
254
277
  };
278
+
255
279
  const grouped = data === undefined && chart.groupKeys !== null;
256
280
  // A point names itself by its label where it has one, and its x stands in a column of its own.
257
281
  const xColumn = data === undefined && chart.points && chart.rowLabels !== null;
258
282
  const columns = data?.columns ?? [...(xColumn ? [chart.xTitle ?? ''] : []), ...chart.readable.map(([, entry]) => entry.label)];
283
+
259
284
  const rows: { key: string; group: string | null; label: string; cells: readonly string[] }[] =
260
285
  data?.rows.map((row) => ({ ...row, group: null })) ??
261
286
  chart.xs.flatMap((key, index) =>
@@ -271,14 +296,16 @@ export function ChartTable({ toggle = true, open, defaultOpen = false, onOpenCha
271
296
  ...(xColumn ? [Number.isFinite(key) ? chart.formatX(key) : ''] : []),
272
297
  ...chart.readable.map(([, entry]) => {
273
298
  const value = entry.values[index];
299
+
274
300
  return value === null || value === undefined ? '' : chart.formatY(value);
275
301
  })
276
302
  ]
277
303
  }
278
304
  ]
279
305
  );
280
- const head = shown ? 'h-8 px-2 text-right font-medium whitespace-nowrap text-text-muted' : undefined;
281
- const cell = shown ? 'h-8 px-2 text-right whitespace-nowrap text-text' : undefined;
306
+
307
+ const classes = tableClasses(shown);
308
+
282
309
  return createPortal(
283
310
  <div ref={ref} className={clsx('flex flex-col items-start gap-2', className)}>
284
311
  {toggle && (
@@ -286,15 +313,15 @@ export function ChartTable({ toggle = true, open, defaultOpen = false, onOpenCha
286
313
  {shown ? t('values.hide') : t('values.show')}
287
314
  </Button>
288
315
  )}
289
- <div id={id} className={shown ? 'max-h-80 w-full overflow-auto rounded-md border border-border-soft' : 'sr-only'}>
290
- <table className={shown ? 'w-full border-collapse text-xs tabular-nums' : undefined}>
316
+ <div id={id} className={classes.box}>
317
+ <table className={classes.table}>
291
318
  <caption className="sr-only">{t('values.caption', { label: chart.label })}</caption>
292
- <thead className={shown ? 'sticky top-0 bg-surface-hover' : undefined}>
319
+ <thead className={classes.head}>
293
320
  <tr>
294
321
  {grouped && <td />}
295
322
  <td />
296
323
  {columns.map((column, index) => (
297
- <th key={index} scope="col" className={head}>
324
+ <th key={index} scope="col" className={classes.column}>
298
325
  {column}
299
326
  </th>
300
327
  ))}
@@ -302,13 +329,13 @@ export function ChartTable({ toggle = true, open, defaultOpen = false, onOpenCha
302
329
  </thead>
303
330
  <tbody>
304
331
  {rows.map((row) => (
305
- <tr key={row.key} className={shown ? 'border-t border-border-soft' : undefined}>
332
+ <tr key={row.key} className={classes.row}>
306
333
  {grouped && <td className={shown ? 'h-8 px-2 text-text-muted' : undefined}>{row.group}</td>}
307
- <th scope="row" className={shown ? 'h-8 px-2 text-left font-normal whitespace-nowrap text-text-muted' : undefined}>
334
+ <th scope="row" className={classes.rowHeading}>
308
335
  {row.label}
309
336
  </th>
310
337
  {row.cells.map((value, index) => (
311
- <td key={index} className={cell}>
338
+ <td key={index} className={classes.cell}>
312
339
  {value}
313
340
  </td>
314
341
  ))}
package/src/points.ts CHANGED
@@ -1,5 +1,3 @@
1
- /* The pure geometry of a point chart: the nearest point, moving between points, the frontier and the end labels. */
2
-
3
1
  export interface PlacedPoint {
4
2
  readonly index: number;
5
3
  readonly x: number;
@@ -10,13 +8,16 @@ export interface PlacedPoint {
10
8
  export function nearestPoint(points: readonly PlacedPoint[], x: number, y: number, reach: number): number {
11
9
  let nearest = -1;
12
10
  let distance = reach;
11
+
13
12
  for (const point of points) {
14
13
  const away = Math.hypot(point.x - x, point.y - y);
14
+
15
15
  if (away <= distance) {
16
16
  distance = away;
17
17
  nearest = point.index;
18
18
  }
19
19
  }
20
+
20
21
  return nearest;
21
22
  }
22
23
 
@@ -27,22 +28,30 @@ export function nearestPoint(points: readonly PlacedPoint[], x: number, y: numbe
27
28
  */
28
29
  export function movePoint(lines: readonly (readonly number[])[], current: number, key: string): number | null | undefined {
29
30
  const filled = lines.filter((line) => line.length > 0);
31
+
30
32
  if (filled.length === 0) {
31
33
  return undefined;
32
34
  }
35
+
33
36
  const line = filled.findIndex((indexes) => indexes.includes(current));
37
+
34
38
  if (line < 0) {
35
39
  if (key === 'Escape') {
36
40
  return undefined;
37
41
  }
42
+
38
43
  const arrows = ['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp', 'Home', 'End'];
44
+
39
45
  if (!arrows.includes(key)) {
40
46
  return undefined;
41
47
  }
48
+
42
49
  return key === 'ArrowLeft' || key === 'ArrowUp' || key === 'End' ? filled.at(-1)!.at(-1)! : filled[0]![0]!;
43
50
  }
51
+
44
52
  const indexes = filled[line]!;
45
53
  const at = indexes.indexOf(current);
54
+
46
55
  switch (key) {
47
56
  case 'ArrowRight':
48
57
  return indexes[Math.min(indexes.length - 1, at + 1)];
@@ -51,6 +60,7 @@ export function movePoint(lines: readonly (readonly number[])[], current: number
51
60
  case 'ArrowDown':
52
61
  case 'ArrowUp': {
53
62
  const next = filled[line + (key === 'ArrowDown' ? 1 : -1)];
63
+
54
64
  return next === undefined ? current : next[Math.min(at, next.length - 1)];
55
65
  }
56
66
  case 'Home':
@@ -73,12 +83,14 @@ export function frontierOf<Point extends { readonly x: number; readonly y: numbe
73
83
  const sorted = [...points].sort((one, other) => sign.x * (one.x - other.x) || sign.y * (other.y - one.y));
74
84
  const kept: Point[] = [];
75
85
  let best = -Infinity;
86
+
76
87
  for (const point of sorted) {
77
88
  if (sign.y * point.y > best) {
78
89
  kept.push(point);
79
90
  best = sign.y * point.y;
80
91
  }
81
92
  }
93
+
82
94
  return kept.sort((one, other) => one.x - other.x);
83
95
  }
84
96
 
@@ -90,15 +102,20 @@ export function spreadLabels(wishes: readonly number[], wanted: number, top: num
90
102
  const order = wishes.map((wish, index) => ({ wish, index })).sort((one, other) => one.wish - other.wish || one.index - other.index);
91
103
  const placed = order.map(({ wish }) => wish);
92
104
  const gap = placed.length > 1 ? Math.min(wanted, Math.max(0, bottom - top) / (placed.length - 1)) : wanted;
105
+
93
106
  for (let i = 0; i < placed.length; i++) {
94
107
  placed[i] = Math.max(top, placed[i]!, i === 0 ? top : placed[i - 1]! + gap);
95
108
  }
109
+
96
110
  for (let i = placed.length - 1; i >= 0; i--) {
97
111
  placed[i] = Math.min(placed[i]!, i === placed.length - 1 ? bottom : placed[i + 1]! - gap);
98
112
  }
113
+
99
114
  const result: number[] = [];
115
+
100
116
  order.forEach(({ index }, i) => {
101
117
  result[index] = placed[i]!;
102
118
  });
119
+
103
120
  return result;
104
121
  }
package/src/register.ts CHANGED
@@ -25,14 +25,14 @@ const write = <Kind extends keyof Entries>(store: ChartStore, kind: Kind, id: st
25
25
  };
26
26
 
27
27
  /*
28
- * Tells the root about a part on every render, before paint, and takes it out on unmount. The store
29
- * ignores an entry equal to the one it holds, so a render that changes nothing costs nothing; the
30
- * removal stays apart from the update, or every update would move the part to the end.
28
+ * Tells the root about a part on every render, before paint, and takes it out on unmount. The removal
29
+ * stays apart from the update, or every update would move the part to the end.
31
30
  */
32
31
  export function useRegistration<Kind extends keyof Entries>(store: ChartStore, kind: Kind, id: string, entry: Entries[Kind]): void {
33
32
  useBeforePaint(() => {
34
33
  write(store, kind, id, entry);
35
34
  });
35
+
36
36
  useBeforePaint(() => () => write(store, kind, id, null), [store, kind, id]);
37
37
  }
38
38
 
package/src/scale.ts CHANGED
@@ -18,31 +18,42 @@ export interface Stacked {
18
18
  export function stackSeries(series: readonly StackInput[], count: number): Map<string, Stacked> {
19
19
  const result = new Map<string, Stacked>();
20
20
  const piles = new Map<string, { up: number[]; down: number[] }>();
21
+
21
22
  for (const { id, values, stack } of series) {
22
23
  if (stack === null) {
23
24
  result.set(id, { base: Array.from({ length: count }, () => 0), top: Array.from({ length: count }, (_, i) => values[i] ?? null) });
25
+
24
26
  continue;
25
27
  }
28
+
26
29
  let pile = piles.get(stack);
30
+
27
31
  if (pile === undefined) {
28
32
  pile = { up: Array.from({ length: count }, () => 0), down: Array.from({ length: count }, () => 0) };
29
33
  piles.set(stack, pile);
30
34
  }
35
+
31
36
  const base: number[] = [];
32
37
  const top: (number | null)[] = [];
38
+
33
39
  for (let i = 0; i < count; i++) {
34
40
  const value = values[i] ?? null;
35
41
  const side = value !== null && value < 0 ? pile.down : pile.up;
36
42
  base.push(side[i]!);
43
+
37
44
  if (value === null) {
38
45
  top.push(null);
46
+
39
47
  continue;
40
48
  }
49
+
41
50
  side[i] = side[i]! + value;
42
51
  top.push(side[i]!);
43
52
  }
53
+
44
54
  result.set(id, { base, top });
45
55
  }
56
+
46
57
  return result;
47
58
  }
48
59
 
@@ -50,17 +61,21 @@ export function stackSeries(series: readonly StackInput[], count: number): Map<s
50
61
  export function extentOf(stacked: Iterable<Stacked>, kind: ChartYScale, ground = true): [number, number] | null {
51
62
  let low = Infinity;
52
63
  let high = -Infinity;
64
+
53
65
  for (const { base, top } of stacked) {
54
66
  for (let i = 0; i < top.length; i++) {
55
67
  const value = top[i];
68
+
56
69
  if (value === null || value === undefined || (kind === 'log' && value <= 0)) {
57
70
  continue;
58
71
  }
72
+
59
73
  const floor = kind === 'log' || !ground ? value : base[i]!;
60
74
  low = Math.min(low, value, floor);
61
75
  high = Math.max(high, value, floor);
62
76
  }
63
77
  }
78
+
64
79
  return low === Infinity ? null : [low, high];
65
80
  }
66
81
 
@@ -75,14 +90,18 @@ export interface YAxisScale {
75
90
  function steppedScale(low: number, high: number, step: number, options: ChartYOptions, range: [number, number]): YAxisScale {
76
91
  const start = options.min ?? Math.floor(low / step) * step;
77
92
  let end = options.max ?? Math.ceil(high / step) * step;
93
+
78
94
  if (end <= start) {
79
95
  end = start + step;
80
96
  }
97
+
81
98
  const scale = scaleLinear().domain([start, end]).range(range);
82
99
  const ticks: number[] = [];
100
+
83
101
  for (let tick = Math.ceil(start / step) * step; tick <= end + step / 1e6; tick += step) {
84
102
  ticks.push(Number(tick.toFixed(10)));
85
103
  }
104
+
86
105
  return { domain: [start, end], ticks, at: (value) => scale(value) };
87
106
  }
88
107
 
@@ -100,38 +119,50 @@ export function yScaleOf(
100
119
  ground = true
101
120
  ): YAxisScale {
102
121
  const include = (options.include ?? []).filter((value) => kind !== 'log' || value > 0);
122
+
103
123
  const extent: [number, number] | null =
104
124
  include.length === 0 ? data : [Math.min(data?.[0] ?? Infinity, ...include), Math.max(data?.[1] ?? -Infinity, ...include)];
125
+
105
126
  if (kind === 'log') {
106
127
  const low = options.min ?? Math.max(extent?.[0] ?? 1, Number.MIN_VALUE);
107
128
  const high = options.max ?? Math.max(extent?.[1] ?? 10, low * 10);
108
129
  const scale = scaleLog().domain([low, high]).range(range);
130
+
109
131
  if (options.min === undefined || options.max === undefined) {
110
132
  scale.nice();
111
133
  }
134
+
112
135
  const [min, max] = scale.domain() as [number, number];
113
136
  const domain: [number, number] = [options.min ?? min, options.max ?? max];
114
137
  scale.domain(domain);
115
138
  const ticks = scale.ticks(count).filter((tick) => Math.log10(tick) % 1 === 0);
139
+
116
140
  return { domain, ticks: ticks.length >= 2 ? ticks : scale.ticks(count), at: (value) => (value > 0 ? scale(value) : null) };
117
141
  }
142
+
118
143
  const floor = ground ? 0 : (extent?.[0] ?? 0);
119
144
  const ceiling = ground ? 0 : (extent?.[1] ?? 0);
145
+
120
146
  if (options.step !== undefined && options.step > 0) {
121
147
  return steppedScale(Math.min(floor, extent?.[0] ?? 0), Math.max(ceiling, extent?.[1] ?? 0), options.step, options, range);
122
148
  }
149
+
123
150
  let low = options.min ?? Math.min(floor, extent?.[0] ?? 0);
124
151
  let high = options.max ?? Math.max(ceiling, extent?.[1] ?? 0);
152
+
125
153
  if (high <= low) {
126
154
  high = low + (options.integer === true ? count : 1);
127
155
  }
156
+
128
157
  if (options.integer === true && options.max === undefined) {
129
158
  high = Math.max(high, low + 1);
130
159
  }
160
+
131
161
  const top = high;
132
162
  const scale = scaleLinear().domain([low, high]).range(range);
133
163
  scale.nice(count);
134
164
  [low, high] = scale.domain() as [number, number];
165
+
135
166
  if (options.max === undefined && options.headroom === 'none') {
136
167
  high = top;
137
168
  } else if (options.max === undefined && options.headroom === 'step' && top > 0 && high === top) {
@@ -139,12 +170,15 @@ export function yScaleOf(
139
170
  const ticked = scale.ticks(count);
140
171
  high += ticked.length > 1 ? ticked[1]! - ticked[0]! : top;
141
172
  }
173
+
142
174
  const domain: [number, number] = [options.min ?? low, options.max ?? high];
143
175
  scale.domain(domain);
144
176
  let ticks = scale.ticks(count);
177
+
145
178
  if (options.integer === true) {
146
179
  ticks = ticks.filter((tick) => Number.isInteger(tick));
147
180
  }
181
+
148
182
  return { domain, ticks, at: (value) => scale(value) };
149
183
  }
150
184
 
@@ -163,23 +197,29 @@ export interface ContinuousXScale {
163
197
  /* The smallest distance between two rows, so a row that is missing does not make every bucket twice as long; 0 for one row. */
164
198
  export function bucketStepOf(xs: readonly number[]): number {
165
199
  let step = Infinity;
200
+
166
201
  for (let i = 1; i < xs.length; i++) {
167
202
  const distance = xs[i]! - xs[i - 1]!;
203
+
168
204
  if (distance > 0) {
169
205
  step = Math.min(step, distance);
170
206
  }
171
207
  }
208
+
172
209
  return step === Infinity ? 0 : step;
173
210
  }
174
211
 
175
212
  /* The whole decades around the positive values, at least one apart: `[0.03, 4]` lies in 10^-2 to 10^1. */
176
213
  export function decadesOf(values: readonly number[]): { readonly low: number; readonly high: number } {
177
214
  const positive = values.filter((value) => value > 0 && Number.isFinite(value));
215
+
178
216
  if (positive.length === 0) {
179
217
  return { low: 0, high: 1 };
180
218
  }
219
+
181
220
  const low = Math.floor(Math.log10(Math.min(...positive)));
182
221
  const high = Math.ceil(Math.log10(Math.max(...positive)));
222
+
183
223
  return { low, high: high > low ? high : low + 1 };
184
224
  }
185
225
 
@@ -189,13 +229,17 @@ export function decadesOf(values: readonly number[]): { readonly low: number; re
189
229
  */
190
230
  export function thinTicks(ticks: readonly number[], count: number): number[] {
191
231
  const intervals = ticks.length - 1;
232
+
192
233
  if (intervals <= 1 || intervals <= count) {
193
234
  return [...ticks];
194
235
  }
236
+
195
237
  let stride = Math.ceil(intervals / Math.max(1, count));
238
+
196
239
  while (intervals % stride !== 0) {
197
240
  stride++;
198
241
  }
242
+
199
243
  return ticks.filter((_, i) => i % stride === 0);
200
244
  }
201
245
 
@@ -203,9 +247,11 @@ export function thinTicks(ticks: readonly number[], count: number): number[] {
203
247
  function logXScale(values: readonly number[], range: [number, number]): ContinuousXScale {
204
248
  const { low, high } = decadesOf(values);
205
249
  const decades = Array.from({ length: high - low + 1 }, (_, i) => 10 ** (low + i));
250
+
206
251
  const scale = scaleLog()
207
252
  .domain([10 ** low, 10 ** high])
208
253
  .range(range);
254
+
209
255
  return {
210
256
  domain: [10 ** low, 10 ** high],
211
257
  at: (value) => (value > 0 ? scale(value) : Number.NaN),
@@ -217,21 +263,27 @@ function logXScale(values: readonly number[], range: [number, number]): Continuo
217
263
  /* The x axis of a point chart: it covers every point, rounded out to a tick, or the ends the caller fixed. */
218
264
  export function pointXScale(kind: 'time' | 'linear' | 'log', xs: readonly number[], range: [number, number], options: ChartXOptions = {}): ContinuousXScale {
219
265
  const finite = xs.filter((value) => Number.isFinite(value));
266
+
220
267
  if (kind === 'log') {
221
268
  return logXScale([...finite, ...(options.min === undefined ? [] : [options.min]), ...(options.max === undefined ? [] : [options.max])], range);
222
269
  }
270
+
223
271
  if (kind === 'time') {
224
272
  return continuousXScale('time', finite, range);
225
273
  }
274
+
226
275
  let low = options.min ?? (finite.length === 0 ? 0 : Math.min(...finite));
227
276
  let high = options.max ?? (finite.length === 0 ? 1 : Math.max(...finite));
277
+
228
278
  if (high <= low) {
229
279
  high = low + 1;
230
280
  }
281
+
231
282
  const scale = scaleLinear().domain([low, high]).range(range).nice();
232
283
  [low, high] = scale.domain() as [number, number];
233
284
  scale.domain([options.min ?? low, options.max ?? high]);
234
285
  const domain = scale.domain() as [number, number];
286
+
235
287
  return { domain, at: (value) => scale(value), invert: (pixel) => scale.invert(pixel), ticks: (count) => scale.ticks(count) };
236
288
  }
237
289
 
@@ -246,15 +298,19 @@ export function continuousXScale(
246
298
  if (kind === 'log') {
247
299
  return logXScale(xs, range);
248
300
  }
301
+
249
302
  let low = options.min ?? (xs.length === 0 ? 0 : Math.min(...xs));
250
303
  let high = options.max ?? (xs.length === 0 ? 1 : Math.max(...xs) + step);
304
+
251
305
  if (high <= low) {
252
306
  const pad = kind === 'time' ? 30 * 60 * 1000 : 1;
253
307
  high = low + pad;
254
308
  low -= pad;
255
309
  }
310
+
256
311
  if (kind === 'time') {
257
312
  const scale = scaleTime().domain([low, high]).range(range);
313
+
258
314
  return {
259
315
  domain: [low, high],
260
316
  at: (value) => scale(value),
@@ -262,7 +318,9 @@ export function continuousXScale(
262
318
  ticks: (count) => scale.ticks(count).map((tick) => tick.getTime())
263
319
  };
264
320
  }
321
+
265
322
  const scale = scaleLinear().domain([low, high]).range(range);
323
+
266
324
  return { domain: [low, high], at: (value) => scale(value), invert: (pixel) => scale.invert(pixel), ticks: (count) => scale.ticks(count) };
267
325
  }
268
326
 
@@ -271,7 +329,9 @@ export function decimalsOf(step: number): number {
271
329
  if (!Number.isFinite(step) || step <= 0) {
272
330
  return 0;
273
331
  }
332
+
274
333
  // Through a fixed width first, so the float noise of `0.1 + 0.2` does not count as digits.
275
334
  const fraction = String(Number(step.toFixed(6))).split('.')[1];
335
+
276
336
  return fraction?.length ?? 0;
277
337
  }
package/src/scatter.tsx CHANGED
@@ -50,9 +50,11 @@ export function ChartFrontier({ lowerX = true, higherY = true, width = 14, tone,
50
50
  // On pixels a higher value stands lower, so the y is turned around before the frontier compares it.
51
51
  const placed = chart.positions.flatMap((position) => (position === null ? [] : [{ x: position[0], y: -position[1] }]));
52
52
  const band = frontierOf(placed, lowerX, higherY);
53
+
53
54
  if (band.length < 2) {
54
55
  return null;
55
56
  }
57
+
56
58
  return (
57
59
  <polyline
58
60
  ref={ref}
@@ -78,32 +80,39 @@ export function ChartEndLabels<Row>({ children, width, className, ref }: ChartEn
78
80
  useBeforePaint(() => {
79
81
  store.setAxis('end', room);
80
82
  });
83
+
81
84
  useBeforePaint(() => () => store.setAxis('end', null), [store]);
82
85
 
83
86
  const ends = pointGroups.flatMap((run) => {
84
87
  const last = run.indexes.findLast((index) => positions[index] !== null);
88
+
85
89
  return last === undefined ? [] : [{ run, point: positions[last]! }];
86
90
  });
91
+
87
92
  const centers = spreadLabels(
88
93
  ends.map(({ point }) => point[1]),
89
94
  LABEL_SPACING,
90
95
  plot.top,
91
96
  plot.bottom - 8
92
97
  );
98
+
93
99
  const rows = chart.data as Row[];
94
100
  const left = Math.round(plot.right);
101
+
95
102
  return (
96
103
  <g ref={ref} className={clsx('pointer-events-none', className)} aria-hidden>
97
104
  {ends.map(({ run, point }, i) => {
98
105
  const first = run.indexes[0]!;
99
106
  const color = chart.pointColor(first);
100
107
  const center = Math.round(centers[i]!);
108
+
101
109
  const series = {
102
110
  key: run.key,
103
111
  label: chart.groupLabels?.[first] ?? run.key,
104
112
  rows: run.indexes.map((index) => rows[index]!),
105
113
  color
106
114
  };
115
+
107
116
  return (
108
117
  <g key={run.key} opacity={chart.dimmedGroups.has(run.key) ? DIMMED_POINT : 1} style={{ color }}>
109
118
  <line x1={point[0] + 7} y1={point[1]} x2={left + LEADER_END} y2={center} stroke="currentColor" opacity={0.3} />