chart.tsx353 lines, 9.5 KB
| 1 | "use client" |
| 2 | |
| 3 | import * as React from "react" |
| 4 | import * as RechartsPrimitive from "recharts" |
| 5 | |
| 6 | import { cn } from "@/lib/utils" |
| 7 | |
| 8 | // Format: { THEME_NAME: CSS_SELECTOR } |
| 9 | const THEMES = { light: "", dark: ".dark" } as const |
| 10 | |
| 11 | export type ChartConfig = { |
| 12 | [k in string]: { |
| 13 | label?: React.ReactNode |
| 14 | icon?: React.ComponentType |
| 15 | } & ( |
| 16 | | { color?: string; theme?: never } |
| 17 | | { color?: never; theme: Record<keyof typeof THEMES, string> } |
| 18 | ) |
| 19 | } |
| 20 | |
| 21 | type ChartContextProps = { |
| 22 | config: ChartConfig |
| 23 | } |
| 24 | |
| 25 | const ChartContext = React.createContext<ChartContextProps | null>(null) |
| 26 | |
| 27 | function useChart() { |
| 28 | const context = React.useContext(ChartContext) |
| 29 | |
| 30 | if (!context) { |
| 31 | throw new Error("useChart must be used within a <ChartContainer />") |
| 32 | } |
| 33 | |
| 34 | return context |
| 35 | } |
| 36 | |
| 37 | function ChartContainer({ |
| 38 | id, |
| 39 | className, |
| 40 | children, |
| 41 | config, |
| 42 | ...props |
| 43 | }: React.ComponentProps<"div"> & { |
| 44 | config: ChartConfig |
| 45 | children: React.ComponentProps< |
| 46 | typeof RechartsPrimitive.ResponsiveContainer |
| 47 | >["children"] |
| 48 | }) { |
| 49 | const uniqueId = React.useId() |
| 50 | const chartId = `chart-${id || uniqueId.replace(/:/g, "")}` |
| 51 | |
| 52 | return ( |
| 53 | <ChartContext.Provider value={{ config }}> |
| 54 | <div |
| 55 | data-slot="chart" |
| 56 | data-chart={chartId} |
| 57 | className={cn( |
| 58 | "[&_.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-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 flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden", |
| 59 | className |
| 60 | )} |
| 61 | {...props} |
| 62 | > |
| 63 | <ChartStyle id={chartId} config={config} /> |
| 64 | <RechartsPrimitive.ResponsiveContainer> |
| 65 | {children} |
| 66 | </RechartsPrimitive.ResponsiveContainer> |
| 67 | </div> |
| 68 | </ChartContext.Provider> |
| 69 | ) |
| 70 | } |
| 71 | |
| 72 | const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { |
| 73 | const colorConfig = Object.entries(config).filter( |
| 74 | ([, config]) => config.theme || config.color |
| 75 | ) |
| 76 | |
| 77 | if (!colorConfig.length) { |
| 78 | return null |
| 79 | } |
| 80 | |
| 81 | return ( |
| 82 | <style |
| 83 | dangerouslySetInnerHTML={{ |
| 84 | __html: Object.entries(THEMES) |
| 85 | .map( |
| 86 | ([theme, prefix]) => ` |
| 87 | ${prefix} [data-chart=${id}] { |
| 88 | ${colorConfig |
| 89 | .map(([key, itemConfig]) => { |
| 90 | const color = |
| 91 | itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || |
| 92 | itemConfig.color |
| 93 | return color ? ` --color-${key}: ${color};` : null |
| 94 | }) |
| 95 | .join("\n")} |
| 96 | } |
| 97 | ` |
| 98 | ) |
| 99 | .join("\n"), |
| 100 | }} |
| 101 | /> |
| 102 | ) |
| 103 | } |
| 104 | |
| 105 | const ChartTooltip = RechartsPrimitive.Tooltip |
| 106 | |
| 107 | function ChartTooltipContent({ |
| 108 | active, |
| 109 | payload, |
| 110 | className, |
| 111 | indicator = "dot", |
| 112 | hideLabel = false, |
| 113 | hideIndicator = false, |
| 114 | label, |
| 115 | labelFormatter, |
| 116 | labelClassName, |
| 117 | formatter, |
| 118 | color, |
| 119 | nameKey, |
| 120 | labelKey, |
| 121 | }: React.ComponentProps<typeof RechartsPrimitive.Tooltip> & |
| 122 | React.ComponentProps<"div"> & { |
| 123 | hideLabel?: boolean |
| 124 | hideIndicator?: boolean |
| 125 | indicator?: "line" | "dot" | "dashed" |
| 126 | nameKey?: string |
| 127 | labelKey?: string |
| 128 | }) { |
| 129 | const { config } = useChart() |
| 130 | |
| 131 | const tooltipLabel = React.useMemo(() => { |
| 132 | if (hideLabel || !payload?.length) { |
| 133 | return null |
| 134 | } |
| 135 | |
| 136 | const [item] = payload |
| 137 | const key = `${labelKey || item.dataKey || item.name || "value"}` |
| 138 | const itemConfig = getPayloadConfigFromPayload(config, item, key) |
| 139 | const value = |
| 140 | !labelKey && typeof label === "string" |
| 141 | ? config[label as keyof typeof config]?.label || label |
| 142 | : itemConfig?.label |
| 143 | |
| 144 | if (labelFormatter) { |
| 145 | return ( |
| 146 | <div className={cn("font-medium", labelClassName)}> |
| 147 | {labelFormatter(value, payload)} |
| 148 | </div> |
| 149 | ) |
| 150 | } |
| 151 | |
| 152 | if (!value) { |
| 153 | return null |
| 154 | } |
| 155 | |
| 156 | return <div className={cn("font-medium", labelClassName)}>{value}</div> |
| 157 | }, [ |
| 158 | label, |
| 159 | labelFormatter, |
| 160 | payload, |
| 161 | hideLabel, |
| 162 | labelClassName, |
| 163 | config, |
| 164 | labelKey, |
| 165 | ]) |
| 166 | |
| 167 | if (!active || !payload?.length) { |
| 168 | return null |
| 169 | } |
| 170 | |
| 171 | const nestLabel = payload.length === 1 && indicator !== "dot" |
| 172 | |
| 173 | return ( |
| 174 | <div |
| 175 | className={cn( |
| 176 | "border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl", |
| 177 | className |
| 178 | )} |
| 179 | > |
| 180 | {!nestLabel ? tooltipLabel : null} |
| 181 | <div className="grid gap-1.5"> |
| 182 | {payload.map((item, index) => { |
| 183 | const key = `${nameKey || item.name || item.dataKey || "value"}` |
| 184 | const itemConfig = getPayloadConfigFromPayload(config, item, key) |
| 185 | const indicatorColor = color || item.payload.fill || item.color |
| 186 | |
| 187 | return ( |
| 188 | <div |
| 189 | key={item.dataKey} |
| 190 | className={cn( |
| 191 | "[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5", |
| 192 | indicator === "dot" && "items-center" |
| 193 | )} |
| 194 | > |
| 195 | {formatter && item?.value !== undefined && item.name ? ( |
| 196 | formatter(item.value, item.name, item, index, item.payload) |
| 197 | ) : ( |
| 198 | <> |
| 199 | {itemConfig?.icon ? ( |
| 200 | <itemConfig.icon /> |
| 201 | ) : ( |
| 202 | !hideIndicator && ( |
| 203 | <div |
| 204 | className={cn( |
| 205 | "shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)", |
| 206 | { |
| 207 | "h-2.5 w-2.5": indicator === "dot", |
| 208 | "w-1": indicator === "line", |
| 209 | "w-0 border-[1.5px] border-dashed bg-transparent": |
| 210 | indicator === "dashed", |
| 211 | "my-0.5": nestLabel && indicator === "dashed", |
| 212 | } |
| 213 | )} |
| 214 | style={ |
| 215 | { |
| 216 | "--color-bg": indicatorColor, |
| 217 | "--color-border": indicatorColor, |
| 218 | } as React.CSSProperties |
| 219 | } |
| 220 | /> |
| 221 | ) |
| 222 | )} |
| 223 | <div |
| 224 | className={cn( |
| 225 | "flex flex-1 justify-between leading-none", |
| 226 | nestLabel ? "items-end" : "items-center" |
| 227 | )} |
| 228 | > |
| 229 | <div className="grid gap-1.5"> |
| 230 | {nestLabel ? tooltipLabel : null} |
| 231 | <span className="text-muted-foreground"> |
| 232 | {itemConfig?.label || item.name} |
| 233 | </span> |
| 234 | </div> |
| 235 | {item.value && ( |
| 236 | <span className="text-foreground font-mono font-medium tabular-nums"> |
| 237 | {item.value.toLocaleString()} |
| 238 | </span> |
| 239 | )} |
| 240 | </div> |
| 241 | </> |
| 242 | )} |
| 243 | </div> |
| 244 | ) |
| 245 | })} |
| 246 | </div> |
| 247 | </div> |
| 248 | ) |
| 249 | } |
| 250 | |
| 251 | const ChartLegend = RechartsPrimitive.Legend |
| 252 | |
| 253 | function ChartLegendContent({ |
| 254 | className, |
| 255 | hideIcon = false, |
| 256 | payload, |
| 257 | verticalAlign = "bottom", |
| 258 | nameKey, |
| 259 | }: React.ComponentProps<"div"> & |
| 260 | Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & { |
| 261 | hideIcon?: boolean |
| 262 | nameKey?: string |
| 263 | }) { |
| 264 | const { config } = useChart() |
| 265 | |
| 266 | if (!payload?.length) { |
| 267 | return null |
| 268 | } |
| 269 | |
| 270 | return ( |
| 271 | <div |
| 272 | className={cn( |
| 273 | "flex items-center justify-center gap-4", |
| 274 | verticalAlign === "top" ? "pb-3" : "pt-3", |
| 275 | className |
| 276 | )} |
| 277 | > |
| 278 | {payload.map((item) => { |
| 279 | const key = `${nameKey || item.dataKey || "value"}` |
| 280 | const itemConfig = getPayloadConfigFromPayload(config, item, key) |
| 281 | |
| 282 | return ( |
| 283 | <div |
| 284 | key={item.value} |
| 285 | className={cn( |
| 286 | "[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3" |
| 287 | )} |
| 288 | > |
| 289 | {itemConfig?.icon && !hideIcon ? ( |
| 290 | <itemConfig.icon /> |
| 291 | ) : ( |
| 292 | <div |
| 293 | className="h-2 w-2 shrink-0 rounded-[2px]" |
| 294 | style={{ |
| 295 | backgroundColor: item.color, |
| 296 | }} |
| 297 | /> |
| 298 | )} |
| 299 | {itemConfig?.label} |
| 300 | </div> |
| 301 | ) |
| 302 | })} |
| 303 | </div> |
| 304 | ) |
| 305 | } |
| 306 | |
| 307 | // Helper to extract item config from a payload. |
| 308 | function getPayloadConfigFromPayload( |
| 309 | config: ChartConfig, |
| 310 | payload: unknown, |
| 311 | key: string |
| 312 | ) { |
| 313 | if (typeof payload !== "object" || payload === null) { |
| 314 | return undefined |
| 315 | } |
| 316 | |
| 317 | const payloadPayload = |
| 318 | "payload" in payload && |
| 319 | typeof payload.payload === "object" && |
| 320 | payload.payload !== null |
| 321 | ? payload.payload |
| 322 | : undefined |
| 323 | |
| 324 | let configLabelKey: string = key |
| 325 | |
| 326 | if ( |
| 327 | key in payload && |
| 328 | typeof payload[key as keyof typeof payload] === "string" |
| 329 | ) { |
| 330 | configLabelKey = payload[key as keyof typeof payload] as string |
| 331 | } else if ( |
| 332 | payloadPayload && |
| 333 | key in payloadPayload && |
| 334 | typeof payloadPayload[key as keyof typeof payloadPayload] === "string" |
| 335 | ) { |
| 336 | configLabelKey = payloadPayload[ |
| 337 | key as keyof typeof payloadPayload |
| 338 | ] as string |
| 339 | } |
| 340 | |
| 341 | return configLabelKey in config |
| 342 | ? config[configLabelKey] |
| 343 | : config[key as keyof typeof config] |
| 344 | } |
| 345 | |
| 346 | export { |
| 347 | ChartContainer, |
| 348 | ChartTooltip, |
| 349 | ChartTooltipContent, |
| 350 | ChartLegend, |
| 351 | ChartLegendContent, |
| 352 | ChartStyle, |
| 353 | } |