@adecore/charts 0.41.1 → 0.42.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/axes.tsx CHANGED
@@ -1,4 +1,4 @@
1
- import { useEffect, useId, useRef, useSyncExternalStore, type ReactNode, type Ref } from 'react';
1
+ import { useEffect, useId, useRef, useState, useSyncExternalStore, type ReactNode, type Ref } from 'react';
2
2
  import { createPortal } from 'react-dom';
3
3
  import clsx from 'clsx';
4
4
  import { useTranslation } from 'react-i18next';
@@ -38,6 +38,11 @@ export interface ChartXAxisProps {
38
38
  readonly logLabel?: string;
39
39
  /* Hears whether labels of buckets were left out for lack of room, such as to tell a person the table has them all. */
40
40
  readonly onThinnedChange?: (thinned: boolean) => void;
41
+ /*
42
+ * In a horizontal chart, the widest the names of the rows may be, in pixels: 240 by default and never more than 40% of
43
+ * the chart. A longer name is cut short with an ellipsis and read whole in the tooltip, the live region and the table.
44
+ */
45
+ readonly maxWidth?: number;
41
46
  readonly className?: string;
42
47
  readonly ref?: Ref<SVGGElement>;
43
48
  }
@@ -85,6 +90,10 @@ const X_TITLE_ROOM = 21;
85
90
  /* The baseline of a y axis title from the top of the chart, and the room above the plot it needs. */
86
91
  const Y_TITLE_BASELINE = 15;
87
92
  const Y_TITLE_ROOM = 28;
93
+ /* The names of the rows of a horizontal chart: their widest and the share of the chart they may take, and their line. */
94
+ const ROW_LABEL_LIMIT = 240;
95
+ const ROW_LABEL_SHARE = 0.4;
96
+ const ROW_LABEL_LINE = 16;
88
97
 
89
98
  /* The height a row of labels takes under the plot, more for a slanted one. */
90
99
  const roomOf = (widest: number, angle: number): number => Math.ceil(angle === 0 ? X_LABEL_LINE : widest * Math.sin(SLANT) + X_LABEL_LINE * Math.cos(SLANT));
@@ -123,6 +132,43 @@ export function ChartGrid({ axis = 'y', dashed = false, lines = 'all', className
123
132
  const { plot, y, continuous, band } = chart;
124
133
  const ground = y.domain[0] <= 0 && y.domain[1] >= 0 ? 0 : y.domain[0];
125
134
 
135
+ if (chart.horizontal) {
136
+ // The values run across, so the lines on their ticks stand upright and the lines between rows lie down.
137
+ const ticks = lines === 'ground' ? [ground] : axis === 'x' ? [] : y.ticks;
138
+ const rows = lines === 'ground' || axis === 'y' ? [] : chart.xs.map((_, index) => chart.centerOf(index));
139
+
140
+ return (
141
+ <g ref={ref} className={clsx('pointer-events-none', className)} aria-hidden>
142
+ {ticks.map((tick) => {
143
+ const pixel = y.at(tick);
144
+
145
+ return pixel === null ? null : (
146
+ <line
147
+ key={tick}
148
+ x1={crisp(pixel)}
149
+ x2={crisp(pixel)}
150
+ y1={plot.top}
151
+ y2={plot.bottom}
152
+ strokeDasharray={dashed && tick !== ground ? DASH : undefined}
153
+ className={dashed ? 'stroke-border' : tick === ground ? 'stroke-border-strong' : 'stroke-border-soft'}
154
+ />
155
+ );
156
+ })}
157
+ {rows.map((pixel) => (
158
+ <line
159
+ key={pixel}
160
+ x1={plot.left}
161
+ x2={plot.right}
162
+ y1={crisp(pixel)}
163
+ y2={crisp(pixel)}
164
+ strokeDasharray={dashed ? DASH : undefined}
165
+ className={dashed ? 'stroke-border' : 'stroke-border-soft'}
166
+ />
167
+ ))}
168
+ </g>
169
+ );
170
+ }
171
+
126
172
  if (lines === 'ground') {
127
173
  const pixel = y.at(ground);
128
174
 
@@ -173,8 +219,81 @@ export function ChartGrid({ axis = 'y', dashed = false, lines = 'all', className
173
219
  );
174
220
  }
175
221
 
176
- /* The labels under the plot: one per bucket on a band scale as far as they fit, round ticks on a continuous one. */
177
- export function ChartXAxis({
222
+ /*
223
+ * The labels under the plot: one per bucket on a band scale as far as they fit, round ticks on a continuous one. In a
224
+ * horizontal chart, the name of every row left of the plot.
225
+ */
226
+ export function ChartXAxis(props: ChartXAxisProps) {
227
+ const chart = useChartContext('Chart.XAxis');
228
+
229
+ return chart.horizontal ? <RowAxis {...props} /> : <ColumnAxis {...props} />;
230
+ }
231
+
232
+ /* The names of the rows of a horizontal chart, never left out: the column takes the widest, up to its limit, and cuts the rest short. */
233
+ function RowAxis({ format, title, label: spoken, maxWidth = ROW_LABEL_LIMIT, onThinnedChange, className, ref }: ChartXAxisProps) {
234
+ const chart = useChartContext('Chart.XAxis');
235
+ const { store, xs } = chart;
236
+ useAxisTitle(spoken ?? title);
237
+ const candidates = useRef<SVGGElement>(null);
238
+ const write = format ?? chart.formatX;
239
+ const limit = chart.box > 0 ? Math.min(maxWidth, Math.floor(chart.box * ROW_LABEL_SHARE)) : maxWidth;
240
+ const target = chart.elements.rows;
241
+
242
+ useBeforePaint(() => {
243
+ // A pixel more than measured, so a name that fits is never cut short by how the page rounds its own text.
244
+ store.setAxis('start', Math.min(limit, Math.ceil(widestIn(candidates.current)) + 1) + LABEL_GAP);
245
+ });
246
+
247
+ useBeforePaint(() => () => store.setAxis('start', null), [store]);
248
+
249
+ const reported = useRef(false);
250
+
251
+ useEffect(() => {
252
+ if (!reported.current) {
253
+ reported.current = true;
254
+ onThinnedChange?.(false);
255
+ }
256
+ });
257
+
258
+ const column = Math.max(0, chart.leftAxis - LABEL_GAP);
259
+
260
+ return (
261
+ <g ref={ref} aria-hidden>
262
+ <g ref={candidates} visibility="hidden">
263
+ {xs.map((key) => (
264
+ <text key={String(key)} className="text-xs">
265
+ {write(key)}
266
+ </text>
267
+ ))}
268
+ </g>
269
+ {target !== null &&
270
+ createPortal(
271
+ <div className={clsx('pointer-events-none', className)}>
272
+ {xs.map((key, index) => {
273
+ const focus = chart.labelFocus[index] ?? null;
274
+
275
+ return (
276
+ <div
277
+ key={String(key)}
278
+ className={clsx('absolute left-0 truncate text-right text-xs/4', focus === 'strong' ? 'text-text' : 'text-text-muted')}
279
+ style={{
280
+ top: Math.round(chart.centerOf(index)) - ROW_LABEL_LINE / 2,
281
+ width: column,
282
+ opacity: focus === 'dim' ? chart.labelDim : undefined
283
+ }}
284
+ >
285
+ {write(key)}
286
+ </div>
287
+ );
288
+ })}
289
+ </div>,
290
+ target
291
+ )}
292
+ </g>
293
+ );
294
+ }
295
+
296
+ function ColumnAxis({
178
297
  format,
179
298
  ticks,
180
299
  angle = 0,
@@ -370,8 +489,64 @@ function useAxisTitle(title: string | undefined): void {
370
489
  );
371
490
  }
372
491
 
373
- /* The value labels beside the plot. It measures its widest label and gives the plot the rest. */
374
- export function ChartYAxis({ format, ticks, side = 'left', title, className, ref }: ChartYAxisProps) {
492
+ /* The value labels beside the plot. It measures its widest label and gives the plot the rest. In a horizontal chart they stand under it. */
493
+ export function ChartYAxis(props: ChartYAxisProps) {
494
+ const chart = useChartContext('Chart.YAxis');
495
+
496
+ return chart.horizontal ? <BottomAxis {...props} /> : <SideAxis {...props} />;
497
+ }
498
+
499
+ /* The values under the rows of a horizontal chart, with its title above the plot where the values start. */
500
+ function BottomAxis({ format, ticks, side = 'left', title, className, ref }: ChartYAxisProps) {
501
+ const chart = useChartContext('Chart.YAxis');
502
+ const { store, y, yStep, plot } = chart;
503
+ const labels = useRef<SVGGElement>(null);
504
+ const [widest, setWidest] = useState(0);
505
+
506
+ useBeforePaint(() => {
507
+ store.setYAxis(side, { width: 0, ticks: ticks ?? null, top: title === undefined ? null : Y_TITLE_ROOM, format });
508
+ const measured = Math.ceil(widestIn(labels.current));
509
+
510
+ if (measured !== widest) {
511
+ setWidest(measured);
512
+ }
513
+ });
514
+
515
+ useBeforePaint(() => () => store.setYAxis(side, null), [store, side]);
516
+ const decimals = decimalsOf(yStep);
517
+ // The ticks at the ends stay over the chart rather than hang past it.
518
+ const inward = (x: number): number => Math.min(Math.max(x, widest / 2 - chart.leftAxis), chart.width - widest / 2);
519
+
520
+ return (
521
+ <g ref={ref} className={clsx('pointer-events-none', className)} aria-hidden>
522
+ <g ref={labels}>
523
+ {y.ticks.map((tick) => {
524
+ const pixel = y.at(tick);
525
+
526
+ return pixel === null ? null : (
527
+ <text
528
+ key={tick}
529
+ x={Math.round(inward(pixel))}
530
+ y={plot.bottom + LABEL_GAP}
531
+ dy="0.8em"
532
+ textAnchor="middle"
533
+ className="fill-text-faint text-xs tabular-nums"
534
+ >
535
+ {(format ?? chart.valueFormat)?.(tick) ?? formatRounded(tick, decimals)}
536
+ </text>
537
+ );
538
+ })}
539
+ </g>
540
+ {title !== undefined && (
541
+ <text x={Math.round(plot.left)} y={Y_TITLE_BASELINE} className="fill-text-muted text-xs">
542
+ {title}
543
+ </text>
544
+ )}
545
+ </g>
546
+ );
547
+ }
548
+
549
+ function SideAxis({ format, ticks, side = 'left', title, className, ref }: ChartYAxisProps) {
375
550
  const chart = useChartContext('Chart.YAxis');
376
551
  const { store, y, yStep } = chart;
377
552
  const labels = useRef<SVGGElement>(null);
@@ -435,7 +610,8 @@ export function ChartGroupAxis<Row>({ children, className, ref }: ChartGroupAxis
435
610
  const chart = useChartContext('Chart.GroupAxis');
436
611
  const target = chart.elements.groups;
437
612
 
438
- if (target === null || chart.band === null) {
613
+ // The groups of a horizontal chart read from the gaps between their rows and from the tooltip.
614
+ if (target === null || chart.band === null || chart.horizontal) {
439
615
  return null;
440
616
  }
441
617
 
package/src/band.ts CHANGED
@@ -143,8 +143,21 @@ export function endRoundedColumn(x: number, y: number, width: number, height: nu
143
143
  return `M${x},${y}H${x + width}V${y + height - corner}A${corner},${corner} 0 0 1 ${x + width - corner},${y + height}H${x + corner}A${corner},${corner} 0 0 1 ${x},${y + height - corner}Z`;
144
144
  }
145
145
 
146
+ /* The outline of a bar of a horizontal chart rounded only at its end away from the ground: the right for a value rightward, else the left. */
147
+ export function endRoundedBar(x: number, y: number, width: number, height: number, radius: number, rightward: boolean): string {
148
+ const corner = Math.max(0, Math.min(radius, width, height / 2));
149
+
150
+ if (rightward) {
151
+ return `M${x},${y}H${x + width - corner}A${corner},${corner} 0 0 1 ${x + width},${y + corner}V${y + height - corner}A${corner},${corner} 0 0 1 ${x + width - corner},${y + height}H${x}Z`;
152
+ }
153
+
154
+ return `M${x + width},${y}V${y + height}H${x + corner}A${corner},${corner} 0 0 1 ${x},${y + height - corner}V${y + corner}A${corner},${corner} 0 0 1 ${x + corner},${y}Z`;
155
+ }
156
+
146
157
  /* Between the top of a column and the baseline of its value. */
147
158
  export const LABEL_LIFT = 10;
159
+ /* Between the end of a bar of a horizontal chart and the start of its value. */
160
+ export const LABEL_INSET = 6;
148
161
  /* The height of a row of labels and what a label is taken to measure per character until it has been drawn once, per size. */
149
162
  const LABEL_SIZES = { '2xs': { row: 16, char: 8 }, xs: { row: 18, char: 9 } } as const;
150
163
 
package/src/context.ts CHANGED
@@ -14,6 +14,8 @@ export interface ChartSlots {
14
14
  readonly right: SVGGElement | null;
15
15
  /* Above the series in the plot, where `Chart.Rule` draws whatever its place among the children. */
16
16
  readonly rules: SVGGElement | null;
17
+ /* Left of the plot of a horizontal chart, where `Chart.XAxis` writes the name of each row. */
18
+ readonly rows: HTMLElement | null;
17
19
  }
18
20
 
19
21
  export interface ChartContextValue {
@@ -22,6 +24,13 @@ export interface ChartContextValue {
22
24
  readonly data: readonly unknown[];
23
25
  readonly xs: readonly ChartX[];
24
26
  readonly xScale: ChartXScale;
27
+ /*
28
+ * The buckets are rows down the chart and the values run to the right. The value scale stays `y` and the buckets
29
+ * `x`, so `centerOf` and `bucketAt` measure down and `pixelOfY` across.
30
+ */
31
+ readonly horizontal: boolean;
32
+ /* The room right of the plot of a horizontal chart that its value labels take. */
33
+ readonly valueRoom: number;
25
34
  readonly height: number;
26
35
  /* In the coordinates of the plot's own svg, which scrolls apart from the y axes. */
27
36
  readonly plot: ChartRect;
package/src/cursor.ts CHANGED
@@ -85,17 +85,25 @@ export function snapIndex(xs: readonly ChartX[], scale: ChartXScale, x: ChartX |
85
85
  /*
86
86
  * Where a key moves the cursor: the arrows step a bucket, Home and End go to the ends, Page Up and Page
87
87
  * Down to the first bucket of the previous or the next group. `null` clears the cursor, `undefined`
88
- * leaves the key to the page.
88
+ * leaves the key to the page. Buckets in `rows` step with Up and Down and leave Left and Right to the page.
89
89
  */
90
- export function moveIndex(key: string, current: number, count: number, groupStarts: readonly number[] = []): number | null | undefined {
90
+ export function moveIndex(
91
+ key: string,
92
+ current: number,
93
+ count: number,
94
+ groupStarts: readonly number[] = [],
95
+ along: 'columns' | 'rows' = 'columns'
96
+ ): number | null | undefined {
91
97
  if (count === 0) {
92
98
  return undefined;
93
99
  }
94
100
 
101
+ const [previous, next] = along === 'rows' ? ['ArrowUp', 'ArrowDown'] : ['ArrowLeft', 'ArrowRight'];
102
+
95
103
  switch (key) {
96
- case 'ArrowRight':
104
+ case next:
97
105
  return current < 0 ? 0 : Math.min(count - 1, current + 1);
98
- case 'ArrowLeft':
106
+ case previous:
99
107
  return current < 0 ? count - 1 : Math.max(0, current - 1);
100
108
  case 'Home':
101
109
  return 0;
package/src/locales/en.ts CHANGED
@@ -25,6 +25,7 @@ export default {
25
25
  },
26
26
  keyboard: {
27
27
  move: 'Arrow keys move between values, Home and End go to the ends, Escape clears.',
28
+ rows: 'Up and Down move between rows, Home and End go to the first and the last, Escape clears.',
28
29
  points: 'Left and Right move along a series, Up and Down to the next series, Home and End to its ends, Escape clears.',
29
30
  groups: 'Page Up and Page Down move between groups.',
30
31
  activate: 'Enter or Space picks a value.'
package/src/locales/nl.ts CHANGED
@@ -25,6 +25,7 @@ export default {
25
25
  },
26
26
  keyboard: {
27
27
  move: 'Pijltjestoetsen gaan langs de waarden, Home en End naar het begin en het eind, Escape wist.',
28
+ rows: 'Omhoog en omlaag gaan langs de rijen, Home en End naar de eerste en de laatste, Escape wist.',
28
29
  points: 'Links en rechts gaan langs een reeks, omhoog en omlaag naar de volgende reeks, Home en End naar de uiteinden, Escape wist.',
29
30
  groups: 'Page Up en Page Down gaan naar de vorige of volgende groep.',
30
31
  activate: 'Enter of spatie kiest een waarde.'
package/src/overlays.tsx CHANGED
@@ -94,6 +94,54 @@ const bucketOf = <Row,>(chart: ChartContextValue, index: number): ChartBucket<Ro
94
94
  notes: chart.notesAt(index)
95
95
  });
96
96
 
97
+ /*
98
+ * Where the card stands in a horizontal chart. Beside the cursor, it follows the end of the row's longest bar and its
99
+ * value, or goes over or under the row where that leaves no room. In a corner, it moves to the other end of the plot
100
+ * where it would cover the row.
101
+ */
102
+ function rowPlace(chart: ChartContextValue, placement: ChartTooltipPlacement, card: { width: number; height: number }): CSSProperties {
103
+ const { activeIndex, plot, leftAxis, box, height } = chart;
104
+ const row = chart.bucketAt(activeIndex) ?? { left: plot.top, width: 0 };
105
+ const plotLeft = leftAxis + plot.left;
106
+ const plotRight = leftAxis + plot.right + chart.valueRoom;
107
+
108
+ if (placement !== 'cursor') {
109
+ const [vertical, horizontal] = placement.split('-') as ['top' | 'bottom', 'left' | 'right'];
110
+ const coversTop = row.left < plot.top + card.height;
111
+ const coversBottom = row.left + row.width > plot.bottom - card.height;
112
+ const side = vertical === 'top' ? (coversTop && !coversBottom ? 'bottom' : 'top') : coversBottom && !coversTop ? 'top' : 'bottom';
113
+
114
+ return {
115
+ ...(horizontal === 'left' ? { left: Math.round(plotLeft) } : { right: Math.round(box - plotRight) }),
116
+ top: side === 'top' ? Math.round(plot.top) : Math.round(plot.bottom - card.height),
117
+ maxWidth: Math.max(0, Math.round(plotRight - plotLeft))
118
+ };
119
+ }
120
+
121
+ const ends = [...chart.series].flatMap(([id]) => {
122
+ const top = chart.stacked.get(id)?.top[activeIndex];
123
+ const pixel = top === null || top === undefined ? null : chart.pixelOfY(top);
124
+
125
+ return pixel === null ? [] : [pixel];
126
+ });
127
+
128
+ const end = leftAxis + Math.max(plot.left, ...ends) + chart.valueRoom + OFFSET;
129
+
130
+ if (end + card.width <= box - EDGE) {
131
+ const center = row.left + row.width / 2;
132
+
133
+ return { left: Math.round(end), top: Math.round(Math.max(0, Math.min(height - card.height, center - card.height / 2))) };
134
+ }
135
+
136
+ const below = row.left + row.width / 2 < height / 2;
137
+
138
+ return {
139
+ left: Math.round(plotLeft),
140
+ maxWidth: Math.max(0, Math.round(box - plotLeft - EDGE)),
141
+ ...(below ? { top: Math.round(row.left + row.width + EDGE) } : { bottom: Math.round(height - row.left + EDGE) })
142
+ };
143
+ }
144
+
97
145
  /* The swatch of a series: its icon in its color, else a dash for a line and a square for a column. */
98
146
  function Swatch({ color, entry, size }: { color: string; entry: SeriesEntry; size: 12 | 14 }) {
99
147
  if (entry.icon !== null) {
@@ -135,7 +183,9 @@ export function ChartTooltip<Row>({ total = false, format, children, placement =
135
183
  const pixel = chart.leftAxis + (position?.[0] ?? chart.centerOf(activeIndex)) - chart.scroll;
136
184
  let place: CSSProperties;
137
185
 
138
- if (placement === 'cursor') {
186
+ if (chart.horizontal) {
187
+ place = rowPlace(chart, placement, card);
188
+ } else if (placement === 'cursor') {
139
189
  // The card hangs on the side with the most room, so it never covers the cursor and never runs off.
140
190
  place = {
141
191
  ...(pixel > chart.box / 2