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,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