Skip to content

Commit

Permalink
feat: add charts
Browse files Browse the repository at this point in the history
  • Loading branch information
nahoc committed Jul 23, 2024
1 parent 4d16275 commit 67f9acf
Show file tree
Hide file tree
Showing 4 changed files with 332 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ https://www.npmjs.com/package/@risc0/ui

| Statements | Branches | Functions | Lines |
| --------------------------- | ----------------------- | ------------------------- | ----------------- |
| ![Statements](https://img.shields.io/badge/statements-42.75%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-71.83%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-52.94%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-42.75%25-red.svg?style=flat) |
| ![Statements](https://img.shields.io/badge/statements-37.43%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-70.83%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-51.42%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-37.43%25-red.svg?style=flat) |
316 changes: 316 additions & 0 deletions chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,316 @@
"use client";

import {
type CSSProperties,
type ComponentProps,
type ComponentType,
type ReactNode,
createContext,
forwardRef,
useContext,
useId,
useMemo,
} from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "./cn";

// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const;

export type ChartConfig = {
[k in string]: {
label?: ReactNode;
icon?: ComponentType;
} & ({ color?: string; theme?: never } | { color?: never; theme: Record<keyof typeof THEMES, string> });
};

type ChartContextProps = {
config: ChartConfig;
};

const ChartContext = createContext<ChartContextProps | null>(null);

function useChart() {
const context = useContext(ChartContext);

if (!context) {
throw new Error("useChart must be used within a <ChartContainer />");
}

return context;
}

const ChartContainer = forwardRef<
HTMLDivElement,
ComponentProps<"div"> & {
config: ChartConfig;
children: ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>["children"];
}
>(({ id, className, children, config, ...props }, ref) => {
const uniqueId = useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;

return (
<ChartContext.Provider value={{ config }}>
<div
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-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",
className,
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
});

const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(([_, config]) => config.theme || config.color);

if (!colorConfig.length) {
return null;
}

return (
<style
// biome-ignore lint/security/noDangerouslySetInnerHtml: ignore
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.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")}
}
`,
)
.join("\n"),
}}
/>
);
};

const ChartTooltip = RechartsPrimitive.Tooltip;

const ChartTooltipContent = forwardRef<
HTMLDivElement,
ComponentProps<typeof RechartsPrimitive.Tooltip> &
ComponentProps<"div"> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
}
>(
(
{
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
},
ref,
) => {
const { config } = useChart();

const tooltipLabel = useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}

const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value =
!labelKey && typeof label === "string"
? config[label as keyof typeof config]?.label || label
: itemConfig?.label;

if (labelFormatter) {
return <div className={cn("font-medium", 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 null;
}

const nestLabel = payload.length === 1 && indicator !== "dot";

return (
<div
ref={ref}
className={cn(
"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",
className,
)}
>
{nestLabel ? null : tooltipLabel}
<div className="grid gap-1.5">
{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={item.dataKey}
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 CSSProperties
}
/>
)
)}
<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 && (
<span className="font-medium font-mono text-foreground tabular-nums">
{item.value.toLocaleString()}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
},
);

const ChartLegend = RechartsPrimitive.Legend;

const ChartLegendContent = forwardRef<
HTMLDivElement,
ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean;
nameKey?: string;
}
>(({ className, hideIcon = false, payload, verticalAlign = "bottom", nameKey }, ref) => {
const { config } = useChart();

if (!payload?.length) {
return null;
}

return (
<div
ref={ref}
className={cn("flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", className)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);

return (
<div
key={item.value}
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>
);
});

// Helper to extract item config from a payload.
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];
}

ChartTooltipContent.displayName = "ChartTooltip";
ChartContainer.displayName = "Chart";
ChartLegendContent.displayName = "ChartLegend";

export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle };
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@risc0/ui",
"version": "0.0.127",
"version": "0.0.128",
"private": false,
"sideEffects": false,
"type": "module",
Expand Down Expand Up @@ -38,6 +38,7 @@
"next-themes": "0.3.0",
"radash": "12.1.0",
"react-hook-form": "7.52.1",
"recharts": "2.12.7",
"simplebar-react": "3.2.6",
"sonner": "1.5.0",
"string-ts": "2.2.0",
Expand Down
14 changes: 13 additions & 1 deletion styles/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@
--input: 20 5.9% 90%;
--ring: 20 14.3% 4.1%;
--radius: 0.3rem;

--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
}

.dark {
Expand All @@ -46,6 +52,12 @@
--border: 12 6.5% 15.1%;
--input: 12 6.5% 15.1%;
--ring: 61 100% 80.8%;

--chart-1: 220 70% 50%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
}
}

Expand Down Expand Up @@ -114,4 +126,4 @@ iframe {
.lucide {
/* bigger stroke for ALL icons */
stroke-width: 1.75px !important;
}
}

0 comments on commit 67f9acf

Please sign in to comment.