// ~/src/siteplane/components/radar-chart/radar-chart.tsx "use client"; import * as React from "react"; import { useFormatLocale, useSiteplaneMessages, } from "../../system/locale/messages-context"; import { cn } from "../../system/utils/cn"; import { Badge } from "../badge"; import { CHART_LEGEND_BAND, ChartActiveDot, ChartEmptyState, chartAxisLabelClassName, useChartBox, useFadeClassName, useLastValue, } from "../chart/chart-cartesian"; import { chartDimOpacity, seriesSteppedBack, useChartDimClassName, } from "../chart/chart-dimming"; import { CHART_DEFAULT_LOCALE, chartLabels, chartNumberFormatter, chartTickLabels, chartXFormatter, } from "../chart/chart-format"; import { useChartInteraction } from "../chart/chart-interaction"; import { ChartLegend, useChartSeriesFocus } from "../chart/chart-legend"; import { buildCartesianModel, cartesianSummary, type CartesianModel, } from "../chart/chart-model"; import { seriesColors } from "../chart/chart-palette"; import { valueScale, valueTicks } from "../chart/chart-scales"; import { ChartPlotPlaceholder, ChartTooltip, ChartTooltipContent, chartTooltipText, } from "../chart/chart-tooltip"; import type { CartesianChartLabels, ChartDatum, ChartPalette, ChartSeries, ChartXValue, } from "../chart/chart-types"; import { followed, useFollowDerived, useFollowValue, useTweenedValues, } from "../motion"; import { nearestTurn, radarAngle, radarLabelPlace, radarLayout, radarPoint, radarPolygonPath, radarSpokeAt, type RadarLayout, } from "./radar-geometry"; export type RadarChartProps = { /** One row per spoke, from 12 o'clock clockwise: its name and one number per series. */ data: readonly ChartDatum[]; /** Key of the name of a spoke in the data. */ x: string; series: readonly ChartSeries[]; /** The accessible name of the chart. */ label: string; /** * The id of an element that describes the chart, read after the summary of * its data that the chart gives assistive technology itself. */ "aria-describedby"?: string; /** The height of the chart in px, a legend included; the width follows the container. 240 by default. */ height?: number; /** Formats a value in the tooltip and on the pills of the vertical spoke. */ formatValue?: (value: number) => string; /** * Rolls the values in the tooltip to the next spoke's, digit by digit * (MotionNumber). Off by default: they change at once, so a pointer that * moves round the chart costs the page little work. */ rollingNumbers?: boolean; /** Formats the name of a spoke around the rim and in the tooltip heading. */ formatX?: (value: ChartXValue) => string; /** The locale of the numbers: the SiteplaneLocaleProvider's unless set, en-US without one. */ locale?: string; /** * The colours of the series that name none. `brand` (the default) shades the * brand colour from strong to light, spread over the number of series (up to * eight); `categorical` gives each series its own chart colour, `--chart-1` * to `--chart-8` in order. Both start over from the ninth series. A series * that names its `color` keeps it either way. */ palette?: ChartPalette; /** Whether to list the series below the plot. On when there is more than one series. */ legend?: boolean; /** The rings of the value axis and the spokes. */ grid?: boolean; /** Shown in place of the marks when there is nothing to draw. */ emptyLabel?: string; /** * Replaces words that the chart gives screen readers, merged with the * English defaults: its role description, the keyboard hint and the words of * the summary of its data. */ labels?: Partial | undefined; className?: string; }; // A series is drawn as a tint of its colour, as the Area Chart's solid fill, // with a 2 px outline, as the Line Chart's lines. const fillOpacity = 0.18; const outlineWidth = 2; // The focus stop that holds the plot, and the box of the plot before it is drawn. const plotClassName = "relative block w-full rounded-lg"; /** * One or several series on spokes that share one value axis from the centre * out: a spoke per row of the data, from 12 o'clock clockwise, the values of a * series joined into a tinted polygon. Rings mark the values of the axis, whose * figures stand on pills along the spoke at 12 o'clock; the names of the spokes * stand around the rim. The spoke under the pointer is marked by a crosshair * and a dot on each series, and the tooltip lists its values; the plot is one * focus stop whose arrow keys step round the spokes. A mouse over an entry of * the legend steps the other series back. The plot is drawn once the chart has * measured its width; new data glides in. */ export function RadarChart({ data, x, series, label, "aria-describedby": describedBy, height: givenHeight, formatValue, formatX, locale: localeProp, palette = "brand", legend = series.length > 1, grid = true, emptyLabel: emptyLabelProp, labels, className, rollingNumbers = false, }: RadarChartProps): React.ReactElement { const messages = useSiteplaneMessages("chart"); const emptyLabel = emptyLabelProp ?? messages.noData; // The chart's own locale, else the provider's, else en-US. const locale = useFormatLocale(localeProp, CHART_DEFAULT_LOCALE); const root = React.useRef(null); // The chart core sizes the chart: its width follows the container. const box = useChartBox(root, { height: givenHeight }); const { height, width } = box; const colors = seriesColors(series, palette); const showLegend = legend && series.length > 0; const focus = useChartSeriesFocus(series.map((item) => item.key)); const words = chartLabels(labels, messages); // A row per spoke and the numbers of each series, read as the other charts // read theirs. const model = React.useMemo( () => buildCartesianModel({ data, series, stacked: false, x }), [data, series, x], ); const formatHeading = formatX ?? chartXFormatter(locale, "long"); const formatNumber = formatValue ?? chartNumberFormatter(locale); const description = cartesianSummary({ emptyLabel, formatValue: formatNumber, formatX: formatHeading, labels: words, model, series, }); const plotHeight = Math.max(0, height - (showLegend ? CHART_LEGEND_BAND : 0)); return ( // The figure holds the plot and the legend. The focus stop inside is the // chart for assistive technology, named by the label alone.
{width === null ? ( ) : ( )} {showLegend && ( ({ color: colors[place]!, key: item.key, label: item.label, }))} layout="row" /> )}
); } /** * The hairline from the centre to the rim along the active spoke. It turns to * the next spoke the short way round with the follow motion, fades in and out * with the active spoke, and waits out of sight where it last was. */ function RadarCrosshair({ angle, container, layout, }: { /** The angle of the active spoke, null for none. */ angle: number | null; container: React.RefObject; layout: RadarLayout; }): React.ReactElement { const fade = useFadeClassName(); const held = useLastValue(angle) ?? 0; // The angle it heads for, unwound so that it never turns more than half // round: from the last spoke to the first across 12 o'clock. const [turn, setTurn] = React.useState(held); const next = nearestTurn(turn, held); if (next !== turn) setTurn(next); const along = useFollowValue(next, { active: angle !== null, container }); const x2 = useFollowDerived( along, (value) => radarPoint(layout, value, layout.radius)[0], ); const y2 = useFollowDerived( along, (value) => radarPoint(layout, value, layout.radius)[1], ); return (