Set up @charcoal-ui in an app, choose the right token for a color, text style, spacing, radius or border, and turn a Figma link into files a teammate can build from without any Figma access of their own. Covers Design Token 2.0 opt-in, theme switching, and the gotchas that silently produce an unstyled or Token 1.0 app.

version
0.1.0
GitHub stars
378

Install

/plugin install charcoal@charcoal

Run it inside Claude Code after adding the marketplace with /plugin marketplace add pixiv/charcoal.

Contents

Discovered from source

Skills 7

Choosing a charcoal styling approach

@charcoal-ui is pixiv's design system. It ships tokens once and lets you consume them three different ways. Picking the wrong one — or picking right but skipping the opt-in — is the main source of failure.

The official docs are not readable by agents

Do not try to look this up on the web first.

  • https://charcoal-web.pixiv.design/ is a Storybook SPA. Fetching it returns a title and no content.
  • The npm package pages return 403.
  • pages/ in the GitHub repo is a docsify site last updated 2023-03-22. It predates v4 and v6. Its instructions are wrong — it tells you @charcoal-ui/react needs a styled-components ThemeProvider, which stopped being true in v4.

Trust this skill and the package contents (node_modules/@charcoal-ui/*, or jsDelivr/unpkg) over search results.

Three layers, one choice

LayerWhat it isPackagesYour choice?
ConstantsDesign tokens@charcoal-ui/foundation, @charcoal-ui/themeNo — everyone uses these
UtilitiesTurning tokens into CSS you write@charcoal-ui/tailwind-config, @charcoal-ui/styled, or plain CSSYes — here only
ComponentsPrebuilt UI (Button, Modal…)@charcoal-ui/reactNo — plain CSS, no alternative

Two things people confuse:

  • "styled → pure CSS" describes the component layer's internals. v4 removed styled-components from @charcoal-ui/react. You get no say in it.
  • "styled vs Tailwind" is the utility layer choice — how you style your own markup.

Using @charcoal-ui/react does not require styled-components or Tailwind. They are unrelated decisions.

Pick the utility

Do you use @charcoal-ui/react components?
  → Yes: install it and load the token CSS. No styling library needed.
  → Either way, continue below for your own markup.

How do you want to style your own markup?
  ├─ Tailwind already in the project  → setting-up-charcoal-tailwind
  ├─ Large existing styled-components codebase → setting-up-charcoal-styled
  └─ Anything else (plain CSS, CSS Modules, vanilla-extract)
                                       → setting-up-charcoal-css-variables

Default to setting-up-charcoal-css-variables. It has no extra dependency and works with any stack.

Design Token 2.0 is opt-in, and the default is silent

This is the single most common failure. Every route has an opt-in flag, and every route silently gives you the old generation — or nothing at all — if you skip it.

RouteOpt-inSkip it and you get
CSS variablesLoad @charcoal-ui/theme/css/v2/{light,dark}.css and put class="ch-token-v2" on <html> or an ancestorNo tokens at all — components render with no color
TailwindunstableTokenV2: true plus the same two steps aboveDesign Token 1.0
styled-componentsnot availableDesign Token 1.0 only — the package has no v2 support

No error, no warning. The page just looks wrong.

.ch-token-v2 is not a CSS-variables-route detail. It gates the v2 variables themselves, so every route that wants Design Token 2.0 needs it — the Tailwind preset emits var(--charcoal-color-*) references but never defines them.

Is @charcoal-ui/styled deprecated?

Not formally — only createTheme carries @deprecated. But the package has no Design Token 2.0 support and receives no new features, while @charcoal-ui/tailwind-config keeps getting them. Treat it as a dead end you migrate off, not as a forbidden API.

Packages that are formally deprecated: @charcoal-ui/react-sandbox (removal planned) and @charcoal-ui/tailwind-diff (announced as 廃止予定).

Common mistakes

MistakeReality
Loading only @charcoal-ui/react/dist/index.cssThat file uses var(--charcoal-color-*) but never defines them. You must also load @charcoal-ui/theme/css/v2/{light,dark}.css.
Reading light.css's selector as :root:not([data-theme])The real selector is :root:not([data-theme]) .ch-token-v2. Drop .ch-token-v2 and nothing matches.
Prescribing Tailwind to fix missing colorsColors are not built by Tailwind. Static CSS ships in @charcoal-ui/theme.
Wrapping the app in ThemeProvider for <Button>Button imports its own CSS and needs no provider. Only overlays (Modal, DropdownSelector) need CharcoalProvider.
Assuming v6 does not existIt does. Search summaries lag; check registry.npmjs.org/@charcoal-ui/react.

Charcoal のトークンを選ぶ

Charcoal の値は好みで決めない。用途ごとに使うトークンが決まっている。迷ったら推測せず、 下の参照先で用途の表を引く。

原則として、hex・px の直書きをしない。 値はトークン名で書く。

どれを読むか

決めること参照
背景・文字・アイコン・ボーダーの色、状態(hover/press)、強さreferences/color.md
本文か見出しか、Body / Caption / Heading / Paragraph の選択、字間・字幅references/typography.md
余白、要素間の間隔、コンポーネント内部の padding、タップ領域の大きさreferences/spacing.md
角丸の大きさ、円形にするかどうかreferences/radius.md
線を引くかどうか、太さ、どの色かreferences/border.md
上の各ガイドラインに無い判断、全体の方針references/design-philosophy.md

読む前に外さないこと

参照を開かずに書き始める場合でも、次は守る。

  • 文字色に #000000 を使わない。 既定は text.default。
  • プライマリーカラーは重要アクションと誘導にだけ使う。 目立たせたいという理由で使わない。
  • 警告色はその状態を示すときだけ使う。 強調の手段にしない。
  • ボーダーは、無いと理解を妨げるときだけ引く。 まず余白か背景色の差で足りないか試す。 区切り線の既定は border.secondary。
  • 余白はレイアウトトークンから選ぶ。 トークンに無い数値を作らない。迷ったら layout.30。
  • 本文の基準は Body(body.Regular)。 テキストスタイルは 4 種類しかない。5 種類目を作らない。
  • 派手なグラデーション、過剰な線、過剰な装飾を足さない。 コンテンツより UI が目立たない。

トークン名を CSS 変数に直す

ガイドラインはトークンを layout.30 のように書く。CSS 変数の名前はそれとは違う。 推測すると --charcoal-layout-30 のような存在しない名前になり、値は当たらない。

ガイドラインCSS 変数
layout.30--charcoal-space-layout-30
target.m--charcoal-space-target-m
space.30--charcoal-space-30
text.default--charcoal-color-text-default
container.primary.default--charcoal-color-container-primary-default
radius.m--charcoal-radius-m
border-width.m--charcoal-border-width-m
Body--charcoal-text-font-size-body ほか
heading.M--charcoal-text-font-size-heading-m ほか
caption.S--charcoal-text-font-size-caption-s ほか

規則は --charcoal-<カテゴリ>-<キーを - でつないだもの>。色は color、余白は space(layout と target はその下)、角丸は radius、線の太さは border-width、 文字は text。

テキストスタイルは font-size と line-height の 2 本で指定する。 1 本で済ませない。 スタイル名は小文字にしてつなぐ(heading.M → heading-m、caption.S → caption-s)。 px は書かない。

確証がなければ node_modules/@charcoal-ui/theme/dist/css/v2/light.css で名前を確かめる。無い名前は書かない。

判断の順番

  1. その値にトークンがあるか。あれば必ずトークンを使う。
  2. 用途の表で、書こうとしている部品が名指しされているか。されていなければ、近い値を理由に 割り当てない。表が名指ししている用途にだけ使う。
  3. 状態(hover / press / disabled)が要るか。要る状態にだけ付ける。
  4. 迷いが残るなら references/design-philosophy.md の原則で決める。

Building a screen from a design pack

You have been given the design as files: design/design.md says what the design is, design/spec.json says the same thing as facts a script can check, and design/assets/ holds its bitmaps. That is everything. You do not need Figma, a token, or a seat.

flowchart LR
    pack[design.md<br>spec.json<br>assets/] --> build[Build the screen]
    build --> app[Running app]
    app -->|check-design.mjs| ask{Matches the spec?}
    ask -->|No, here is what is off| build
    ask -->|Yes| done[Done]

The loop is the point. Read the pack once, build the frame tree outside in, use the token where one is given, then let the check tell you what is still wrong.

No pack? prepare-figma-design makes one from a figma.com link with a read-only token. Do not implement from Figma MCP's get_design_context instead: it returns reference markup, and building from markup means transliterating it — you rewrite someone else's DOM and inherit a structure that was never meant to be code.

Stale pack? If the design has moved, the pack is regenerated by whoever has the token, not patched by hand here. A hand-edited pack and a real design disagree silently.

How to read the pack

- instance "Icon Button" 32×32 at (296, 8) — `Size=S, Type=Default, State=Default`
  flex-direction: row; padding: var(--charcoal-space-10); border-radius: var(--charcoal-radius-oval)
  - instance "24 / Close" 24×24 at (300, 12) — `24 / Close`
    - vector "Shape" 14×14 at (305, 17)
      color: var(--charcoal-color-icon-tertiary-default)

Each line is one element: its box, then its materials, then the component and variant it came from. The nesting is the structure to build. Position children with their parent's gap and padding, not with offsets on the children — the coordinates are there to identify an element, not to be typed into your CSS.

Values with a token are written as that token. Values without one are literal — and that is information too: it means the design system has no opinion here and you should not go looking for a token.

Widths and heights are geometry, not tokens. The design says a card is 294px wide because the layout says so. There is no token for it and none is expected. If you find yourself writing height: var(--charcoal-text-line-height-100) for a 72px header, the number matched and the meaning did not.

A color is read against what it sits on. White is the resting text color of five different roles at once, and nothing about the color says which. What says it is the surface underneath, so a white label inside a primary container is written text/on-primary/default rather than whichever white token sorts first.

Where the surface does not settle it, the pack says so instead of picking:

color: #ffffff /* text/on-on-img/default | text/on-primary/default | text/on-negative/default | text/on-positive/default | text/on-discovery/default */

That is the design system offering several words for this color and the design not saying which. Choose the role the element actually plays.

A gradient or a pattern is named, not valued. background: linear gradient /* no token for this; read it from the design */ means there is a fill here that the design system has no word for and the pack cannot write as a value. Open the design and copy it. The one thing it does not mean is an unpainted box.

There is no markup, on purpose. The pack says what the design is. Turning that into components, props and state is the implementation, and it is yours to write.

Where an element has words they are given as text: — use them verbatim. A node name is its Figma layer, which is often a label rather than what it says.

Check your own work

check-design.mjs decides when you are done. Run it, fix what it names, run it again. An implementation that has never been rendered is a guess, however carefully it was built from the pack — and the most expensive mistake it can make is invisible from the source: a screen can import every component, write every value as a token, and render with none of them applied.

With the app running:

node <this-skill>/bin/check-design.mjs --spec design/spec.json --url http://localhost:4173

<this-skill> is wherever this skill was installed: ${CLAUDE_PLUGIN_ROOT}/skills/implement-figma-design under the Claude Code plugin, .claude/skills/implement-figma-design or .agents/skills/implement-figma-design under npx skills.

It names what is off — outermost first, because a container in the wrong place moves everything inside it — and says nothing about how well you did. The first thing it asks is whether charcoal's variables resolve at all, because that failure is the one the source cannot show you. Fix that before reading anything below it: until the tokens land, every box will look wrong for the same single reason.

Needs playwright installed in the project being checked — it is resolved from there, not from wherever this skill lives — and without it the check declines rather than guessing.

Every file it touches

check-design.mjs writes nothing at all: findings go to stdout, and the exit code is what a script should branch on.

PathR/WWhat
--spec <path>readThe spec from the pack.
--url <url>readThe running app, over HTTP.
playwrightreadResolved from the project being checked, not from where this skill is installed.

What the pack does not replace

It is one frame as the designer drew it. It does not carry:

  • Which component in your library each instance is. It gives you Figma's instance name and its variant properties; the mapping is yours to make. Figma's Search Field is often your TextField. Check the names against your library's exports rather than trusting them — a wrong component mapping costs more than a wrong color.
  • Any state the frame is not drawn in. Hover, focus, error and empty states are other frames, or not in the file at all.
  • Behaviour. What a button does, what validates, what navigates where.
  • Which theme it is. --theme dark and --theme light give different token names for the same drawing, and the pack does not record which was used. Ask if it matters.

Getting a Figma design out of Figma, once, for everyone

A design link holds two different things: where everything sits, and what everything is made of. What an implementer wants is both, joined, with your own token names on the materials — and nothing else. This emits exactly that, from Figma's free REST API.

It is deliberately a separate step from building the screen, because the two jobs need different things. This one needs a Figma credential and access to the file. Building the screen needs neither.

flowchart LR
    subgraph prep["prepare-figma-design — the only step that touches Figma"]
        link[Figma link<br>--url, needs a token] -->|fetch-design.mjs| pack[design.md<br>spec.json<br>assets/]
        fig[".fig export<br>--fig, needs nothing"] -->|fetch-design.mjs| pack
    end
    subgraph impl["implement-figma-design — needs no Figma access"]
        build[Build the screen] --> check{check-design.mjs}
        check -->|what is off| build
        check -->|matches| done[Done]
    end
    pack -->|commit, hand over| build

Run this once and commit what it writes. Whoever builds the screen — a teammate, an agent, you tomorrow — works from those files and never needs the token, the file permission, or a seat.

If you also have Figma's MCP and a Dev Mode seat, still do not hand over get_design_context. It returns reference markup, and building from markup means transliterating it: the implementer rewrites someone else's DOM instead of building the design, and inherits a structure that was never meant to be code — wrapper divs that exist for Figma's layout engine, absolute positioning where the design means a gap.

Do this

There are two ways in, and they produce the same three files. Use the link if you can reach the file; use a .fig when you have no token, when Figma is unreachable, or when you want a pack rebuildable from something committed.

From a link

A read-only personal access token is enough, created at Figma Settings → Security → Personal access tokens. No Dev Mode seat is needed.

The token is read from FIGMA_TOKEN in the environment. Ask whoever is running this to put it there — a shell profile, a .env the project already loads, whatever they use for credentials. Do not paste it into the command: an inline assignment lands in shell history and in the environment of every process started from that shell.

node <this-skill>/bin/fetch-design.mjs \
  --url "https://www.figma.com/design/<key>/<name>?node-id=36-6579" \
  --tokens node_modules/@charcoal-ui/theme/src/json \
  --assets design/assets \
  --spec design/spec.json \
  > design/design.md

<this-skill> is wherever this skill was installed: ${CLAUDE_PLUGIN_ROOT}/skills/prepare-figma-design under the Claude Code plugin, .claude/skills/prepare-figma-design or .agents/skills/prepare-figma-design under npx skills.

From a .fig

File → Save local copy in Figma writes a .fig: the whole document, and every bitmap in it. Reading one needs no token, no network and no access to the original file — the bitmaps come straight out of the archive instead of being downloaded.

node <this-skill>/bin/fetch-design.mjs \
  --fig design.fig \
  --node 110-8609 \
  --tokens node_modules/@charcoal-ui/theme/src/json \
  --assets design/assets \
  --spec design/spec.json \
  > design/design.md

--node is required here and takes the node-id from the frame's link, because a .fig holds the whole file and there is no one frame to default to. Right-click the frame in Figma → Copy link to get it.

Two things to know. It needs Node 22.15 or newer, because a recent export compresses its document with zstd. And it reads the design as the export froze it, so a .fig taken last month describes last month's design however current the link looks.

Either way

--tokens points at your design system's Style Dictionary JSON. Without it values come out literally; with it, every value the system has a token for is named as that token. A path that holds no tokens is an error rather than a pack full of raw hex.

--theme light|dark picks which theme file to resolve against, defaulting to light. The other theme's values are left out entirely, so a light design never gets named with a dark token.

--assets downloads the design's bitmaps and names each on the box that paints it, together with the object-fit its crop implies. Leave it out and the pack describes the boxes without the images.

--spec writes the same design as facts a script can compare a render against. Pass it: it is what lets the implementer check their own work, and it costs nothing to produce here. Without it they can build the screen but cannot tell when they are done.

Then hand it over

Commit all three — design/design.md, design/spec.json, design/assets/ — and point whoever is building at implement-figma-design. They are the complete input. Nothing else from Figma is needed, and no part of this step has to be repeated until the design itself changes.

Say which frame it is and which theme you resolved against. --theme dark and --theme light produce different token names for the same drawing, and nothing in the pack records which you picked.

Re-run this when the design changes, not when the implementation does. The pack is a snapshot of one frame as the designer drew it; a stale pack is worse than none, because the check loop will keep reporting a screen as wrong when it is the design that moved.

Every file it touches

Nothing is written anywhere you did not name. There is no cache, no temp directory, and nothing is ever written inside node_modules — the outputs describe your screen, so they belong in your repository next to the code they explain, where a reviewer can see what the implementation was built from.

PathR/WWhat
FIGMA_TOKEN (environment)readThe credential, for --url only. Read only when a request is about to be made, never stored. Never read on the --fig route.
--fig <file>readA local Figma export. The only input the --fig route has: no network call is made at all.
--tokens <dir>readYour design system's Style Dictionary JSON. For charcoal: node_modules/@charcoal-ui/theme/src/json. Read-only; one *.json per theme plus the shared palette.
stdoutwriteThe pack. Redirect it where you want it — the examples use design/design.md.
--spec <path>writeThe same design as facts check-design.mjs can compare a render against. Only written when the flag is given.
--assets <dir>/writeThe design's bitmaps, one file per image, named from its Figma reference. The directory is created if it is missing. Only written when the flag is given.

Why the tokens come from the JSON rather than charcoal's generated light.css: the CSS keeps each token as a reference to another token (var(--charcoal-color-light-blue-50)) where this needs the literal a Figma color can be matched against, and it flattens text/on-primary/default into text-on-primary-default, losing the / boundaries that tell a role from a state from a palette entry.

What you are handing over

- instance "Icon Button" 32×32 at (296, 8) — `Size=S, Type=Default, State=Default`
  flex-direction: row; padding: var(--charcoal-space-10); border-radius: var(--charcoal-radius-oval)
  - instance "24 / Close" 24×24 at (300, 12) — `24 / Close`
    - vector "Shape" 14×14 at (305, 17)
      color: var(--charcoal-color-icon-tertiary-default)

Each line is one element: its box, then its materials, then the component and variant it came from. implement-figma-design explains how to read it; what matters here is that it is complete without Figma, and that there is no markup in it on purpose.

A fill the design system cannot name — a gradient, a pattern — is written as what it is, background: linear gradient /* ... */, rather than left out. A box painted with a gradient must not read like a box painted with nothing.

If the pack comes out full of raw hex, --tokens is pointing at the wrong directory — fix that before handing it over, because a literal reads as "the design system has no word for this" and sends the implementer looking for one that does not exist.

Setting up charcoal with CSS variables

The lowest-dependency way to use charcoal: load two stylesheets, add one class, then write var(--charcoal-*) anywhere.

Install

npm install @charcoal-ui/react@^6 @charcoal-ui/theme@^6 react-aria react-stately

Pin the major. Design Token 2.0 and the CSS layout below are v6; v5 and earlier differ. Keep every @charcoal-ui/* package on the same major.

Peer dependencies of @charcoal-ui/react: react >=17.0.0, react-aria >=3.48.0, react-stately >=3.46.0. The two react-aria packages are not installed for you. React 18 and 19 both satisfy the range.

Skip @charcoal-ui/react if you only want tokens — @charcoal-ui/theme alone is enough.

Load the CSS

// Load once at the app root.
import '@charcoal-ui/react/dist/index.css' // component implementation CSS
import '@charcoal-ui/theme/css/v2/light.css' // Design Token 2.0 — light
import '@charcoal-ui/theme/css/v2/dark.css' // Design Token 2.0 — dark

dist/index.css only consumes var(--charcoal-color-*). It never defines them.

The failure this causes is lopsided in a way that misleads people: colors go through var(), but layout does not. Padding, radius, font-size, and line-height are written as literal values, so they keep working. Load dist/index.css alone and you get a correctly shaped, correctly sized button with a transparent background and default black text. Nothing errors — an undefined custom property just makes that one declaration invalid, and the property falls back to its initial value.

If a charcoal component looks structurally right but colorless, this is why.

Prefer @charcoal-ui/react/dist/layered.css over dist/index.css when you need to override charcoal styles from your own CSS. Its contents are wrapped in @layer charcoal, so any unlayered rule of yours wins without a specificity fight. It requires iOS 15.4+.

Opt in to Design Token 2.0 — required

Token 2.0 only applies inside .ch-token-v2.

<html class="ch-token-v2" lang="ja"></html>

The shipped selectors are:

/* light.css */
:root.ch-token-v2[data-theme='light'],
:root.ch-token-v2:not([data-theme]),
:root[data-theme='light'] .ch-token-v2,
:root:not([data-theme]) .ch-token-v2 {
  --charcoal-color-…: …;
}

/* dark.css */
:root[data-theme='dark'] {
  --charcoal-color-…: …;
}

Two consequences:

  • Without .ch-token-v2, no light-theme rule matches and every token is undefined.
  • Dark is scoped to :root only, so data-theme="dark" applies page-wide regardless of .ch-token-v2.

Put the class on <html>, or on an ancestor of the components you want themed. Variables inherit, so siblings are unaffected.

Use the tokens

.card {
  background-color: var(--charcoal-color-background-default);
  color: var(--charcoal-color-text-default);
  border: 1px solid var(--charcoal-color-border-secondary);
  border-radius: var(--charcoal-radius-s);
  padding: var(--charcoal-space-40);
}

Names follow --charcoal-<category>-<semantic>-<state>. Common ones: color-text-default / -secondary-default / -tertiary-default, color-background-default / -secondary / -tertiary, color-border-default / -secondary, color-container-primary-default, radius-xs|s|m|l, space-*. Read node_modules/@charcoal-ui/theme/dist/css/v2/light.css for the full list.

Components need no provider

import { Button } from '@charcoal-ui/react'

export const Save = () => <Button variant="Primary">保存</Button>

Button imports its own CSS and uses no context. Wrap in CharcoalProvider only when you use overlays (Modal, DropdownSelector) — it supplies react-aria's SSRProvider and OverlayProvider.

Theme switching

document.documentElement.dataset.theme = 'dark' // or 'light'

For SSR, run this before paint to avoid a flash:

import { makeSetThemeScriptCode } from '@charcoal-ui/react'

;<script dangerouslySetInnerHTML={{ __html: makeSetThemeScriptCode() }} />

Use makeSetThemeScriptCode(), not <SetThemeScript />. The component's props type requires both localStorageKey and rootAttribute, so <SetThemeScript /> is a type error; makeSetThemeScriptCode() accepts zero arguments.

System theme does not follow the OS

useThemeSetter() removes data-theme when the user is on "system", by design — it expects CSS to handle prefers-color-scheme. Design Token 2.0's CSS has no prefers-color-scheme block, so with the attribute removed :root:not([data-theme]) .ch-token-v2 matches and the page is stuck on light even on a dark OS.

Either always write an explicit data-theme, or add the missing bridge yourself:

@media (prefers-color-scheme: dark) {
  :root:not([data-theme='light']).ch-token-v2,
  :root:not([data-theme='light']) .ch-token-v2 {
    /* copy the declarations from @charcoal-ui/theme/css/v2/dark.css */
  }
}

Mirror light.css's selector shape. Targeting bare :root fails when .ch-token-v2 sits on a descendant: that descendant's own light values beat inherited dark values from an ancestor.

Common mistakes

MistakeFix
Only dist/index.css loadedAdd @charcoal-ui/theme/css/v2/{light,dark}.css
.ch-token-v2 missingAdd it to <html> or an ancestor
<SetThemeScript /> with no propsUse makeSetThemeScriptCode()
Own CSS loses to charcoal'sSwitch to dist/layered.css
Dark mode ignored on "system"Add the prefers-color-scheme bridge above

Setting up charcoal with styled-components

@charcoal-ui/styled exists for codebases already written in styled-components. Read the next section before wiring it in.

Choose this only for existing code

@charcoal-ui/styled is frozen at Design Token 1.0. Its source contains no reference to Token 2.0, and it receives only maintenance commits while @charcoal-ui/tailwind-config keeps gaining v2 features.

The package is not formally deprecated — only createTheme carries @deprecated. The problem is not that it is forbidden; it is that it cannot reach the current token generation.

It also drags in the component library: @charcoal-ui/styled peer-depends on @charcoal-ui/react, because useTheme, useThemeSetter, themeSelector, and SetThemeScript are re-exports whose implementations live there. You get that dependency even if you never render a charcoal component.

For a new project, or when you only want tokens, use setting-up-charcoal-css-variables instead.

Install

npm install @charcoal-ui/styled@^6 @charcoal-ui/theme@^6 @charcoal-ui/react@^6

Pin the major and keep every @charcoal-ui/* package on the same one. styled-components >=5.1.1 and react >=17.0.0 are peers.

Provider

Two independent mechanisms, both usually needed:

  • ThemeProvider (styled-components) supplies the JS theme object so ${({ theme }) => theme.color.text1} resolves. The values are literal hex strings, not var().
  • TokenInjector (@charcoal-ui/styled) emits --charcoal-color-* CSS variables at runtime via createGlobalStyle, for anything not going through styled-components.
import { ThemeProvider } from 'styled-components'
import {
  TokenInjector,
  addThemeUtils,
  useTheme,
  useThemeSetter,
  themeSelector,
} from '@charcoal-ui/styled'
import { light, dark } from '@charcoal-ui/theme'

const lightTheme = addThemeUtils(light)
const darkTheme = addThemeUtils(dark)

export function ThemeRoot({ children }: { children: React.ReactNode }) {
  const [mode] = useTheme()
  useThemeSetter()

  return (
    <ThemeProvider theme={mode === 'dark' ? darkTheme : lightTheme}>
      <TokenInjector
        theme={{ ':root': light, [themeSelector('dark')]: dark }}
        background="background1"
      />
      {children}
    </ThemeProvider>
  )
}

TokenInjector's optional background prop takes any key of theme.color (background1, background2, surface1…) and paints it as the page background on each selector.

Because the JS objects hold literal colors, switching themes requires swapping ThemeProvider's theme prop. Rewriting CSS variables alone does not change ${({ theme }) => …} output. The two systems must be kept in sync — that is what useTheme plus useThemeSetter do here.

Types

// styled.d.ts
import 'styled-components'
import type { CharcoalTheme } from '@charcoal-ui/theme'
import type { CharcoalThemeUtils } from '@charcoal-ui/styled'

declare module 'styled-components' {
  export interface DefaultTheme extends CharcoalTheme, CharcoalThemeUtils {}
}

Writing components

Use styled-components' own theming. Do not use createTheme / theme(o => [...]) — it is @deprecated for runtime performance (PR #377).

const Card = styled.div`
  background-color: ${({ theme }) => theme.color.background1};
  color: ${({ theme }) => theme.color.text1};
  border-radius: ${({ theme }) => theme.borderRadius[8]}px;
  ${({ theme }) => theme.utils.padding(16)}
  ${({ theme }) => theme.utils.typography(16)}
`

addThemeUtils() adds theme.utils: margin*, padding*, gap, typography, focusVisibleFocusRingCss, assertiveRingCss, disabledCss.

Constraints worth knowing before you hit them:

  • theme.utils.typography(size) accepts only 12 | 14 | 16 | 20. 32 is not supported — expand it by hand. theme.typography.size[n] is { fontSize: number; lineHeight: number } in px, keyed by 12 | 14 | 16 | 20 | 32:

    font-size: ${({ theme }) => theme.typography.size[32].fontSize}px;
    line-height: ${({ theme }) => theme.typography.size[32].lineHeight}px;
    
  • theme.utils.margin / padding accept only the spacing scale (0, 4, 8, 16, 24, 40, 64, 104, 168, 272, 440) or 'auto'. Arbitrary px values are rejected by the type.

  • theme.spacing and theme.typography are identical in light and dark.

Theme switching and SSR

import { makeSetThemeScriptCode } from '@charcoal-ui/styled'

;<script dangerouslySetInnerHTML={{ __html: makeSetThemeScriptCode() }} />

Prefer makeSetThemeScriptCode() over <SetThemeScript />; the component's props type requires both localStorageKey and rootAttribute.

Migrating off, in dependency order

You do not have to leave in one step.

  1. Drop createTheme. The only @deprecated API here. Move to plain ${({ theme }) => theme.color.*} or addThemeUtils.
  2. Drop TokenInjector. Import @charcoal-ui/theme/css/v2/{light,dark}.css instead — static CSS supplies the same variables with no runtime createGlobalStyle. This is also the step that unlocks Design Token 2.0.
  3. Drop ThemeProvider. Replace theme.color.text1 reads with var(--charcoal-color-text-default).
  4. Drop styled-components if you want. By this point charcoal no longer cares.

If you only render @charcoal-ui/react components, steps 1–3 are already unnecessary — since v4 it does not depend on styled-components at all.

Common mistakes

MistakeFix
Reaching for createTheme because docs show itIt is @deprecated. Use styled-components theming.
Expecting Design Token 2.0 hereNot supported. Move to CSS variables or Tailwind.
Swapping CSS variables to change themeJS theme objects hold literal colors — swap ThemeProvider's theme too.
theme.utils.typography(32)Type error. Expand theme.typography.size[32] manually.
Following pages/ docs in the repoLast updated 2023-03-22, pre-v4. Its @charcoal-ui/react instructions are wrong.

Setting up charcoal with Tailwind

@charcoal-ui/tailwind-config turns charcoal tokens into a Tailwind preset. This is the actively developed utility route — new Design Token 2.0 features land here first.

Install

npm install --save-dev @charcoal-ui/tailwind-config @charcoal-ui/theme

Peer dependencies: tailwindcss >=1.4.6, postcss >=7.0.32, csstype >=3.0.0. Tailwind v4 support is WIP — v4 works only by pointing @config at a v3-shaped config.

Configure

// tailwind.config.js
const { light, dark } = require('@charcoal-ui/theme')
const { createTailwindConfig } = require('@charcoal-ui/tailwind-config')

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ['./src/**/*.{js,ts,jsx,tsx}'],
  presets: [
    createTailwindConfig({
      version: 'v3',
      theme: {
        ':root': light,
        '@media (prefers-color-scheme: dark)': dark,
      },
      unstableTokenV2: true, // Design Token 2.0 — omit and you get 1.0
      iconsV2: true,
    }),
  ],
}

createTailwindConfig() options: version ('v1' | 'v2' | 'v3', Tailwind's version — unrelated to charcoal's), theme, cssVariablesV1, unstableTokenV2, iconsV1, iconsV2. A bare default preset is also exported as config.

unstableTokenV2: true needs the theme CSS too

The preset does not define Design Token 2.0 variables. unstable_createTailwindConfigTokenV2() contains no plugin and no addBase() — it only emits class values that reference var(--charcoal-color-*). Something else has to define them.

Two disjoint namespaces are in play:

Defined byNamesExample
The preset, when cssVariablesV1 is on (default)--charcoal-<v1 token>--charcoal-background1, --charcoal-text1
@charcoal-ui/theme/css/v2/*.css--charcoal-color-<v2 token>--charcoal-color-container-default

customPropertyToken() produces --charcoal-${id}, so the v1 variables never satisfy a v2 reference. Turning on unstableTokenV2 without loading the theme CSS gives you classes that resolve to nothing — colors silently disappear.

So with unstableTokenV2: true, do all three:

/* globals.css */
@import '@charcoal-ui/theme/css/v2/light.css';
@import '@charcoal-ui/theme/css/v2/dark.css';

@tailwind base;
@tailwind components;
@tailwind utilities;
<html lang="ja" class="ch-token-v2">
  <body>
    <div id="root"></div>
  </body>
</html>

.ch-token-v2 gates the light-theme rules in light.css. Without it, no light rule matches and every v2 variable is undefined — the same failure described in setting-up-charcoal-css-variables.

If you stay on Design Token 1.0 (unstableTokenV2 omitted), the preset's own addBase() supplies everything and the three @tailwind lines are all you need.

The preset replaces Tailwind's defaults

createTailwindConfig() writes colors, spacing, width, gap, borderRadius, screens, and transitionDuration at the top level of theme, not under extend. Tailwind's preset merge therefore replaces the stock scales:

  • bg-red-500, text-blue-600 and the rest of the default palette stop existing. Only transparent, current, black, white, and charcoal tokens remain.
  • p-4 no longer means 1rem. Spacing keys are charcoal's px values: 0, 4, 8, 16, 24, 40, 64, 104, 168, 272, 440 — so p-16 is 16px.
  • corePlugins: { lineHeight: false } disables every leading-* utility.

If existing markup relies on stock Tailwind classes, add them back explicitly:

const colors = require('tailwindcss/colors')
module.exports = {
  presets: [createTailwindConfig({/* … */})],
  theme: { extend: { colors: { red: colors.red } } },
}

Classes you get

<div className="bg-background1 text-text1 rounded-8 p-16">
  <h2 className="typography-20">タイトル</h2>
  <button className="ch-focus-ring bg-brand hover:bg-brand-hover active:bg-brand-press">
    送信
  </button>
</div>
  • Colors carry DEFAULT / hover / press / disabled variants — bg-brand, bg-brand-hover, …
  • typography-{12|14|16|20|32} sets font-size and line-height together.
  • .ch-focus-ring reproduces the focus ring used by @charcoal-ui/react.
  • w-col-span-{n} and w-{n}/12 come from the grid system.

Those names are Design Token 1.0. They keep working when unstableTokenV2 is on, because the preset merges v2 entries on top of v1 rather than replacing them.

Design Token 2.0 adds five color groups — background, border, container, icon, text — folded so that a default key becomes the bare class:

color.container.default      → bg-container
color.container.hover        → bg-container-hover
color.text.default           → text-text
color.text.info.default      → text-text-info
color.text.negative.hover    → text-text-negative-hover
color.background.secondary   → bg-background-secondary

Spacing splits into component-* and layout-* (p-component-20, gap-layout-40), radius becomes rounded-{xs|s|m|l|xl|xxl|oval}, and border colors take a ch prefix (border-ch-secondary).

To see exactly what your config produces, resolve it rather than guessing:

console.log(
  require('tailwindcss/resolveConfig')(require('./tailwind.config.js')).theme
    .colors,
)

Dark theme

Tailwind's dark: variant is not supported. A charcoal token keeps its name across themes while its value changes, so dark:bg-background1 is meaningless. Pass a theme map instead and the generated var() switches for you.

// follow the OS
theme: { ':root': light, '@media (prefers-color-scheme: dark)': dark }

// or switch from JS
theme: { ':root': light, 'html[data-theme="dark"]': dark }
document.documentElement.dataset.theme = 'dark'

Do not nest :root under the @media key — the build inserts it for you.

The theme map only drives Design Token 1.0. It feeds cssVariablesV1, which defines --charcoal-<v1 token>. Token 2.0 variables come from @charcoal-ui/theme/css/v2/*.css, and that CSS defines dark only at :root[data-theme='dark'] — it has no prefers-color-scheme block. So on unstableTokenV2: true, '@media (prefers-color-scheme: dark)': dark does not make v2 tokens follow the OS.

Either write data-theme explicitly from JS, or add the bridge described in setting-up-charcoal-css-variables:

@media (prefers-color-scheme: dark) {
  :root:not([data-theme='light']).ch-token-v2,
  :root:not([data-theme='light']) .ch-token-v2 {
    /* copy the declarations from @charcoal-ui/theme/css/v2/dark.css */
  }
}

Common mistakes

MistakeFix
unstableTokenV2 omittedYou silently get Design Token 1.0. Set it to true.
unstableTokenV2: true but no theme CSSThe preset never defines --charcoal-color-*. Import @charcoal-ui/theme/css/v2/{light,dark}.css and add .ch-token-v2.
Assuming .ch-token-v2 is a CSS-variables-route-only concernIt gates the v2 variables themselves, so the Tailwind v2 route needs it too.
Confusing version: 'v3' with charcoal v3It means Tailwind v3.
dark:bg-*Unsupported. Use the theme map.
Stock Tailwind classes vanishedThe preset replaces the default scales — add them back under theme.extend.
leading-* has no effectcorePlugins.lineHeight is off. Use typography-*.
Nesting ':root' inside the @media keyPass the theme object directly.

Using charcoal React components too

@charcoal-ui/react is independent of this preset. It needs its own CSS and the .ch-token-v2 opt-in — see setting-up-charcoal-css-variables. Set corePlugins: { preflight: false } if Tailwind's reset interferes with charcoal component styles.

Sponsors

Details

Marketplace
pixiv/charcoal
Author
pixiv
Category
Web Development
License
Apache-2.0
Keywords
charcoal, pixiv, design-system, design-tokens, css-variables, tailwind, styled-components, react, figma