@momoi-labs/kiso-react 0.18.0 → 0.19.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.
@@ -14,11 +14,10 @@ export declare const chartSlot: (series: ChartSeries, index: number) => number;
14
14
  export declare const chartColor: (slot: number) => string;
15
15
  export declare const measured: (value: number | null | undefined) => value is number;
16
16
  export declare function validateChart(data: readonly ChartSample[], series: readonly ChartSeries[]): void;
17
- export declare function seriesSummary(data: readonly ChartSample[], key: string): {
18
- min: number | null;
19
- max: number | null;
20
- avg: number | null;
21
- current: number | null;
22
- };
17
+ export type ChartSummaryStat = "min" | "max" | "avg" | "current" | "p50" | "p75" | "p90" | "p95" | "p99";
18
+ export declare const chartSummaryStats: readonly ChartSummaryStat[];
19
+ export declare const defaultChartSummary: readonly ChartSummaryStat[];
20
+ export declare const chartSummaryLabel: (stat: ChartSummaryStat) => string;
21
+ export declare function seriesSummary(data: readonly ChartSample[], key: string, stats?: readonly ChartSummaryStat[]): Record<ChartSummaryStat, number | null>;
23
22
  export declare const formatChartTime: (timestamp: number) => string;
24
23
  export declare const formatChartValue: (value: number) => string;
@@ -35,14 +35,36 @@ export function validateChart(data, series) {
35
35
  }
36
36
  });
37
37
  }
38
- export function seriesSummary(data, key) {
38
+ export const chartSummaryStats = ["min", "max", "avg", "current", "p50", "p75", "p90", "p95", "p99"];
39
+ export const defaultChartSummary = ["min", "max", "avg", "current"];
40
+ export const chartSummaryLabel = (stat) => stat.startsWith("p") ? stat : stat[0].toUpperCase() + stat.slice(1);
41
+ /** Linear interpolation between the closest ranks of sorted values. */
42
+ function percentile(sorted, fraction) {
43
+ const rank = (sorted.length - 1) * fraction;
44
+ const low = Math.floor(rank);
45
+ const high = Math.ceil(rank);
46
+ return sorted[low] + (sorted[high] - sorted[low]) * (rank - low);
47
+ }
48
+ export function seriesSummary(data, key, stats = defaultChartSummary) {
49
+ const unknown = stats.find(stat => !chartSummaryStats.includes(stat));
50
+ if (unknown)
51
+ throw new Error(`Unknown chart summary column: ${unknown}`);
39
52
  const values = data.map(sample => sample.values[key]).filter(measured);
40
- return {
41
- min: values.length ? Math.min(...values) : null,
42
- max: values.length ? Math.max(...values) : null,
43
- avg: values.length ? values.reduce((sum, value) => sum + value / values.length, 0) : null,
44
- current: measured(data.at(-1)?.values[key]) ? data.at(-1).values[key] : null,
53
+ const sorted = [...values].sort((a, b) => a - b);
54
+ const value = (stat) => {
55
+ if (stat === "current")
56
+ return measured(data.at(-1)?.values[key]) ? data.at(-1).values[key] : null;
57
+ if (!values.length)
58
+ return null;
59
+ if (stat === "min")
60
+ return sorted[0];
61
+ if (stat === "max")
62
+ return sorted.at(-1);
63
+ if (stat === "avg")
64
+ return values.reduce((sum, item) => sum + item / values.length, 0);
65
+ return percentile(sorted, Number(stat.slice(1)) / 100);
45
66
  };
67
+ return Object.fromEntries(stats.map(stat => [stat, value(stat)]));
46
68
  }
47
69
  export const formatChartTime = (timestamp) => new Date(timestamp).toISOString();
48
70
  export const formatChartValue = (value) => String(value);
@@ -0,0 +1,6 @@
1
+ import * as React from "react";
2
+ export declare const ChartFillContext: React.Context<boolean>;
3
+ export declare function useChartFill(frame: React.RefObject<HTMLElement | null>, key: string, fallback: number): {
4
+ fill: boolean;
5
+ height: number | undefined;
6
+ };
@@ -0,0 +1,42 @@
1
+ "use client";
2
+ import * as React from "react";
3
+ import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect.js";
4
+ /* True inside an expanded DashboardPanel. A Chart there takes the height its
5
+ box leaves after the legend and the closed exact-values summary, and no
6
+ longer synchronizes with the Charts left on the grid. Not exported. */
7
+ export const ChartFillContext = React.createContext(false);
8
+ // The last plot height per chart and window size, so reopening the same panel
9
+ // mounts its Chart once at the right height instead of measuring again.
10
+ const fillHeights = new Map();
11
+ export function useChartFill(frame, key, fallback) {
12
+ const fill = React.useContext(ChartFillContext);
13
+ const cacheKey = typeof window === "undefined" ? key : `${key}|${window.innerWidth}x${window.innerHeight}`;
14
+ const [height, setHeight] = React.useState(() => fill ? fillHeights.get(cacheKey) : undefined);
15
+ useIsomorphicLayoutEffect(() => {
16
+ const figure = frame.current;
17
+ const box = figure?.parentElement;
18
+ if (!fill || !figure || !box || typeof ResizeObserver === "undefined")
19
+ return;
20
+ const measure = () => {
21
+ const style = getComputedStyle(box);
22
+ const room = box.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
23
+ // Opened exact values scroll the box instead of squeezing the plot.
24
+ const details = figure.querySelector("details.chart-values");
25
+ const opened = details?.open ? details.offsetHeight - (details.querySelector("summary")?.offsetHeight ?? 0) : 0;
26
+ // scrollHeight never drops below the box, so measure the content itself.
27
+ const first = box.firstElementChild, last = box.lastElementChild;
28
+ const used = first && last ? last.getBoundingClientRect().bottom - first.getBoundingClientRect().top - opened : room;
29
+ const plots = figure.querySelectorAll(".chart-plot, .chart-empty");
30
+ const charts = Math.max(1, box.querySelectorAll(":scope > [data-slot='chart']").length);
31
+ const current = plots[0]?.offsetHeight ?? fallback;
32
+ const next = Math.max(fallback, Math.floor(current + (room - used) / charts / Math.max(1, plots.length)));
33
+ fillHeights.set(cacheKey, next);
34
+ setHeight(next);
35
+ };
36
+ const observer = new ResizeObserver(measure);
37
+ observer.observe(box);
38
+ measure();
39
+ return () => observer.disconnect();
40
+ }, [fill, frame, cacheKey, fallback]);
41
+ return { fill, height: fill ? height : undefined };
42
+ }
@@ -1,11 +1,14 @@
1
1
  import * as React from "react";
2
- import { type ChartSample, type ChartSeries } from "./chart-data.js";
2
+ import { type ChartSample, type ChartSeries, type ChartSummaryStat } from "./chart-data.js";
3
+ export type { ChartSummaryStat } from "./chart-data.js";
3
4
  export type ChartLegendProps = React.ComponentProps<"div"> & {
4
5
  data: readonly ChartSample[];
5
6
  series: readonly ChartSeries[];
6
7
  label: string;
7
8
  formatValue?: (value: number) => string;
8
9
  variant?: "table" | "inline" | "sidebar";
10
+ /** Columns of the table legend, in order. The inline and sidebar legends ignore it. */
11
+ summary?: readonly ChartSummaryStat[];
9
12
  activeTimestamp?: number | null;
10
13
  formatTime?: (timestamp: number) => string;
11
14
  highlightSeries?: string | null;
@@ -15,4 +18,4 @@ export declare function ChartSeriesLabel({ series, index }: {
15
18
  series: ChartSeries;
16
19
  index: number;
17
20
  }): React.JSX.Element;
18
- export declare function ChartLegend({ data, series, label, formatValue, variant, activeTimestamp, formatTime, highlightSeries, onHighlightSeriesChange, className, ...props }: ChartLegendProps): React.JSX.Element;
21
+ export declare function ChartLegend({ data, series, label, formatValue, variant, summary: stats, activeTimestamp, formatTime, highlightSeries, onHighlightSeriesChange, className, ...props }: ChartLegendProps): React.JSX.Element;
@@ -1,12 +1,12 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { clsx as cn } from "clsx";
4
- import { chartColor, chartSlot, formatChartTime, formatChartValue, measured, seriesSummary, validateChart } from "./chart-data.js";
4
+ import { chartColor, chartSlot, chartSummaryLabel, defaultChartSummary, formatChartTime, formatChartValue, measured, seriesSummary, validateChart } from "./chart-data.js";
5
5
  export function ChartSeriesLabel({ series, index }) {
6
6
  const slot = chartSlot(series, index);
7
7
  return _jsxs("span", { className: "chart-series-label", children: [_jsx("svg", { className: "chart-series-swatch", "aria-hidden": "true", width: "28", height: "12", viewBox: "0 0 28 12", children: _jsx("path", { d: "M0 6H28", stroke: chartColor(slot), strokeWidth: "2" }) }), _jsxs("span", { children: [slot, ". ", series.label] })] });
8
8
  }
9
- export function ChartLegend({ data, series, label, formatValue = formatChartValue, variant = "table", activeTimestamp, formatTime = formatChartTime, highlightSeries, onHighlightSeriesChange, className, ...props }) {
9
+ export function ChartLegend({ data, series, label, formatValue = formatChartValue, variant = "table", summary: stats = defaultChartSummary, activeTimestamp, formatTime = formatChartTime, highlightSeries, onHighlightSeriesChange, className, ...props }) {
10
10
  validateChart(data, series);
11
11
  const seriesLabel = (item, index) => onHighlightSeriesChange
12
12
  ? _jsx("button", { type: "button", className: "chart-series-button", "aria-pressed": highlightSeries === item.key, onClick: () => onHighlightSeriesChange(highlightSeries === item.key ? null : item.key), children: _jsx(ChartSeriesLabel, { series: item, index: index }) })
@@ -16,8 +16,8 @@ export function ChartLegend({ data, series, label, formatValue = formatChartValu
16
16
  return _jsxs("div", { ...props, "data-slot": "chart-legend", "data-variant": variant, className: cn("chart-legend", `chart-legend-${variant}`, className), "aria-label": label, "aria-live": variant === "sidebar" ? "polite" : undefined, children: [_jsx("span", { className: "chart-legend-caption", children: variant === "sidebar" && activeTimestamp != null
17
17
  ? formatTime(activeTimestamp) : "Current" }), _jsx("dl", { children: series.map((item, index) => _jsxs("div", { children: [_jsx("dt", { children: seriesLabel(item, index) }), _jsx("dd", { children: measured(sample?.values[item.key]) ? formatValue(sample.values[item.key]) : "Not collected" })] }, item.key)) })] });
18
18
  }
19
- return _jsx("div", { ...props, "data-slot": "chart-legend", "data-variant": "table", className: cn("chart-table-scroll", className), children: _jsxs("table", { className: "chart-table", children: [_jsx("caption", { children: label }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Series" }), ["Min", "Max", "Avg", "Current"].map(name => _jsx("th", { scope: "col", children: name }, name))] }) }), _jsx("tbody", { children: series.map((item, index) => {
20
- const summary = seriesSummary(data, item.key);
21
- return _jsxs("tr", { children: [_jsx("th", { scope: "row", children: seriesLabel(item, index) }), ["min", "max", "avg", "current"].map(stat => _jsx("td", { children: summary[stat] === null ? "Not collected" : formatValue(summary[stat]) }, stat))] }, item.key);
19
+ return _jsx("div", { ...props, "data-slot": "chart-legend", "data-variant": "table", className: cn("chart-table-scroll", className), children: _jsxs("table", { className: "chart-table", children: [_jsx("caption", { children: label }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Series" }), stats.map(stat => _jsx("th", { scope: "col", children: chartSummaryLabel(stat) }, stat))] }) }), _jsx("tbody", { children: series.map((item, index) => {
20
+ const summary = seriesSummary(data, item.key, stats);
21
+ return _jsxs("tr", { children: [_jsx("th", { scope: "row", children: seriesLabel(item, index) }), stats.map(stat => _jsx("td", { children: summary[stat] === null ? "Not collected" : formatValue(summary[stat]) }, stat))] }, item.key);
22
22
  }) })] }) });
23
23
  }
package/dist/chart.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as React from "react";
2
2
  import { type ChartLayout, type ChartLegendPlacement, type ChartTreatmentProps } from "./chart-style.js";
3
- import { type ChartSample, type ChartSeries } from "./chart-data.js";
3
+ import { type ChartSample, type ChartSeries, type ChartSummaryStat } from "./chart-data.js";
4
+ import type { TimeRange } from "./time-range-control.js";
4
5
  export type { ChartSample, ChartSeries } from "./chart-data.js";
5
6
  export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
6
7
  data: readonly ChartSample[];
@@ -11,6 +12,8 @@ export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
11
12
  layout?: ChartLayout;
12
13
  /** Overrides the inherited data-chart-legend, otherwise table. */
13
14
  legend?: ChartLegendPlacement;
15
+ /** Columns of the table legend, in order. Default min, max, avg and current. */
16
+ summary?: readonly ChartSummaryStat[];
14
17
  /** A controlled highlight. Pass null to clear it, or omit for local selection. */
15
18
  highlightSeries?: string | null;
16
19
  onHighlightSeriesChange?: (key: string | null) => void;
@@ -21,5 +24,8 @@ export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
21
24
  formatValue?: (value: number) => string;
22
25
  min?: number;
23
26
  max?: number;
27
+ /** Drag across the plot with a mouse or pen to select samples from one
28
+ timestamp to another. TimeRangeControl stays the keyboard and touch path. */
29
+ onRangeSelect?: (range: TimeRange) => void;
24
30
  } & ChartTreatmentProps;
25
- export declare function Chart({ data, series, label, variant, layout: layoutProp, legend: legendProp, highlightSeries, onHighlightSeriesChange, height: heightProp, syncId, formatTime, formatValue, min, max, chartStyle, chartLine, chartFill, ref, className, ...props }: ChartProps): React.JSX.Element;
31
+ export declare function Chart({ data, series, label, variant, layout: layoutProp, legend: legendProp, summary, highlightSeries, onHighlightSeriesChange, height: heightProp, syncId, formatTime, formatValue, min, max, onRangeSelect, chartStyle, chartLine, chartFill, ref, className, ...props }: ChartProps): React.JSX.Element;
package/dist/chart.js CHANGED
@@ -5,8 +5,9 @@ import { clsx as cn } from "clsx";
5
5
  import { Area, CartesianGrid, ComposedChart, Line, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
6
6
  import { ChartLegend, ChartSeriesLabel } from "./chart-legend.js";
7
7
  import { ChartDot, ChartPattern, pixelCurve, useChartPresentation, useChartStyle } from "./chart-style.js";
8
+ import { useChartFill } from "./chart-fill.js";
8
9
  import { chartColor, chartSlot, formatChartTime, formatChartValue, measured, validateChart } from "./chart-data.js";
9
- export function Chart({ data, series, label, variant = "line", layout: layoutProp, legend: legendProp, highlightSeries, onHighlightSeriesChange, height: heightProp, syncId, formatTime = formatChartTime, formatValue = formatChartValue, min, max, chartStyle, chartLine, chartFill, ref, className, ...props }) {
10
+ export function Chart({ data, series, label, variant = "line", layout: layoutProp, legend: legendProp, summary, highlightSeries, onHighlightSeriesChange, height: heightProp, syncId, formatTime = formatChartTime, formatValue = formatChartValue, min, max, onRangeSelect, chartStyle, chartLine, chartFill, ref, className, ...props }) {
10
11
  const id = React.useId();
11
12
  const frame = React.useRef(null);
12
13
  const { line, fill } = useChartStyle(frame, { chartStyle, chartLine, chartFill });
@@ -14,10 +15,26 @@ export function Chart({ data, series, label, variant = "line", layout: layoutPro
14
15
  const legend = presentation.legend;
15
16
  // An inherited split cannot hold a stack, so a stacked chart keeps one plot.
16
17
  const layout = !layoutProp && presentation.layout === "split" && variant === "stacked-area" ? "standard" : presentation.layout;
17
- const height = heightProp ?? (layout === "compact" ? 165 : layout === "split" ? 90 : 200);
18
+ const defaultHeight = layout === "compact" ? 165 : layout === "split" ? 90 : 200;
19
+ // In an expanded DashboardPanel the plot takes the room the dialog leaves.
20
+ const expanded = useChartFill(frame, `${label}|${layout}|${legend}`, defaultHeight);
21
+ const height = heightProp ?? expanded.height ?? defaultHeight;
18
22
  const bold = line === "stepped" || line === "curved";
19
23
  const [localHighlight, setLocalHighlight] = React.useState(null);
20
24
  const [activeTimestamp, setActiveTimestamp] = React.useState(null);
25
+ // A drag moves the band in the DOM. Rendering the Chart on every pointer
26
+ // move is far too slow for a stack of many series.
27
+ const drag = React.useRef(null);
28
+ const stopDrag = React.useRef(null);
29
+ React.useEffect(() => () => stopDrag.current?.(), []);
30
+ const paintDrag = () => frame.current?.querySelectorAll(".chart-range-band").forEach(band => {
31
+ const range = drag.current;
32
+ band.hidden = !range || range.from === range.to;
33
+ if (!range)
34
+ return;
35
+ band.style.left = `${Math.min(range.x1, range.x2)}px`;
36
+ band.style.width = `${Math.abs(range.x2 - range.x1)}px`;
37
+ });
21
38
  const requestedHighlight = highlightSeries === undefined ? localHighlight : highlightSeries;
22
39
  const highlighted = series.some(item => item.key === requestedHighlight) ? requestedHighlight : null;
23
40
  const highlight = (key) => {
@@ -53,30 +70,69 @@ export function Chart({ data, series, label, variant = "line", layout: layoutPro
53
70
  else
54
71
  splitMin -= Math.max(1, Math.abs(splitMin) * 0.1);
55
72
  }
56
- const renderPlot = (indices, lane) => _jsx("div", { className: "chart-plot", style: { height }, children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(ComposedChart, { data: plot, syncId: syncId ?? (layout === "split" ? id : undefined), syncMethod: "value", accessibilityLayer: true, "aria-label": lane ? `${label}: ${lane.label}` : label, "aria-describedby": `${id}-help`, margin: { top: 8, right: 20, bottom: 0, left: 0 }, children: [_jsx("defs", { children: indices.map(index => _jsx(ChartPattern, { id: `${id}-fill-${index}`, color: chartColor(chartSlot(series[index], index)), fill: fill }, series[index].key)) }), _jsx(CartesianGrid, { vertical: false, stroke: "var(--color-border)", strokeWidth: 0.5 }), _jsx(XAxis, { dataKey: "timestamp", type: "number", domain: ["dataMin", "dataMax"], scale: "time", axisLine: false, tickLine: false, tickFormatter: formatTime, minTickGap: 48, tick: { fill: "var(--color-muted-foreground)" } }), _jsx(YAxis, { domain: layout === "split" ? [splitMin, splitMax]
57
- : [min ?? (variant === "stacked-area" ? 0 : "auto"), max ?? "auto"], tickCount: 3, axisLine: false, tickLine: false, tickFormatter: formatValue, tick: { fill: "var(--color-muted-foreground)" }, width: 56 }), _jsx(Tooltip, { filterNull: false, isAnimationActive: false, cursor: { stroke: "var(--color-border-strong)", strokeDasharray: "3 3" }, content: ({ active, label: timestamp }) => _jsx(ChartReadout, { active: active, timestamp: Number(timestamp), data: data, series: series, formatTime: formatTime, displayValue: displayValue, sidebar: legend === "sidebar", onInspect: legend === "sidebar" && (!lane || indices[0] === 0) ? setActiveTimestamp : undefined }) }), indices.map(index => {
58
- const item = series[index];
59
- const slot = chartSlot(item, index);
60
- const dimmed = highlighted !== null && item.key !== highlighted;
61
- const common = { dataKey: `values.${index}`, name: item.label, stroke: chartColor(slot),
62
- strokeWidth: item.key === highlighted ? (bold ? 2.7 : 2.2) : bold ? 2 : 1.5,
63
- strokeOpacity: dimmed ? 0.3 : 1, strokeLinecap: line === "curved" ? "round" : "butt",
64
- strokeLinejoin: line === "curved" ? "round" : "miter",
65
- connectNulls: false, isAnimationActive: false,
66
- dot: (dotProps) => {
67
- const at = dotProps.index ?? -1;
68
- const isolated = measured(plot[at]?.values[index])
69
- && !measured(plot[at - 1]?.values[index]) && !measured(plot[at + 1]?.values[index]);
70
- return _jsx(ChartDot, { cx: dotProps.cx, cy: dotProps.cy, r: isolated ? 3 : 0, line: line, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }, at);
71
- }, activeDot: (dotProps) => _jsx(ChartDot, { ...dotProps, line: line, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }) };
72
- const curve = line === "stepped" ? pixelCurve : line === "curved" && variant === "line" ? "monotone" : "linear";
73
- // A stack needs an area even without a fill; it uses the tint.
74
- const textured = fill === "dots" || fill === "squares" || fill === "scanlines";
75
- return variant === "stacked-area" || fill !== "none"
76
- ? _jsx(Area, { ...common, type: curve, stackId: variant === "stacked-area" ? "total" : undefined, fill: textured ? `url(#${id}-fill-${index})` : chartColor(slot), fillOpacity: dimmed ? 0.06 : 0.2 }, item.key)
77
- : _jsx(Line, { ...common, type: curve }, item.key);
78
- })] }) }) });
79
- const legendContent = _jsx(ChartLegend, { data: data, series: series, label: `${label}: summary`, variant: legend, formatValue: formatValue, formatTime: formatTime, activeTimestamp: legend === "sidebar" && hasData ? activeTimestamp : null, highlightSeries: highlighted, onHighlightSeriesChange: highlight });
73
+ const sampleAt = (index) => typeof index === "number" ? plot[index]?.timestamp
74
+ : typeof index === "string" && index !== "" ? plot[Number(index)]?.timestamp : undefined;
75
+ const rangeHandlers = onRangeSelect && plot.length > 1 ? {
76
+ onMouseDown: (state, event) => {
77
+ const at = sampleAt(state.activeTooltipIndex), x = state.activeCoordinate?.x;
78
+ if (at === undefined || x === undefined || event.button !== 0)
79
+ return;
80
+ stopDrag.current?.();
81
+ drag.current = { from: at, to: at, x1: x, x2: x };
82
+ // The drag may end outside the plot, and Escape cancels it.
83
+ const end = () => {
84
+ const range = drag.current;
85
+ stop();
86
+ if (range && range.from !== range.to)
87
+ onRangeSelect({ from: Math.min(range.from, range.to), to: Math.max(range.from, range.to) });
88
+ };
89
+ const cancel = (key) => { if (key.key === "Escape") {
90
+ key.preventDefault();
91
+ stop();
92
+ } };
93
+ const stop = () => {
94
+ drag.current = null;
95
+ paintDrag();
96
+ document.removeEventListener("mouseup", end);
97
+ document.removeEventListener("keydown", cancel);
98
+ stopDrag.current = null;
99
+ };
100
+ document.addEventListener("mouseup", end);
101
+ document.addEventListener("keydown", cancel);
102
+ stopDrag.current = stop;
103
+ },
104
+ onMouseMove: (state) => {
105
+ const at = sampleAt(state.activeTooltipIndex), x = state.activeCoordinate?.x;
106
+ if (!drag.current || at === undefined || x === undefined || at === drag.current.to)
107
+ return;
108
+ drag.current = { ...drag.current, to: at, x2: x };
109
+ paintDrag();
110
+ },
111
+ } : undefined;
112
+ const renderPlot = (indices, lane) => _jsxs("div", { className: "chart-plot", style: { height }, "data-range-select": rangeHandlers ? "" : undefined, children: [_jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(ComposedChart, { data: plot, syncId: (expanded.fill ? undefined : syncId) ?? (layout === "split" ? id : undefined), syncMethod: "value", accessibilityLayer: true, "aria-label": lane ? `${label}: ${lane.label}` : label, "aria-describedby": `${id}-help`, margin: { top: 8, right: 20, bottom: 0, left: 0 }, ...rangeHandlers, children: [_jsx("defs", { children: indices.map(index => _jsx(ChartPattern, { id: `${id}-fill-${index}`, color: chartColor(chartSlot(series[index], index)), fill: fill }, series[index].key)) }), _jsx(CartesianGrid, { vertical: false, stroke: "var(--color-border)", strokeWidth: 0.5 }), _jsx(XAxis, { dataKey: "timestamp", type: "number", domain: ["dataMin", "dataMax"], scale: "time", axisLine: false, tickLine: false, tickFormatter: formatTime, minTickGap: 48, tick: { fill: "var(--color-muted-foreground)" } }), _jsx(YAxis, { domain: layout === "split" ? [splitMin, splitMax]
113
+ : [min ?? (variant === "stacked-area" ? 0 : "auto"), max ?? "auto"], tickCount: 3, axisLine: false, tickLine: false, tickFormatter: formatValue, tick: { fill: "var(--color-muted-foreground)" }, width: 56 }), _jsx(Tooltip, { filterNull: false, isAnimationActive: false, cursor: { stroke: "var(--color-border-strong)", strokeDasharray: "3 3" }, content: ({ active, label: timestamp }) => _jsx(ChartReadout, { active: active, timestamp: Number(timestamp), data: data, series: series, formatTime: formatTime, displayValue: displayValue, sidebar: legend === "sidebar", onInspect: legend === "sidebar" && (!lane || indices[0] === 0) ? setActiveTimestamp : undefined }) }), indices.map(index => {
114
+ const item = series[index];
115
+ const slot = chartSlot(item, index);
116
+ const dimmed = highlighted !== null && item.key !== highlighted;
117
+ const common = { dataKey: `values.${index}`, name: item.label, stroke: chartColor(slot),
118
+ strokeWidth: item.key === highlighted ? (bold ? 2.7 : 2.2) : bold ? 2 : 1.5,
119
+ strokeOpacity: dimmed ? 0.3 : 1, strokeLinecap: line === "curved" ? "round" : "butt",
120
+ strokeLinejoin: line === "curved" ? "round" : "miter",
121
+ connectNulls: false, isAnimationActive: false,
122
+ dot: (dotProps) => {
123
+ const at = dotProps.index ?? -1;
124
+ const isolated = measured(plot[at]?.values[index])
125
+ && !measured(plot[at - 1]?.values[index]) && !measured(plot[at + 1]?.values[index]);
126
+ return _jsx(ChartDot, { cx: dotProps.cx, cy: dotProps.cy, r: isolated ? 3 : 0, line: line, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }, at);
127
+ }, activeDot: (dotProps) => _jsx(ChartDot, { ...dotProps, line: line, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }) };
128
+ const curve = line === "stepped" ? pixelCurve : line === "curved" && variant === "line" ? "monotone" : "linear";
129
+ // A stack needs an area even without a fill; it uses the tint.
130
+ const textured = fill === "dots" || fill === "squares" || fill === "scanlines";
131
+ return variant === "stacked-area" || fill !== "none"
132
+ ? _jsx(Area, { ...common, type: curve, stackId: variant === "stacked-area" ? "total" : undefined, fill: textured ? `url(#${id}-fill-${index})` : chartColor(slot), fillOpacity: dimmed ? 0.06 : 0.2 }, item.key)
133
+ : _jsx(Line, { ...common, type: curve }, item.key);
134
+ })] }) }), rangeHandlers && _jsx("div", { className: "chart-range-band", hidden: true, "aria-hidden": "true" })] });
135
+ const legendContent = _jsx(ChartLegend, { data: data, series: series, label: `${label}: summary`, variant: legend, summary: summary, formatValue: formatValue, formatTime: formatTime, activeTimestamp: legend === "sidebar" && hasData ? activeTimestamp : null, highlightSeries: highlighted, onHighlightSeriesChange: highlight });
80
136
  return _jsxs("figure", { ...props, ref: element => {
81
137
  frame.current = element;
82
138
  if (typeof ref === "function")
@@ -1,6 +1,8 @@
1
1
  import * as React from "react";
2
2
  import { type GridPaneProps, type PaneGridProps } from "./pane-grid.js";
3
3
  export type DashboardGridProps = PaneGridProps;
4
- export declare function DashboardGrid({ className, ...props }: DashboardGridProps): React.JSX.Element;
5
- export type DashboardPanelProps = GridPaneProps;
6
- export declare function DashboardPanel({ className, ...props }: DashboardPanelProps): React.JSX.Element;
4
+ export declare function DashboardGrid({ className, onPointerMove, onPointerLeave, ...props }: DashboardGridProps): React.JSX.Element;
5
+ export type DashboardPanelProps = GridPaneProps & {
6
+ expandable?: boolean;
7
+ };
8
+ export declare function DashboardPanel({ className, expandable, id, title, actions, children, ref, ...props }: DashboardPanelProps): React.JSX.Element;
@@ -1,9 +1,103 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ "use client";
2
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
2
4
  import { clsx as cn } from "clsx";
5
+ import { Maximize2, X } from "lucide-react";
6
+ import { Button } from "./button.js";
7
+ import { ChartFillContext } from "./chart-fill.js";
8
+ import { Dialog, DialogBody, DialogClose, DialogContent, DialogHeader, DialogTitle } from "./dialog.js";
3
9
  import { GridPane, PaneGrid } from "./pane-grid.js";
4
- export function DashboardGrid({ className, ...props }) {
5
- return _jsx(PaneGrid, { "data-slot": "dashboard-grid", className: cn("dashboard-grid", className), ...props });
10
+ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./tooltip.js";
11
+ const ExpandContext = React.createContext(null);
12
+ const typing = (target) => target instanceof Element && !!target.closest("input, textarea, select, [contenteditable]:not([contenteditable='false'])");
13
+ export function DashboardGrid({ className, onPointerMove, onPointerLeave, ...props }) {
14
+ const grid = React.useRef(null);
15
+ const panels = React.useRef(new Map());
16
+ // A click on a pane head starts a move and does not focus it, so a mouse
17
+ // reader rarely has a focused pane. The latest input wins: after the pointer
18
+ // moves, V expands the pane under it; after another key, the focused pane.
19
+ const pointed = React.useRef(null);
20
+ const pointerLast = React.useRef(false);
21
+ const context = React.useMemo(() => ({
22
+ register: (id, expand) => {
23
+ panels.current.set(id, expand);
24
+ return () => { if (panels.current.get(id) === expand)
25
+ panels.current.delete(id); };
26
+ },
27
+ }), []);
28
+ React.useEffect(() => {
29
+ const listener = (event) => {
30
+ if (event.key !== "v" && event.key !== "V") {
31
+ pointerLast.current = false;
32
+ return;
33
+ }
34
+ if (event.ctrlKey || event.metaKey || event.altKey || event.repeat || event.defaultPrevented || typing(event.target))
35
+ return;
36
+ if (document.querySelector("[role='dialog'][data-state='open']"))
37
+ return;
38
+ const target = event.target instanceof Element ? event.target : null;
39
+ const pane = target?.closest("[data-pane-id]");
40
+ const focused = pane && grid.current?.contains(pane) ? pane.dataset.paneId : undefined;
41
+ const id = pointerLast.current && pointed.current ? pointed.current
42
+ : focused ?? (target === document.body ? pointed.current : null);
43
+ const expand = id ? panels.current.get(id) : undefined;
44
+ if (!expand)
45
+ return;
46
+ event.preventDefault();
47
+ expand(id === focused ? target : null);
48
+ };
49
+ document.addEventListener("keydown", listener);
50
+ return () => document.removeEventListener("keydown", listener);
51
+ }, []);
52
+ return _jsx(ExpandContext.Provider, { value: context, children: _jsx(PaneGrid, { ref: grid, "data-slot": "dashboard-grid", className: cn("dashboard-grid", className), onPointerMove: event => {
53
+ pointed.current = event.target.closest("[data-pane-id]")?.dataset.paneId ?? null;
54
+ pointerLast.current = true;
55
+ onPointerMove?.(event);
56
+ }, onPointerLeave: event => { pointed.current = null; onPointerLeave?.(event); }, ...props }) });
6
57
  }
7
- export function DashboardPanel({ className, ...props }) {
8
- return _jsx(GridPane, { "data-slot": "dashboard-panel", className: cn("dashboard-panel", className), ...props });
58
+ export function DashboardPanel({ className, expandable = false, id, title, actions, children, ref, ...props }) {
59
+ const grid = React.useContext(ExpandContext);
60
+ const pane = React.useRef(null);
61
+ const body = React.useRef(null);
62
+ const opener = React.useRef(null);
63
+ const [open, setOpen] = React.useState(false);
64
+ const expand = React.useCallback((from) => {
65
+ // Return focus where it was: the Expand button, a control in the pane, or
66
+ // the head when the pointer opened it.
67
+ opener.current = from instanceof HTMLElement && pane.current?.contains(from) ? from
68
+ : pane.current?.querySelector("[data-slot='grid-pane-head']") ?? null;
69
+ setOpen(true);
70
+ }, []);
71
+ React.useEffect(() => expandable && grid ? grid.register(id, expand) : undefined, [expandable, grid, id, expand]);
72
+ const button = expandable && _jsx(TooltipProvider, { children: _jsxs(Tooltip, { children: [_jsx(TooltipTrigger, { asChild: true, children: _jsx(Button, { className: "btn-icon", size: "sm", variant: "ghost", "aria-label": `Expand ${title}`, "aria-keyshortcuts": "v", onClick: event => expand(event.currentTarget), children: _jsx(Maximize2, { className: "icon icon-sm", "aria-hidden": "true" }) }) }), _jsx(TooltipContent, { children: "Expand" })] }) });
73
+ return _jsxs(_Fragment, { children: [_jsx(GridPane, { "data-slot": "dashboard-panel", className: cn("dashboard-panel", className), id: id, title: title, ref: element => {
74
+ pane.current = element;
75
+ if (typeof ref === "function")
76
+ return ref(element);
77
+ if (ref)
78
+ ref.current = element;
79
+ }, actions: expandable ? _jsxs(_Fragment, { children: [actions, button] }) : actions, ...props, children: children }), expandable && _jsx(Dialog, { open: open, onOpenChange: setOpen, children: open && _jsxs(DialogContent, { className: "dashboard-panel-dialog", "aria-describedby": undefined,
80
+ // The chart plot, so Left and Right inspect at once. Recharts makes the
81
+ // plot focusable only once it has measured, so wait a few frames; any
82
+ // other content gets the first control, as a Dialog does.
83
+ onOpenAutoFocus: event => {
84
+ const plot = () => body.current?.querySelector(".chart-plot [tabindex='0']");
85
+ if (!body.current?.querySelector(".chart-plot"))
86
+ return;
87
+ event.preventDefault();
88
+ let tries = 10;
89
+ const focus = () => { const target = plot(); if (target)
90
+ target.focus();
91
+ else if (tries-- > 0)
92
+ requestAnimationFrame(focus); };
93
+ focus();
94
+ },
95
+ // Radix returns focus to a Dialog Trigger. The opener here is the pane
96
+ // head or a control in it, so focus goes back by hand.
97
+ onCloseAutoFocus: event => { event.preventDefault(); opener.current?.focus(); }, onKeyDown: event => {
98
+ if ((event.key === "v" || event.key === "V") && !event.ctrlKey && !event.metaKey && !event.altKey && !typing(event.target)) {
99
+ event.preventDefault();
100
+ setOpen(false);
101
+ }
102
+ }, children: [_jsxs(DialogHeader, { className: "dashboard-panel-dialog-head", children: [_jsx(DialogTitle, { children: title }), _jsx(DialogClose, { asChild: true, children: _jsx(Button, { className: "btn-icon", size: "sm", variant: "ghost", "aria-label": "Close", "aria-keyshortcuts": "Escape v", children: _jsx(X, { className: "icon icon-sm", "aria-hidden": "true" }) }) })] }), _jsx(DialogBody, { ref: body, className: "dashboard-panel-dialog-body", children: _jsx(ChartFillContext.Provider, { value: true, children: children }) })] }) })] });
9
103
  }
package/dist/styles.css CHANGED
@@ -436,6 +436,32 @@
436
436
  [data-slot="toast"][data-variant="warning"] { border-color: var(--color-warning-border); }
437
437
  [data-slot="toast"][data-variant="error"] { border-color: var(--color-danger-border); }
438
438
 
439
+ /* An expanded DashboardPanel: the dialog surface fills the viewport less a
440
+ margin, and edge to edge on a phone. The body gives its Chart the height
441
+ left after the head. */
442
+ .kiso-react-dialog.dashboard-panel-dialog {
443
+ inset: var(--spacing-lg);
444
+ transform: none;
445
+ width: auto;
446
+ max-height: none;
447
+ }
448
+ .kiso-react-dialog .dialog-header.dashboard-panel-dialog-head {
449
+ display: flex; align-items: center; gap: var(--spacing-md);
450
+ padding: var(--spacing-md) var(--spacing-lg);
451
+ border-bottom: 1px solid var(--color-border);
452
+ }
453
+ .dashboard-panel-dialog-head > h2 { flex: 1 1 0; min-width: 0; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
454
+ .kiso-react-dialog .dialog-body.dashboard-panel-dialog-body {
455
+ flex: 1 1 auto; min-height: 0; overflow-y: auto; align-content: start;
456
+ padding: var(--spacing-lg);
457
+ }
458
+ /* The dialog title names the chart, as the pane title does on the grid. */
459
+ .dashboard-panel-dialog-body > .framed-chart > figcaption { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
460
+ @media (max-width: 640px) {
461
+ .kiso-react-dialog.dashboard-panel-dialog { inset: 0; border: 0; border-radius: 0; }
462
+ .kiso-react-dialog .dialog-body.dashboard-panel-dialog-body { padding: var(--spacing-md); }
463
+ }
464
+
439
465
  /* A Drawer is the dialog surface moved to an edge. */
440
466
  .kiso-react-drawer {
441
467
  position: fixed;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@momoi-labs/kiso-react",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Kiso React components built with shadcn/ui and Radix",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,7 +32,7 @@
32
32
  "prepack": "npm run build"
33
33
  },
34
34
  "dependencies": {
35
- "@momoi-labs/kiso": "^0.22.0",
35
+ "@momoi-labs/kiso": "^0.23.0",
36
36
  "class-variance-authority": "0.7.1",
37
37
  "clsx": "2.1.1",
38
38
  "radix-ui": "1.6.7",