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