Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(frontend): add Intent UI's chart components

spacesdrive33b14dbeee70
diff --git a/DECISIONS.md b/DECISIONS.md
index 2fcb2aa..9913839 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1042,3 +1042,22 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
- A mistyped docs address still answers 200, and a new top-level page on the site needs a rewrite line.
- A delete reaches the server 8 seconds late; leaving the page sends any waiting delete at once.
- Old `/upload` and `/reels` links keep working only through the redirects.
+
+## ADR-048: Charts are built with Intent UI's Recharts components, and react-aria-components joins the app
+
+**Date:** 2026-11-05
+**Status:** Accepted
+
+**Decision:** Charts in the app use Intent UI's chart components (`components/ui/chart.tsx`, `area-chart.tsx`, `bar-chart.tsx`, `line-chart.tsx`), copied from its shadcn registry and credited in `THIRD_PARTY_NOTICES.md` (#140). They wrap the Recharts the app already uses, so the data stays the same; they add a themed tooltip, a legend that highlights one series when pressed, and responsive heights. `react-aria-components` is added to the frontend for the legend's toggle buttons. The chart types and layout return to how they were before #132; the visible summary line and Show table button go, and each chart keeps its screen-reader name and description. Daily and weekly counts may use a stacked bar card adapted from Bencho's free Stacked bars block (MIT), and metric values roll like an odometer when they change, adapted from Bencho's Rolling counter.
+
+**Context:** The owner asked for the earlier charts back, built with Intent UI, and for elements from bencho.dev.
+
+**Why install by hand:** the shadcn CLI would run `npm install` inside `frontend/`, which this repository forbids, would overwrite `hooks/use-mobile.ts`, and would add neutral overlay colours outside the brand. The files were taken from the registry, adapted, and the one package installed from the root.
+
+**Alternatives considered:**
+- The `cn` package and the `tailwindcss-react-aria-components` plugin, as the registry lists. The app's own `cn()` knows its token sizes, and React Aria's `data-selected` attribute does what the plugin's variant does, so neither is needed.
+- `framer-motion` for the stacked bar ring and tooltip, as the Bencho block uses. CSS transitions on transform do the same glide without a dependency.
+
+**Trade-offs:**
+- `react-aria-components` is a second headless library beside Base UI; it is used only inside the chart legend.
+- The charts lose the visible summary and data table added in #132; screen readers still get each chart's description.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 22ccef6..35e3b49 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -9,3 +9,21 @@ Twiligent includes work by others under their own licences. This file gives the
- **Source:** [Solar Icons Set](https://www.figma.com/community/file/1166831539721848736), through the `@iconify-json/solar` package
- **Licence:** [Creative Commons Attribution 4.0 International (CC BY 4.0)](https://creativecommons.org/licenses/by/4.0/)
- **Changes:** a selection of the icons, converted to React components that draw in the current text colour. The drawings themselves are unchanged.
+
+## Intent UI chart components
+
+- **Used in:** the app (`frontend/`): `src/components/ui/chart.tsx`, `area-chart.tsx`, `bar-chart.tsx`, `line-chart.tsx` and `src/lib/primitive.ts`
+- **Author:** Irsyad A. Panjaitan
+- **Source:** [Intent UI](https://intentui.com), [github.com/intentui/intentui](https://github.com/intentui/intentui), taken from its shadcn registry (`@intentui/chart`, `area-chart`, `bar-chart`, `line-chart`, `primitive`) on 2026-11-05
+- **Licence:** MIT. Copyright (c) 2024 Irsyad A. Panjaitan. The full MIT text is at the end of this file
+- **Changes:** class names merge through the app's own `cn()` instead of the `cn` package; React Aria's `selected:` variant is written as `data-selected:` so no Tailwind plugin is needed; the tooltip's overlay colours map to the app's surface and ink tokens; legend buttons take their accessible name from their visible label
+
+## MIT licence text
+
+The works above marked MIT are given under this text, with their own copyright line:
+
+> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.md
index d686859..8633a2d 100644
--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md
+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md
@@ -10,7 +10,8 @@
| Build tool | Vite | 7 |
| UI components | shadcn/ui (base-nova style) | - |
| Styling | Tailwind CSS | 4 |
-| Charts | Recharts | 3 |
+| Charts | Recharts, through Intent UI's chart components (`components/ui/chart.tsx` and the area, bar and line charts; ADR-048) | 3 |
+| Chart legend toggles | react-aria-components | 1 |
| Theming | next-themes | - |
| Toasts | Sonner | - |
| Icons | Lucide React | - |
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index d4d3770..85faa3f 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -134,7 +134,7 @@ One ESLint run from the root covers the whole repository. The shared config is `
- `backend/tests/**`, `frontend/tests/**`, `frontend/vite.config.ts`, `site/vite.config.ts`, `site/build/**`, `site/tests/**` and `scripts/**`: Node globals
- Root `*.js` and `*.mjs` config files: the ESLint recommended rules with Node globals
-Lint must report 0 problems; the CI workflow fails on any error. The shadcn files that export their cva variants next to the component (`badgeVariants`, `buttonVariants`, `tabsListVariants`, `toggleVariants`, `useSidebar`) and the contexts that export their hooks (`useAppContext`, `useAuth`) are listed in `allowExportNames` for `react-refresh/only-export-components` in `eslint.config.mjs`; editing one of those files reloads the page instead of hot-updating it. Add a name there only for the same pattern.
+Lint must report 0 problems; the CI workflow fails on any error. The shadcn files that export their cva variants next to the component (`badgeVariants`, `buttonVariants`, `tabsListVariants`, `toggleVariants`, `useSidebar`), Intent UI's chart file with its helpers (`useChart`, `valueToPercent`, `constructCategoryColors`, `getColorValue`) and the contexts that export their hooks (`useAppContext`, `useAuth`) are listed in `allowExportNames` for `react-refresh/only-export-components` in `eslint.config.mjs`; editing one of those files reloads the page instead of hot-updating it. Add a name there only for the same pattern.
### Formatting
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 9f0ca2c..4abbfbd 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -22,10 +22,10 @@ export default defineConfig([
},
rules: {
'@typescript-eslint/no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
- // shadcn files export their cva variants and contexts export their hooks; editing those files reloads the page
+ // shadcn files export their cva variants, Intent UI's chart its helpers, and contexts their hooks; editing those files reloads the page
'react-refresh/only-export-components': ['error', {
allowConstantExport: true,
- allowExportNames: ['badgeVariants', 'buttonVariants', 'tabsListVariants', 'toggleVariants', 'useSidebar', 'useAppContext', 'useAuth'],
+ allowExportNames: ['badgeVariants', 'buttonVariants', 'tabsListVariants', 'toggleVariants', 'useSidebar', 'useAppContext', 'useAuth', 'useChart', 'valueToPercent', 'constructCategoryColors', 'getColorValue'],
}],
},
},
diff --git a/frontend/package.json b/frontend/package.json
index c759d63..ded16f4 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -20,6 +20,7 @@
"lucide-react": "^1.17.0",
"next-themes": "^0.4.6",
"react": "^19.2.0",
+ "react-aria-components": "^1.22.1",
"react-dom": "^19.2.0",
"react-router-dom": "^7.18.4",
"recharts": "^3.8.0",
diff --git a/frontend/src/components/ui/area-chart.tsx b/frontend/src/components/ui/area-chart.tsx
new file mode 100644
index 0000000..89a2e67
--- /dev/null
+++ b/frontend/src/components/ui/area-chart.tsx
@@ -0,0 +1,208 @@
+"use client"
+// Intent UI (https://intentui.com, MIT), vendored; see THIRD_PARTY_NOTICES.md
+
+import { type ComponentProps, Fragment, useId, useMemo } from "react"
+import { Area, AreaChart as AreaChartPrimitive } from "recharts"
+import {
+ type BaseChartProps,
+ CartesianGrid,
+ Chart,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+ ChartTooltipContent,
+ constructCategoryColors,
+ DEFAULT_COLORS,
+ getColorValue,
+ valueToPercent,
+ XAxis,
+ YAxis,
+} from "./chart"
+
+const slugRegExp = /[^a-zA-Z0-9]/g
+
+const fillNone = <stop stopColor="currentColor" stopOpacity={0} />
+
+const fillGradientEnd = <stop offset="95%" stopColor="currentColor" stopOpacity={0} />
+
+function getFillContent({
+ fillType,
+ stopOpacity,
+}: {
+ fillType: AreaChartProps["fillType"]
+ stopOpacity: number
+}): React.ReactNode {
+ switch (fillType) {
+ case "none":
+ return fillNone
+ case "gradient":
+ return (
+ <>
+ <stop offset="5%" stopColor="currentColor" stopOpacity={stopOpacity} />
+ {fillGradientEnd}
+ </>
+ )
+ default:
+ return <stop stopColor="currentColor" stopOpacity={stopOpacity} />
+ }
+}
+
+export interface AreaChartProps extends BaseChartProps {
+ chartProps?: Omit<ComponentProps<typeof AreaChartPrimitive>, "data" | "stackOffset">
+ areaProps?: Partial<ComponentProps<typeof Area>>
+ connectNulls?: boolean
+ fillType?: "gradient" | "solid" | "none"
+}
+
+export function AreaChart({
+ data = [],
+ dataKey,
+ colors = DEFAULT_COLORS,
+ connectNulls = false,
+ type = "default",
+
+ fillType = "gradient",
+ config,
+ children,
+
+ areaProps,
+
+ // Components
+ tooltip = true,
+ tooltipProps,
+
+ cartesianGridProps,
+
+ legend = true,
+ legendProps,
+
+ intervalType = "equidistantPreserveStart",
+
+ valueFormatter = (value: number) => value.toString(),
+
+ // XAxis
+ displayEdgeLabelsOnly = false,
+ hideXAxis = false,
+ xAxisProps,
+
+ // YAxis
+ hideYAxis = false,
+ yAxisProps,
+
+ hideGridLines = false,
+ chartProps,
+ ...props
+}: AreaChartProps) {
+ const configKeys = useMemo(() => Object.keys(config), [config])
+ const categoryColors = useMemo(
+ () => constructCategoryColors(configKeys, colors),
+ [configKeys, colors]
+ )
+ const stacked = type === "stacked" || type === "percent"
+ const areaId = useId()
+
+ const configEntries = useMemo(() => Object.entries(config), [config])
+
+ return (
+ <Chart config={config} data={data} dataKey={dataKey} {...props}>
+ {({ onLegendSelect, selectedLegend }) => (
+ <AreaChartPrimitive
+ onClick={() => {
+ onLegendSelect(null)
+ }}
+ data={data}
+ margin={{
+ bottom: 0,
+ left: 0,
+ right: 0,
+ top: 5,
+ }}
+ stackOffset={type === "percent" ? "expand" : undefined}
+ {...chartProps}
+ >
+ {!hideGridLines && <CartesianGrid {...cartesianGridProps} strokeDasharray="3 3" />}
+ <XAxis
+ className="**:[text]:fill-muted-foreground"
+ hide={hideXAxis}
+ displayEdgeLabelsOnly={displayEdgeLabelsOnly}
+ intervalType={intervalType}
+ {...xAxisProps}
+ />
+ <YAxis
+ className="**:[text]:fill-muted-foreground"
+ hide={hideYAxis}
+ tickFormatter={type === "percent" ? valueToPercent : valueFormatter}
+ {...yAxisProps}
+ />
+
+ {legend && (
+ <ChartLegend
+ content={typeof legend === "boolean" ? <ChartLegendContent /> : legend}
+ {...legendProps}
+ />
+ )}
+
+ {tooltip && (
+ <ChartTooltip
+ content={
+ typeof tooltip === "boolean" ? (
+ <ChartTooltipContent
+ {...{
+ hideIndicator: tooltipProps?.hideIndicator,
+ hideLabel: tooltipProps?.hideLabel,
+ cursor: tooltipProps?.cursor,
+ indicator: tooltipProps?.indicator,
+ labelSeparator: tooltipProps?.labelSeparator,
+ formatter: tooltipProps?.formatter,
+ labelFormatter: tooltipProps?.labelFormatter,
+ }}
+ accessibilityLayer
+ />
+ ) : (
+ tooltip
+ )
+ }
+ {...tooltipProps}
+ />
+ )}
+
+ {!children
+ ? configEntries.map(([category, values]) => {
+ const categoryId = `${areaId}-${category.replace(slugRegExp, "")}`
+ const strokeOpacity = selectedLegend && selectedLegend !== category ? 0.1 : 1
+ const stopOpacity = selectedLegend && selectedLegend !== category ? 0.1 : 0.5
+ const color = getColorValue(values.color || categoryColors.get(category))
+
+ return (
+ <Fragment key={categoryId}>
+ <defs>
+ <linearGradient style={{ color }} id={categoryId} x1="0" y1="0" x2="0" y2="1">
+ {getFillContent({ fillType, stopOpacity })}
+ </linearGradient>
+ </defs>
+ <Area
+ dot={false}
+ name={category}
+ dataKey={category}
+ stroke={color}
+ style={{
+ strokeWidth: 2,
+ strokeOpacity,
+ }}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ isAnimationActive={true}
+ connectNulls={connectNulls}
+ stackId={stacked ? "stack" : undefined}
+ fill={`url(#${categoryId})`}
+ {...areaProps}
+ />
+ </Fragment>
+ )
+ })
+ : children}
+ </AreaChartPrimitive>
+ )}
+ </Chart>
+ )
+}
diff --git a/frontend/src/components/ui/bar-chart.tsx b/frontend/src/components/ui/bar-chart.tsx
new file mode 100644
index 0000000..535dccd
--- /dev/null
+++ b/frontend/src/components/ui/bar-chart.tsx
@@ -0,0 +1,170 @@
+"use client"
+// Intent UI (https://intentui.com, MIT), vendored; see THIRD_PARTY_NOTICES.md
+
+import { type ComponentProps, startTransition, useMemo } from "react"
+import { Bar, BarChart as BarChartPrimitive } from "recharts"
+import {
+ type BaseChartProps,
+ CartesianGrid,
+ Chart,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+ ChartTooltipContent,
+ constructCategoryColors,
+ DEFAULT_COLORS,
+ getColorValue,
+ valueToPercent,
+ XAxis,
+ YAxis,
+} from "./chart"
+
+export interface BarChartProps extends BaseChartProps {
+ barCategoryGap?: number
+ barRadius?: number
+ barGap?: number
+ barSize?: number
+ cartesianGridProps?: ComponentProps<typeof CartesianGrid>
+ barProps?: Partial<React.ComponentProps<typeof Bar>>
+ chartProps?: Omit<ComponentProps<typeof BarChartPrimitive>, "data" | "stackOffset">
+}
+
+export function BarChart({
+ data = [],
+ dataKey,
+ colors = DEFAULT_COLORS,
+ type = "default",
+ config,
+ children,
+ layout = "horizontal",
+
+ // Components
+ tooltip = true,
+ tooltipProps,
+
+ legend = true,
+ legendProps,
+
+ intervalType = "equidistantPreserveStart",
+
+ barCategoryGap = 5,
+ barGap,
+ barSize,
+ barRadius,
+ barProps,
+
+ valueFormatter = (value: number) => value.toString(),
+
+ // XAxis
+ displayEdgeLabelsOnly = false,
+ xAxisProps,
+ hideXAxis = false,
+
+ // YAxis
+ yAxisProps,
+ hideYAxis = false,
+
+ hideGridLines = false,
+ cartesianGridProps,
+ chartProps,
+
+ ...props
+}: BarChartProps) {
+ const configKeys = useMemo(() => Object.keys(config), [config])
+ const categoryColors = useMemo(
+ () => constructCategoryColors(configKeys, colors),
+ [configKeys, colors]
+ )
+
+ const configEntries = useMemo(() => Object.entries(config), [config])
+
+ const stacked = type === "stacked" || type === "percent"
+ const defaultBarRadius = stacked ? undefined : 4
+
+ return (
+ <Chart config={config} data={data} dataKey={dataKey} layout={layout} {...props}>
+ {({ onLegendSelect, selectedLegend }) => (
+ <BarChartPrimitive
+ onClick={() => {
+ onLegendSelect(null)
+ }}
+ data={data}
+ margin={{
+ bottom: 0,
+ left: 5,
+ right: 0,
+ top: 5,
+ }}
+ layout={layout === "radial" ? "horizontal" : layout}
+ barGap={barGap}
+ barSize={barSize}
+ barCategoryGap={barCategoryGap}
+ stackOffset={type === "percent" ? "expand" : stacked ? "sign" : undefined}
+ {...chartProps}
+ >
+ {!hideGridLines && <CartesianGrid strokeDasharray="4 4" {...cartesianGridProps} />}
+ <XAxis
+ hide={hideXAxis}
+ className="**:[text]:fill-muted-foreground"
+ displayEdgeLabelsOnly={displayEdgeLabelsOnly}
+ intervalType={intervalType}
+ {...xAxisProps}
+ />
+ <YAxis
+ hide={hideYAxis}
+ className="**:[text]:fill-muted-foreground"
+ tickFormatter={type === "percent" ? valueToPercent : valueFormatter}
+ {...yAxisProps}
+ />
+
+ {legend && (
+ <ChartLegend
+ content={typeof legend === "boolean" ? <ChartLegendContent /> : legend}
+ {...legendProps}
+ />
+ )}
+
+ {tooltip && (
+ <ChartTooltip
+ content={
+ typeof tooltip === "boolean" ? <ChartTooltipContent accessibilityLayer /> : tooltip
+ }
+ {...tooltipProps}
+ />
+ )}
+
+ {!children
+ ? configEntries.map(([category, values]) => {
+ const color = getColorValue(values.color || categoryColors.get(category))
+ const strokeOpacity = selectedLegend && selectedLegend !== category ? 0.2 : 0
+ const fillOpacity = selectedLegend && selectedLegend !== category ? 0.1 : 1
+
+ return (
+ <Bar
+ key={category}
+ name={category}
+ dataKey={category}
+ stroke={color}
+ strokeWidth={1}
+ stackId={stacked ? "stack" : undefined}
+ onClick={(_item, _number, event) => {
+ event.stopPropagation()
+
+ startTransition(() => {
+ onLegendSelect(category)
+ })
+ }}
+ radius={barRadius ?? defaultBarRadius}
+ strokeOpacity={strokeOpacity}
+ fillOpacity={fillOpacity}
+ fill={color}
+ {...barProps}
+ />
+ )
+ })
+ : children}
+ </BarChartPrimitive>
+ )}
+ </Chart>
+ )
+}
diff --git a/frontend/src/components/ui/chart.tsx b/frontend/src/components/ui/chart.tsx
index 0436fc3..74a46b8 100644
--- a/frontend/src/components/ui/chart.tsx
+++ b/frontend/src/components/ui/chart.tsx
@@ -1,93 +1,251 @@
-"use client";
-import * as React from "react"
-import * as RechartsPrimitive from "recharts"
-import type { TooltipValueType } from "recharts"
-
+"use client"
+// Intent UI (https://intentui.com, MIT), vendored; see THIRD_PARTY_NOTICES.md
+
+import { createContext, type ReactElement, use, useCallback, useId, useMemo, useState } from "react"
+import { ToggleButton } from "react-aria-components/ToggleButton"
+import {
+ ToggleButtonGroup,
+ type ToggleButtonGroupProps,
+} from "react-aria-components/ToggleButtonGroup"
+import type {
+ CartesianGridProps as CartesianGridPrimitiveProps,
+ CartesianGridProps,
+ LegendPayload,
+ LegendProps,
+ TooltipProps,
+ XAxisProps as XAxisPropsPrimitive,
+ YAxisProps as YAxisPrimitiveProps,
+} from "recharts"
+import {
+ CartesianGrid as CartesianGridPrimitive,
+ Legend as LegendPrimitive,
+ ResponsiveContainer,
+ Tooltip as TooltipPrimitive,
+ XAxis as XAxisPrimitive,
+ YAxis as YAxisPrimitive,
+} from "recharts"
+import type { ContentType as LegendContentType } from "recharts/types/component/DefaultLegendContent"
+import type {
+ NameType,
+ Props as TooltipContentProps,
+ ValueType,
+} from "recharts/types/component/DefaultTooltipContent"
+import type { ContentType as TooltipContentType } from "recharts/types/component/Tooltip"
+import { twJoin } from "tailwind-merge"
import { cn } from "@/lib/utils"
+import { useIsMobile } from "@/hooks/use-mobile"
+import { cx } from "@/lib/primitive"
-// Format: { THEME_NAME: CSS_SELECTOR }
-const THEMES = {
- light: "",
- dark: ".dark"
-} as const
-
-const INITIAL_DIMENSION = {
- width: 320,
- height: 200
-} as const
-type TooltipNameType = number | string
+// #region Chart Types
+export type ChartType = "default" | "stacked" | "percent"
+export type ChartLayout = "horizontal" | "vertical" | "radial"
+export type IntervalType = "preserveStartEnd" | "equidistantPreserveStart"
-export type ChartConfig = Record<
- string,
- {
+export type ChartConfig = {
+ [k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
} & (
- | { color?: string; theme?: never }
+ | { color?: ChartColorKeys | (string & {}); theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
->
+}
-interface ChartContextValue {
+export const CHART_COLORS = {
+ "chart-1": "var(--chart-1)",
+ "chart-2": "var(--chart-2)",
+ "chart-3": "var(--chart-3)",
+ "chart-4": "var(--chart-4)",
+ "chart-5": "var(--chart-5)",
+} as const
+
+export type ChartColorKeys = keyof typeof CHART_COLORS | (string & {})
+
+export const DEFAULT_COLORS = ["chart-1", "chart-2", "chart-3", "chart-4", "chart-5"] as const
+
+export type ChartContextProps = {
config: ChartConfig
+ data?: Record<string, unknown>[]
+ layout: ChartLayout
+ dataKey?: string
+ selectedLegend: string | null
+ onLegendSelect: (legendItem: string | null) => void
}
-const ChartContext = React.createContext<ChartContextValue | null>(null)
+const ChartContext = createContext<ChartContextProps | null>(null)
-function useChart() {
- const context = React.useContext(ChartContext)
+export function useChart() {
+ const context = use(ChartContext)
if (!context) {
- throw new Error("useChart must be used within a <ChartContainer />")
+ throw new Error("useChart must be used within a <Chart />")
}
return context
}
-function ChartContainer({
+export function valueToPercent(value: number) {
+ return `${(value * 100).toFixed(0)}%`
+}
+
+export function constructCategoryColors(
+ categories: string[],
+ colors: readonly ChartColorKeys[]
+): Map<string, ChartColorKeys> {
+ const categoryColors = new Map<string, ChartColorKeys>()
+
+ categories.forEach((category, index) => {
+ const color = colors[index % colors.length]
+ if (color !== undefined) {
+ categoryColors.set(category, color)
+ }
+ })
+
+ return categoryColors
+}
+
+export function getColorValue(color?: string): string {
+ if (!color) {
+ return "var(--chart-1)"
+ }
+
+ return CHART_COLORS[color as "chart-1"] ?? color
+}
+
+function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
+ if (typeof payload !== "object" || payload === null) {
+ return undefined
+ }
+
+ const payloadPayload =
+ "payload" in payload && typeof payload.payload === "object" && payload.payload !== null
+ ? payload.payload
+ : undefined
+
+ let configLabelKey: string = key
+
+ if (key in payload && typeof payload[key as keyof typeof payload] === "string") {
+ configLabelKey = payload[key as keyof typeof payload] as string
+ } else if (
+ payloadPayload &&
+ key in payloadPayload &&
+ typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
+ ) {
+ configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string
+ }
+
+ return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config]
+}
+
+export interface BaseChartProps extends React.HTMLAttributes<HTMLDivElement> {
+ containerHeight?: number
+ config: ChartConfig
+ data: Record<string, unknown>[]
+ dataKey: string
+ colors?: readonly (ChartColorKeys | (string & {}))[]
+ type?: ChartType
+ intervalType?: IntervalType
+ layout?: ChartLayout
+ valueFormatter?: (value: number) => string
+
+ tooltip?: TooltipContentType<ValueType, NameType> | boolean
+ tooltipProps?: Omit<TooltipProps, "content"> & {
+ hideLabel?: boolean
+ labelSeparator?: boolean
+ hideIndicator?: boolean
+ indicator?: "line" | "dot" | "dashed"
+ nameKey?: string
+ labelKey?: string
+ }
+
+ cartesianGridProps?: CartesianGridProps
+
+ legend?: LegendContentType | boolean
+ legendProps?: Omit<React.ComponentProps<typeof LegendPrimitive>, "content" | "ref">
+
+ xAxisProps?: XAxisPropsPrimitive
+ yAxisProps?: YAxisPrimitiveProps
+
+ // XAxis
+ displayEdgeLabelsOnly?: boolean
+
+ hideGridLines?: boolean
+ hideXAxis?: boolean
+ hideYAxis?: boolean
+}
+
+export function Chart({
id,
className,
children,
config,
- initialDimension = INITIAL_DIMENSION,
+ data,
+ dataKey,
+ ref,
+ layout = "horizontal",
+ containerHeight,
...props
-}: React.ComponentProps<"div"> & {
- config: ChartConfig
- children: React.ComponentProps<
- typeof RechartsPrimitive.ResponsiveContainer
- >["children"]
- initialDimension?: {
- width: number
- height: number
- }
-}) {
- const uniqueId = React.useId()
- const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
+}: Omit<React.ComponentProps<"div">, "children"> &
+ Pick<ChartContextProps, "data" | "dataKey"> & {
+ config: ChartConfig
+ containerHeight?: number
+ layout?: ChartLayout
+ children: ReactElement | ((props: ChartContextProps) => ReactElement)
+ }) {
+ const isMobile = useIsMobile()
+ const uniqueId = useId()
+ const chartId = useMemo(() => `chart-${id || uniqueId.replace(/:/g, "")}`, [id, uniqueId])
+
+ const [selectedLegend, setSelectedLegend] = useState<string | null>(null)
+
+ const onLegendSelect = useCallback((legendItem: string | null) => {
+ setSelectedLegend(legendItem)
+ }, [])
+
+ const _data = useMemo(() => data ?? [], [data])
+ const _dataKey = dataKey ?? "value"
+
+ const value = useMemo(
+ () => ({
+ config,
+ selectedLegend,
+ onLegendSelect,
+ data: _data,
+ dataKey: _dataKey,
+ layout,
+ }),
+ [config, selectedLegend, onLegendSelect, _data, _dataKey, layout]
+ )
return (
- <ChartContext.Provider value={{ config }}>
+ <ChartContext value={value}>
<div
- data-slot="chart"
data-chart={chartId}
+ ref={ref}
className={cn(
- "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
+ "z-20 flex w-full justify-center text-xs",
+ "[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/80 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-sector]:outline-hidden [&_.recharts-surface]:outline-hidden [&_.recharts-surface_.recharts-text.recharts-cartesian-axis-tick-value]:*:fill-muted-foreground",
+ "[&_.recharts-dot[fill='#fff']]:fill-(--line-color)",
+ "[&_.recharts-active-dot>.recharts-dot]:stroke-foreground/10",
+
+ "[&_.recharts-surface_g]:focus:outline-hidden",
+
className
)}
- {...props}>
+ {...props}
+ >
<ChartStyle id={chartId} config={config} />
- <RechartsPrimitive.ResponsiveContainer initialDimension={initialDimension}>
- {children}
- </RechartsPrimitive.ResponsiveContainer>
+ <ResponsiveContainer height={containerHeight ?? (isMobile ? 200 : 370)}>
+ {typeof children === "function" ? children(value) : children}
+ </ResponsiveContainer>
</div>
- </ChartContext.Provider>
- );
+ </ChartContext>
+ )
}
-const ChartStyle = ({
- id,
- config
-}: { id: string; config: ChartConfig }) => {
- const colorConfig = Object.entries(config).filter(([, config]) => config.theme ?? config.color)
+const THEMES = { light: "", dark: ".dark" } as const
+function ChartStyle({ id, config }: { id: string; config: ChartConfig }) {
+ const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color)
if (!colorConfig.length) {
return null
@@ -97,92 +255,202 @@ const ChartStyle = ({
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
- .map(([theme, prefix]) => `
+ .map(
+ ([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
-.map(([key, itemConfig]) => {
-const color =
- itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
- itemConfig.color
-return color ? ` --color-${key}: ${color};` : null
-})
-.join("\n")}
+ .map(([key, itemConfig]) => {
+ const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color
+ return color ? ` --color-${key}: ${color};` : null
+ })
+ .join("\n")}
}
-`)
+`
+ )
.join("\n"),
- }} />
- );
+ }}
+ />
+ )
+}
+
+export type ChartTooltipProps<TValue extends ValueType, TName extends NameType> = TooltipProps<
+ TValue,
+ TName
+>
+
+const tooltipWrapperStyle = { outline: "none" } as const
+
+const cursorStyleRadial = {
+ stroke: "var(--muted)",
+ strokeWidth: 0.1,
+ fill: "var(--muted)",
+ fillOpacity: 0.5,
+} as const
+
+const cursorStyleDefault = {
+ stroke: "var(--muted)",
+ strokeWidth: 1,
+ fill: "var(--muted)",
+ fillOpacity: 0.5,
+} as const
+
+export function ChartTooltip(props: TooltipProps) {
+ const { layout } = useChart()
+ const cursorStyle = layout === "radial" ? cursorStyleRadial : cursorStyleDefault
+
+ return <TooltipPrimitive wrapperStyle={tooltipWrapperStyle} cursor={cursorStyle} {...props} />
+}
+
+export type ChartLegendProps = Omit<React.ComponentProps<typeof LegendPrimitive>, "ref">
+
+export function ChartLegend(props: ChartLegendProps) {
+ return <LegendPrimitive align="center" verticalAlign="bottom" {...props} />
+}
+
+export interface XAxisProps extends Omit<XAxisPropsPrimitive, "ref"> {
+ displayEdgeLabelsOnly?: boolean
+ intervalType?: IntervalType
+}
+
+const tickHorizontal = {
+ transform: "translate(0, 6)",
+} as const
+
+export function XAxis({
+ displayEdgeLabelsOnly,
+ className,
+ intervalType = "preserveStartEnd",
+ minTickGap = 5,
+ ...props
+}: XAxisProps) {
+ const { dataKey, data, layout } = useChart()
+
+ const ticks =
+ displayEdgeLabelsOnly && data?.length && dataKey
+ ? [data[0]?.[dataKey], data[data.length - 1]?.[dataKey]].filter(
+ (tick): tick is string | number => typeof tick === "string" || typeof tick === "number"
+ )
+ : undefined
+
+ const tick = layout === "horizontal" ? tickHorizontal : undefined
+ return (
+ <XAxisPrimitive
+ className={cn("text-muted-foreground text-xs **:[text]:fill-muted-foreground", className)}
+ interval={displayEdgeLabelsOnly ? "preserveStartEnd" : intervalType}
+ tick={tick}
+ ticks={ticks}
+ tickLine={false}
+ axisLine={false}
+ minTickGap={minTickGap}
+ dataKey={layout === "horizontal" ? dataKey : undefined}
+ {...props}
+ />
+ )
}
-const ChartTooltip = RechartsPrimitive.Tooltip
+const yAxisTickHorizontal = {
+ transform: "translate(-3, 0)",
+} as const
+
+const yAxisTickVertical = {
+ transform: "translate(0, 0)",
+} as const
+
+export function YAxis({
+ className,
+ width,
+ domain = ["auto", "auto"],
+ type,
+ ...props
+}: Omit<YAxisPrimitiveProps, "ref">) {
+ const { layout, dataKey } = useChart()
+
+ const tick = layout === "horizontal" ? yAxisTickHorizontal : yAxisTickVertical
+
+ return (
+ <YAxisPrimitive
+ className={cn("text-muted-foreground text-xs **:[text]:fill-muted-foreground", className)}
+ width={width ?? (layout === "horizontal" ? 48 : 80)}
+ domain={domain}
+ tick={tick}
+ dataKey={layout === "horizontal" ? undefined : dataKey}
+ type={type ?? (layout === "horizontal" ? "number" : "category")}
+ interval={layout === "horizontal" ? undefined : "equidistantPreserveStart"}
+ axisLine={false}
+ tickLine={false}
+ {...props}
+ />
+ )
+}
+
+export function CartesianGrid({ className, ...props }: CartesianGridPrimitiveProps) {
+ const { layout } = useChart()
+ return (
+ <CartesianGridPrimitive
+ className={cn("stroke-1 stroke-muted", className)}
+ horizontal={layout !== "vertical"}
+ vertical={layout === "vertical"}
+ {...props}
+ />
+ )
+}
-function ChartTooltipContent({
- active,
+export function ChartTooltipContent<TValue extends ValueType, TName extends NameType>({
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
+ labelSeparator = true,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
- labelKey
-}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
+ labelKey,
+ ref,
+}: TooltipContentProps<TValue, TName> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
+ labelSeparator?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
- } & Omit<
- RechartsPrimitive.DefaultTooltipContentProps<
- TooltipValueType,
- TooltipNameType
- >,
- "accessibilityLayer"
- >) {
+ }) {
const { config } = useChart()
- const tooltipLabel = React.useMemo(() => {
+ const tooltipLabel = useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
- const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
+
+ if (!item) {
+ return null
+ }
+
+ const key = `${labelKey || item.dataKey || item.name || "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
- ? (config[label]?.label ?? label)
+ ? config[label as keyof typeof config]?.label || label
: itemConfig?.label
if (labelFormatter) {
- return (
- <div className={cn("font-medium", labelClassName)}>
- {labelFormatter(value, payload)}
- </div>
- );
+ return <div className={labelClassName}>{labelFormatter(value, payload)}</div>
}
if (!value) {
return null
}
- return <div className={cn("font-medium", labelClassName)}>{value}</div>;
- }, [
- label,
- labelFormatter,
- payload,
- hideLabel,
- labelClassName,
- config,
- labelKey,
- ])
-
- if (!active || !payload?.length) {
+ return <div className={labelClassName}>{value}</div>
+ }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey])
+
+ if (!payload?.length) {
return null
}
@@ -190,172 +458,159 @@ function ChartTooltipContent({
return (
<div
+ ref={ref}
className={cn(
- "grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
+ "grid min-w-48 items-start rounded-lg bg-overlay/70 p-3 py-2 text-overlay-foreground text-xs ring ring-current/10 backdrop-blur-lg",
className
- )}>
- {!nestLabel ? tooltipLabel : null}
- <div className="grid gap-1.5">
- {payload
- .filter((item) => item.type !== "none")
- .map((item, index) => {
- const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
- const itemConfig = getPayloadConfigFromPayload(config, item, key)
- const indicatorColor = color ?? item.payload?.fill ?? item.color
-
- return (
- <div
- key={index}
- className={cn(
- "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
- indicator === "dot" && "items-center"
- )}>
- {formatter && item?.value !== undefined && item.name ? (
- formatter(item.value, item.name, item, index, item.payload)
- ) : (
- <>
- {itemConfig?.icon ? (
- <itemConfig.icon />
- ) : (
- !hideIndicator && (
- <div
- className={cn("shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)", {
- "h-2.5 w-2.5": indicator === "dot",
- "w-1": indicator === "line",
- "w-0 border-[1.5px] border-dashed bg-transparent":
- indicator === "dashed",
- "my-0.5": nestLabel && indicator === "dashed",
- })}
- style={
- {
- "--color-bg": indicatorColor,
- "--color-border": indicatorColor
- } as React.CSSProperties
- } />
- )
+ )}
+ >
+ {!hideLabel && (
+ <>
+ {!nestLabel ? <span className="font-medium">{tooltipLabel}</span> : null}
+ {labelSeparator && (
+ <span aria-hidden className="mt-2 mb-3 block h-px w-full bg-background/10" />
+ )}
+ </>
+ )}
+ <div className="grid gap-3">
+ {payload.map((item, index) => {
+ const key = `${nameKey || item.name || item.dataKey || "value"}`
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
+ const indicatorColor = color || item.payload.fill || item.color
+
+ return (
+ <div
+ key={key}
+ className={cn(
+ "flex w-full flex-wrap items-stretch gap-2 *:[svg]:text-muted-foreground",
+ indicator === "dot" && "items-center *:[svg]:size-2.5",
+ indicator === "line" && "*:[svg]:h-full *:[svg]:w-2.5"
+ )}
+ >
+ {formatter && item?.value !== undefined && item.name ? (
+ formatter(item.value, item.name, item, index, item.payload)
+ ) : (
+ <>
+ {itemConfig?.icon ? (
+ <itemConfig.icon />
+ ) : (
+ !hideIndicator && (
+ <div
+ className={cn(
+ "shrink-0 rounded-full border-(--color-border) bg-(--color-bg)",
+ indicator === "dot" && "size-2.5",
+ indicator === "line" && "w-1",
+ indicator === "dashed" &&
+ "w-0 border-[1.5px] border-dashed bg-transparent",
+ nestLabel && indicator === "dashed" && "my-0.5"
+ )}
+ style={
+ {
+ "--color-bg": indicatorColor,
+ "--color-border": indicatorColor,
+ } as React.CSSProperties
+ }
+ />
+ )
+ )}
+ <div
+ className={cn(
+ "flex flex-1 justify-between leading-none",
+ nestLabel ? "items-end" : "items-center"
)}
- <div
- className={cn(
- "flex flex-1 justify-between leading-none",
- nestLabel ? "items-end" : "items-center"
- )}>
- <div className="grid gap-1.5">
- {nestLabel ? tooltipLabel : null}
- <span className="text-muted-foreground">
- {itemConfig?.label ?? item.name}
- </span>
- </div>
- {item.value != null && (
- <span className="font-mono font-medium text-foreground tabular-nums">
- {typeof item.value === "number"
- ? item.value.toLocaleString()
- : String(item.value)}
- </span>
- )}
+ >
+ <div className="grid gap-1.5">
+ {nestLabel ? tooltipLabel : null}
+ <span className="text-muted-foreground">
+ {itemConfig?.label || item.name}
+ </span>
</div>
- </>
- )}
- </div>
- );
- })}
+
+ {item.value && (
+ <span className="font-medium font-mono text-foreground tabular-nums">
+ {item.value.toString()}
+ </span>
+ )}
+ </div>
+ </>
+ )}
+ </div>
+ )
+ })}
</div>
</div>
- );
+ )
}
-const ChartLegend = RechartsPrimitive.Legend
+export type ChartLegendContentProps = ToggleButtonGroupProps &
+ Pick<LegendProps, "align" | "verticalAlign"> & {
+ payload?: ReadonlyArray<LegendPayload>
+ hideIcon?: boolean
+ nameKey?: string
+ ref?: React.Ref<HTMLDivElement>
+ }
-function ChartLegendContent({
+export function ChartLegendContent({
className,
hideIcon = false,
payload,
+ align = "right",
verticalAlign = "bottom",
- nameKey
-}: React.ComponentProps<"div"> & {
- hideIcon?: boolean
- nameKey?: string
-} & RechartsPrimitive.DefaultLegendContentProps) {
- const { config } = useChart()
+ nameKey,
+ ref,
+}: ChartLegendContentProps) {
+ const { config, selectedLegend, onLegendSelect } = useChart()
if (!payload?.length) {
return null
}
return (
- <div
- className={cn(
- "flex items-center justify-center gap-4",
- verticalAlign === "top" ? "pb-3" : "pt-3",
+ <ToggleButtonGroup
+ ref={ref}
+ className={cx(
+ twJoin(
+ "flex flex-wrap items-center gap-x-1",
+ verticalAlign === "top" ? "pb-3" : "pt-3",
+ align === "right" ? "justify-end" : align === "left" ? "justify-start" : "justify-center"
+ ),
className
- )}>
- {payload
- .filter((item) => item.type !== "none")
- .map((item, index) => {
- const key = `${nameKey ?? item.dataKey ?? "value"}`
- const itemConfig = getPayloadConfigFromPayload(config, item, key)
-
- return (
- <div
- key={index}
- className={cn(
- "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
- )}>
- {itemConfig?.icon && !hideIcon ? (
- <itemConfig.icon />
- ) : (
- <div
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{
- backgroundColor: item.color,
- }} />
- )}
- {itemConfig?.label}
- </div>
- );
- })}
- </div>
- );
-}
-
-function getPayloadConfigFromPayload(
- config: ChartConfig,
- payload: unknown,
- key: string
-) {
- if (typeof payload !== "object" || payload === null) {
- return undefined
- }
-
- const payloadPayload =
- "payload" in payload &&
- typeof payload.payload === "object" &&
- payload.payload !== null
- ? payload.payload
- : undefined
-
- let configLabelKey: string = key
-
- if (
- key in payload &&
- typeof payload[key as keyof typeof payload] === "string"
- ) {
- configLabelKey = payload[key as keyof typeof payload] as string
- } else if (
- payloadPayload &&
- key in payloadPayload &&
- typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
- ) {
- configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string
- }
-
- return configLabelKey in config ? config[configLabelKey] : config[key]
-}
-
-export {
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
- ChartLegend,
- ChartLegendContent,
- ChartStyle,
+ )}
+ selectedKeys={selectedLegend ? [selectedLegend] : []}
+ onSelectionChange={(v) => {
+ const key = [...v][0]?.toString() ?? null
+ onLegendSelect(key)
+ }}
+ selectionMode="single"
+ >
+ {payload.map((item: LegendPayload) => {
+ const key = `${nameKey || item.dataKey || "value"}`
+ const itemConfig = getPayloadConfigFromPayload(config, item, key)
+
+ return (
+ <ToggleButton
+ key={key}
+ id={key}
+ className={cn(
+ "flex items-center gap-2 rounded-sm px-2 py-1 text-muted-foreground *:[svg]:-mx-0.5 *:[svg]:size-2.5 *:[svg]:shrink-0 *:[svg]:text-muted-foreground",
+ "data-selected:bg-secondary/70 data-selected:text-secondary-foreground",
+ "hover:bg-secondary/70 hover:text-secondary-foreground"
+ )}
+ >
+ {itemConfig?.icon && !hideIcon ? (
+ <itemConfig.icon />
+ ) : (
+ <div
+ className="size-2.5 rounded-full"
+ style={{
+ backgroundColor: item.color,
+ }}
+ />
+ )}
+ {itemConfig?.label}
+ </ToggleButton>
+ )
+ })}
+ </ToggleButtonGroup>
+ )
}
diff --git a/frontend/src/components/ui/line-chart.tsx b/frontend/src/components/ui/line-chart.tsx
new file mode 100644
index 0000000..e61ea92
--- /dev/null
+++ b/frontend/src/components/ui/line-chart.tsx
@@ -0,0 +1,148 @@
+"use client"
+// Intent UI (https://intentui.com, MIT), vendored; see THIRD_PARTY_NOTICES.md
+
+import { useMemo } from "react"
+import { Line, LineChart as LineChartPrimitive, type LineProps } from "recharts"
+import {
+ type BaseChartProps,
+ CartesianGrid,
+ Chart,
+ ChartLegend,
+ ChartLegendContent,
+ ChartTooltip,
+ ChartTooltipContent,
+ constructCategoryColors,
+ DEFAULT_COLORS,
+ getColorValue,
+ valueToPercent,
+ XAxis,
+ YAxis,
+} from "./chart"
+
+export interface LineChartProps extends BaseChartProps {
+ connectNulls?: boolean
+ lineProps?: LineProps
+ chartProps?: Omit<React.ComponentProps<typeof LineChartPrimitive>, "data" | "stackOffset">
+}
+
+export function LineChart({
+ data = [],
+ dataKey,
+ colors = DEFAULT_COLORS,
+ connectNulls = false,
+ type = "default",
+ config,
+ children,
+
+ // Components
+ tooltip = true,
+ tooltipProps,
+
+ legend = true,
+ legendProps,
+
+ intervalType = "equidistantPreserveStart",
+
+ valueFormatter = (value: number) => value.toString(),
+
+ // XAxis
+ displayEdgeLabelsOnly = false,
+ xAxisProps,
+ hideXAxis = false,
+
+ // YAxis
+ yAxisProps,
+ hideYAxis = false,
+
+ hideGridLines = false,
+ chartProps,
+ lineProps,
+ ...props
+}: LineChartProps) {
+ const configKeys = useMemo(() => Object.keys(config), [config])
+ const categoryColors = useMemo(
+ () => constructCategoryColors(configKeys, colors),
+ [configKeys, colors]
+ )
+
+ const configEntries = useMemo(() => Object.entries(config), [config])
+
+ return (
+ <Chart config={config} data={data} dataKey={dataKey} {...props}>
+ {({ onLegendSelect, selectedLegend }) => (
+ <LineChartPrimitive
+ onClick={() => {
+ onLegendSelect(null)
+ }}
+ data={data}
+ margin={{
+ bottom: 0,
+ left: 0,
+ right: 0,
+ top: 5,
+ }}
+ stackOffset={type === "percent" ? "expand" : undefined}
+ {...chartProps}
+ >
+ {!hideGridLines && <CartesianGrid strokeDasharray="4 4" />}
+ <XAxis
+ hide={hideXAxis}
+ displayEdgeLabelsOnly={displayEdgeLabelsOnly}
+ intervalType={intervalType}
+ {...xAxisProps}
+ />
+ <YAxis
+ hide={hideYAxis}
+ tickFormatter={type === "percent" ? valueToPercent : valueFormatter}
+ {...yAxisProps}
+ />
+
+ {legend && (
+ <ChartLegend
+ content={typeof legend === "boolean" ? <ChartLegendContent /> : legend}
+ {...legendProps}
+ />
+ )}
+
+ {tooltip && (
+ <ChartTooltip
+ content={
+ typeof tooltip === "boolean" ? <ChartTooltipContent accessibilityLayer /> : tooltip
+ }
+ {...tooltipProps}
+ />
+ )}
+
+ {!children
+ ? configEntries.map(([category, values]) => {
+ const strokeOpacity = selectedLegend && selectedLegend !== category ? 0.1 : 1
+ const color = getColorValue(values.color || categoryColors.get(category))
+
+ return (
+ <Line
+ key={category}
+ dot={false}
+ name={category}
+ type="linear"
+ dataKey={category}
+ stroke={color}
+ style={
+ {
+ strokeOpacity,
+ strokeWidth: 2,
+ "--line-color": color,
+ } as React.CSSProperties
+ }
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ connectNulls={connectNulls}
+ {...lineProps}
+ />
+ )
+ })
+ : children}
+ </LineChartPrimitive>
+ )}
+ </Chart>
+ )
+}
diff --git a/frontend/src/index.css b/frontend/src/index.css
index babb36b..66e92d3 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -118,6 +118,9 @@
--card: var(--surface-raised);
--card-foreground: var(--ink);
--popover: var(--surface-overlay);
+ /* Intent UI's chart tooltip reads overlay colours; they are the popover surface here */
+ --overlay: var(--surface-overlay);
+ --overlay-foreground: var(--ink);
--popover-foreground: var(--ink);
--primary: var(--brand);
--primary-foreground: var(--on-brand);
@@ -216,6 +219,8 @@
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
+ --color-overlay: var(--overlay);
+ --color-overlay-foreground: var(--overlay-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
diff --git a/frontend/src/lib/primitive.ts b/frontend/src/lib/primitive.ts
new file mode 100644
index 0000000..63cc2f3
--- /dev/null
+++ b/frontend/src/lib/primitive.ts
@@ -0,0 +1,16 @@
+"use client"
+// Intent UI (https://intentui.com, MIT), vendored; see THIRD_PARTY_NOTICES.md
+
+import { composeRenderProps } from "react-aria-components/composeRenderProps"
+import type { ClassNameValue } from "tailwind-merge"
+import { cn } from "@/lib/utils"
+
+type Render<T> = string | ((v: T) => string) | undefined
+
+export function cx<T = unknown>(
+ ...classes: [...ClassNameValue[], Render<T>]
+): string | ((v: T) => string) {
+ const className = classes.pop() as Render<T>
+
+ return composeRenderProps(className, (className) => cn(classes, className))
+}
diff --git a/package-lock.json b/package-lock.json
index 15ca9ba..619e657 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -60,6 +60,7 @@
"lucide-react": "^1.17.0",
"next-themes": "^0.4.6",
"react": "^19.2.0",
+ "react-aria-components": "^1.22.1",
"react-dom": "^19.2.0",
"react-router-dom": "^7.18.4",
"recharts": "^3.8.0",
@@ -2209,6 +2210,33 @@
"url": "https://opencollective.com/libvips"
}
},
+ "node_modules/@internationalized/date": {
+ "version": "3.12.4",
+ "resolved": "https://registry.npmjs.org/@internationalized/date/-/date-3.12.4.tgz",
+ "integrity": "sha512-M1dEn4c1U1HsSlaVR8upZtSqvXrTkHDfv18H01uCSJyjVLDxnBR38v/fMxecmlwXKR4i9HeZcmgQAPE6A+aGJQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/helpers": "^0.5.0"
+ }
+ },
+ "node_modules/@internationalized/number": {
+ "version": "3.6.9",
+ "resolved": "https://registry.npmjs.org/@internationalized/number/-/number-3.6.9.tgz",
+ "integrity": "sha512-GgWy2caO/+hV9sT/oCTWGHvbjmJMPT9kkXzoKRLnkEq7adghhR7UprhvY9sXrKfrp3NcDfhF6QQHXR1KfQbB8g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/helpers": "^0.5.0"
+ }
+ },
+ "node_modules/@internationalized/string": {
+ "version": "3.2.10",
+ "resolved": "https://registry.npmjs.org/@internationalized/string/-/string-3.2.10.tgz",
+ "integrity": "sha512-PDx6//vHSpRnHfxqMqto11zQvhsaU74O3mKv2F/0eicGZcl9NLjQmGlbHz/LsJh5tLKp4A4L7ZVTzN1/MmMTvA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/helpers": "^0.5.0"
+ }
+ },
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -2862,6 +2890,15 @@
}
}
},
+ "node_modules/@react-types/shared": {
+ "version": "3.37.0",
+ "resolved": "https://registry.npmjs.org/@react-types/shared/-/shared-3.37.0.tgz",
+ "integrity": "sha512-VNlZuifu4tHdxWPfHvoMfKsHA9kVTCGkduv5vKVTdinm8wHFJNhyVB5RzIMiRFj0q3RKoCbP68u2zaoBSiFueg==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
+ }
+ },
"node_modules/@reduxjs/toolkit": {
"version": "2.13.0",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.13.0.tgz",
@@ -3700,6 +3737,12 @@
"node": ">=22.0.0"
}
},
+ "node_modules/@swc/helpers": {
+ "version": "0.5.24",
+ "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.24.tgz",
+ "integrity": "sha512-6tcXo4kA8HgGO7AVmawB57RYi/piBPYVHVcO6dXjX+SZw8GoHmi262sp4v2Ha2kNP9Cx84qei27yT+fjS1lxgg==",
+ "license": "Apache-2.0"
+ },
"node_modules/@tailwindcss/node": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz",
@@ -5075,6 +5118,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/client-only": {
+ "version": "0.0.1",
+ "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
+ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
+ "license": "MIT"
+ },
"node_modules/cliui": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",
@@ -10033,6 +10082,47 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react-aria": {
+ "version": "3.53.1",
+ "resolved": "https://registry.npmjs.org/react-aria/-/react-aria-3.53.1.tgz",
+ "integrity": "sha512-dikisyOjJd3D2fFrIDWmVWzqiLz5B86GzZv1zxs7xI4dVc0JIz/1Wa52I20gYvVL2WXeFXlygYsle/QcOMhtcg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@internationalized/date": "^3.12.4",
+ "@internationalized/number": "^3.6.9",
+ "@internationalized/string": "^3.2.10",
+ "@react-types/shared": "^3.37.0",
+ "@swc/helpers": "^0.5.0",
+ "aria-hidden": "^1.2.3",
+ "clsx": "^2.0.0",
+ "react-stately": "3.51.0",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1",
+ "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
+ }
+ },
+ "node_modules/react-aria-components": {
+ "version": "1.22.1",
+ "resolved": "https://registry.npmjs.org/react-aria-components/-/react-aria-components-1.22.1.tgz",
+ "integrity": "sha512-UTHaYHOaM71bOCjGPF50DcLywlrwAodE63IP64LB4kO+OizatQEL8TesVEOM8+TkBeSgHoflJ45388IlJfa7aw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@internationalized/date": "^3.12.4",
+ "@internationalized/string": "^3.2.10",
+ "@react-types/shared": "^3.37.0",
+ "@swc/helpers": "^0.5.0",
+ "client-only": "^0.0.1",
+ "react-aria": "3.53.1",
+ "react-stately": "3.51.0",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1",
+ "react-dom": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
+ }
+ },
"node_modules/react-dom": {
"version": "19.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz",
@@ -10172,6 +10262,23 @@
"react-dom": ">=18"
}
},
+ "node_modules/react-stately": {
+ "version": "3.51.0",
+ "resolved": "https://registry.npmjs.org/react-stately/-/react-stately-3.51.0.tgz",
+ "integrity": "sha512-YJcmkAXu2XOQP97hO/qz/cC3qv9kni3oVhwBlxWr358BHePJUpY15XwL3YSRMKxYt4EkslPqAz11JRirMfANGw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@internationalized/date": "^3.12.4",
+ "@internationalized/number": "^3.6.9",
+ "@internationalized/string": "^3.2.10",
+ "@react-types/shared": "^3.37.0",
+ "@swc/helpers": "^0.5.0",
+ "use-sync-external-store": "^1.6.0"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
+ }
+ },
"node_modules/react-style-singleton": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",