@momoi-labs/kiso-react 0.17.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.
package/README.md CHANGED
@@ -329,7 +329,7 @@ code retains its upstream MIT notice in `SHADCN-LICENSE`.
329
329
 
330
330
  ## Metrics dashboards
331
331
 
332
- Chart supports `line` and `stacked-area`, one to five named series, null gaps,
332
+ Chart supports `line` and `stacked-area`, any number of named series, null gaps,
333
333
  UTC timestamps, synchronized inspection through `syncId`, a summary legend,
334
334
  and a disclosure containing every exact sample. Pass the same timestamp grid
335
335
  to synchronized panels. Put the common unit in `label`.
@@ -7,18 +7,17 @@ export type ChartSeries = {
7
7
  key: string;
8
8
  label: string;
9
9
  /** Stable identity across panels. Defaults to its position, starting at 1. */
10
- slot?: 1 | 2 | 3 | 4 | 5;
10
+ slot?: number;
11
11
  };
12
12
  export declare const chartStrokes: readonly [undefined, "8 4", "2 3", "8 3 2 3", "12 3 2 3 2 3"];
13
13
  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;
@@ -1,16 +1,30 @@
1
1
  export const chartStrokes = [undefined, "8 4", "2 3", "8 3 2 3", "12 3 2 3 2 3"];
2
2
  export const chartSlot = (series, index) => series.slot ?? index + 1;
3
- export const chartColor = (slot) => `var(--color-chart-${slot})`;
3
+ /* Slots 1 to 5 use the validated palette. Later slots get a generated
4
+ color in the palette's lightness band for each theme. The first four take
5
+ the hues between the palette's own (magenta, teal, lime, orange); after
6
+ that the hue turns by the golden angle and the lightness alternates.
7
+ Generated colors are not checked for color-vision deficiency, so the
8
+ numbered label and exact values carry identity. */
9
+ const gapHues = [330, 195, 115, 50];
10
+ export const chartColor = (slot) => {
11
+ if (slot <= 5)
12
+ return `var(--color-chart-${slot})`;
13
+ const extra = slot - 6;
14
+ const hue = gapHues[extra] ?? Math.round((gapHues[0] + extra * 137.508) % 360);
15
+ const shift = extra >= gapHues.length && extra % 2 ? 0.08 : 0;
16
+ return `light-dark(oklch(${0.55 - shift} 0.13 ${hue}), oklch(${0.8 + shift} 0.12 ${hue}))`;
17
+ };
4
18
  export const measured = (value) => typeof value === "number" && Number.isFinite(value);
5
19
  export function validateChart(data, series) {
6
- if (series.length < 1 || series.length > 5)
7
- throw new RangeError("Charts require one to five series.");
20
+ if (series.length < 1)
21
+ throw new RangeError("Charts require at least one series.");
8
22
  const keys = new Set();
9
23
  const slots = new Set();
10
24
  series.forEach((item, index) => {
11
25
  const slot = chartSlot(item, index);
12
- if (!item.key || !item.label || keys.has(item.key) || slots.has(slot) || slot < 1 || slot > 5 || !Number.isInteger(slot)) {
13
- throw new RangeError("Chart series require unique keys, slots from 1 to 5, and labels.");
26
+ if (!item.key || !item.label || keys.has(item.key) || slots.has(slot) || slot < 1 || !Number.isInteger(slot)) {
27
+ throw new RangeError("Chart series require unique keys, positive integer slots, and labels.");
14
28
  }
15
29
  keys.add(item.key);
16
30
  slots.add(slot);
@@ -21,14 +35,36 @@ export function validateChart(data, series) {
21
35
  }
22
36
  });
23
37
  }
24
- 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}`);
25
52
  const values = data.map(sample => sample.values[key]).filter(measured);
26
- return {
27
- min: values.length ? Math.min(...values) : null,
28
- max: values.length ? Math.max(...values) : null,
29
- avg: values.length ? values.reduce((sum, value) => sum + value / values.length, 0) : null,
30
- 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);
31
66
  };
67
+ return Object.fromEntries(stats.map(stat => [stat, value(stat)]));
32
68
  }
33
69
  export const formatChartTime = (timestamp) => new Date(timestamp).toISOString();
34
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
  }
@@ -1,19 +1,38 @@
1
1
  import * as React from "react";
2
2
  import { Line } from "recharts";
3
+ export type ChartLine = "straight" | "stepped" | "curved";
4
+ export type ChartFill = "none" | "dots" | "tint" | "squares" | "scanlines";
3
5
  export type ChartStyle = "solid" | "pixel" | "halftone" | "rounded";
4
- export declare function useChartStyle(ref: React.RefObject<HTMLElement | null>, override?: ChartStyle, mounted?: boolean): ChartStyle;
6
+ export type ChartTreatment = {
7
+ line: ChartLine;
8
+ fill: ChartFill;
9
+ };
10
+ export declare const chartStylePresets: Record<ChartStyle, ChartTreatment>;
11
+ export type ChartTreatmentProps = {
12
+ chartStyle?: ChartStyle;
13
+ chartLine?: ChartLine;
14
+ chartFill?: ChartFill;
15
+ };
16
+ export declare function useChartStyle(ref: React.RefObject<HTMLElement | null>, override?: ChartTreatmentProps, mounted?: boolean): ChartTreatment;
17
+ export type ChartLayout = "standard" | "compact" | "split";
18
+ export type ChartLegendPlacement = "table" | "inline" | "sidebar";
19
+ export declare function useChartPresentation(ref: React.RefObject<HTMLElement | null>, layout?: ChartLayout, legend?: ChartLegendPlacement): {
20
+ layout: ChartLayout;
21
+ legend: ChartLegendPlacement;
22
+ };
5
23
  type CurveFactory = Exclude<NonNullable<React.ComponentProps<typeof Line>["type"]>, string>;
6
24
  export declare const pixelCurve: CurveFactory;
7
- export declare function ChartPattern({ id, color }: {
25
+ export declare function ChartPattern({ id, color, fill }: {
8
26
  id: string;
9
27
  color: string;
28
+ fill: ChartFill;
10
29
  }): React.JSX.Element;
11
- export declare function ChartDot({ cx, cy, r, fill, opacity, chartStyle }: {
30
+ export declare function ChartDot({ cx, cy, r, fill, opacity, line }: {
12
31
  cx?: number;
13
32
  cy?: number;
14
33
  r?: number;
15
34
  fill?: string;
16
35
  opacity?: number;
17
- chartStyle: ChartStyle;
36
+ line: ChartLine;
18
37
  }): React.JSX.Element | null;
19
38
  export {};
@@ -1,26 +1,67 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import * as React from "react";
4
- const chartStyles = ["solid", "pixel", "halftone", "rounded"];
4
+ export const chartStylePresets = {
5
+ solid: { line: "straight", fill: "none" },
6
+ pixel: { line: "stepped", fill: "none" },
7
+ halftone: { line: "straight", fill: "dots" },
8
+ rounded: { line: "curved", fill: "none" },
9
+ };
10
+ const chartLines = ["straight", "stepped", "curved"];
11
+ const chartFills = ["none", "dots", "tint", "squares", "scanlines"];
5
12
  // Geometry must update with a scoped appearance attribute, not just CSS paint.
6
- export function useChartStyle(ref, override, mounted = true) {
7
- const [inherited, setInherited] = React.useState("solid");
13
+ export function useChartStyle(ref, override = {}, mounted = true) {
14
+ const [inherited, setInherited] = React.useState(chartStylePresets.solid);
15
+ const fixed = override.chartStyle || (override.chartLine && override.chartFill);
16
+ React.useLayoutEffect(() => {
17
+ if (fixed)
18
+ return;
19
+ const element = ref.current;
20
+ if (!element)
21
+ return;
22
+ const read = () => {
23
+ const style = getComputedStyle(element);
24
+ const line = style.getPropertyValue("--chart-line").trim();
25
+ const fill = style.getPropertyValue("--chart-fill").trim();
26
+ setInherited(current => {
27
+ const next = { line: chartLines.includes(line) ? line : "straight", fill: chartFills.includes(fill) ? fill : "none" };
28
+ return next.line === current.line && next.fill === current.fill ? current : next;
29
+ });
30
+ };
31
+ read();
32
+ const observer = new MutationObserver(read);
33
+ observer.observe(element.ownerDocument.documentElement, { attributes: true, subtree: true, attributeFilter: ["data-chart-style", "data-chart-line", "data-chart-fill"] });
34
+ return () => observer.disconnect();
35
+ }, [ref, fixed, mounted]);
36
+ const base = override.chartStyle ? chartStylePresets[override.chartStyle] : inherited;
37
+ return { line: override.chartLine ?? base.line, fill: override.chartFill ?? base.fill };
38
+ }
39
+ const chartLayouts = ["standard", "compact", "split"];
40
+ const chartLegends = ["table", "inline", "sidebar"];
41
+ export function useChartPresentation(ref, layout, legend) {
42
+ const [inherited, setInherited] = React.useState({ layout: "standard", legend: "table" });
43
+ const fixed = !!layout && !!legend;
8
44
  React.useLayoutEffect(() => {
9
- if (override)
45
+ if (fixed)
10
46
  return;
11
47
  const element = ref.current;
12
48
  if (!element)
13
49
  return;
14
50
  const read = () => {
15
- const style = getComputedStyle(element).getPropertyValue("--chart-style").trim();
16
- setInherited(chartStyles.includes(style) ? style : "solid");
51
+ const style = getComputedStyle(element);
52
+ const nextLayout = style.getPropertyValue("--chart-layout").trim();
53
+ const nextLegend = style.getPropertyValue("--chart-legend").trim();
54
+ setInherited(current => {
55
+ const next = { layout: chartLayouts.includes(nextLayout) ? nextLayout : "standard", legend: chartLegends.includes(nextLegend) ? nextLegend : "table" };
56
+ return next.layout === current.layout && next.legend === current.legend ? current : next;
57
+ });
17
58
  };
18
59
  read();
19
60
  const observer = new MutationObserver(read);
20
- observer.observe(element.ownerDocument.documentElement, { attributes: true, subtree: true, attributeFilter: ["data-chart-style"] });
61
+ observer.observe(element.ownerDocument.documentElement, { attributes: true, subtree: true, attributeFilter: ["data-chart-layout", "data-chart-legend"] });
21
62
  return () => observer.disconnect();
22
- }, [ref, override, mounted]);
23
- return override ?? inherited;
63
+ }, [ref, fixed]);
64
+ return { layout: layout ?? inherited.layout, legend: legend ?? inherited.legend };
24
65
  }
25
66
  export const pixelCurve = context => {
26
67
  let areaLine = NaN, count = 0, previousX = 0, previousY = 0;
@@ -56,13 +97,17 @@ export const pixelCurve = context => {
56
97
  },
57
98
  };
58
99
  };
59
- export function ChartPattern({ id, color }) {
60
- return _jsx("pattern", { id: id, width: 4, height: 4, patternUnits: "userSpaceOnUse", children: _jsx("circle", { cx: 1, cy: 1, r: 0.8, fill: color }) });
100
+ /* The texture under a line. Dots and squares sit on a 4px screen; scanlines
101
+ are 1px rules every 3px. None and tint need no pattern. */
102
+ export function ChartPattern({ id, color, fill }) {
103
+ if (fill === "scanlines")
104
+ return _jsx("pattern", { id: id, width: 4, height: 3, patternUnits: "userSpaceOnUse", children: _jsx("rect", { width: 4, height: 1, fill: color }) });
105
+ return _jsx("pattern", { id: id, width: 4, height: 4, patternUnits: "userSpaceOnUse", children: fill === "squares" ? _jsx("rect", { width: 2, height: 2, fill: color }) : _jsx("circle", { cx: 1, cy: 1, r: 0.8, fill: color }) });
61
106
  }
62
- export function ChartDot({ cx, cy, r = 4, fill, opacity, chartStyle }) {
107
+ export function ChartDot({ cx, cy, r = 4, fill, opacity, line }) {
63
108
  if (cx === undefined || cy === undefined)
64
109
  return null;
65
- return chartStyle === "pixel"
110
+ return line === "stepped"
66
111
  ? _jsx("rect", { x: cx - r, y: cy - r, width: 2 * r, height: 2 * r, fill: fill, opacity: opacity })
67
112
  : _jsx("circle", { cx: cx, cy: cy, r: r, fill: fill, opacity: opacity });
68
113
  }
package/dist/chart.d.ts CHANGED
@@ -1,14 +1,19 @@
1
1
  import * as React from "react";
2
- import { type ChartStyle } from "./chart-style.js";
3
- import { type ChartSample, type ChartSeries } from "./chart-data.js";
2
+ import { type ChartLayout, type ChartLegendPlacement, type ChartTreatmentProps } from "./chart-style.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[];
7
8
  series: readonly ChartSeries[];
8
9
  label: string;
9
10
  variant?: "line" | "stacked-area";
10
- layout?: "standard" | "compact" | "split";
11
- legend?: "table" | "inline" | "sidebar";
11
+ /** Overrides the inherited data-chart-layout, otherwise standard. */
12
+ layout?: ChartLayout;
13
+ /** Overrides the inherited data-chart-legend, otherwise table. */
14
+ legend?: ChartLegendPlacement;
15
+ /** Columns of the table legend, in order. Default min, max, avg and current. */
16
+ summary?: readonly ChartSummaryStat[];
12
17
  /** A controlled highlight. Pass null to clear it, or omit for local selection. */
13
18
  highlightSeries?: string | null;
14
19
  onHighlightSeriesChange?: (key: string | null) => void;
@@ -19,6 +24,8 @@ export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
19
24
  formatValue?: (value: number) => string;
20
25
  min?: number;
21
26
  max?: number;
22
- chartStyle?: ChartStyle;
23
- };
24
- export declare function Chart({ data, series, label, variant, layout, legend, highlightSeries, onHighlightSeriesChange, height, syncId, formatTime, formatValue, min, max, chartStyle, ref, className, ...props }: ChartProps): React.JSX.Element;
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;
30
+ } & ChartTreatmentProps;
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
@@ -4,14 +4,37 @@ import * as React from "react";
4
4
  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
- import { ChartDot, ChartPattern, pixelCurve, useChartStyle } from "./chart-style.js";
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 = "standard", legend = "table", highlightSeries, onHighlightSeriesChange, height = layout === "compact" ? 165 : layout === "split" ? 90 : 200, syncId, formatTime = formatChartTime, formatValue = formatChartValue, min, max, chartStyle, 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
- const treatment = useChartStyle(frame, chartStyle);
13
+ const { line, fill } = useChartStyle(frame, { chartStyle, chartLine, chartFill });
14
+ const presentation = useChartPresentation(frame, layoutProp, legendProp);
15
+ const legend = presentation.legend;
16
+ // An inherited split cannot hold a stack, so a stacked chart keeps one plot.
17
+ const layout = !layoutProp && presentation.layout === "split" && variant === "stacked-area" ? "standard" : presentation.layout;
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;
22
+ const bold = line === "stepped" || line === "curved";
13
23
  const [localHighlight, setLocalHighlight] = React.useState(null);
14
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
+ });
15
38
  const requestedHighlight = highlightSeries === undefined ? localHighlight : highlightSeries;
16
39
  const highlighted = series.some(item => item.key === requestedHighlight) ? requestedHighlight : null;
17
40
  const highlight = (key) => {
@@ -47,35 +70,76 @@ export function Chart({ data, series, label, variant = "line", layout = "standar
47
70
  else
48
71
  splitMin -= Math.max(1, Math.abs(splitMin) * 0.1);
49
72
  }
50
- 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}-halftone-${index}`, color: chartColor(chartSlot(series[index], index)) }, 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]
51
- : [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 => {
52
- const item = series[index];
53
- const slot = chartSlot(item, index);
54
- const dimmed = highlighted !== null && item.key !== highlighted;
55
- const common = { dataKey: `values.${index}`, name: item.label, stroke: chartColor(slot),
56
- strokeWidth: item.key === highlighted ? (treatment === "pixel" || treatment === "rounded" ? 2.7 : 2.2) : treatment === "pixel" || treatment === "rounded" ? 2 : 1.5,
57
- strokeOpacity: dimmed ? 0.3 : 1, strokeLinecap: treatment === "rounded" ? "round" : "butt",
58
- strokeLinejoin: treatment === "rounded" ? "round" : "miter",
59
- connectNulls: false, isAnimationActive: false,
60
- dot: (dotProps) => {
61
- const at = dotProps.index ?? -1;
62
- const isolated = measured(plot[at]?.values[index])
63
- && !measured(plot[at - 1]?.values[index]) && !measured(plot[at + 1]?.values[index]);
64
- return _jsx(ChartDot, { cx: dotProps.cx, cy: dotProps.cy, r: isolated ? 3 : 0, chartStyle: treatment, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }, at);
65
- }, activeDot: (dotProps) => _jsx(ChartDot, { ...dotProps, chartStyle: treatment, fill: chartColor(slot), opacity: dimmed ? 0.3 : 1 }) };
66
- const curve = treatment === "pixel" ? pixelCurve : treatment === "rounded" && variant === "line" ? "monotone" : "linear";
67
- return variant === "stacked-area" || treatment === "halftone"
68
- ? _jsx(Area, { ...common, type: curve, stackId: variant === "stacked-area" ? "total" : undefined, fill: treatment === "halftone" ? `url(#${id}-halftone-${index})` : chartColor(slot), fillOpacity: dimmed ? 0.06 : 0.2 }, item.key)
69
- : _jsx(Line, { ...common, type: curve }, item.key);
70
- })] }) }) });
71
- 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 });
72
136
  return _jsxs("figure", { ...props, ref: element => {
73
137
  frame.current = element;
74
138
  if (typeof ref === "function")
75
139
  return ref(element);
76
140
  if (ref)
77
141
  ref.current = element;
78
- }, "data-slot": "chart", "data-layout": layout, "data-legend": legend, "data-chart-treatment": treatment, className: cn("framed-chart", className), "aria-labelledby": `${id}-title`, children: [_jsx("figcaption", { id: `${id}-title`, className: "t-h3", children: label }), _jsx("p", { id: `${id}-help`, className: "chart-help", children: "Focus the chart and use Left and Right to inspect samples. Select a series in the legend to highlight it. Exact values are available below." }), _jsxs("div", { className: "chart-body", children: [_jsx("div", { className: "chart-plots", children: hasData ? layout === "split" ? series.map((item, index) => _jsxs("div", { className: "chart-lane", children: [_jsxs("div", { className: "chart-lane-heading", children: [_jsx(ChartSeriesLabel, { series: item, index: index }), _jsx("span", { children: displayValue(data.at(-1)?.values[item.key]) })] }), renderPlot([index], item)] }, item.key)) : renderPlot(series.map((_, index) => index))
142
+ }, "data-slot": "chart", "data-layout": layout, "data-legend": legend, "data-line": line, "data-fill": fill, className: cn("framed-chart", className), "aria-labelledby": `${id}-title`, children: [_jsx("figcaption", { id: `${id}-title`, className: "t-h3", children: label }), _jsx("p", { id: `${id}-help`, className: "chart-help", children: "Focus the chart and use Left and Right to inspect samples. Select a series in the legend to highlight it. Exact values are available below." }), _jsxs("div", { className: "chart-body", children: [_jsx("div", { className: "chart-plots", children: hasData ? layout === "split" ? series.map((item, index) => _jsxs("div", { className: "chart-lane", children: [_jsxs("div", { className: "chart-lane-heading", children: [_jsx(ChartSeriesLabel, { series: item, index: index }), _jsx("span", { children: displayValue(data.at(-1)?.values[item.key]) })] }), renderPlot([index], item)] }, item.key)) : renderPlot(series.map((_, index) => index))
79
143
  : _jsx("div", { className: "chart-empty hatch", style: { minHeight: height }, children: "No collected samples in this window." }) }), legend === "sidebar" && legendContent] }), legend !== "sidebar" && legendContent, _jsxs("details", { className: "disclosure chart-values", children: [_jsx("summary", { children: "View exact values" }), _jsx("div", { className: "chart-table-scroll", children: _jsxs("table", { className: "chart-table", children: [_jsxs("caption", { children: [label, ": collected samples, timestamps in UTC"] }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Timestamp" }), series.map(item => _jsx("th", { scope: "col", children: item.label }, item.key))] }) }), _jsx("tbody", { children: data.map(sample => _jsxs("tr", { children: [_jsx("th", { scope: "row", children: formatChartTime(sample.timestamp) }), series.map(item => _jsx("td", { children: measured(sample.values[item.key]) ? String(sample.values[item.key]) : "Not collected" }, item.key))] }, sample.timestamp)) })] }) })] })] });
80
144
  }
81
145
  // Observe Recharts' synchronized tooltip state after render. This keeps the
@@ -1,6 +1,8 @@
1
1
  import * as React from "react";
2
- export declare function DashboardGrid({ className, ...props }: React.ComponentProps<"div">): React.JSX.Element;
3
- export type DashboardPanelProps = React.ComponentProps<"div"> & {
4
- span?: 3 | 4 | 6 | 8 | 12;
2
+ import { type GridPaneProps, type PaneGridProps } from "./pane-grid.js";
3
+ export type DashboardGridProps = PaneGridProps;
4
+ export declare function DashboardGrid({ className, onPointerMove, onPointerLeave, ...props }: DashboardGridProps): React.JSX.Element;
5
+ export type DashboardPanelProps = GridPaneProps & {
6
+ expandable?: boolean;
5
7
  };
6
- export declare function DashboardPanel({ span, className, style, ...props }: DashboardPanelProps): React.JSX.Element;
8
+ export declare function DashboardPanel({ className, expandable, id, title, actions, children, ref, ...props }: DashboardPanelProps): React.JSX.Element;
@@ -1,8 +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";
3
- export function DashboardGrid({ className, ...props }) {
4
- return _jsx("div", { ...props, "data-slot": "dashboard-grid", className: cn("dashboard-grid", className) });
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";
9
+ import { GridPane, PaneGrid } from "./pane-grid.js";
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 }) });
5
57
  }
6
- export function DashboardPanel({ span = 6, className, style, ...props }) {
7
- return _jsx("div", { ...props, "data-slot": "dashboard-panel", "data-span": span, className: cn("dashboard-panel", className), style: { "--dashboard-span": span, ...style } });
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 }) })] }) })] });
8
103
  }
package/dist/index.d.ts CHANGED
@@ -35,7 +35,7 @@ export * from "./search.js";
35
35
  export * from "./select.js";
36
36
  export * from "./detail-select.js";
37
37
  export * from "./media-preview.js";
38
- export type { ChartStyle } from "./chart-style.js";
38
+ export type { ChartFill, ChartLayout, ChartLegendPlacement, ChartLine, ChartStyle, ChartTreatment } from "./chart-style.js";
39
39
  export * from "./separator.js";
40
40
  export * from "./sidebar.js";
41
41
  export * from "./skeleton.js";
package/dist/pane-grid.js CHANGED
@@ -7,8 +7,8 @@ import { useIsomorphicLayoutEffect } from "./use-isomorphic-layout-effect.js";
7
7
  const COLUMNS = 12;
8
8
  /* A drag ends on release, on cancellation, or when capture is lost. */
9
9
  const RELEASE = ["pointerup", "pointercancel", "lostpointercapture"];
10
- /* DashboardGrid's breakpoints, measured on the grid's own width so a grid
11
- beside a sidebar or panel gets the columns its space allows: above 1024px
10
+ /* Breakpoints measured on the grid's own width, so a grid beside a sidebar
11
+ or panel gets the columns its space allows: above 1024px
12
12
  twelve columns, above 640px six, then one. Unmeasured grids use twelve. */
13
13
  const pickColumns = (width) => !width ? COLUMNS : width <= 640 ? 1 : width <= 1024 ? 6 : COLUMNS;
14
14
  const PaneContext = React.createContext(null);
@@ -1,5 +1,5 @@
1
1
  import * as React from "react";
2
- import { type ChartStyle } from "./chart-style.js";
2
+ import { type ChartTreatmentProps } from "./chart-style.js";
3
3
  export type SparklineProps = Omit<React.ComponentProps<"div">, "ref"> & {
4
4
  values: readonly (number | null)[];
5
5
  height?: number;
@@ -9,7 +9,6 @@ export type SparklineProps = Omit<React.ComponentProps<"div">, "ref"> & {
9
9
  max?: number;
10
10
  label?: string;
11
11
  ref?: React.Ref<HTMLDivElement>;
12
- chartStyle?: ChartStyle;
13
- };
14
- declare function Sparkline({ values, height, tone, fill, min, max, label, className, style, ref, chartStyle, ...props }: SparklineProps): React.JSX.Element | null;
12
+ } & ChartTreatmentProps;
13
+ declare function Sparkline({ values, height, tone, fill, min, max, label, className, style, ref, chartStyle, chartLine, chartFill, ...props }: SparklineProps): React.JSX.Element | null;
15
14
  export { Sparkline };
package/dist/sparkline.js CHANGED
@@ -7,13 +7,16 @@ import * as React from "react";
7
7
  import { Area, AreaChart, ResponsiveContainer, YAxis } from "recharts";
8
8
  import { clsx as cn } from "clsx";
9
9
  import { ChartPattern, pixelCurve, useChartStyle } from "./chart-style.js";
10
- function Sparkline({ values, height = 24, tone = "neutral", fill = false, min, max, label, className, style, ref, chartStyle, ...props }) {
10
+ function Sparkline({ values, height = 24, tone = "neutral", fill = false, min, max, label, className, style, ref, chartStyle, chartLine, chartFill, ...props }) {
11
11
  const id = React.useId();
12
12
  const frame = React.useRef(null);
13
13
  // Below two samples there is no shape to show, and a flat rule across a
14
14
  // cell reads as a border rather than as a measurement.
15
15
  const known = values.filter((value) => value !== null && Number.isFinite(value));
16
- const treatment = useChartStyle(frame, chartStyle, known.length >= 2);
16
+ const { line, fill: texture } = useChartStyle(frame, { chartStyle, chartLine, chartFill }, known.length >= 2);
17
+ const textured = texture === "dots" || texture === "squares" || texture === "scanlines";
18
+ // The `fill` prop asks for a tint when the treatment has none.
19
+ const tinted = texture === "tint" || (fill && texture === "none");
17
20
  if (known.length < 2)
18
21
  return null;
19
22
  // Default domain is the data's own extent; pass min and max to make
@@ -29,6 +32,6 @@ function Sparkline({ values, height = 24, tone = "neutral", fill = false, min, m
29
32
  return ref(element);
30
33
  if (ref)
31
34
  ref.current = element;
32
- }, "data-slot": "sparkline", "data-chart-treatment": treatment, "data-tone": tone, role: label ? "img" : undefined, "aria-label": label, "aria-hidden": label ? undefined : true, className: cn("sparkline", tone === "primary" && "primary", className), style: { height, ...style }, ...props, children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(AreaChart, { data: values.map((value) => ({ value: value !== null && Number.isFinite(value) ? value : null })), margin: { top: 2, right: 0, bottom: 2, left: 0 }, children: [_jsx("defs", { children: _jsx(ChartPattern, { id: `${id}-halftone`, color: "currentColor" }) }), _jsx(YAxis, { hide: true, domain: [lo, hi] }), _jsx(Area, { type: treatment === "pixel" ? pixelCurve : treatment === "rounded" ? "monotone" : "linear", connectNulls: false, dataKey: "value", stroke: "currentColor", strokeWidth: treatment === "pixel" || treatment === "rounded" ? 2 : 1.5, strokeLinecap: treatment === "rounded" ? "round" : "butt", strokeLinejoin: treatment === "rounded" ? "round" : "miter", fill: treatment === "halftone" ? `url(#${id}-halftone)` : fill ? "currentColor" : "none", fillOpacity: treatment === "halftone" ? 0.3 : fill ? 0.12 : 0, isAnimationActive: false, dot: false, activeDot: false })] }) }) }));
35
+ }, "data-slot": "sparkline", "data-line": line, "data-fill": texture, "data-tone": tone, role: label ? "img" : undefined, "aria-label": label, "aria-hidden": label ? undefined : true, className: cn("sparkline", tone === "primary" && "primary", className), style: { height, ...style }, ...props, children: _jsx(ResponsiveContainer, { width: "100%", height: "100%", children: _jsxs(AreaChart, { data: values.map((value) => ({ value: value !== null && Number.isFinite(value) ? value : null })), margin: { top: 2, right: 0, bottom: 2, left: 0 }, children: [_jsx("defs", { children: _jsx(ChartPattern, { id: `${id}-fill`, color: "currentColor", fill: texture }) }), _jsx(YAxis, { hide: true, domain: [lo, hi] }), _jsx(Area, { type: line === "stepped" ? pixelCurve : line === "curved" ? "monotone" : "linear", connectNulls: false, dataKey: "value", stroke: "currentColor", strokeWidth: line === "stepped" || line === "curved" ? 2 : 1.5, strokeLinecap: line === "curved" ? "round" : "butt", strokeLinejoin: line === "curved" ? "round" : "miter", fill: textured ? `url(#${id}-fill)` : tinted ? "currentColor" : "none", fillOpacity: textured ? 0.3 : tinted ? 0.12 : 0, isAnimationActive: false, dot: false, activeDot: false })] }) }) }));
33
36
  }
34
37
  export { Sparkline };
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.17.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.21.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",