Adds Chakra UI CLI, self-hosted fonts, and prettier config
Moves prettier config into web/, adds @chakra-ui/cli for typegen and the fontsource font packages needed for self-hosted Jost and Marcellus, and brings in the chakra-ui-* skill docs.
This commit is contained in:
@@ -0,0 +1,374 @@
|
||||
---
|
||||
name: chakra-ui-builder
|
||||
description: >
|
||||
Build responsive, accessible UI components and layouts using Chakra UI v3,
|
||||
install or configure Chakra UI in new and existing projects, and design
|
||||
scalable themes using tokens, semantic tokens, recipes, and slot recipes. Use
|
||||
this skill whenever a user asks to build, create, or generate any UI
|
||||
component, page, form, dashboard, navbar, card, landing section, pricing
|
||||
table, or layout using Chakra UI; wants to add Chakra UI to a project, set up
|
||||
ChakraProvider, run CLI snippets, configure color mode, or fix provider
|
||||
wrapping; or asks about theming — defining brand colors, design tokens,
|
||||
semantic tokens, dark mode values, component recipes, slot recipes, typegen,
|
||||
or ejecting the default theme. Trigger on any Chakra UI building, setup, or
|
||||
theming or charts request, however casually phrased — "add my brand colors",
|
||||
"make a reusable card style", "build a bar chart", "show me a line chart",
|
||||
"make me a login form", "build a sidebar", "add Chakra to my app".
|
||||
---
|
||||
|
||||
# Chakra UI Builder
|
||||
|
||||
You are building UI with Chakra UI v3 and helping developers set up Chakra UI in
|
||||
their projects. Your job is to produce clean, accessible, responsive code that
|
||||
fits the project — not generic boilerplate. Read the project context first, then
|
||||
build or set up.
|
||||
|
||||
---
|
||||
|
||||
## Step 1 — Read the project context
|
||||
|
||||
Check `package.json` if available. Look for:
|
||||
|
||||
- Chakra UI version (use v3 patterns by default; only use v2 if explicitly on
|
||||
v2)
|
||||
- Framework: Next.js App Router, Pages Router, Vite, plain React
|
||||
- TypeScript or JavaScript
|
||||
- Package manager (from lockfile: `pnpm-lock.yaml`, `yarn.lock`, `bun.lock`,
|
||||
`package-lock.json`)
|
||||
|
||||
Also glance at existing components if the user references them, so your code
|
||||
matches the conventions already in use (naming, file structure, import style).
|
||||
|
||||
If the requirements are vague or the component is complex enough that choices
|
||||
matter (layout direction, data shape, color palette, number of variants), ask
|
||||
before building rather than generating something that needs to be thrown away.
|
||||
|
||||
---
|
||||
|
||||
## Project setup
|
||||
|
||||
If Chakra UI isn't installed yet, complete setup before building.
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm install @chakra-ui/react @emotion/react
|
||||
|
||||
# pnpm
|
||||
pnpm add @chakra-ui/react @emotion/react
|
||||
|
||||
# yarn
|
||||
yarn add @chakra-ui/react @emotion/react
|
||||
|
||||
# bun
|
||||
bun add @chakra-ui/react @emotion/react
|
||||
```
|
||||
|
||||
### Generate snippets with the CLI
|
||||
|
||||
```bash
|
||||
npx @chakra-ui/cli snippet add
|
||||
```
|
||||
|
||||
With no arguments this adds the recommended set — `provider`, `toaster`, and
|
||||
`tooltip` — and automatically installs required dependencies (including
|
||||
`next-themes`). Use `--all` to add every snippet, or `snippet list` to browse
|
||||
first.
|
||||
|
||||
The CLI detects your framework and writes files to the right place:
|
||||
|
||||
| Framework | Output path |
|
||||
| --------------------- | -------------------- |
|
||||
| Next.js (with `src/`) | `src/components/ui/` |
|
||||
| Next.js (no `src/`) | `components/ui/` |
|
||||
| Vite / plain React | `src/components/ui/` |
|
||||
| Remix | `app/components/ui/` |
|
||||
|
||||
### Wire up the Provider
|
||||
|
||||
**Next.js App Router** (`app/layout.tsx`):
|
||||
|
||||
```tsx
|
||||
import { Provider } from "@/components/ui/provider"
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<html lang="en" suppressHydrationWarning>
|
||||
<body>
|
||||
<Provider>{children}</Provider>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`suppressHydrationWarning` prevents a mismatch caused by `next-themes` injecting
|
||||
the color-mode class. Do **not** add `"use client"` to `layout.tsx` — the
|
||||
generated provider file already has it.
|
||||
|
||||
**Next.js Pages Router** (`pages/_app.tsx`):
|
||||
|
||||
```tsx
|
||||
import { Provider } from "@/components/ui/provider"
|
||||
|
||||
export default function App({ Component, pageProps }) {
|
||||
return (
|
||||
<Provider>
|
||||
<Component {...pageProps} />
|
||||
</Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Vite** (`src/main.tsx`):
|
||||
|
||||
```tsx
|
||||
import { Provider } from "./components/ui/provider"
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<Provider>
|
||||
<App />
|
||||
</Provider>
|
||||
</StrictMode>,
|
||||
)
|
||||
```
|
||||
|
||||
### Manual Provider (if CLI is unavailable)
|
||||
|
||||
If the CLI fails, create `components/ui/provider.tsx` manually and install
|
||||
`next-themes` separately:
|
||||
|
||||
```tsx
|
||||
"use client"
|
||||
import { ChakraProvider, defaultSystem } from "@chakra-ui/react"
|
||||
import { ThemeProvider } from "next-themes"
|
||||
|
||||
export function Provider({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<ChakraProvider value={defaultSystem}>
|
||||
<ThemeProvider attribute="class" disableTransitionOnChange>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
</ChakraProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Common setup issues
|
||||
|
||||
- **Unstyled components** — app is not wrapped in `<Provider>`. Check the import
|
||||
path and that `Provider` wraps the component tree.
|
||||
- **Hydration mismatch** — add `suppressHydrationWarning` to `<html>` in App
|
||||
Router.
|
||||
- **`next-themes` not found** — install it: `npm install next-themes` (only
|
||||
needed for the manual fallback; the CLI handles it automatically).
|
||||
- **`extendTheme` not exported** — this is a v2 pattern. Use `createSystem` in
|
||||
v3.
|
||||
|
||||
---
|
||||
|
||||
## Step 2 — Choose the right layout primitives
|
||||
|
||||
Reach for the right Chakra primitive rather than wrapping everything in `Box`:
|
||||
|
||||
| Need | Use |
|
||||
| ------------------------ | --------------------------------------- |
|
||||
| Vertical stack of items | `Stack` (default) or `VStack` |
|
||||
| Horizontal row | `HStack` or `Flex` |
|
||||
| CSS Grid | `Grid` + `GridItem` |
|
||||
| Equal-column grid | `SimpleGrid columns={N}` |
|
||||
| Centered page content | `Container maxW="container.lg"` |
|
||||
| Full flexbox control | `Flex` with explicit props |
|
||||
| Semantic section/article | `Box as="section"` / `Box as="article"` |
|
||||
|
||||
Avoid deep nesting. If you're three `Box` levels deep with no semantic reason,
|
||||
flatten it. Prefer `gap` over margin between siblings.
|
||||
|
||||
---
|
||||
|
||||
## Step 3 — Use tokens, not raw values
|
||||
|
||||
Chakra v3 ships semantic tokens that automatically adapt to light/dark mode.
|
||||
Prefer them over hard-coded palette values — they make the component theme-aware
|
||||
without any extra work.
|
||||
|
||||
```tsx
|
||||
// Prefer semantic tokens
|
||||
<Box bg="bg.subtle" color="fg.default" borderColor="border.subtle" />
|
||||
<Text color="fg.muted" />
|
||||
<Box shadow="md" rounded="lg" />
|
||||
|
||||
// Use colorPalette for interactive components (not colorScheme)
|
||||
<Button colorPalette="blue">Submit</Button>
|
||||
<Badge colorPalette="green">Active</Badge>
|
||||
```
|
||||
|
||||
Use raw palette values (`blue.500`, `gray.100`) only when a specific color is
|
||||
intentional and should not shift with color mode.
|
||||
|
||||
---
|
||||
|
||||
## Step 4 — Responsive styles
|
||||
|
||||
Chakra uses mobile-first breakpoints. Use array or object syntax consistently:
|
||||
|
||||
```tsx
|
||||
// Array: [base, sm, md, lg, xl]
|
||||
<Box px={[4, 6, 8]} fontSize={["sm", "md", "lg"]} />
|
||||
|
||||
// Object: explicit breakpoints
|
||||
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={6} />
|
||||
<Stack direction={{ base: "column", md: "row" }} gap={4} />
|
||||
```
|
||||
|
||||
Every layout component should handle at least `base` (mobile) and `md` (desktop)
|
||||
breakpoints unless the request is explicitly desktop-only.
|
||||
|
||||
---
|
||||
|
||||
## Step 5 — Forms
|
||||
|
||||
Use `Field.Root` for all form fields — it wires up label, input, error, and help
|
||||
text correctly:
|
||||
|
||||
```tsx
|
||||
<Field.Root invalid={!!error} required>
|
||||
<Field.Label>Email address</Field.Label>
|
||||
<Input type="email" placeholder="you@example.com" />
|
||||
<Field.ErrorText>{error}</Field.ErrorText>
|
||||
<Field.HelpText>We'll never share your email.</Field.HelpText>
|
||||
</Field.Root>
|
||||
```
|
||||
|
||||
For form submission state, use `disabled` (not `isDisabled`) on inputs and
|
||||
buttons. Group related fields in a `Stack gap={4}`.
|
||||
|
||||
---
|
||||
|
||||
## Step 6 — Accessibility
|
||||
|
||||
Chakra's built-in components handle most accessibility automatically — don't
|
||||
override it. The things you do need to provide:
|
||||
|
||||
- **Icon-only buttons**: always add `aria-label`
|
||||
```tsx
|
||||
<IconButton aria-label="Close dialog" icon={<CloseIcon />} />
|
||||
```
|
||||
- **Images**: always pass meaningful `alt` text (or `alt=""` for decorative)
|
||||
- **Form labels**: use `Field.Label` or ensure `htmlFor` matches the input `id`
|
||||
- **Interactive custom elements**: if you build something with `onClick` on a
|
||||
`Box`, use `as="button"` or an actual `<button>` so keyboard navigation works
|
||||
- **Semantic headings**: use `h1`–`h6` hierarchy; don't skip levels
|
||||
- **Color contrast**: don't use light gray text on white backgrounds; rely on
|
||||
semantic tokens which are contrast-tested
|
||||
|
||||
---
|
||||
|
||||
## Step 7 — Next.js: where to add `"use client"`
|
||||
|
||||
In Next.js App Router, Server Components are the default. Add `"use client"`
|
||||
only to files that need it — not to entire layouts or pages.
|
||||
|
||||
A component needs `"use client"` when it:
|
||||
|
||||
- Uses React hooks (`useState`, `useEffect`, `useContext`, etc.)
|
||||
- Handles browser events (`onClick` with state, form submission, etc.)
|
||||
- Uses browser APIs
|
||||
|
||||
```tsx
|
||||
// Server Component — no directive needed
|
||||
export default function ProductCard({ name, price }: Props) {
|
||||
return (
|
||||
<Box p={4} borderWidth={1} rounded="md">
|
||||
<Text fontWeight="bold">{name}</Text>
|
||||
<Text color="fg.muted">{price}</Text>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
|
||||
// Client Component — needs the directive
|
||||
;("use client")
|
||||
export function AddToCartButton({ productId }: { productId: string }) {
|
||||
const [added, setAdded] = useState(false)
|
||||
return (
|
||||
<Button onClick={() => setAdded(true)} colorPalette="blue">
|
||||
{added ? "Added!" : "Add to cart"}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The goal is to push interactivity to the leaves — keep as much of the tree as
|
||||
Server Components as possible.
|
||||
|
||||
---
|
||||
|
||||
## Step 8 — When to extract components, use recipes, and customize the theme
|
||||
|
||||
Extract a component when the same structure appears more than twice, or when a
|
||||
piece is complex enough that naming it makes the parent clearer.
|
||||
|
||||
Suggest a **recipe** when a component has meaningful style variants that a
|
||||
developer would want to customize. Suggest a **slot recipe** for components with
|
||||
multiple coordinated parts (card with header/body/footer, stat with
|
||||
label/value/icon, etc.).
|
||||
|
||||
For deeper theming work — defining brand color tokens, semantic tokens with dark
|
||||
mode values, full recipe/slot-recipe authoring, typegen, or ejecting the default
|
||||
theme — read `references/theming.md` before responding. It covers the complete
|
||||
`defineConfig` / `createSystem` API with full examples.
|
||||
|
||||
For any chart request — bar charts, area charts, line charts, pie/donut charts,
|
||||
`BarList`, `BarSegment`, or anything involving `@chakra-ui/charts` — read
|
||||
`references/charts.md` before responding. It covers the `useChart` hook, all
|
||||
three chart types, Recharts integration, color tokens, and complete runnable
|
||||
examples.
|
||||
|
||||
When you're unsure which component to use, or the user hasn't specified one,
|
||||
read `references/component-decision-tree.md`. It covers every Chakra component
|
||||
with guidance on when to choose one over a similar alternative.
|
||||
|
||||
---
|
||||
|
||||
## Output format
|
||||
|
||||
Produce:
|
||||
|
||||
1. **Complete, runnable code** — correct imports, no placeholders like `TODO` or
|
||||
`...rest of component`
|
||||
2. **Proper import statements** — group Chakra imports, then local imports
|
||||
3. **Component separation** — split into multiple components/files if the
|
||||
component is complex or contains clearly separable parts
|
||||
4. **Responsive styles** — at minimum `base` and `md` breakpoints for layout
|
||||
5. **Brief explanation after the code** — 2–4 sentences on the key decisions
|
||||
made (layout approach, accessibility choices, responsive strategy). Skip the
|
||||
explanation if the request was trivial.
|
||||
|
||||
```tsx
|
||||
// Good import style
|
||||
import { Box, Button, Field, Stack, Text } from "@chakra-ui/react"
|
||||
// Then local
|
||||
import { SomeLocalComponent } from "./SomeLocalComponent"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## When to ask first
|
||||
|
||||
Build immediately if the request is clear enough to produce something useful.
|
||||
Ask first when:
|
||||
|
||||
- The data shape is unknown and it changes the entire structure (e.g., "build a
|
||||
table" — how many columns? what data?)
|
||||
- There are meaningful design choices the user might care about (layout
|
||||
direction, number of columns, color palette)
|
||||
- The user references files or existing components you haven't seen
|
||||
|
||||
When in doubt, state your assumptions at the top of the response and build —
|
||||
it's faster for the user to redirect from something concrete than from nothing.
|
||||
@@ -0,0 +1,461 @@
|
||||
# Chakra UI Charts Reference
|
||||
|
||||
Charts live in a separate package. Install it alongside `@chakra-ui/react`:
|
||||
|
||||
```bash
|
||||
# npm
|
||||
npm install @chakra-ui/charts recharts
|
||||
|
||||
# pnpm
|
||||
pnpm add @chakra-ui/charts recharts
|
||||
|
||||
# yarn
|
||||
yarn add @chakra-ui/charts recharts
|
||||
```
|
||||
|
||||
Imports come from `@chakra-ui/charts`, not `@chakra-ui/react`:
|
||||
|
||||
```ts
|
||||
import { BarList, BarSegment, Chart, useChart } from "@chakra-ui/charts"
|
||||
import type { BarListData, BarSegmentData } from "@chakra-ui/charts"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Three chart types
|
||||
|
||||
| Component | Best for | Recharts? |
|
||||
| ----------------------- | ---------------------------------------------- | --------- |
|
||||
| `BarList` | Rankings, comparisons (horizontal bar per row) | No |
|
||||
| `BarSegment` | Composition / parts of a whole (stacked bar) | No |
|
||||
| `Chart.Root` + Recharts | Line, area, bar, pie, radar, and more | Yes |
|
||||
|
||||
---
|
||||
|
||||
## `useChart` — the core hook
|
||||
|
||||
Every chart starts with `useChart`. It processes data, resolves color tokens,
|
||||
and provides utilities used throughout the chart's compound components.
|
||||
|
||||
```ts
|
||||
const chart = useChart({
|
||||
data: [...], // array of data objects
|
||||
series: [...], // which keys to plot and how to color them
|
||||
sort: { by: "value", direction: "desc" }, // optional
|
||||
})
|
||||
```
|
||||
|
||||
**`series` items:**
|
||||
|
||||
```ts
|
||||
{
|
||||
name: keyof T // data key to read values from
|
||||
color: ChartColor // Chakra token ("teal.solid") or CSS color ("#FF0000")
|
||||
label?: ReactNode // display name in legend/tooltip (defaults to name)
|
||||
stackId?: string // for stacking in Recharts charts
|
||||
yAxisId?: string // for dual-axis charts
|
||||
}
|
||||
```
|
||||
|
||||
**Color type** — accepts any Chakra color token or CSS color:
|
||||
|
||||
```ts
|
||||
type ChartColor = Tokens["colors"] | CSSProperties["color"]
|
||||
// "teal.solid" | "blue.subtle" | "red.500" | "#FF0000" | "hsl(...)"
|
||||
```
|
||||
|
||||
**Useful return values:**
|
||||
|
||||
```ts
|
||||
chart.data // sorted data array
|
||||
chart.series // resolved series config
|
||||
chart.color("teal.solid") // resolves token → CSS color
|
||||
chart.key("revenue") // safe key accessor
|
||||
chart.formatNumber({ notation: "compact" })(1234567) // "1.2M"
|
||||
chart.formatDate({ month: "short" })("2024-01-15") // locale-aware
|
||||
chart.getTotal("revenue") // sum all values
|
||||
chart.getMin("revenue") / chart.getMax("revenue")
|
||||
chart.getValuePercent("revenue", value) // % of total
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## BarList
|
||||
|
||||
Horizontal bar chart — one bar per data row. Good for leaderboards, traffic
|
||||
sources, top items.
|
||||
|
||||
**Data shape:**
|
||||
|
||||
```ts
|
||||
interface BarListData {
|
||||
name: string // label shown on the bar
|
||||
value: number // determines bar width
|
||||
href?: string // optional link
|
||||
}
|
||||
```
|
||||
|
||||
**Basic example:**
|
||||
|
||||
```tsx
|
||||
import { BarList, type BarListData, useChart } from "@chakra-ui/charts"
|
||||
|
||||
const chart = useChart<BarListData>({
|
||||
data: [
|
||||
{ name: "Google", value: 1_200_000 },
|
||||
{ name: "Direct", value: 840_000 },
|
||||
{ name: "Twitter", value: 320_000 },
|
||||
{ name: "LinkedIn", value: 95_000 },
|
||||
],
|
||||
sort: { by: "value", direction: "desc" },
|
||||
series: [{ name: "name", color: "teal.subtle" }],
|
||||
})
|
||||
|
||||
return (
|
||||
<BarList.Root chart={chart}>
|
||||
<BarList.Content>
|
||||
<BarList.Label title="Source" flex="1">
|
||||
<BarList.Bar tooltip />
|
||||
</BarList.Label>
|
||||
<BarList.Label title="Visits" titleAlignment="end">
|
||||
<BarList.Value />
|
||||
</BarList.Label>
|
||||
</BarList.Content>
|
||||
</BarList.Root>
|
||||
)
|
||||
```
|
||||
|
||||
**With a custom value formatter:**
|
||||
|
||||
```tsx
|
||||
<BarList.Value valueFormatter={(v) => `${(v / 1000).toFixed(0)}K`} />
|
||||
```
|
||||
|
||||
**With multiple value columns:**
|
||||
|
||||
```tsx
|
||||
<BarList.Label title="Visits" minW="16" titleAlignment="end">
|
||||
<BarList.Value />
|
||||
</BarList.Label>
|
||||
<BarList.Label title="%" minW="12" titleAlignment="end">
|
||||
<BarList.Value
|
||||
valueFormatter={(v) =>
|
||||
`${chart.getValuePercent("value", v).toFixed(0)}%`
|
||||
}
|
||||
/>
|
||||
</BarList.Label>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## BarSegment
|
||||
|
||||
Single horizontal bar broken into colored segments. Good for showing how a total
|
||||
is split across categories (budget, traffic, inventory).
|
||||
|
||||
**Data shape:**
|
||||
|
||||
```ts
|
||||
interface BarSegmentData {
|
||||
name: string // segment label
|
||||
value: number // determines segment width
|
||||
color: string // Chakra color token for this segment
|
||||
}
|
||||
```
|
||||
|
||||
**Basic example:**
|
||||
|
||||
```tsx
|
||||
import { BarSegment, useChart } from "@chakra-ui/charts"
|
||||
|
||||
const chart = useChart({
|
||||
data: [
|
||||
{ name: "Google", value: 500_000, color: "teal.solid" },
|
||||
{ name: "Direct", value: 300_000, color: "blue.solid" },
|
||||
{ name: "Twitter", value: 150_000, color: "purple.solid" },
|
||||
{ name: "LinkedIn", value: 50_000, color: "orange.solid" },
|
||||
],
|
||||
sort: { by: "value", direction: "desc" },
|
||||
})
|
||||
|
||||
return (
|
||||
<BarSegment.Root chart={chart}>
|
||||
<BarSegment.Content>
|
||||
<BarSegment.Value />
|
||||
<BarSegment.Bar tooltip />
|
||||
<BarSegment.Label />
|
||||
</BarSegment.Content>
|
||||
<BarSegment.Legend showPercent showValue />
|
||||
</BarSegment.Root>
|
||||
)
|
||||
```
|
||||
|
||||
**With a reference line (e.g. target):**
|
||||
|
||||
```tsx
|
||||
<BarSegment.Bar tooltip>
|
||||
<BarSegment.Reference label="Target" value={600_000} />
|
||||
</BarSegment.Bar>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chart.Root + Recharts
|
||||
|
||||
Wrapper for any Recharts chart. Handles sizing, token resolution, and styled
|
||||
tooltips and legends. You still compose the chart using standard Recharts
|
||||
components — `BarChart`, `AreaChart`, `LineChart`, `PieChart`, etc.
|
||||
|
||||
### Bar chart
|
||||
|
||||
```tsx
|
||||
import { Chart, useChart } from "@chakra-ui/charts"
|
||||
import {
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Legend,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts"
|
||||
|
||||
const chart = useChart({
|
||||
data: [
|
||||
{ month: "Jan", revenue: 186, expenses: 80 },
|
||||
{ month: "Feb", revenue: 165, expenses: 95 },
|
||||
{ month: "Mar", revenue: 210, expenses: 110 },
|
||||
],
|
||||
series: [
|
||||
{ name: "revenue", color: "teal.solid" },
|
||||
{ name: "expenses", color: "orange.solid" },
|
||||
],
|
||||
})
|
||||
|
||||
return (
|
||||
<Chart.Root maxH="sm" chart={chart}>
|
||||
<BarChart data={chart.data}>
|
||||
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||
<XAxis dataKey={chart.key("month")} />
|
||||
<YAxis />
|
||||
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||
<Legend content={<Chart.Legend />} />
|
||||
{chart.series.map((item) => (
|
||||
<Bar
|
||||
key={item.name}
|
||||
dataKey={chart.key(item.name)}
|
||||
fill={chart.color(item.color)}
|
||||
radius={4}
|
||||
/>
|
||||
))}
|
||||
</BarChart>
|
||||
</Chart.Root>
|
||||
)
|
||||
```
|
||||
|
||||
### Area chart
|
||||
|
||||
```tsx
|
||||
import { Area, AreaChart, CartesianGrid, Tooltip, XAxis } from "recharts"
|
||||
|
||||
return (
|
||||
<Chart.Root maxH="sm" chart={chart}>
|
||||
<AreaChart data={chart.data}>
|
||||
<defs>
|
||||
{chart.series.map((item) => (
|
||||
<Chart.Gradient
|
||||
key={item.name}
|
||||
id={item.name}
|
||||
stops={[
|
||||
{ offset: "0%", color: item.color, opacity: 0.2 },
|
||||
{ offset: "100%", color: item.color, opacity: 0 },
|
||||
]}
|
||||
/>
|
||||
))}
|
||||
</defs>
|
||||
<CartesianGrid stroke={chart.color("border.muted")} vertical={false} />
|
||||
<XAxis dataKey={chart.key("month")} />
|
||||
<Tooltip cursor={false} content={<Chart.Tooltip />} />
|
||||
{chart.series.map((item) => (
|
||||
<Area
|
||||
key={item.name}
|
||||
dataKey={chart.key(item.name)}
|
||||
stroke={chart.color(item.color)}
|
||||
fill={`url(#${item.name})`}
|
||||
stackId="a"
|
||||
/>
|
||||
))}
|
||||
</AreaChart>
|
||||
</Chart.Root>
|
||||
)
|
||||
```
|
||||
|
||||
### Pie / donut chart
|
||||
|
||||
```tsx
|
||||
import { Pie, PieChart, Tooltip } from "recharts"
|
||||
|
||||
const chart = useChart({
|
||||
data: [
|
||||
{ browser: "Chrome", visitors: 275, color: "teal.solid" },
|
||||
{ browser: "Safari", visitors: 200, color: "blue.solid" },
|
||||
{ browser: "Firefox", visitors: 120, color: "orange.solid" },
|
||||
{ browser: "Edge", visitors: 80, color: "purple.solid" },
|
||||
],
|
||||
series: [{ name: "visitors" }],
|
||||
})
|
||||
|
||||
return (
|
||||
<Chart.Root maxH="sm" chart={chart}>
|
||||
<PieChart>
|
||||
<Tooltip content={<Chart.Tooltip hideLabel />} />
|
||||
<Pie
|
||||
data={chart.data}
|
||||
dataKey={chart.key("visitors")}
|
||||
nameKey={chart.key("browser")}
|
||||
innerRadius="60%" // remove for a filled pie
|
||||
paddingAngle={2}
|
||||
>
|
||||
{chart.data.map((item, index) => (
|
||||
<Cell key={index} fill={chart.color(item.color)} />
|
||||
))}
|
||||
{/* Center text for donut */}
|
||||
<Label
|
||||
content={
|
||||
<Chart.RadialText
|
||||
viewBox={undefined}
|
||||
title={chart.getTotal("visitors").toLocaleString()}
|
||||
description="Total visitors"
|
||||
/>
|
||||
}
|
||||
position="center"
|
||||
/>
|
||||
</Pie>
|
||||
</PieChart>
|
||||
</Chart.Root>
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chart sub-components
|
||||
|
||||
### `Chart.Tooltip`
|
||||
|
||||
```tsx
|
||||
<Tooltip
|
||||
cursor={false}
|
||||
content={
|
||||
<Chart.Tooltip
|
||||
showTotal // show sum of all series at bottom
|
||||
hideLabel // hide the x-axis label row
|
||||
hideSeriesLabel // hide series names
|
||||
indicator="line" // "dot" | "line" | "dashed"
|
||||
formatter={(value, name) => [`$${value}`, name]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
```
|
||||
|
||||
### `Chart.Legend`
|
||||
|
||||
```tsx
|
||||
<Legend
|
||||
content={
|
||||
<Chart.Legend
|
||||
title="Channels"
|
||||
interaction="click" // "hover" (default) | "click"
|
||||
verticalAlign="top" // "top" | "bottom" (default)
|
||||
align="right" // "left" | "center" (default) | "right"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
```
|
||||
|
||||
Legend interaction highlights/dims series on hover or click.
|
||||
|
||||
### `Chart.Gradient`
|
||||
|
||||
Defines an SVG gradient for area fills. Must be inside a `<defs>` block:
|
||||
|
||||
```tsx
|
||||
<defs>
|
||||
<Chart.Gradient
|
||||
id="revenue-gradient"
|
||||
stops={[
|
||||
{ offset: "0%", color: "teal.solid", opacity: 0.3 },
|
||||
{ offset: "100%", color: "teal.solid", opacity: 0 },
|
||||
]}
|
||||
/>
|
||||
</defs>
|
||||
|
||||
<Area fill="url(#revenue-gradient)" ... />
|
||||
```
|
||||
|
||||
### `Chart.RadialText`
|
||||
|
||||
Centers a title + description inside a pie or donut chart:
|
||||
|
||||
```tsx
|
||||
<Label
|
||||
content={
|
||||
<Chart.RadialText
|
||||
viewBox={undefined}
|
||||
title="$1.2M"
|
||||
description="Total revenue"
|
||||
/>
|
||||
}
|
||||
position="center"
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Colors and theming
|
||||
|
||||
All chart colors accept Chakra token strings or plain CSS colors:
|
||||
|
||||
```ts
|
||||
// Chakra semantic tokens — respond to light/dark mode
|
||||
color: "teal.solid"
|
||||
color: "blue.subtle"
|
||||
color: "border.muted" // useful for grid lines
|
||||
|
||||
// Palette steps
|
||||
color: "blue.500"
|
||||
|
||||
// Raw CSS
|
||||
color: "#3b82f6"
|
||||
color: "hsl(210, 100%, 56%)"
|
||||
```
|
||||
|
||||
Use `chart.color(token)` to resolve a token to a CSS value wherever Recharts
|
||||
needs a string (e.g. `fill`, `stroke`, `CartesianGrid stroke`).
|
||||
|
||||
Recommended color tokens for multi-series charts:
|
||||
|
||||
```ts
|
||||
series: [
|
||||
{ name: "a", color: "teal.solid" },
|
||||
{ name: "b", color: "blue.solid" },
|
||||
{ name: "c", color: "purple.solid" },
|
||||
{ name: "d", color: "orange.solid" },
|
||||
{ name: "e", color: "red.solid" },
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Output format
|
||||
|
||||
When building chart components:
|
||||
|
||||
1. Show the `useChart` setup and data shape first
|
||||
2. Produce complete, runnable JSX with correct imports from both
|
||||
`@chakra-ui/charts` and `recharts`
|
||||
3. Use `chart.color("border.muted")` for grid lines so they respect dark mode
|
||||
4. Default `Chart.Root` to `maxH="sm"` unless the user specifies a size
|
||||
5. Include a `Tooltip` with `<Chart.Tooltip />` on every chart — it's almost
|
||||
always wanted
|
||||
6. Note the install command if the project doesn't already have
|
||||
`@chakra-ui/charts`
|
||||
@@ -0,0 +1,287 @@
|
||||
# Chakra UI Component Decision Tree
|
||||
|
||||
When the user hasn't specified a component, choose the most appropriate one
|
||||
based on the guidelines below. Prefer an existing Chakra component over a custom
|
||||
implementation. Match the interaction model first, then the visual treatment.
|
||||
Prefer the narrowest component that fits — don't reach for `Box` when a more
|
||||
specific primitive exists.
|
||||
|
||||
---
|
||||
|
||||
## Layout and structure
|
||||
|
||||
- Use `Stack` (or `VStack`) for a vertical sequence of elements with consistent
|
||||
spacing.
|
||||
- Use `HStack` for a horizontal sequence of elements with consistent spacing.
|
||||
- Use `Flex` when you need explicit control over flexbox properties (direction,
|
||||
wrap, alignment).
|
||||
- Use `Grid` + `GridItem` for two-dimensional layouts (rows and columns).
|
||||
- Use `SimpleGrid` for equal-width columns that wrap automatically — good for
|
||||
card grids and dashboards.
|
||||
- Use `Container` to constrain page content to a max-width with horizontal
|
||||
centering.
|
||||
- Use `Center` to center content both horizontally and vertically without manual
|
||||
flex setup.
|
||||
- Use `AbsoluteCenter` when centering with `position: absolute` — useful for
|
||||
overlays and loaders.
|
||||
- Use `Card` when content is a self-contained unit that needs visual separation
|
||||
(border, shadow, padding). Use `Box` only when no built-in container semantics
|
||||
apply.
|
||||
- Use `Wrap` for tag clouds, badge sets, or button groups that should flow and
|
||||
wrap automatically.
|
||||
- Use `Spacer` inside `Flex` to push elements to opposite ends.
|
||||
- Use `Group` to visually merge related elements (buttons, inputs) into a single
|
||||
bordered unit.
|
||||
- Use `Bleed` to extend a background or image beyond the padding of its parent
|
||||
container.
|
||||
- Use `Splitter` when the user should be able to resize two adjacent panels.
|
||||
- Use `ScrollArea` for a container that needs custom cross-browser styled
|
||||
scrollbars.
|
||||
- Use `AspectRatio` to lock a child element (video, image, map) to a fixed
|
||||
aspect ratio.
|
||||
|
||||
### Stack vs Flex vs Grid
|
||||
|
||||
- Choose `Stack` or `HStack`/`VStack` for uniform spacing along one axis — it's
|
||||
the most common case.
|
||||
- Choose `Flex` when you need `flexWrap`, `justifyContent`, `alignItems`, or
|
||||
other flex properties beyond spacing.
|
||||
- Choose `Grid` when you need to position elements across both rows and columns
|
||||
at the same time.
|
||||
- Choose `SimpleGrid` when you only need responsive equal-width columns and
|
||||
nothing more.
|
||||
|
||||
---
|
||||
|
||||
## Typography
|
||||
|
||||
- Use `Heading` for page and section titles (`h1`–`h6`). Don't use `Text` as a
|
||||
heading shortcut.
|
||||
- Use `Text` for body copy, labels, and descriptive text.
|
||||
- Use `Span` for inline styled text inside a paragraph.
|
||||
- Use `Em` and `Strong` for semantically emphasized or important text.
|
||||
- Use `Mark` for highlighted text (e.g. search result matches).
|
||||
- Use `Code` for short inline code snippets.
|
||||
- Use `CodeBlock` for multi-line code with copy button and optional collapse —
|
||||
not for single-line snippets.
|
||||
- Use `Kbd` to display keyboard shortcuts.
|
||||
- Use `Blockquote` for pull quotes with attribution.
|
||||
- Use `Highlight` to highlight matching substrings dynamically in text.
|
||||
|
||||
---
|
||||
|
||||
## Actions and links
|
||||
|
||||
- Use `Button` for primary and secondary actions (form submissions,
|
||||
confirmations, key page actions).
|
||||
- Use `IconButton` for icon-only actions — always provide `aria-label`.
|
||||
- Use `CloseButton` for dismiss/close actions in dialogs, drawers, and toasts.
|
||||
- Use `ButtonGroup` to group related actions (e.g. Save / Cancel) with
|
||||
consistent sizing and variant.
|
||||
- Use `Link` for text navigation — inline within a sentence or standalone. Use
|
||||
`asChild` with Next.js `<Link>` in App Router projects.
|
||||
- Use `LinkBox` + `LinkOverlay` to make an entire card or row clickable while
|
||||
preserving accessible markup.
|
||||
- Use `Toggle` when a button should visually represent an on/off pressed state.
|
||||
- Use `Switch` (not `Toggle`) when the interaction is a persistent on/off
|
||||
setting (e.g. enable notifications).
|
||||
- Use `DownloadTrigger` for file download buttons.
|
||||
|
||||
---
|
||||
|
||||
## Choosing from options
|
||||
|
||||
- Use `Switch` for turning a single setting on or off.
|
||||
- Use `Checkbox` for a single independent yes/no option. Use `CheckboxGroup` for
|
||||
a set of independent options where many can be selected.
|
||||
- Use `CheckboxCard` over `Checkbox` when the option needs a title, description,
|
||||
or more visual emphasis.
|
||||
- Use `RadioGroup` for mutually exclusive options when 2–4 options should always
|
||||
be visible.
|
||||
- Use `RadioCard` over `RadioGroup` when each option benefits from a
|
||||
description, icon, or richer presentation.
|
||||
- Use `SegmentGroup` for a compact mutually exclusive mode/view switch
|
||||
(iOS-style segmented control) — typically 2–4 options.
|
||||
- Use `NativeSelect` for mobile-first dropdowns where the platform picker is
|
||||
preferred.
|
||||
- Use `Select` for styled dropdowns with full design control — prefer over
|
||||
`NativeSelect` on desktop.
|
||||
- Use `Combobox` when the user should type to filter a long list or search
|
||||
options — prefer over `Select` for lists longer than ~15 items.
|
||||
- Use `Listbox` when options must always be visible and scrollable without a
|
||||
dropdown trigger.
|
||||
- Use `TagsInput` for entering multiple free-form or autocompleted values
|
||||
(skills, labels, emails).
|
||||
- Use `RatingGroup` for star or point ratings.
|
||||
|
||||
### Select vs Combobox vs NativeSelect
|
||||
|
||||
- Choose `NativeSelect` for mobile-first or form-heavy interfaces where native
|
||||
picker behavior is expected.
|
||||
- Choose `Select` for styled dropdowns on desktop with a known, bounded list.
|
||||
- Choose `Combobox` when filtering/searching is important or the list is long.
|
||||
|
||||
---
|
||||
|
||||
## Text and value input
|
||||
|
||||
- Use `Input` for single-line plain text.
|
||||
- Use `Textarea` for multi-line text.
|
||||
- Use `NumberInput` for numeric entry with increment/decrement controls.
|
||||
- Use `Slider` for adjusting a value when direct manipulation is preferred over
|
||||
exact entry. Use a range slider (dual thumbs) for min/max ranges.
|
||||
- Use `PinInput` for fixed-length codes — OTP verification, PIN entry. It
|
||||
auto-advances focus between fields.
|
||||
- Use `Editable` for click-to-edit inline text — useful for titles,
|
||||
descriptions, and table cells.
|
||||
- Use `DatePicker` when a calendar popover should assist with date selection.
|
||||
- Use `ColorPicker` for full color selection with RGB/HSL/hex modes and
|
||||
eyedropper.
|
||||
- Use `FileUpload` for file selection with drag-and-drop and preview.
|
||||
- Use `Clipboard` for copy-to-clipboard functionality with visual feedback.
|
||||
- Use `Field.Root` to wrap every form input — it wires up the label, helper
|
||||
text, error text, and required indicator correctly.
|
||||
- Use `InputGroup` to attach prefix/suffix addons (icons, currency symbols,
|
||||
units) to an `Input`.
|
||||
- Use `Fieldset` to group semantically related form fields under a shared
|
||||
legend.
|
||||
|
||||
---
|
||||
|
||||
## Overlays and pop-ups
|
||||
|
||||
- Use `Tooltip` for a short text description of a focusable element. Don't put
|
||||
interactive content in a tooltip.
|
||||
- Use `HoverCard` for richer preview content on hover (user profiles, link
|
||||
previews) — more than a tooltip, less than a popover.
|
||||
- Use `Popover` for interactive contextual content anchored to a trigger —
|
||||
forms, filters, settings panels.
|
||||
- Use `Dialog` for modal tasks that require user attention before continuing.
|
||||
- Use `Drawer` for off-canvas panels — navigation, detail views, settings — when
|
||||
modal behavior is needed but the content is beside rather than over the page.
|
||||
- Use `Toast` for brief transient feedback after an action (saved, error,
|
||||
copied). Use the `Toaster` component to render stacked toasts.
|
||||
- Use `ActionBar` for mobile-style bulk action bars that appear after selection.
|
||||
- Use `Menu` for action menus triggered by a button — "more options",
|
||||
right-click menus. Use `Menu.CheckboxItem` and `Menu.RadioItem` for
|
||||
toggle/selection actions within a menu.
|
||||
|
||||
### Tooltip vs HoverCard vs Popover
|
||||
|
||||
- Choose `Tooltip` for a single line of non-interactive help text.
|
||||
- Choose `HoverCard` for hover-triggered preview cards with structured content.
|
||||
- Choose `Popover` when the floating content needs to be interactive (has
|
||||
buttons, inputs, or links).
|
||||
|
||||
### Dialog vs Drawer
|
||||
|
||||
- Choose `Dialog` when the overlay should be centered, blocking, and focus
|
||||
attention on a specific task or confirmation.
|
||||
- Choose `Drawer` when the content slides in from an edge and relates to what's
|
||||
already on screen (details, navigation, filters).
|
||||
|
||||
---
|
||||
|
||||
## Disclosure and navigation
|
||||
|
||||
- Use `Accordion` for a set of related collapsible sections where only one (or a
|
||||
few) should be open at a time — FAQs, grouped settings.
|
||||
- Use `Collapsible` for a single expandable section — don't use `Accordion` with
|
||||
one item.
|
||||
- Use `Tabs` for peer content panels where switching shows one panel at a time —
|
||||
prefer for horizontal layouts.
|
||||
- Use `SegmentGroup` instead of `Tabs` when switching modes or views rather than
|
||||
showing different full content panels.
|
||||
- Use `Steps` for multi-step wizards and onboarding flows — shows progress and
|
||||
allows back/next navigation.
|
||||
- Use `Breadcrumb` to show the user's location in a hierarchy.
|
||||
- Use `Pagination` for navigating paged datasets.
|
||||
- Use `Menu` for dropdown navigation menus.
|
||||
- Use `TreeView` when a file-system-style hierarchy must stay visible and
|
||||
expandable in place.
|
||||
|
||||
### Accordion vs Tabs vs Collapsible
|
||||
|
||||
- Choose `Accordion` for vertically stacked collapsible sections (FAQs, settings
|
||||
groups).
|
||||
- Choose `Tabs` for horizontal peer sections where all tabs are always visible.
|
||||
- Choose `Collapsible` for a single show/hide section — not a group.
|
||||
|
||||
---
|
||||
|
||||
## Data display
|
||||
|
||||
- Use `Table` for structured tabular data with rows and columns — sortable
|
||||
headers, dense comparison.
|
||||
- Use `DataList` for key-value pairs (user profile details, metadata) — not true
|
||||
tabular data.
|
||||
- Use `Stat` + `StatGroup` for KPI metrics and dashboard numbers with up/down
|
||||
indicators.
|
||||
- Use `Timeline` for chronological events, changelogs, or process steps.
|
||||
- Use `Badge` for compact non-removable status labels (Active, Beta, New).
|
||||
- Use `Tag` over `Badge` when the label should be removable or interactive.
|
||||
- Use `Avatar` + `AvatarGroup` for user profile pictures with fallback initials
|
||||
or icon.
|
||||
- Use `Carousel` for image galleries, feature showcases, or content sliders.
|
||||
- Use `QrCode` to render a QR code from a string value.
|
||||
- Use `ColorSwatch` to display a color value visually.
|
||||
|
||||
### Table vs DataList
|
||||
|
||||
- Choose `Table` when data has multiple comparable columns and rows.
|
||||
- Choose `DataList` for a single record's attributes displayed as label/value
|
||||
pairs.
|
||||
|
||||
---
|
||||
|
||||
## Feedback and status
|
||||
|
||||
- Use `Alert` for persistent in-page messages (warnings, info, errors) that are
|
||||
part of the page layout.
|
||||
- Use `Toast` for transient post-action feedback — it disappears automatically.
|
||||
- Use `EmptyState` for no-data and no-results states — provides structured
|
||||
layout for illustration, title, description, and actions.
|
||||
- Use `Spinner` for indeterminate loading — content is fetching, duration
|
||||
unknown.
|
||||
- Use `Skeleton` for loading placeholders that approximate the shape of incoming
|
||||
content.
|
||||
- Use `Progress` for a linear progress bar on an operation with a known
|
||||
completion percentage.
|
||||
- Use `ProgressCircle` for the same use case when a circular indicator fits the
|
||||
layout better.
|
||||
- Use `Loader` as an alternative to `Spinner` for a different visual style of
|
||||
indeterminate loading.
|
||||
|
||||
### Alert vs Toast vs EmptyState
|
||||
|
||||
- Choose `Alert` when the message is persistent and tied to content on the
|
||||
current view.
|
||||
- Choose `Toast` when the message is temporary and triggered by a user action.
|
||||
- Choose `EmptyState` when there is no content to display and you want to
|
||||
explain why and offer a next action.
|
||||
|
||||
### Spinner vs Skeleton vs Progress
|
||||
|
||||
- Choose `Spinner` when loading is happening and the layout isn't known yet.
|
||||
- Choose `Skeleton` when the layout is known — show placeholder shapes that
|
||||
match the expected content.
|
||||
- Choose `Progress` when the operation has a measurable percentage.
|
||||
|
||||
---
|
||||
|
||||
## Utilities
|
||||
|
||||
- Use `VisuallyHidden` for screen-reader-only text — skip links, icon button
|
||||
labels added outside the button.
|
||||
- Use `SkipNav` to add a skip-to-main-content accessibility link.
|
||||
- Use `Portal` when a component must render outside its DOM parent to avoid
|
||||
z-index or overflow clipping issues.
|
||||
- Use `FocusTrap` to constrain keyboard focus within a region (custom modals,
|
||||
custom drawers).
|
||||
- Use `Presence` to animate components on mount and unmount.
|
||||
- Use `Show` / `Hide` for responsive conditional rendering based on breakpoints.
|
||||
- Use `For` as a typed loop utility when rendering lists of components.
|
||||
- Use `ClientOnly` to prevent SSR hydration mismatches for browser-only content.
|
||||
- Use `FormatNumber` / `FormatByte` for locale-aware number and file-size
|
||||
formatting.
|
||||
- Use `Marquee` for scrolling announcement banners or news tickers.
|
||||
@@ -0,0 +1,331 @@
|
||||
# Chakra UI Theming Reference
|
||||
|
||||
Use v3 patterns (`defineConfig`, `createSystem`, `defineRecipe`,
|
||||
`defineSlotRecipe`) by default. Only use v2 patterns (`extendTheme`,
|
||||
`styleConfig`) if the project is explicitly on v2.
|
||||
|
||||
Before starting, check `package.json` for the Chakra UI version and look for an
|
||||
existing theme file (`theme.ts`, `system.ts`) to understand what's already
|
||||
defined.
|
||||
|
||||
Clarify scope when needed:
|
||||
|
||||
- **Full design system** — tokens, semantic tokens, and component recipes from
|
||||
scratch
|
||||
- **Partial update** — adding or changing specific tokens or recipes
|
||||
- **Single recipe** — one component's styles with variants
|
||||
- **Typegen only** — running `@chakra-ui/cli typegen` after custom additions
|
||||
|
||||
If the user says "add my brand colors" without specifying the colors, ask first.
|
||||
A partial answer is worse than pausing to clarify.
|
||||
|
||||
---
|
||||
|
||||
## System setup: `defineConfig` and `createSystem`
|
||||
|
||||
All theming in v3 starts with `createSystem`. Use `defineConfig` to author
|
||||
customizations, then merge with `defaultConfig`:
|
||||
|
||||
```ts
|
||||
// theme.ts
|
||||
import { createSystem, defaultConfig, defineConfig } from "@chakra-ui/react"
|
||||
|
||||
const config = defineConfig({
|
||||
theme: {
|
||||
tokens: {
|
||||
/* ... */
|
||||
},
|
||||
semanticTokens: {
|
||||
/* ... */
|
||||
},
|
||||
recipes: {
|
||||
/* ... */
|
||||
},
|
||||
slotRecipes: {
|
||||
/* ... */
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export const system = createSystem(defaultConfig, config)
|
||||
```
|
||||
|
||||
Pass `system` to `ChakraProvider`:
|
||||
|
||||
```tsx
|
||||
// components/ui/provider.tsx
|
||||
"use client"
|
||||
import { system } from "@/theme"
|
||||
import { ChakraProvider } from "@chakra-ui/react"
|
||||
|
||||
export function Provider({ children }) {
|
||||
return <ChakraProvider value={system}>{children}</ChakraProvider>
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tokens
|
||||
|
||||
Tokens are the raw, concrete values in your design system — the foundation
|
||||
everything else references.
|
||||
|
||||
```ts
|
||||
const config = defineConfig({
|
||||
theme: {
|
||||
tokens: {
|
||||
colors: {
|
||||
brand: {
|
||||
50: { value: "#eff6ff" },
|
||||
100: { value: "#dbeafe" },
|
||||
200: { value: "#bfdbfe" },
|
||||
500: { value: "#3b82f6" },
|
||||
600: { value: "#2563eb" },
|
||||
700: { value: "#1d4ed8" },
|
||||
900: { value: "#1e3a8a" },
|
||||
},
|
||||
},
|
||||
fonts: {
|
||||
heading: { value: "var(--font-geist-sans), sans-serif" },
|
||||
body: { value: "var(--font-geist-sans), sans-serif" },
|
||||
mono: { value: "var(--font-geist-mono), monospace" },
|
||||
},
|
||||
fontSizes: {
|
||||
xs: { value: "0.75rem" },
|
||||
sm: { value: "0.875rem" },
|
||||
md: { value: "1rem" },
|
||||
lg: { value: "1.125rem" },
|
||||
xl: { value: "1.25rem" },
|
||||
"2xl": { value: "1.5rem" },
|
||||
},
|
||||
radii: {
|
||||
sm: { value: "0.25rem" },
|
||||
md: { value: "0.375rem" },
|
||||
lg: { value: "0.5rem" },
|
||||
xl: { value: "0.75rem" },
|
||||
full: { value: "9999px" },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Use scale-based keys for palettes (`50`, `100`, …, `900`) and semantic keys for
|
||||
single values (`sm`, `md`, `lg`).
|
||||
|
||||
---
|
||||
|
||||
## Semantic tokens
|
||||
|
||||
Semantic tokens reference base tokens and assign _meaning_ to them. Their key
|
||||
feature: different values per color mode, making dark mode automatic.
|
||||
|
||||
```ts
|
||||
const config = defineConfig({
|
||||
theme: {
|
||||
semanticTokens: {
|
||||
colors: {
|
||||
"brand.solid": {
|
||||
value: { base: "{colors.brand.600}", _dark: "{colors.brand.400}" },
|
||||
},
|
||||
"brand.muted": {
|
||||
value: { base: "{colors.brand.100}", _dark: "{colors.brand.900}" },
|
||||
},
|
||||
"brand.subtle": {
|
||||
value: { base: "{colors.brand.50}", _dark: "{colors.brand.950}" },
|
||||
},
|
||||
|
||||
"bg.default": { value: { base: "white", _dark: "{colors.gray.900}" } },
|
||||
"bg.subtle": {
|
||||
value: { base: "{colors.gray.50}", _dark: "{colors.gray.800}" },
|
||||
},
|
||||
"bg.muted": {
|
||||
value: { base: "{colors.gray.100}", _dark: "{colors.gray.700}" },
|
||||
},
|
||||
|
||||
"fg.default": { value: { base: "{colors.gray.900}", _dark: "white" } },
|
||||
"fg.muted": {
|
||||
value: { base: "{colors.gray.600}", _dark: "{colors.gray.400}" },
|
||||
},
|
||||
"fg.subtle": {
|
||||
value: { base: "{colors.gray.400}", _dark: "{colors.gray.600}" },
|
||||
},
|
||||
|
||||
"border.default": {
|
||||
value: { base: "{colors.gray.200}", _dark: "{colors.gray.700}" },
|
||||
},
|
||||
"border.muted": {
|
||||
value: { base: "{colors.gray.100}", _dark: "{colors.gray.800}" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Components that use `bg="bg.subtle"` instead of `bg="gray.50"` automatically get
|
||||
the correct dark mode value — no conditional logic needed. Build on semantic
|
||||
tokens wherever possible.
|
||||
|
||||
---
|
||||
|
||||
## Recipes (single-component styles)
|
||||
|
||||
Recipes replace `styleConfig` from v2. Use them when a single component has
|
||||
meaningful style variants that developers will reuse across the project.
|
||||
|
||||
```ts
|
||||
import { defineRecipe } from "@chakra-ui/react"
|
||||
|
||||
export const badgeRecipe = defineRecipe({
|
||||
base: {
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
px: 2,
|
||||
py: 0.5,
|
||||
borderRadius: "full",
|
||||
fontSize: "xs",
|
||||
fontWeight: "medium",
|
||||
},
|
||||
variants: {
|
||||
variant: {
|
||||
solid: { bg: "colorPalette.500", color: "white" },
|
||||
subtle: { bg: "colorPalette.100", color: "colorPalette.800" },
|
||||
outline: {
|
||||
borderWidth: 1,
|
||||
borderColor: "colorPalette.500",
|
||||
color: "colorPalette.600",
|
||||
},
|
||||
},
|
||||
size: {
|
||||
sm: { px: 1.5, py: 0.5, fontSize: "2xs" },
|
||||
md: { px: 2, py: 0.5, fontSize: "xs" },
|
||||
lg: { px: 3, py: 1, fontSize: "sm" },
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "subtle", size: "md" },
|
||||
})
|
||||
```
|
||||
|
||||
Register in the theme config:
|
||||
|
||||
```ts
|
||||
const config = defineConfig({ theme: { recipes: { badge: badgeRecipe } } })
|
||||
```
|
||||
|
||||
`colorPalette` inside a recipe is a placeholder — it resolves to whatever
|
||||
`colorPalette` prop the consumer passes (`colorPalette="blue"` → `blue.500`).
|
||||
|
||||
---
|
||||
|
||||
## Slot recipes (multi-part components)
|
||||
|
||||
Slot recipes replace `multiStyleConfig` from v2. Use them when a component has
|
||||
multiple coordinated parts that all respond to the same variants.
|
||||
|
||||
```ts
|
||||
import { defineSlotRecipe } from "@chakra-ui/react"
|
||||
|
||||
export const cardSlotRecipe = defineSlotRecipe({
|
||||
slots: ["root", "header", "body", "footer", "title"],
|
||||
base: {
|
||||
root: { bg: "bg.surface", rounded: "xl", overflow: "hidden", shadow: "sm" },
|
||||
header: { px: 6, py: 4, borderBottomWidth: 1, borderColor: "border.muted" },
|
||||
body: { px: 6, py: 4 },
|
||||
footer: { px: 6, py: 4, borderTopWidth: 1, borderColor: "border.muted" },
|
||||
title: { fontSize: "lg", fontWeight: "semibold", color: "fg.default" },
|
||||
},
|
||||
variants: {
|
||||
variant: {
|
||||
elevated: { root: { shadow: "md" } },
|
||||
outline: {
|
||||
root: { shadow: "none", borderWidth: 1, borderColor: "border.default" },
|
||||
},
|
||||
filled: { root: { bg: "bg.subtle", shadow: "none" } },
|
||||
},
|
||||
size: {
|
||||
sm: {
|
||||
root: { rounded: "lg" },
|
||||
body: { px: 4, py: 3 },
|
||||
header: { px: 4, py: 3 },
|
||||
},
|
||||
md: {},
|
||||
lg: { body: { px: 8, py: 6 }, header: { px: 8, py: 6 } },
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "elevated", size: "md" },
|
||||
})
|
||||
```
|
||||
|
||||
Register:
|
||||
`const config = defineConfig({ theme: { slotRecipes: { card: cardSlotRecipe } } })`
|
||||
|
||||
Consume with `useSlotRecipe`:
|
||||
|
||||
```tsx
|
||||
import { useSlotRecipe } from "@chakra-ui/react"
|
||||
|
||||
function Card({ variant = "elevated", size = "md", children }) {
|
||||
const recipe = useSlotRecipe({ key: "card" })
|
||||
const styles = recipe({ variant, size })
|
||||
return <Box css={styles.root}>{children}</Box>
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Typegen
|
||||
|
||||
Run typegen after adding custom tokens, semantic tokens, recipes, or slot
|
||||
recipes. Without it, TypeScript won't know your custom values exist.
|
||||
|
||||
```bash
|
||||
npx @chakra-ui/cli typegen ./theme.ts
|
||||
```
|
||||
|
||||
| Flag | Effect |
|
||||
| ------------------- | ------------------------------------------------------------- |
|
||||
| `--strict` | Strict literal types for variant and size props (recommended) |
|
||||
| `--watch` | Re-runs automatically whenever the theme file changes |
|
||||
| `--outdir <dir>` | Custom output directory for generated types |
|
||||
| `--tsconfig <path>` | Path to tsconfig when using path aliases |
|
||||
|
||||
For active development: `npx @chakra-ui/cli typegen ./theme.ts --watch`
|
||||
|
||||
Typegen is required when you've added custom color tokens, semantic tokens,
|
||||
spacing/font/radius tokens, or new recipes or slot recipes.
|
||||
|
||||
---
|
||||
|
||||
## Ejecting the default theme
|
||||
|
||||
For full control over Chakra's built-in tokens, recipes, and styles:
|
||||
|
||||
```bash
|
||||
npx @chakra-ui/cli eject
|
||||
```
|
||||
|
||||
Writes the complete default theme into a `theme/` directory (`--outdir <dir>` to
|
||||
override), including separate files for tokens, semantic tokens, recipes, slot
|
||||
recipes, text styles, layer styles, and animation styles — all as editable
|
||||
`defineConfig` exports.
|
||||
|
||||
Use `eject` when modifying built-in component recipes or replacing large parts
|
||||
of the default token scale. For smaller customizations (adding brand colors,
|
||||
overriding a few tokens), extending with `defineConfig` is simpler.
|
||||
|
||||
---
|
||||
|
||||
## Output format
|
||||
|
||||
Produce:
|
||||
|
||||
1. **Complete theme config** — `defineConfig` with all relevant sections
|
||||
2. **Proper imports** — `defineConfig`, `createSystem`, `defineRecipe`, etc.
|
||||
from `@chakra-ui/react`
|
||||
3. **Provider wiring** — how to pass `system` to `ChakraProvider` if needed
|
||||
4. **Usage examples** — show tokens/recipes consumed in a component
|
||||
5. **Typegen reminder** — note when to run typegen
|
||||
|
||||
Brief explanation after the code (2–4 sentences) on key decisions. Skip for
|
||||
trivial requests.
|
||||
Reference in New Issue
Block a user