@adecore/charts 0.48.4 → 0.49.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.
@@ -0,0 +1,9 @@
1
+ import type { HeatCell } from './heat.ts';
2
+ export interface HeatmapCursor {
3
+ getSnapshot(): HeatCell | null;
4
+ isActive(cell: HeatCell): boolean;
5
+ set(cell: HeatCell | null): void;
6
+ subscribe(listener: () => void): () => void;
7
+ subscribeCell(cell: HeatCell, listener: () => void): () => void;
8
+ }
9
+ export declare function createHeatmapCursor(): HeatmapCursor;
@@ -0,0 +1,59 @@
1
+ /* Only the old and new cell subscriptions need a cursor update. */
2
+ export function createHeatmapCursor() {
3
+ let current = null;
4
+ const listeners = new Set();
5
+ const cells = new Map();
6
+ const keyOf = cell => `${cell.row}:${cell.column}`;
7
+ const isActive = cell => current !== null && current.row === cell.row && current.column === cell.column;
8
+ const emit = subscribers => {
9
+ if (subscribers === undefined) {
10
+ return;
11
+ }
12
+ for (const listener of [...subscribers]) {
13
+ listener();
14
+ }
15
+ };
16
+ return {
17
+ getSnapshot: () => current,
18
+ isActive,
19
+ set(cell) {
20
+ if (cell === null ? current === null : isActive(cell)) {
21
+ return;
22
+ }
23
+ const previous = current;
24
+ const next = cell === null ? null : {
25
+ ...cell
26
+ };
27
+ current = next;
28
+ if (previous !== null) {
29
+ emit(cells.get(keyOf(previous)));
30
+ }
31
+ if (next !== null) {
32
+ emit(cells.get(keyOf(next)));
33
+ }
34
+ emit(listeners);
35
+ },
36
+ subscribe(listener) {
37
+ listeners.add(listener);
38
+ return () => {
39
+ listeners.delete(listener);
40
+ };
41
+ },
42
+ subscribeCell(cell, listener) {
43
+ const key = keyOf(cell);
44
+ let subscribers = cells.get(key);
45
+ if (subscribers === undefined) {
46
+ subscribers = new Set();
47
+ cells.set(key, subscribers);
48
+ }
49
+ const subscribed = subscribers;
50
+ subscribed.add(listener);
51
+ return () => {
52
+ subscribed.delete(listener);
53
+ if (subscribed.size === 0 && cells.get(key) === subscribed) {
54
+ cells.delete(key);
55
+ }
56
+ };
57
+ }
58
+ };
59
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adecore/charts",
3
- "version": "0.48.4",
3
+ "version": "0.49.0",
4
4
  "description": "Series charts, scatters, heatmaps, trace timelines and sparklines in the theme of @adecore/ui, readable by keyboard and screen reader.",
5
5
  "license": "FSL-1.1-MIT",
6
6
  "author": "Bas Milius",
@@ -43,14 +43,14 @@
43
43
  "lucide-react": "^1.61.0"
44
44
  },
45
45
  "peerDependencies": {
46
- "@adecore/ui": "^0.48.4",
46
+ "@adecore/ui": "^0.49.0",
47
47
  "i18next": "^26.4.2",
48
48
  "react": "^19.3.0",
49
49
  "react-dom": "^19.3.0",
50
50
  "react-i18next": "^17.0.15"
51
51
  },
52
52
  "devDependencies": {
53
- "@adecore/ui": "0.48.4",
53
+ "@adecore/ui": "0.49.0",
54
54
  "@types/bun": "^1.4.4",
55
55
  "@types/react": "^19.3.0",
56
56
  "@types/react-dom": "^19.3.0",
package/src/Heatmap.tsx CHANGED
@@ -1,9 +1,10 @@
1
- import { useId, useState, type CSSProperties, type KeyboardEvent, type Ref } from 'react';
1
+ import { useId, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent, type Ref } from 'react';
2
2
  import clsx from 'clsx';
3
3
  import { useTranslation } from 'react-i18next';
4
4
  import { Button, Surface } from '@adecore/ui';
5
5
  import { formatNumber } from '@adecore/ui/format';
6
6
  import { colorOf } from './color.ts';
7
+ import { createHeatmapCursor, type HeatmapCursor } from './heat-cursor.ts';
7
8
  import { FLOOR, heatMix, heatShare, moveCell, type HeatCell } from './heat.ts';
8
9
  import type { ChartColor } from './types.ts';
9
10
  import { tableClasses } from './values-table.ts';
@@ -62,6 +63,113 @@ const cardPlace = (toRight: boolean, down: boolean): CSSProperties => ({
62
63
  bottom: down ? undefined : 0
63
64
  });
64
65
 
66
+ interface HeatmapGridProps extends Pick<HeatmapProps, 'rows' | 'columns' | 'values' | 'valueLabel'> {
67
+ readonly cursor: HeatmapCursor;
68
+ readonly color: string;
69
+ readonly top: number;
70
+ readonly steps: number | undefined;
71
+ readonly cellHeight: number;
72
+ readonly write: (value: number | null) => string;
73
+ readonly onHover: (cell: HeatCell) => void;
74
+ }
75
+
76
+ interface HeatmapCellProps extends Pick<HeatmapGridProps, 'cursor' | 'color' | 'top' | 'steps' | 'cellHeight' | 'valueLabel' | 'write' | 'onHover'> {
77
+ readonly row: number;
78
+ readonly column: number;
79
+ readonly value: number | null;
80
+ readonly rowLabel: string;
81
+ readonly columnLabel: string;
82
+ readonly toRight: boolean;
83
+ readonly down: boolean;
84
+ }
85
+
86
+ function HeatmapCellView({
87
+ cursor,
88
+ color,
89
+ top,
90
+ steps,
91
+ cellHeight,
92
+ valueLabel,
93
+ write,
94
+ onHover,
95
+ row,
96
+ column,
97
+ rowLabel,
98
+ columnLabel,
99
+ toRight,
100
+ down,
101
+ value
102
+ }: HeatmapCellProps) {
103
+ const cell = { row, column };
104
+ const subscribe = (listener: () => void): (() => void) => cursor.subscribeCell(cell, listener);
105
+ const selected = (): boolean => cursor.isActive(cell);
106
+ const active = useSyncExternalStore(subscribe, selected, selected);
107
+ const mix = heatMix(value, top, steps);
108
+
109
+ return (
110
+ <span
111
+ data-mix={mix}
112
+ className={clsx('rounded-xs', mix === 0 && 'bg-surface-sunken', active && 'relative z-10 outline-1 outline-offset-1 outline-text')}
113
+ style={{ height: cellHeight, backgroundColor: shade(color, mix) }}
114
+ onPointerEnter={() => onHover(cell)}
115
+ >
116
+ {active && (
117
+ <Surface
118
+ className="pointer-events-none absolute flex w-max min-w-36 flex-col gap-1 rounded-lg px-2.5 py-2 text-xs"
119
+ style={cardPlace(toRight, down)}
120
+ >
121
+ <p className="font-medium whitespace-nowrap text-text">
122
+ {rowLabel} · {columnLabel}
123
+ </p>
124
+ <p className="flex items-center gap-2 text-text-muted">
125
+ <span className={clsx('size-2 shrink-0 rounded-xs', mix === 0 && 'bg-surface-sunken')} style={{ backgroundColor: shade(color, mix) }} />
126
+ <span className="min-w-0 truncate">{valueLabel}</span>
127
+ <span className="ml-auto pl-3 text-text tabular-nums">{write(value)}</span>
128
+ </p>
129
+ </Surface>
130
+ )}
131
+ </span>
132
+ );
133
+ }
134
+
135
+ function HeatmapGrid({ rows, columns, values, valueLabel, cursor, color, top, steps, cellHeight, write, onHover }: HeatmapGridProps) {
136
+ return (
137
+ <div aria-hidden className="grid gap-0.5 text-xs text-text-muted" style={{ gridTemplateColumns: `auto repeat(${columns.length}, minmax(0, 1fr))` }}>
138
+ <span />
139
+ {columns.map((column) => (
140
+ <span key={column.key} className="flex justify-center leading-4 whitespace-nowrap tabular-nums">
141
+ {column.short === undefined ? column.label : column.short}
142
+ </span>
143
+ ))}
144
+ {rows.map((row, rowIndex) => (
145
+ <div key={row.key} className="contents">
146
+ <span className="flex items-center pr-2 leading-4 whitespace-nowrap">{row.short === undefined ? row.label : row.short}</span>
147
+ {columns.map((column, columnIndex) => (
148
+ <HeatmapCellView
149
+ key={column.key}
150
+ cursor={cursor}
151
+ row={rowIndex}
152
+ column={columnIndex}
153
+ rowLabel={row.label}
154
+ columnLabel={column.label}
155
+ value={values[rowIndex]?.[columnIndex] ?? null}
156
+ color={color}
157
+ top={top}
158
+ steps={steps}
159
+ cellHeight={cellHeight}
160
+ valueLabel={valueLabel}
161
+ write={write}
162
+ onHover={onHover}
163
+ toRight={columnIndex < columns.length / 2}
164
+ down={rowIndex < rows.length / 2}
165
+ />
166
+ ))}
167
+ </div>
168
+ ))}
169
+ </div>
170
+ );
171
+ }
172
+
65
173
  /* A grid of rows by columns, each cell shaded by its value, such as events per weekday and hour. */
66
174
  export function Heatmap({
67
175
  rows,
@@ -82,7 +190,8 @@ export function Heatmap({
82
190
  }: HeatmapProps) {
83
191
  const { t } = useTranslation('charts');
84
192
  const id = useId();
85
- const [active, setActive] = useState<HeatCell | null>(null);
193
+ const [cursor] = useState(createHeatmapCursor);
194
+ const active = useSyncExternalStore(cursor.subscribe, cursor.getSnapshot, cursor.getSnapshot);
86
195
  const [announce, setAnnounce] = useState(false);
87
196
  const [shown, setShown] = useState(false);
88
197
 
@@ -105,13 +214,20 @@ export function Heatmap({
105
214
  const classes = tableClasses(table && shown);
106
215
 
107
216
  const activate = (cell: HeatCell | null): void => {
108
- setActive(cell);
217
+ const previous = cursor.getSnapshot();
218
+ const before = previous !== null && previous.row < rows.length && previous.column < columns.length ? previous : null;
219
+ cursor.set(cell);
109
220
 
110
- if (!sameCell(cell, current)) {
221
+ if (!sameCell(cell, before)) {
111
222
  onActiveChange?.(cell);
112
223
  }
113
224
  };
114
225
 
226
+ const hover = (cell: HeatCell): void => {
227
+ setAnnounce(false);
228
+ activate(cell);
229
+ };
230
+
115
231
  const onKeyDown = (e: KeyboardEvent<HTMLDivElement>): void => {
116
232
  const target = moveCell(e.key, current, rows.length, columns.length, e.ctrlKey || e.metaKey);
117
233
 
@@ -143,64 +259,19 @@ export function Heatmap({
143
259
  {empty ? (
144
260
  <p className="py-6 text-center text-xs text-text-faint">{t('noData')}</p>
145
261
  ) : (
146
- <div
147
- aria-hidden
148
- className="grid gap-0.5 text-xs text-text-muted"
149
- style={{ gridTemplateColumns: `auto repeat(${columns.length}, minmax(0, 1fr))` }}
150
- >
151
- <span />
152
- {columns.map((column) => (
153
- <span key={column.key} className="flex justify-center leading-4 whitespace-nowrap tabular-nums">
154
- {column.short === undefined ? column.label : column.short}
155
- </span>
156
- ))}
157
- {rows.map((row, rowIndex) => (
158
- <div key={row.key} className="contents">
159
- <span className="flex items-center pr-2 leading-4 whitespace-nowrap">{row.short === undefined ? row.label : row.short}</span>
160
- {columns.map((column, columnIndex) => {
161
- const value = valueAt(rowIndex, columnIndex);
162
- const mix = heatMix(value, top, steps);
163
- const isActive = current !== null && current.row === rowIndex && current.column === columnIndex;
164
-
165
- return (
166
- <span
167
- key={column.key}
168
- data-mix={mix}
169
- className={clsx(
170
- 'rounded-xs',
171
- mix === 0 && 'bg-surface-sunken',
172
- isActive && 'relative z-10 outline-1 outline-offset-1 outline-text'
173
- )}
174
- style={{ height: cellHeight, backgroundColor: shade(color, mix) }}
175
- onPointerEnter={() => {
176
- setAnnounce(false);
177
- activate({ row: rowIndex, column: columnIndex });
178
- }}
179
- >
180
- {isActive && (
181
- <Surface
182
- className="pointer-events-none absolute flex w-max min-w-36 flex-col gap-1 rounded-lg px-2.5 py-2 text-xs"
183
- style={cardPlace(columnIndex < columns.length / 2, rowIndex < rows.length / 2)}
184
- >
185
- <p className="font-medium whitespace-nowrap text-text">
186
- {row.label} · {column.label}
187
- </p>
188
- <p className="flex items-center gap-2 text-text-muted">
189
- <span
190
- className={clsx('size-2 shrink-0 rounded-xs', mix === 0 && 'bg-surface-sunken')}
191
- style={{ backgroundColor: shade(color, mix) }}
192
- />
193
- <span className="min-w-0 truncate">{valueLabel}</span>
194
- <span className="ml-auto pl-3 text-text tabular-nums">{write(value)}</span>
195
- </p>
196
- </Surface>
197
- )}
198
- </span>
199
- );
200
- })}
201
- </div>
202
- ))}
203
- </div>
262
+ <HeatmapGrid
263
+ rows={rows}
264
+ columns={columns}
265
+ values={values}
266
+ valueLabel={valueLabel}
267
+ cursor={cursor}
268
+ color={color}
269
+ top={top}
270
+ steps={steps}
271
+ cellHeight={cellHeight}
272
+ write={write}
273
+ onHover={hover}
274
+ />
204
275
  )}
205
276
  </div>
206
277
  {legend && !empty && (
package/src/Root.tsx CHANGED
@@ -2,6 +2,7 @@ import {
2
2
  useContext,
3
3
  useEffect,
4
4
  useId,
5
+ useMemo,
5
6
  useRef,
6
7
  useState,
7
8
  useSyncExternalStore,
@@ -213,16 +214,23 @@ export function ChartRoot<Row>({
213
214
  }
214
215
  }, [orientation, band, dropped]);
215
216
 
216
- const xs = data.map((row, index) => {
217
- const value = readValue(x, row, index);
217
+ // Without explicit dependencies the emitted cursor render repeats these data accessors.
218
+ const { xs, keys, rowLabels, groupKeys, groupLabels } = useMemo(() => {
219
+ const xs = data.map((row, index) => {
220
+ const value = readValue(x, row, index);
218
221
 
219
- return value === null || value === undefined ? Number.NaN : xOf(value);
220
- });
222
+ return value === null || value === undefined ? Number.NaN : xOf(value);
223
+ });
224
+
225
+ const keys = points ? data.map((row, index) => (rowKey === undefined ? String(index) : String(readValue(rowKey, row, index)))) : null;
226
+ const rowLabels = rowLabel !== undefined ? data.map((row, index) => String(readValue(rowLabel, row, index))) : null;
227
+ const groupKeys = (band || points) && group !== undefined ? data.map((row, index) => String(readValue(group, row, index))) : null;
228
+ const groupLabels =
229
+ groupKeys === null ? null : groupLabel === undefined ? groupKeys : data.map((row, index) => String(readValue(groupLabel, row, index)));
230
+
231
+ return { xs, keys, rowLabels, groupKeys, groupLabels };
232
+ }, [data, x, points, rowKey, rowLabel, band, group, groupLabel]);
221
233
 
222
- const keys = points ? data.map((row, index) => (rowKey === undefined ? String(index) : String(readValue(rowKey, row, index)))) : null;
223
- const rowLabels = rowLabel !== undefined ? data.map((row, index) => String(readValue(rowLabel, row, index))) : null;
224
- const groupKeys = (band || points) && group !== undefined ? data.map((row, index) => String(readValue(group, row, index))) : null;
225
- const groupLabels = groupKeys === null ? null : groupLabel === undefined ? groupKeys : data.map((row, index) => String(readValue(groupLabel, row, index)));
226
234
  const leftY = yAxes.get('left');
227
235
  const rightY = yAxes.get('right');
228
236
  // A horizontal chart has no y axis beside it: the names of its rows take that place, and its values run underneath.
@@ -239,11 +247,16 @@ export function ChartRoot<Row>({
239
247
  const marginLeft = margin.left ?? inset;
240
248
  const marginRight = margin.right ?? inset;
241
249
 
242
- const layout = horizontal
243
- ? bandLayout(xs.length, groupKeys, 0, rowHeight, groupGap)
244
- : band
245
- ? bandLayout(xs.length, groupKeys, Math.max(0, room - marginLeft - marginRight), minBucketWidth, groupGap)
246
- : null;
250
+ // Explicit dependencies keep the emitted band calculation out of cursor-only renders.
251
+ const layout = useMemo(
252
+ () =>
253
+ horizontal
254
+ ? bandLayout(xs.length, groupKeys, 0, rowHeight, groupGap)
255
+ : band
256
+ ? bandLayout(xs.length, groupKeys, Math.max(0, room - marginLeft - marginRight), minBucketWidth, groupGap)
257
+ : null,
258
+ [horizontal, band, xs.length, groupKeys, rowHeight, groupGap, room, marginLeft, marginRight, minBucketWidth]
259
+ );
247
260
 
248
261
  const width = layout === null || horizontal ? room : Math.max(room, Math.ceil(layout.width + marginLeft + marginRight));
249
262
  const scrolls = layout !== null && width > room;
@@ -0,0 +1,77 @@
1
+ import type { HeatCell } from './heat.ts';
2
+
3
+ export interface HeatmapCursor {
4
+ getSnapshot(): HeatCell | null;
5
+ isActive(cell: HeatCell): boolean;
6
+ set(cell: HeatCell | null): void;
7
+ subscribe(listener: () => void): () => void;
8
+ subscribeCell(cell: HeatCell, listener: () => void): () => void;
9
+ }
10
+
11
+ /* Only the old and new cell subscriptions need a cursor update. */
12
+ export function createHeatmapCursor(): HeatmapCursor {
13
+ let current: HeatCell | null = null;
14
+ const listeners = new Set<() => void>();
15
+ const cells = new Map<string, Set<() => void>>();
16
+ const keyOf = (cell: HeatCell): string => `${cell.row}:${cell.column}`;
17
+ const isActive = (cell: HeatCell): boolean => current !== null && current.row === cell.row && current.column === cell.column;
18
+
19
+ const emit = (subscribers: ReadonlySet<() => void> | undefined): void => {
20
+ if (subscribers === undefined) {
21
+ return;
22
+ }
23
+
24
+ for (const listener of [...subscribers]) {
25
+ listener();
26
+ }
27
+ };
28
+
29
+ return {
30
+ getSnapshot: () => current,
31
+ isActive,
32
+ set(cell) {
33
+ if (cell === null ? current === null : isActive(cell)) {
34
+ return;
35
+ }
36
+
37
+ const previous = current;
38
+ const next = cell === null ? null : { ...cell };
39
+ current = next;
40
+
41
+ if (previous !== null) {
42
+ emit(cells.get(keyOf(previous)));
43
+ }
44
+
45
+ if (next !== null) {
46
+ emit(cells.get(keyOf(next)));
47
+ }
48
+
49
+ emit(listeners);
50
+ },
51
+ subscribe(listener) {
52
+ listeners.add(listener);
53
+
54
+ return () => {
55
+ listeners.delete(listener);
56
+ };
57
+ },
58
+ subscribeCell(cell, listener) {
59
+ const key = keyOf(cell);
60
+ let subscribers = cells.get(key);
61
+ if (subscribers === undefined) {
62
+ subscribers = new Set();
63
+ cells.set(key, subscribers);
64
+ }
65
+
66
+ const subscribed = subscribers;
67
+ subscribed.add(listener);
68
+
69
+ return () => {
70
+ subscribed.delete(listener);
71
+ if (subscribed.size === 0 && cells.get(key) === subscribed) {
72
+ cells.delete(key);
73
+ }
74
+ };
75
+ }
76
+ };
77
+ }