@momoi-labs/kiso-react 0.16.2 → 0.18.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,7 +7,7 @@ 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;
@@ -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);
@@ -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,5 +1,5 @@
1
1
  import * as React from "react";
2
- import { type ChartStyle } from "./chart-style.js";
2
+ import { type ChartLayout, type ChartLegendPlacement, type ChartTreatmentProps } from "./chart-style.js";
3
3
  import { type ChartSample, type ChartSeries } from "./chart-data.js";
4
4
  export type { ChartSample, ChartSeries } from "./chart-data.js";
5
5
  export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
@@ -7,8 +7,10 @@ export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
7
7
  series: readonly ChartSeries[];
8
8
  label: string;
9
9
  variant?: "line" | "stacked-area";
10
- layout?: "standard" | "compact" | "split";
11
- legend?: "table" | "inline" | "sidebar";
10
+ /** Overrides the inherited data-chart-layout, otherwise standard. */
11
+ layout?: ChartLayout;
12
+ /** Overrides the inherited data-chart-legend, otherwise table. */
13
+ legend?: ChartLegendPlacement;
12
14
  /** A controlled highlight. Pass null to clear it, or omit for local selection. */
13
15
  highlightSeries?: string | null;
14
16
  onHighlightSeriesChange?: (key: string | null) => void;
@@ -19,6 +21,5 @@ export type ChartProps = Omit<React.ComponentProps<"figure">, "children"> & {
19
21
  formatValue?: (value: number) => string;
20
22
  min?: number;
21
23
  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;
24
+ } & 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;
package/dist/chart.js CHANGED
@@ -4,12 +4,18 @@ 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
8
  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 }) {
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
10
  const id = React.useId();
11
11
  const frame = React.useRef(null);
12
- const treatment = useChartStyle(frame, chartStyle);
12
+ const { line, fill } = useChartStyle(frame, { chartStyle, chartLine, chartFill });
13
+ const presentation = useChartPresentation(frame, layoutProp, legendProp);
14
+ const legend = presentation.legend;
15
+ // An inherited split cannot hold a stack, so a stacked chart keeps one plot.
16
+ 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 bold = line === "stepped" || line === "curved";
13
19
  const [localHighlight, setLocalHighlight] = React.useState(null);
14
20
  const [activeTimestamp, setActiveTimestamp] = React.useState(null);
15
21
  const requestedHighlight = highlightSeries === undefined ? localHighlight : highlightSeries;
@@ -47,25 +53,27 @@ export function Chart({ data, series, label, variant = "line", layout = "standar
47
53
  else
48
54
  splitMin -= Math.max(1, Math.abs(splitMin) * 0.1);
49
55
  }
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]
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]
51
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 => {
52
58
  const item = series[index];
53
59
  const slot = chartSlot(item, index);
54
60
  const dimmed = highlighted !== null && item.key !== highlighted;
55
61
  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",
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",
59
65
  connectNulls: false, isAnimationActive: false,
60
66
  dot: (dotProps) => {
61
67
  const at = dotProps.index ?? -1;
62
68
  const isolated = measured(plot[at]?.values[index])
63
69
  && !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)
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)
69
77
  : _jsx(Line, { ...common, type: curve }, item.key);
70
78
  })] }) }) });
71
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 });
@@ -75,7 +83,7 @@ export function Chart({ data, series, label, variant = "line", layout = "standar
75
83
  return ref(element);
76
84
  if (ref)
77
85
  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))
86
+ }, "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
87
  : _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
88
  }
81
89
  // Observe Recharts' synchronized tooltip state after render. This keeps the
@@ -1,6 +1,6 @@
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;
5
- };
6
- export declare function DashboardPanel({ span, className, style, ...props }: DashboardPanelProps): React.JSX.Element;
2
+ import { type GridPaneProps, type PaneGridProps } from "./pane-grid.js";
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;
@@ -1,8 +1,9 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { clsx as cn } from "clsx";
3
+ import { GridPane, PaneGrid } from "./pane-grid.js";
3
4
  export function DashboardGrid({ className, ...props }) {
4
- return _jsx("div", { ...props, "data-slot": "dashboard-grid", className: cn("dashboard-grid", className) });
5
+ return _jsx(PaneGrid, { "data-slot": "dashboard-grid", className: cn("dashboard-grid", className), ...props });
5
6
  }
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 } });
7
+ export function DashboardPanel({ className, ...props }) {
8
+ return _jsx(GridPane, { "data-slot": "dashboard-panel", className: cn("dashboard-panel", className), ...props });
8
9
  }
@@ -4,6 +4,7 @@ import * as React from "react";
4
4
  import { clsx as cn } from "clsx";
5
5
  import { Check } from "lucide-react";
6
6
  import { Popover, PopoverContent, PopoverTrigger } from "./popover.js";
7
+ import { isPlayPreviewKey, toggleAudioPreview } from "./media-preview.js";
7
8
  export function DetailSelect({ label, options, value, defaultValue, onValueChange, placeholder = "Choose an option", disabled, controlSize, id, className, "aria-describedby": describedBy, "aria-invalid": invalid }) {
8
9
  const generatedId = React.useId();
9
10
  const triggerId = id ?? generatedId;
@@ -39,6 +40,11 @@ export function DetailSelect({ label, options, value, defaultValue, onValueChang
39
40
  if (!interactive || !event.currentTarget.contains(interactive))
40
41
  choose(option);
41
42
  }, "aria-labelledby": `${triggerId}-option-${index}`, children: [_jsx("div", { className: "detail-select-illustration", children: option.illustration }), _jsxs("div", { className: "detail-select-body", children: [_jsx("h3", { className: "detail-select-heading", children: _jsxs("button", { id: `${triggerId}-option-${index}`, type: "button", className: "detail-select-choice", ref: element => { buttons.current[index] = element; }, disabled: option.disabled, "aria-pressed": option.value === selected, "aria-describedby": `${triggerId}-description-${index}`, onClick: () => choose(option), onKeyDown: event => {
43
+ if (isPlayPreviewKey(event)) {
44
+ event.preventDefault();
45
+ toggleAudioPreview(event.currentTarget.closest(".detail-select-option"));
46
+ return;
47
+ }
42
48
  if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key))
43
49
  return;
44
50
  const enabled = options.map((option, index) => ({ option, button: buttons.current[index] }))
package/dist/index.d.ts CHANGED
@@ -34,7 +34,8 @@ export * from "./popover.js";
34
34
  export * from "./search.js";
35
35
  export * from "./select.js";
36
36
  export * from "./detail-select.js";
37
- export type { ChartStyle } from "./chart-style.js";
37
+ export * from "./media-preview.js";
38
+ export type { ChartFill, ChartLayout, ChartLegendPlacement, ChartLine, ChartStyle, ChartTreatment } from "./chart-style.js";
38
39
  export * from "./separator.js";
39
40
  export * from "./sidebar.js";
40
41
  export * from "./skeleton.js";
package/dist/index.js CHANGED
@@ -35,6 +35,7 @@ export * from "./popover.js";
35
35
  export * from "./search.js";
36
36
  export * from "./select.js";
37
37
  export * from "./detail-select.js";
38
+ export * from "./media-preview.js";
38
39
  export * from "./separator.js";
39
40
  export * from "./sidebar.js";
40
41
  export * from "./skeleton.js";
@@ -0,0 +1,40 @@
1
+ import * as React from "react";
2
+ export type ImagePreviewProps = Omit<React.ComponentProps<"img">, "src" | "alt"> & {
3
+ src: string;
4
+ /** Describes the image, or "" when the text beside it already names it. */
5
+ alt: string;
6
+ };
7
+ /** A thumbnail that crops the image to fill its box. */
8
+ export declare function ImagePreview({ className, loading, decoding, ...props }: ImagePreviewProps): React.JSX.Element;
9
+ export type AudioPreviewProps = Omit<React.ComponentProps<"button">, "children" | "type"> & {
10
+ src: string;
11
+ /** What plays. The button is named "Play {label}" or "Pause {label}". */
12
+ label: string;
13
+ };
14
+ /**
15
+ * A button that plays and pauses a short sound. It loads nothing until it is
16
+ * pressed and never starts by itself.
17
+ */
18
+ export declare function AudioPreview({ src, label, className, onClick, ref, ...props }: AudioPreviewProps): React.JSX.Element;
19
+ /**
20
+ * Ctrl+Enter, or Cmd+Enter on macOS, plays or pauses the audio preview of the
21
+ * highlighted option while the focus stays on the selection.
22
+ */
23
+ export declare function isPlayPreviewKey(event: Pick<KeyboardEvent, "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey">): boolean;
24
+ /** Plays or pauses the first audio preview inside `element`. False when it has none. */
25
+ export declare function toggleAudioPreview(element: Element | null | undefined): boolean;
26
+ export type DetailOptionProps = Omit<React.ComponentProps<"div">, "children"> & {
27
+ label: React.ReactNode;
28
+ illustration?: React.ReactNode;
29
+ description?: React.ReactNode;
30
+ /** `sm` fits a row in a compact list, such as an autocomplete. */
31
+ size?: "sm" | "md";
32
+ };
33
+ /**
34
+ * DetailSelect's option layout, for lists it does not own: an illustration
35
+ * beside a title and its description. Pass `role="option"` and
36
+ * `aria-selected` to use it in a listbox. The title names the option and the
37
+ * description describes it, so controls in the illustration stay out of its
38
+ * name.
39
+ */
40
+ export declare function DetailOption({ label, illustration, description, size, className, id, ...props }: DetailOptionProps): React.JSX.Element;
@@ -0,0 +1,89 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import { clsx as cn } from "clsx";
5
+ import { Pause, Play } from "lucide-react";
6
+ /** A thumbnail that crops the image to fill its box. */
7
+ export function ImagePreview({ className, loading = "lazy", decoding = "async", ...props }) {
8
+ return _jsx("img", { "data-slot": "image-preview", className: cn("media-preview", className), loading: loading, decoding: decoding, ...props });
9
+ }
10
+ // One preview plays at a time: starting one pauses the one before.
11
+ let playing = null;
12
+ /**
13
+ * A button that plays and pauses a short sound. It loads nothing until it is
14
+ * pressed and never starts by itself.
15
+ */
16
+ export function AudioPreview({ src, label, className, onClick, ref, ...props }) {
17
+ const audio = React.useRef(null);
18
+ const [on, setOn] = React.useState(false);
19
+ const stop = React.useCallback(() => {
20
+ const current = audio.current;
21
+ if (current)
22
+ current.pause();
23
+ if (playing?.audio === current)
24
+ playing = null;
25
+ setOn(false);
26
+ }, []);
27
+ // A new source, or leaving the page, stops the old sound.
28
+ React.useEffect(() => () => {
29
+ stop();
30
+ audio.current = null;
31
+ }, [src, stop]);
32
+ const toggle = () => {
33
+ // The player, not the last render, says whether this one plays, so a
34
+ // quick second press pauses.
35
+ if (audio.current && playing?.audio === audio.current)
36
+ return stop();
37
+ if (!audio.current) {
38
+ const element = new Audio(src);
39
+ element.addEventListener("ended", () => {
40
+ element.currentTime = 0;
41
+ if (playing?.audio === element)
42
+ playing = null;
43
+ setOn(false);
44
+ });
45
+ element.addEventListener("error", stop);
46
+ audio.current = element;
47
+ }
48
+ const element = audio.current;
49
+ if (playing && playing.audio !== element)
50
+ playing.stop();
51
+ playing = { audio: element, stop };
52
+ setOn(true);
53
+ element.play().catch(error => {
54
+ // A pause before playback starts rejects too; that is not a failure.
55
+ if (error?.name !== "AbortError")
56
+ stop();
57
+ });
58
+ };
59
+ return _jsx("button", { ref: ref, type: "button", "data-slot": "audio-preview", "data-state": on ? "playing" : "paused", "aria-label": `${on ? "Pause" : "Play"} ${label}`, className: cn("btn btn-outline btn-sm btn-icon audio-preview", className), ...props, onClick: event => {
60
+ onClick?.(event);
61
+ if (!event.defaultPrevented)
62
+ toggle();
63
+ }, children: on ? _jsx(Pause, { className: "icon icon-sm", "aria-hidden": "true" }) : _jsx(Play, { className: "icon icon-sm", "aria-hidden": "true" }) });
64
+ }
65
+ /**
66
+ * Ctrl+Enter, or Cmd+Enter on macOS, plays or pauses the audio preview of the
67
+ * highlighted option while the focus stays on the selection.
68
+ */
69
+ export function isPlayPreviewKey(event) {
70
+ return event.key === "Enter" && (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey;
71
+ }
72
+ /** Plays or pauses the first audio preview inside `element`. False when it has none. */
73
+ export function toggleAudioPreview(element) {
74
+ const button = element?.querySelector('[data-slot="audio-preview"]:not(:disabled)');
75
+ button?.click();
76
+ return !!button;
77
+ }
78
+ /**
79
+ * DetailSelect's option layout, for lists it does not own: an illustration
80
+ * beside a title and its description. Pass `role="option"` and
81
+ * `aria-selected` to use it in a listbox. The title names the option and the
82
+ * description describes it, so controls in the illustration stay out of its
83
+ * name.
84
+ */
85
+ export function DetailOption({ label, illustration, description, size = "md", className, id, ...props }) {
86
+ const generated = React.useId();
87
+ const base = id ?? generated;
88
+ return _jsxs("div", { id: id, "data-slot": "detail-option", "data-size": size, className: cn("detail-option", className), "aria-labelledby": `${base}-label`, "aria-describedby": description != null ? `${base}-description` : undefined, ...props, children: [illustration != null && _jsx("div", { className: "detail-option-illustration", children: illustration }), _jsxs("div", { className: "detail-option-body", children: [_jsx("div", { id: `${base}-label`, className: "detail-option-label", children: label }), description != null && _jsx("div", { id: `${base}-description`, className: "detail-option-description", children: description })] })] });
89
+ }
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
@@ -364,6 +364,31 @@
364
364
  .detail-select-choice { min-height: var(--size-touch-min); }
365
365
  .detail-select-description a { display: inline-block; min-height: var(--size-touch-min); align-content: center; }
366
366
  }
367
+ .media-preview { display: block; width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: var(--radius-sm); background-color: var(--color-muted); }
368
+ .audio-preview { flex: none; }
369
+ .detail-option { display: grid; grid-template-columns: minmax(min-content, 8rem) minmax(0, 1fr); gap: var(--spacing-lg); padding: var(--spacing-md); color: var(--color-foreground); }
370
+ .detail-option:not(:has(> .detail-option-illustration)) { grid-template-columns: minmax(0, 1fr); }
371
+ .detail-option-illustration { min-width: 0; align-self: start; }
372
+ .detail-option-illustration :is(img, svg, video) { max-width: 100%; }
373
+ .detail-option-body { min-width: 0; align-self: center; overflow-wrap: anywhere; }
374
+ .detail-option-label { font-size: var(--type-size-body); font-weight: var(--type-weight-medium); }
375
+ .detail-option-description { color: var(--color-muted-foreground); font-size: var(--type-size-label); }
376
+ .detail-option[data-size="sm"] { grid-template-columns: var(--size-control-sm) minmax(0, 1fr); align-items: center; gap: var(--spacing-sm); padding: var(--spacing-xs) var(--spacing-sm); }
377
+ .detail-option[data-size="sm"]:not(:has(> .detail-option-illustration)) { grid-template-columns: minmax(0, 1fr); }
378
+ .detail-option[data-size="sm"] .detail-option-illustration { align-self: center; }
379
+ .detail-option[data-size="sm"] .detail-option-label { font-size: var(--type-size-label); }
380
+ .detail-option[data-size="sm"] .media-preview { aspect-ratio: 1; }
381
+ @media (hover: hover) {
382
+ .detail-option:where([role="option"]:not([aria-disabled="true"]):hover) { background-color: var(--color-accent-surface-hover); }
383
+ }
384
+ .detail-option:where([aria-selected="true"]) { background-color: var(--color-selected); color: var(--color-selected-foreground); }
385
+ .detail-option:where([aria-selected="true"]) .detail-option-description { color: inherit; }
386
+ @media (forced-colors: active) {
387
+ .detail-option:where([aria-selected="true"]) { outline: 2px solid Highlight; outline-offset: -2px; }
388
+ }
389
+ @media (max-width: 480px) {
390
+ .detail-option:not([data-size="sm"]) { grid-template-columns: minmax(0, 4rem) minmax(0, 1fr); gap: var(--spacing-sm); padding: var(--spacing-sm); }
391
+ }
367
392
  /* When frames include controls, these surfaces take the control shape, as
368
393
  the control-sized surfaces in ui.css do. */
369
394
  :where([data-frame-scope="all"]) :is(.kiso-react-popover, .theme-buttons, .accent-preview) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@momoi-labs/kiso-react",
3
- "version": "0.16.2",
3
+ "version": "0.18.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.20.3",
35
+ "@momoi-labs/kiso": "^0.22.0",
36
36
  "class-variance-authority": "0.7.1",
37
37
  "clsx": "2.1.1",
38
38
  "radix-ui": "1.6.7",