@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/series.tsx CHANGED
@@ -3,7 +3,7 @@ import clsx from 'clsx';
3
3
  import type { IconProps } from '@adecore/ui';
4
4
  import { area, curveLinear, curveMonotoneX, curveStepAfter, line } from 'd3-shape';
5
5
  import { numberOf, readValue, warnOnce } from './access.ts';
6
- import { columnsIn, endRoundedColumn, guessLabelWidth, LABEL_LIFT, placeValueLabels, segmentOf } from './band.ts';
6
+ import { columnsIn, endRoundedBar, endRoundedColumn, guessLabelWidth, LABEL_INSET, LABEL_LIFT, placeValueLabels, segmentOf } from './band.ts';
7
7
  import { colorOf, seriesColor } from './color.ts';
8
8
  import { BarsContext, useChartContext, type ChartContextValue } from './context.ts';
9
9
  import { useBeforePaint, useKeyCheck, useRegistration } from './register.ts';
@@ -61,19 +61,25 @@ export interface ChartBarProps<Row> {
61
61
  readonly hoverOpacity?: number;
62
62
  /* The opacity of a column the root dims, or that is not picked while another is. */
63
63
  readonly dimOpacity?: number;
64
- /* The pixels the columns of a bucket take together, from the width of the bucket; 72% of it by default, at most 56px a column. */
64
+ /*
65
+ * The pixels the columns of a bucket take together, from the width of the bucket; 72% of it by default, at most 56px a
66
+ * column. In a horizontal chart the bucket is a row and this is the thickness of its bars.
67
+ */
65
68
  readonly columnWidth?: (bucket: number) => number;
66
69
  /* The corner radius of a column that stands alone; stacked segments stay square. */
67
70
  readonly radius?: number;
68
71
  /* `end` rounds only the end away from the ground, so the column stands flat on it. */
69
72
  readonly rounded?: 'all' | 'end';
70
- /* The least height of a column that stands alone, in pixels, also for a zero; a missing value still draws nothing. */
73
+ /* The least height of a column that stands alone, in pixels, also for a zero; a missing value still draws nothing. The least length of a bar. */
71
74
  readonly minHeight?: number;
72
- /* Writes each column's value over it, as the y axis writes it or through the function; labels that would collide move up a row. */
75
+ /*
76
+ * Writes each column's value over it, as the y axis writes it or through the function; labels that would collide move
77
+ * up a row. In a horizontal chart the value stands past the end of the bar, and a stack writes its total past its end.
78
+ */
73
79
  readonly valueLabels?: boolean | ((value: number, row: Row, index: number) => string);
74
80
  /* The columns grow from the ground when they first draw; not for a person who asks for reduced motion. */
75
81
  readonly animate?: boolean;
76
- /* The type size of the value labels: `2xs` beside a dense row of columns, `xs` over a few wide ones. */
82
+ /* The type size of the value labels: `2xs` beside a dense row of columns, `xs` over a few wide ones and beside rows (the default there). */
77
83
  readonly valueLabelSize?: '2xs' | 'xs';
78
84
  readonly className?: string;
79
85
  readonly ref?: Ref<SVGGElement>;
@@ -194,6 +200,10 @@ export function ChartLine<Row>({ value, label, tone, icon, curve = 'linear', das
194
200
  valueLabels: false
195
201
  });
196
202
 
203
+ if (chart.horizontal) {
204
+ return null;
205
+ }
206
+
197
207
  if (chart.points) {
198
208
  return (
199
209
  <g ref={ref} className={clsx('pointer-events-none', className)}>
@@ -251,6 +261,10 @@ export function ChartPoint<Row>({ value, label, tone, icon, className, ref }: Ch
251
261
 
252
262
  const fallback = chart.colors.get(id) ?? seriesColor(0);
253
263
 
264
+ if (chart.horizontal) {
265
+ return null;
266
+ }
267
+
254
268
  return (
255
269
  <g ref={ref} className={clsx('pointer-events-none', className)}>
256
270
  {values.map((amount, index) => {
@@ -308,6 +322,10 @@ export function ChartArea<Row>({
308
322
  valueLabels: false
309
323
  });
310
324
 
325
+ if (chart.horizontal) {
326
+ return null;
327
+ }
328
+
311
329
  const stacked = chart.stacked.get(id);
312
330
  const tops = pointsOf(chart, stacked?.top ?? values);
313
331
  const ground = groundOf(chart);
@@ -348,7 +366,7 @@ export function ChartBars({ stack = false, children, className, ref }: ChartBars
348
366
  );
349
367
  }
350
368
 
351
- /* Columns, one per bucket: on a `band` scale, or on a `time` scale whose buckets last one step. */
369
+ /* Columns, one per bucket: on a `band` scale, or on a `time` scale whose buckets last one step. Bars per row in a horizontal chart. */
352
370
  export function ChartBar<Row>({
353
371
  value,
354
372
  label,
@@ -362,7 +380,7 @@ export function ChartBar<Row>({
362
380
  minHeight = 0,
363
381
  rounded = 'all',
364
382
  valueLabels,
365
- valueLabelSize = '2xs',
383
+ valueLabelSize: labelSize,
366
384
  animate = false,
367
385
  className,
368
386
  ref
@@ -374,6 +392,30 @@ export function ChartBar<Row>({
374
392
  const rows = chart.data as Row[];
375
393
  const [color, rowColors] = tonesOf(chart, tone);
376
394
  const labeled = valueLabels !== undefined && valueLabels !== false;
395
+ const { horizontal } = chart;
396
+ // A value beside a row reads with the name of the row, which is written a size larger than a label over a column.
397
+ const valueLabelSize = labelSize ?? (horizontal ? 'xs' : '2xs');
398
+ const stack = bars?.stack === true ? bars.id : null;
399
+ const writeValue = typeof valueLabels === 'function' ? valueLabels : (amount: number): string => chart.formatY(amount);
400
+ // A horizontal stack has room for one value past its end: its total, which its last part with labels writes.
401
+ const totals = horizontal && stack !== null;
402
+ const writesLabels = labeled && (!totals || [...chart.series].findLast(([, entry]) => entry.stack === stack && entry.valueLabels)?.[0] === id);
403
+ const others = totals ? [...chart.series].flatMap(([seriesId, entry]) => (entry.stack === stack && seriesId !== id ? [entry] : [])) : [];
404
+
405
+ const labelValueAt = (index: number): number | null => {
406
+ const parts = [values[index], ...others.map((entry) => entry.values[index])].filter((part): part is number => part !== null && part !== undefined);
407
+
408
+ return parts.length === 0 ? null : parts.reduce((sum, part) => sum + part, 0);
409
+ };
410
+
411
+ const rowTexts = values.map((_, index) => {
412
+ const amount = labelValueAt(index);
413
+
414
+ return horizontal && writesLabels && amount !== null ? writeValue(amount, rows[index]!, index) : '';
415
+ });
416
+
417
+ const widthOf = (text: string): number => widths.get(text) ?? guessLabelWidth(text, valueLabelSize);
418
+ const endRoom = horizontal && writesLabels ? Math.max(0, ...rowTexts.map(widthOf)) + LABEL_INSET + 2 : 0;
377
419
 
378
420
  useRegistration(chart.store, 'series', id, {
379
421
  kind: 'bar',
@@ -381,12 +423,13 @@ export function ChartBar<Row>({
381
423
  color,
382
424
  rowColors,
383
425
  values,
384
- stack: bars?.stack === true ? bars.id : null,
426
+ stack,
385
427
  bars: bars?.id ?? null,
386
428
  curve: 'linear',
387
429
  icon: icon ?? null,
388
430
  valueLabels: labeled,
389
- dimOpacity
431
+ dimOpacity,
432
+ endRoom
390
433
  });
391
434
 
392
435
  // A time scale learns how long a bucket is from the distance between two rows, so one row alone has no slot.
@@ -406,13 +449,17 @@ export function ChartBar<Row>({
406
449
  const groupOf = (index: number): { first: number; last: number } =>
407
450
  chart.band?.groups.find((run) => index >= run.first && index <= run.last) ?? { first: 0, last: values.length - 1 };
408
451
 
409
- const writeValue = typeof valueLabels === 'function' ? valueLabels : (amount: number): string => chart.formatY(amount);
452
+ const focusOf = (index: number): { focused: boolean; outOfFocus: boolean } => {
453
+ const focused = index === chart.activeIndex || chart.selected[index] === true;
454
+
455
+ return { focused, outOfFocus: chart.dimmed[index] === true || (anySelected && !focused) };
456
+ };
410
457
 
411
458
  const drawn = values.flatMap((amount, index) => {
412
459
  const top = stacked?.top[index];
413
460
  const base = stacked?.base[index] ?? 0;
414
461
  const topPixel = top === null || top === undefined ? null : chart.pixelOfY(top);
415
- const basePixel = chart.pixelOfY(base) ?? chart.plot.bottom;
462
+ const basePixel = chart.pixelOfY(base) ?? (horizontal ? chart.plot.left : chart.plot.bottom);
416
463
  const bucket = chart.bucketAt(index);
417
464
 
418
465
  if (amount === null || topPixel === null || bucket === null) {
@@ -420,9 +467,19 @@ export function ChartBar<Row>({
420
467
  }
421
468
 
422
469
  const column = columnsIn(bucket.left, bucket.width, count, columnWidth)[slot]!;
423
- const { y, height } = segmentOf(topPixel, basePixel, base === 0, amount, bars?.stack === true ? 0 : minHeight);
424
- const focused = index === chart.activeIndex || chart.selected[index] === true;
425
- const outOfFocus = chart.dimmed[index] === true || (anySelected && !focused);
470
+ const least = stack === null ? minHeight : 0;
471
+ let box: { x: number; y: number; width: number; height: number };
472
+
473
+ if (horizontal) {
474
+ // A segment is measured up an axis that grows downward; mirrored, the same rules hold for a bar that grows rightward.
475
+ const segment = segmentOf(-topPixel, -basePixel, base === 0, amount, least);
476
+ box = { x: -(segment.y + segment.height), y: column.x, width: segment.height, height: column.width };
477
+ } else {
478
+ const segment = segmentOf(topPixel, basePixel, base === 0, amount, least);
479
+ box = { x: column.x, y: segment.y, width: column.width, height: segment.height };
480
+ }
481
+
482
+ const { focused, outOfFocus } = focusOf(index);
426
483
  const run = groupOf(index);
427
484
  let alpha = focused ? 1 : (opacity?.(rows[index]!, index - run.first, run.last - run.first + 1) ?? 1);
428
485
 
@@ -432,15 +489,42 @@ export function ChartBar<Row>({
432
489
  alpha *= hoverOpacity;
433
490
  }
434
491
 
435
- const text = labeled ? writeValue(amount, rows[index]!, index) : '';
492
+ const text = labeled && !horizontal ? writeValue(amount, rows[index]!, index) : '';
436
493
 
437
- return [{ index, column, y, height, alpha, outOfFocus, text }];
494
+ return [{ index, box, alpha, outOfFocus, text }];
438
495
  });
439
496
 
440
- const labelTops = placeValueLabels(
441
- drawn.map(({ column, y, text }) => ({ center: column.x + column.width / 2, top: y, width: widths.get(text) ?? guessLabelWidth(text, valueLabelSize) })),
442
- valueLabelSize
443
- );
497
+ const labelTops = horizontal
498
+ ? []
499
+ : placeValueLabels(
500
+ drawn.map(({ box, text }) => ({ center: box.x + box.width / 2, top: box.y, width: widthOf(text) })),
501
+ valueLabelSize
502
+ );
503
+
504
+ // A value stands past the end of its bar, or of its stack, in the middle of the bar's height.
505
+ const rowLabels = rowTexts.flatMap((text, index) => {
506
+ const total = labelValueAt(index);
507
+ const bucket = chart.bucketAt(index);
508
+
509
+ if (text === '' || total === null || bucket === null) {
510
+ return [];
511
+ }
512
+
513
+ const column = columnsIn(bucket.left, bucket.width, count, columnWidth)[slot]!;
514
+ const own = totals ? undefined : drawn.find((entry) => entry.index === index)?.box;
515
+ const end = own === undefined ? (chart.pixelOfY(total) ?? chart.plot.left) : total >= 0 ? own.x + own.width : own.x;
516
+
517
+ return [
518
+ {
519
+ index,
520
+ text,
521
+ x: Math.round(total >= 0 ? end + LABEL_INSET : end - LABEL_INSET),
522
+ y: Math.round(column.x + column.width / 2),
523
+ anchor: total >= 0 ? ('start' as const) : ('end' as const),
524
+ outOfFocus: focusOf(index).outOfFocus
525
+ }
526
+ ];
527
+ });
444
528
 
445
529
  useBeforePaint(() => {
446
530
  const texts = [...(labels.current?.querySelectorAll('text') ?? [])];
@@ -459,29 +543,61 @@ export function ChartBar<Row>({
459
543
  return (
460
544
  <g ref={ref} className={clsx('pointer-events-none', className)}>
461
545
  <g
462
- className={animate ? 'transition-[scale] duration-400 ease-out starting:scale-y-0 motion-reduce:transition-none' : undefined}
463
- style={animate ? { transformOrigin: `0px ${groundOf(chart)}px` } : undefined}
546
+ className={
547
+ animate
548
+ ? clsx(
549
+ 'transition-[scale] duration-400 ease-out motion-reduce:transition-none',
550
+ horizontal ? 'starting:scale-x-0' : 'starting:scale-y-0'
551
+ )
552
+ : undefined
553
+ }
554
+ style={animate ? { transformOrigin: horizontal ? `${groundOf(chart)}px 0px` : `0px ${groundOf(chart)}px` } : undefined}
464
555
  >
465
- {drawn.map(({ index, column, y, height, alpha }) => {
466
- const corner = bars?.stack === true ? 0 : Math.min(radius, Math.floor(column.width / 4));
556
+ {drawn.map(({ index, box, alpha }) => {
557
+ const thickness = horizontal ? box.height : box.width;
558
+ const corner = stack !== null ? 0 : Math.min(radius, Math.floor(thickness / 4));
467
559
  const fill = rowColors?.[index] ?? color ?? fallback;
560
+ const forward = (values[index] ?? 0) >= 0;
468
561
 
469
562
  return rounded === 'end' && corner > 0 ? (
470
563
  <path
471
564
  key={index}
472
- d={endRoundedColumn(column.x, y, column.width, height, corner, (values[index] ?? 0) >= 0)}
565
+ d={
566
+ horizontal
567
+ ? endRoundedBar(box.x, box.y, box.width, box.height, corner, forward)
568
+ : endRoundedColumn(box.x, box.y, box.width, box.height, corner, forward)
569
+ }
473
570
  opacity={alpha}
474
571
  style={{ fill }}
475
572
  />
476
573
  ) : (
477
- <rect key={index} x={column.x} y={y} width={column.width} height={height} rx={corner} opacity={alpha} style={{ fill }} />
574
+ <rect key={index} {...box} rx={corner} opacity={alpha} style={{ fill }} />
478
575
  );
479
576
  })}
480
577
  </g>
481
578
  <g ref={labels}>
579
+ {rowLabels.map(({ index, text, x, y, anchor, outOfFocus }) => (
580
+ <text
581
+ key={`label-${index}`}
582
+ x={x}
583
+ y={y}
584
+ dy="0.32em"
585
+ textAnchor={anchor}
586
+ opacity={outOfFocus ? dimOpacity : 1}
587
+ aria-hidden
588
+ strokeWidth={3}
589
+ paintOrder="stroke"
590
+ style={{ stroke: chart.halo }}
591
+ className={clsx('fill-text tabular-nums', valueLabelSize === 'xs' ? 'text-xs' : 'text-2xs')}
592
+ >
593
+ {text}
594
+ </text>
595
+ ))}
482
596
  {labeled &&
483
- drawn.map(({ index, column, y, outOfFocus, text }, i) => {
484
- const center = Math.round(column.x + column.width / 2);
597
+ !horizontal &&
598
+ drawn.map(({ index, box, outOfFocus, text }, i) => {
599
+ const center = Math.round(box.x + box.width / 2);
600
+ const y = box.y;
485
601
  const baseline = labelTops[i]!;
486
602
 
487
603
  return (
package/src/store.ts CHANGED
@@ -19,6 +19,8 @@ export interface SeriesEntry {
19
19
  readonly valueLabels: boolean;
20
20
  /* What a column dims to when it is out of focus, which the labels under it follow; columns only. */
21
21
  readonly dimOpacity?: number;
22
+ /* The room its value labels take past the end of the longest bar of a horizontal chart; 0 without them. */
23
+ readonly endRoom?: number;
22
24
  }
23
25
 
24
26
  export interface RuleEntry {
@@ -44,6 +46,8 @@ export interface BandEntry {
44
46
  export interface AxisSizes {
45
47
  /* The room end labels take right of the plot, inside its svg. */
46
48
  readonly end: number | null;
49
+ /* The room the row labels of a horizontal chart take left of the plot. */
50
+ readonly start: number | null;
47
51
  }
48
52
 
49
53
  export type YAxisSide = 'left' | 'right';
@@ -109,7 +113,7 @@ const sameEntry = (one: object | undefined, other: object): boolean =>
109
113
  */
110
114
  export function createChartStore(): ChartStore {
111
115
  const listeners = new Set<() => void>();
112
- let axes: AxisSizes = { end: null };
116
+ let axes: AxisSizes = { end: null, start: null };
113
117
  let formats: ChartFormats = {};
114
118
 
115
119
  const emit = (): void => {