@milktop/react-ui 0.3.19 → 0.3.21

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.
@@ -16,5 +16,8 @@ export type ChartProps = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
16
16
  export type AreaChartProps = ChartProps & {
17
17
  curve?: 'smooth' | 'linear';
18
18
  zero?: boolean;
19
+ time?: boolean;
20
+ formatX?: ((value: unknown) => string) | null;
21
+ tooltipLabel?: ((row: ChartRow) => string) | null;
19
22
  };
20
- export declare function AreaChart({ data, x, y, series, height, format, label: labelProp, grid, curve, stacked, zero, classes, ...rest }: AreaChartProps): import("react").JSX.Element;
23
+ export declare function AreaChart({ data, x, y, series, height, format, label: labelProp, grid, curve, stacked, zero, time, formatX, tooltipLabel, classes, ...rest }: AreaChartProps): import("react").JSX.Element;
@@ -11,17 +11,20 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
11
11
  * - `curve`: 'smooth' (default) or 'linear'; `stacked`: series sit on top of one another
12
12
  * - `zero`: the value axis starts at 0 (default); false fits it to the values, so a small change
13
13
  * on a large value shows (a weight); stacked charts always start at 0
14
+ * - `time`: `x` holds dates (Date, or '2024-03-08'), rows in date order: each point sits by its
15
+ * date, so a year's gap looks like one, and the axis is marked in months and years
16
+ * - `formatX(value)`: the axis' labels (a Date when `time`); `tooltipLabel(row)`: the tooltip's heading
14
17
  * - `height` (240 px), `format(value)` for ticks and tooltips, `grid` (lines; true)
15
18
  * - `label`: what it shows, for assistive tech (a hidden table of the data)
16
19
  */
17
20
  import { useLocale, useMessages } from '../format/LocaleProvider.js';
18
21
  import { useId, useState } from 'react';
19
- import { scalePoint } from 'd3-scale';
22
+ import { scalePoint, scaleTime } from 'd3-scale';
20
23
  import { area, line, curveMonotoneX, curveLinear } from 'd3-shape';
21
24
  import { ChartFrame } from './ChartFrame.js';
22
- import { seriesOf, formatter, pad, yScale, fitScale, leftFor, labelStep, num } from './chart.js';
25
+ import { seriesOf, formatter, pad, yScale, fitScale, leftFor, labelStep, num, toDate } from './chart.js';
23
26
  import { partsOf } from '../utils.js';
24
- export function AreaChart({ data = [], x = 'label', y = null, series = null, height = 240, format = null, label: labelProp, grid = true, curve = 'smooth', stacked = false, zero = true, classes, ...rest }) {
27
+ export function AreaChart({ data = [], x = 'label', y = null, series = null, height = 240, format = null, label: labelProp, grid = true, curve = 'smooth', stacked = false, zero = true, time = false, formatX = null, tooltipLabel = null, classes, ...rest }) {
25
28
  const t = useMessages();
26
29
  const label = labelProp ?? t.chart.label;
27
30
  const part = partsOf('chart', classes);
@@ -31,7 +34,8 @@ export function AreaChart({ data = [], x = 'label', y = null, series = null, hei
31
34
  const [width, setWidth] = useState(0);
32
35
  const rows = data ?? [];
33
36
  const list = seriesOf(series, y);
34
- const fmt = formatter(format, useLocale());
37
+ const locale = useLocale();
38
+ const fmt = formatter(format, locale);
35
39
  const innerH = Math.max(0, height - pad.top - pad.bottom);
36
40
  // Each series' [low, high] per row: from 0, or stacked on the ones before.
37
41
  const base = rows.map(() => 0);
@@ -48,8 +52,16 @@ export function AreaChart({ data = [], x = 'label', y = null, series = null, hei
48
52
  const ticks = ys.ticks(4);
49
53
  const left = leftFor(ticks, fmt);
50
54
  const innerW = Math.max(0, width - left - pad.right);
51
- const xs = scalePoint().domain(rows.map((_, i) => i)).range([0, innerW]);
52
- const at = (i) => xs(i) ?? 0;
55
+ const dates = time ? rows.map((row) => toDate(row[x])) : [];
56
+ const byDate = scaleTime().domain([dates[0] ?? new Date(), dates[dates.length - 1] ?? new Date()]).range([0, innerW]);
57
+ const evenly = scalePoint().domain(rows.map((_, i) => i)).range([0, innerW]);
58
+ const at = (i) => (time ? byDate(dates[i]) : evenly(i)) ?? 0;
59
+ const tickLabel = formatX ?? (time
60
+ ? (value) => toDate(value).toLocaleDateString(locale, { month: 'short', year: 'numeric' })
61
+ : (value) => String(value ?? ''));
62
+ const labelOf = tooltipLabel ?? ((row) => time ? toDate(row[x]).toLocaleDateString(locale, { dateStyle: 'medium' }) : tickLabel(row[x]));
63
+ // About one date every 80px, on whole months and years
64
+ const timeTicks = time && rows.length > 1 ? byDate.ticks(Math.max(2, Math.floor(innerW / 80))) : [];
53
65
  const shape = curve === 'linear' ? curveLinear : curveMonotoneX;
54
66
  // Fitted, the fill runs down to the axis' foot rather than to 0, which is off the chart
55
67
  const fill = area().x((_, i) => at(i)).y0((d) => (fitted ? innerH : ys(d[0]))).y1((d) => ys(d[1])).curve(shape);
@@ -59,8 +71,11 @@ export function AreaChart({ data = [], x = 'label', y = null, series = null, hei
59
71
  if (!rows.length)
60
72
  return;
61
73
  const pos = e.clientX - e.currentTarget.getBoundingClientRect().left - left;
62
- const gap = rows.length > 1 ? innerW / (rows.length - 1) : 0;
63
- setHover(Math.max(0, Math.min(rows.length - 1, gap ? Math.round(pos / gap) : 0)));
74
+ // The nearest point, as they aren't evenly spaced when placed by date
75
+ let nearest = 0;
76
+ rows.forEach((_, i) => { if (Math.abs(at(i) - pos) < Math.abs(at(nearest) - pos))
77
+ nearest = i; });
78
+ setHover(nearest);
64
79
  }
65
- return (_jsx(ChartFrame, { ...rest, rows: rows, x: x, list: list, fmt: fmt, height: height, label: label, classes: classes, hover: hover, onHover: setHover, onMove: move, width: width, onWidth: setWidth, tipLeft: hover == null ? 0 : left + at(hover), flip: hover != null && at(hover) > innerW * 0.6, children: _jsxs("svg", { ...part('svg'), width: width, height: height, "aria-hidden": "true", children: [_jsx("defs", { children: list.map((s, i) => (_jsxs("linearGradient", { id: `${id}-${i}`, x1: "0", x2: "0", y1: "0", y2: "1", children: [_jsx("stop", { offset: "0%", stopColor: s.color, stopOpacity: "0.28" }), _jsx("stop", { offset: "100%", stopColor: s.color, stopOpacity: "0.02" })] }, s.key))) }), _jsxs("g", { transform: `translate(${left},${pad.top})`, children: [ticks.map((tick) => (_jsxs("g", { children: [grid && _jsx("line", { ...part('grid'), x1: "0", x2: innerW, y1: ys(tick), y2: ys(tick) }), _jsx("text", { ...part('tick'), x: "-8", y: ys(tick), dy: "0.32em", textAnchor: "end", children: fmt(tick) })] }, tick))), rows.map((row, i) => i % step === 0 && (_jsx("text", { ...part('tick'), x: at(i), y: innerH + 18, textAnchor: i === 0 ? 'start' : i === rows.length - 1 ? 'end' : 'middle', children: String(row[x] ?? '') }, i))), list.map((s, i) => (_jsxs("g", { children: [_jsx("path", { ...part('area'), d: fill(bands[i]) ?? '', fill: `url(#${id}-${i})` }), _jsx("path", { ...part('line'), d: stroke(bands[i]) ?? '', stroke: s.color })] }, s.key))), hover != null && _jsxs(_Fragment, { children: [_jsx("line", { ...part('cursor'), x1: at(hover), x2: at(hover), y1: "0", y2: innerH }), list.map((s, i) => _jsx("circle", { ...part('dot'), cx: at(hover), cy: ys(bands[i][hover][1]), r: "4", fill: s.color }, s.key))] })] })] }) }));
80
+ return (_jsx(ChartFrame, { ...rest, rows: rows, x: x, labelOf: labelOf, list: list, fmt: fmt, height: height, label: label, classes: classes, hover: hover, onHover: setHover, onMove: move, width: width, onWidth: setWidth, tipLeft: hover == null ? 0 : left + at(hover), flip: hover != null && at(hover) > innerW * 0.6, children: _jsxs("svg", { ...part('svg'), width: width, height: height, "aria-hidden": "true", children: [_jsx("defs", { children: list.map((s, i) => (_jsxs("linearGradient", { id: `${id}-${i}`, x1: "0", x2: "0", y1: "0", y2: "1", children: [_jsx("stop", { offset: "0%", stopColor: s.color, stopOpacity: "0.28" }), _jsx("stop", { offset: "100%", stopColor: s.color, stopOpacity: "0.02" })] }, s.key))) }), _jsxs("g", { transform: `translate(${left},${pad.top})`, children: [ticks.map((tick) => (_jsxs("g", { children: [grid && _jsx("line", { ...part('grid'), x1: "0", x2: innerW, y1: ys(tick), y2: ys(tick) }), _jsx("text", { ...part('tick'), x: "-8", y: ys(tick), dy: "0.32em", textAnchor: "end", children: fmt(tick) })] }, tick))), time ? timeTicks.map((tick) => (_jsx("text", { ...part('tick'), x: byDate(tick), y: innerH + 18, textAnchor: "middle", children: tickLabel(tick) }, +tick))) : rows.map((row, i) => i % step === 0 && (_jsx("text", { ...part('tick'), x: at(i), y: innerH + 18, textAnchor: i === 0 ? 'start' : i === rows.length - 1 ? 'end' : 'middle', children: tickLabel(row[x]) }, i))), list.map((s, i) => (_jsxs("g", { children: [_jsx("path", { ...part('area'), d: fill(bands[i]) ?? '', fill: `url(#${id}-${i})` }), _jsx("path", { ...part('line'), d: stroke(bands[i]) ?? '', stroke: s.color })] }, s.key))), hover != null && _jsxs(_Fragment, { children: [_jsx("line", { ...part('cursor'), x1: at(hover), x2: at(hover), y1: "0", y2: innerH }), list.map((s, i) => _jsx("circle", { ...part('dot'), cx: at(hover), cy: ys(bands[i][hover][1]), r: "4", fill: s.color }, s.key))] })] })] }) }));
66
81
  }
@@ -56,5 +56,5 @@ export function BarChart({ data = [], x = 'label', y = null, series = null, heig
56
56
  setHover(Math.max(0, Math.min(rows.length - 1, Math.floor(pos / (innerW / rows.length)))));
57
57
  }
58
58
  const flip = hover != null && at(hover) > innerW * 0.6;
59
- return (_jsx(ChartFrame, { ...rest, rows: rows, x: x, list: list, fmt: fmt, height: height, label: label, classes: classes, hover: hover, onHover: setHover, onMove: move, width: width, onWidth: setWidth, tipLeft: hover == null ? 0 : left + at(hover) + (flip ? 0 : xs.bandwidth()), flip: flip, children: _jsx("svg", { ...part('svg'), width: width, height: height, "aria-hidden": "true", children: _jsxs("g", { transform: `translate(${left},${pad.top})`, children: [ticks.map((tick) => (_jsxs("g", { children: [grid && _jsx("line", { ...part('grid'), x1: "0", x2: innerW, y1: ys(tick), y2: ys(tick) }), _jsx("text", { ...part('tick'), x: "-8", y: ys(tick), dy: "0.32em", textAnchor: "end", children: fmt(tick) })] }, tick))), hover != null && (_jsx("rect", { ...part('band'), x: at(hover) - (xs.step() * xs.paddingInner()) / 2, y: "0", width: xs.step(), height: innerH })), rows.map((row, i) => (_jsxs("g", { children: [i % step === 0 && _jsx("text", { ...part('tick'), x: at(i) + xs.bandwidth() / 2, y: innerH + 18, textAnchor: "middle", children: String(row[x] ?? '') }), bars[i].map((bar) => (_jsx("rect", { ...part('bar'), x: bar.x, y: bar.y, width: bar.w, height: bar.h, rx: stacked ? 0 : 3, fill: bar.color, "data-dim": (hover != null && hover !== i) || undefined }, bar.key)))] }, i)))] }) }) }));
59
+ return (_jsx(ChartFrame, { ...rest, rows: rows, x: x, labelOf: (row) => String(row[x] ?? ''), list: list, fmt: fmt, height: height, label: label, classes: classes, hover: hover, onHover: setHover, onMove: move, width: width, onWidth: setWidth, tipLeft: hover == null ? 0 : left + at(hover) + (flip ? 0 : xs.bandwidth()), flip: flip, children: _jsx("svg", { ...part('svg'), width: width, height: height, "aria-hidden": "true", children: _jsxs("g", { transform: `translate(${left},${pad.top})`, children: [ticks.map((tick) => (_jsxs("g", { children: [grid && _jsx("line", { ...part('grid'), x1: "0", x2: innerW, y1: ys(tick), y2: ys(tick) }), _jsx("text", { ...part('tick'), x: "-8", y: ys(tick), dy: "0.32em", textAnchor: "end", children: fmt(tick) })] }, tick))), hover != null && (_jsx("rect", { ...part('band'), x: at(hover) - (xs.step() * xs.paddingInner()) / 2, y: "0", width: xs.step(), height: innerH })), rows.map((row, i) => (_jsxs("g", { children: [i % step === 0 && _jsx("text", { ...part('tick'), x: at(i) + xs.bandwidth() / 2, y: innerH + 18, textAnchor: "middle", children: String(row[x] ?? '') }), bars[i].map((bar) => (_jsx("rect", { ...part('bar'), x: bar.x, y: bar.y, width: bar.w, height: bar.h, rx: stacked ? 0 : 3, fill: bar.color, "data-dim": (hover != null && hover !== i) || undefined }, bar.key)))] }, i)))] }) }) }));
60
60
  }
@@ -7,6 +7,7 @@ export type ChartClasses = Classes<'root' | 'frame' | 'svg' | 'grid' | 'tick' |
7
7
  type FrameProps = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
8
8
  rows: ChartRow[];
9
9
  x: string;
10
+ labelOf: (row: ChartRow) => string;
10
11
  list: Series[];
11
12
  fmt: (value: unknown) => string;
12
13
  height: number;
@@ -21,5 +22,5 @@ type FrameProps = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
21
22
  onWidth: (width: number) => void;
22
23
  children: ReactNode;
23
24
  };
24
- export declare function ChartFrame({ rows, x, list, fmt, height, label, hover, onHover, onMove, tipLeft, flip, width, onWidth, className, classes, children, ...rest }: FrameProps): import("react").JSX.Element;
25
+ export declare function ChartFrame({ rows, x, labelOf, list, fmt, height, label, hover, onHover, onMove, tipLeft, flip, width, onWidth, className, classes, children, ...rest }: FrameProps): import("react").JSX.Element;
25
26
  export {};
@@ -5,7 +5,7 @@ import { useEffect, useRef } from 'react';
5
5
  import { cx, partsOf } from '../utils.js';
6
6
  import '../theme.css';
7
7
  import './chart.css';
8
- export function ChartFrame({ rows, x, list, fmt, height, label, hover, onHover, onMove, tipLeft, flip, width, onWidth, className, classes, children, ...rest }) {
8
+ export function ChartFrame({ rows, x, labelOf, list, fmt, height, label, hover, onHover, onMove, tipLeft, flip, width, onWidth, className, classes, children, ...rest }) {
9
9
  const part = partsOf('chart', classes);
10
10
  const frame = useRef(null);
11
11
  const latest = useRef(onWidth);
@@ -18,5 +18,5 @@ export function ChartFrame({ rows, x, list, fmt, height, label, hover, onHover,
18
18
  observer.observe(el);
19
19
  return () => observer.disconnect();
20
20
  }, []);
21
- return (_jsxs("div", { ...rest, ...part('root'), className: cx(className, classes?.root), children: [_jsxs("div", { ...part('frame'), ref: frame, style: { height }, onPointerMove: onMove, onPointerLeave: () => onHover(null), role: "presentation", children: [width > 0 && children, hover != null && rows[hover] && (_jsxs("div", { ...part('tooltip'), "data-flip": flip || undefined, style: { left: tipLeft }, children: [_jsx("div", { ...part('tooltip-label'), children: String(rows[hover][x] ?? '') }), list.map((s) => (_jsxs("div", { ...part('tooltip-row'), children: [_jsx("span", { ...part('swatch'), style: { background: s.color } }), _jsx("span", { ...part('tooltip-name'), children: s.label }), _jsx("span", { ...part('tooltip-value'), children: fmt(rows[hover][s.key]) })] }, s.key)))] }))] }), list.length > 1 && (_jsx("div", { ...part('legend'), children: list.map((s) => _jsxs("span", { ...part('legend-item'), children: [_jsx("span", { ...part('swatch'), style: { background: s.color } }), s.label] }, s.key)) })), _jsx("div", { ...part('sr-only'), children: _jsxs("table", { children: [_jsx("caption", { children: label }), _jsxs("tbody", { children: [_jsxs("tr", { children: [_jsx("th", { children: x }), list.map((s) => _jsx("th", { children: s.label }, s.key))] }), rows.map((row, i) => _jsxs("tr", { children: [_jsx("td", { children: String(row[x] ?? '') }), list.map((s) => _jsx("td", { children: fmt(row[s.key]) }, s.key))] }, i))] })] }) })] }));
21
+ return (_jsxs("div", { ...rest, ...part('root'), className: cx(className, classes?.root), children: [_jsxs("div", { ...part('frame'), ref: frame, style: { height }, onPointerMove: onMove, onPointerLeave: () => onHover(null), role: "presentation", children: [width > 0 && children, hover != null && rows[hover] && (_jsxs("div", { ...part('tooltip'), "data-flip": flip || undefined, style: { left: tipLeft }, children: [_jsx("div", { ...part('tooltip-label'), children: labelOf(rows[hover]) }), list.map((s) => (_jsxs("div", { ...part('tooltip-row'), children: [_jsx("span", { ...part('swatch'), style: { background: s.color } }), _jsx("span", { ...part('tooltip-name'), children: s.label }), _jsx("span", { ...part('tooltip-value'), children: fmt(rows[hover][s.key]) })] }, s.key)))] }))] }), list.length > 1 && (_jsx("div", { ...part('legend'), children: list.map((s) => _jsxs("span", { ...part('legend-item'), children: [_jsx("span", { ...part('swatch'), style: { background: s.color } }), s.label] }, s.key)) })), _jsx("div", { ...part('sr-only'), children: _jsxs("table", { children: [_jsx("caption", { children: label }), _jsxs("tbody", { children: [_jsxs("tr", { children: [_jsx("th", { children: x }), list.map((s) => _jsx("th", { children: s.label }, s.key))] }), rows.map((row, i) => _jsxs("tr", { children: [_jsx("td", { children: labelOf(row) }), list.map((s) => _jsx("td", { children: fmt(row[s.key]) }, s.key))] }, i))] })] }) })] }));
22
22
  }
@@ -22,3 +22,4 @@ export declare const fitScale: (min: number, max: number, innerH: number) => imp
22
22
  export declare const leftFor: (ticks: number[], fmt: (value: unknown) => string) => number;
23
23
  export declare const labelStep: (count: number, innerW: number) => number;
24
24
  export declare const num: (value: unknown) => number;
25
+ export declare const toDate: (value: unknown) => Date;
@@ -24,3 +24,7 @@ export const leftFor = (ticks, fmt) => Math.max(...ticks.map((tick) => fmt(tick)
24
24
  // Every nth x label, so they don't collide.
25
25
  export const labelStep = (count, innerW) => Math.max(1, Math.ceil(count / Math.max(1, Math.floor(innerW / 64))));
26
26
  export const num = (value) => +value || 0;
27
+ // A date from a Date, a timestamp or a string; '2024-03-08' is that day at midnight where the chart is, not in UTC.
28
+ export const toDate = (value) => value instanceof Date ? value
29
+ : typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) ? new Date(`${value}T00:00`)
30
+ : new Date(value);
@@ -1,7 +1,8 @@
1
1
  @layer ui {
2
2
  [data-scope=tabs][data-part=root] { display: block; width: 100%; color: var(--ui-text); font-family: var(--ui-font); }
3
3
  [data-scope=tabs][data-part=list] { position: relative; display: flex; gap: 0.25rem; overflow-x: auto;
4
- [data-variant=line] > & { border-bottom: 1px solid var(--ui-border); }
4
+ /* A shadow, not a border: the list scrolls sideways, and the underline over a border would add a pixel of vertical scroll. */
5
+ [data-variant=line] > & { box-shadow: inset 0 -1px var(--ui-border); }
5
6
  /* Pills: a raised pill behind the selected tab, like Segmented. */
6
7
  [data-variant=pills] > & { display: inline-flex; padding: 0.25rem; background: var(--ui-hover); border-radius: var(--ui-radius); } }
7
8
  [data-scope=tabs][data-part=trigger] {
@@ -49,7 +50,7 @@
49
50
  @keyframes ui-ping { from { scale: 1; opacity: 0.7; } 75%, to { scale: 2.2; opacity: 0; } }
50
51
  @media (prefers-reduced-motion: reduce) { [data-scope=tabs][data-part=count]::after { animation: none; } }
51
52
  [data-scope=tabs][data-part=indicator] { transition-property: var(--transition-property); transition-duration: 200ms;
52
- [data-variant=line] & { position: absolute; bottom: -1px; left: var(--left); width: var(--width); height: 2px; background: var(--ui-accent); }
53
+ [data-variant=line] & { position: absolute; bottom: 0; left: var(--left); width: var(--width); height: 2px; background: var(--ui-accent); }
53
54
  [data-variant=pills] & { position: absolute; z-index: 0; top: var(--top); left: var(--left); width: var(--width); height: var(--height);
54
55
  background: var(--ui-surface); border-radius: calc(var(--ui-radius) - 2px); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12); } }
55
56
  [data-scope=tabs][data-part=panels] { padding-top: 1rem; }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milktop/react-ui",
3
- "version": "0.3.19",
3
+ "version": "0.3.21",
4
4
  "description": "React components on Ark UI (Zag state machines), with imba-ui's API and design",
5
5
  "license": "MIT",
6
6
  "author": "André Goldstein",