Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/mosaic-stylex-migration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
19 changes: 10 additions & 9 deletions .claude/skills/mosaic/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@ this skill is the _how-to_.

## Which reference to read

| You are… | Read |
| ------------------------------------------------------------------ | ------------------------------------------------------ |
| Styling a component (slot recipes, `useRecipe`, variants, slots) | `references/styling.md` |
| Authoring or debugging a state machine, or wiring one to React | `references/machines.md` → in-tree `machine/README.md` |
| Writing the controller (Clerk adapter, permissions, revalidate) | `references/controllers.md` |
| Writing the view (rendering a snapshot, sending events) | `references/views.md` |
| Testing a machine, controller, or view | `references/testing.md` |
| Migrating a legacy component into Mosaic (the end-to-end workflow) | `references/migration.md` |
| Running the parity audit that guards a migration | `references/parity-audit.md` |
| You are… | Read |
| -------------------------------------------------------------------- | ------------------------------------------------------ |
| Styling a component with StyleX (tokens, `stylex.create`, CSS build) | `references/stylex.md` |
| Styling a component the legacy way (slot recipes, `useRecipe`) | `references/styling.md` |
| Authoring or debugging a state machine, or wiring one to React | `references/machines.md` → in-tree `machine/README.md` |
| Writing the controller (Clerk adapter, permissions, revalidate) | `references/controllers.md` |
| Writing the view (rendering a snapshot, sending events) | `references/views.md` |
| Testing a machine, controller, or view | `references/testing.md` |
| Migrating a legacy component into Mosaic (the end-to-end workflow) | `references/migration.md` |
| Running the parity audit that guards a migration | `references/parity-audit.md` |

The migration workflow (`migration.md`) ties the flow references together: it
treats the legacy component as the spec and drives you through the machine,
Expand Down
136 changes: 136 additions & 0 deletions .claude/skills/mosaic/references/stylex.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Styling a component with StyleX

Mosaic styling is migrating off the Emotion slot-recipe engine (`styling.md`)
onto **StyleX** (`@stylexjs/stylex` 0.19). StyleX is compile-time atomic CSS: the
style objects become hashed atom classes plus one static stylesheet, with zero
runtime. This file is the authoring model for the StyleX layer; read it against
the pilot, `packages/ui/src/mosaic/components/button/`.

The public contract is unchanged from the recipe era — consumers still target
`--cl-*` vars, the `.cl-<slot>` class, and `data-<axis>` attrs, never StyleX's
hashed `x…` atoms. What changes is how a component is authored internally.

## File layout & the `.stylex.ts` rule

| File | Holds |
| ------------------------- | ---------------------------------------------------------- |
| `tokens.stylex.ts` | `defineVars` / `defineConsts` only (the tokens) |
| `<comp>/<comp>.styles.ts` | `stylex.create({...})` — the atoms |
| `<comp>/<comp>.tsx` | component; spreads `stylex.props(...)` via `mergeProps` |
| `props.ts` | `themeProps` (`.cl-<slot>` + `data-<axis>`) + `mergeProps` |
| `styles/index.ts` | isolated-build barrel; derives `*VarName` types |

All 9 `@stylexjs` eslint rules run on `src/mosaic/**`. The `enforce-extension`
rule reserves the `.stylex.ts` extension for token files: **a `.stylex.ts` file
may export nothing but `defineVars`/`defineConsts` results.** So:

- `stylex.create(...)` lives in a plain `.styles.ts` file, never `.stylex.ts`.
- Derived types (`type ColorVarName = keyof typeof colorVars`) live in
`styles/index.ts`, not in `tokens.stylex.ts` (they'd be a disallowed export).

## Tokens (`tokens.stylex.ts`)

**`defineVars` keys that start with `--` emit verbatim** as real custom
properties; other keys get hashed. That verbatim behavior is the whole point —
it gives consumers stable `--cl-*` vars to override in plain CSS:

```ts
const colorDefaults = {
// one value carries light + dark; resolves against the in-scope `color-scheme`,
// so dark mode lives in the token, no `@media (prefers-color-scheme)` copy.
'--cl-color-primary': 'light-dark(oklch(0.205 0 0), oklch(0.922 0 0))',
} as const;
export const colorVars = stylex.defineVars(colorDefaults);
```

**Spacing is one exposed var plus a `defineConsts` scale.** Only `--cl-spacing`
is a custom property; every step is inlined at build as `calc(var(--cl-spacing) *
n)` and carries no var of its own:

```ts
export const spacingVars = stylex.defineVars({ '--cl-spacing': '0.25rem' });

const step = (multiple: number): string => `calc(var(--cl-spacing) * ${multiple})`;
export const space = stylex.defineConsts({ '0': '0px', '2': step(2), '8': step(8) /* … */ });
// usage: gap: space['2']
```

Why `defineConsts` and not a `space(n)` helper: StyleX evaluates
`stylex.create` **statically at build time** and cannot inline a helper imported
from a non-`.stylex` module (it errors "Could not resolve the path to the
imported file"). `defineConsts` is StyleX's shareable inlined-value primitive, so
it's the only way to get a scale that is both shared across components and free
of per-step vars.

## Atoms (`<comp>.styles.ts`)

`stylex.create` values must be statically resolvable. Allowed: literals,
**same-file** locals, and references to `.stylex` tokens (`colorVars[...]`,
`space['2']`). Not allowed: a value from a helper imported across modules. For
arithmetic, inline a `calc()` template literal with a token:
`` `calc(-1 * ${space['2']})` ``.

**Conditions.** Use StyleX's conditional-value objects (a `default` plus
pseudo / at-rule keys), and nest to guard hover so it never sticks on touch —
this is the StyleX form of the old `_hover` condition:

```ts
backgroundColor: {
default: colorVars['--cl-color-primary'],
':active': `color-mix(in oklab, ${colorVars['--cl-color-primary']}, ${colorVars['--cl-color-primary-foreground']} 24%)`,
'@media (hover: hover)': {
// only the top-level value needs `default`; the nested block just adds `:hover`
':hover': `color-mix(in oklab, ${colorVars['--cl-color-primary']}, ${colorVars['--cl-color-primary-foreground']} 12%)`,
},
},
```

Guard `:hover` behind `@media (hover: hover)`; leave `:active`, `:focus-visible`,
`:disabled` unguarded. Runtime conditions the component owns (disabled, etc.) are
also reflected as `data-<axis>` attrs via `themeProps` so they stay overridable.

Write the guard **raw**, as above — there is no `hover()` helper to import,
because StyleX can't inline a cross-module helper into `create` (the Emotion
engine's `hover()`/`motionSafe()` utils don't translate). `*.styles.ts` files are
therefore exempted from the repo's `no-restricted-syntax` media-query rule
(`eslint.config.mjs`); the `@stylexjs/*` rules still apply.

## Public contract (`props.ts`)

The element carries three things, and nothing else is a contract:

1. `--cl-*` vars (from tokens), 2. `.cl-<slot>` class, 3. `data-<axis>` attrs.

`mergeProps` fuses them in precedence order — **theme props → StyleX atoms →
consumer `className`/`style`** — so the consumer always wins:

```tsx
<button {...mergeProps(themeProps('button', { intent, variant }), stylex.props(styles.base, ...), className, style)} />
```

## Build & CSS delivery (two contexts, same babel)

- **Published** (`build:mosaic` → `@stylexjs/rollup-plugin`): compiles the
`styles/index.ts` barrel into `dist-mosaic/styles.css`, exported as
`@clerk/ui/styles.css`. Consumers choose the cascade layer at import:
`@import '@clerk/ui/styles.css' layer(components)`.
- **Swingset** (source-consumed): `@stylexjs/unplugin/webpack` in `next.config`
transforms StyleX **JS only** (calls → static atoms; SWC/Emotion untouched);
`@stylexjs/postcss-plugin` extracts the **CSS** by replacing `@stylex;` in
`globals.css`. Both must share the same StyleX babel version + options so atom
hashes line up.

Both set **`useCSSLayers: true`** (StyleX emits `@layer priorityN` for its own
precedence; the consumer's `@import … layer()` picks the outer layer). Both pin
**lightningcss targets** to browsers with native `light-dark()`/`oklch()` so the
token colors aren't down-leveled into an invalid polyfill.

## CSS features we lean on / caveats

- YES: `var()`, `calc()`, `color-mix()`, `light-dark()`, nested `@media`+pseudo,
`:hover`/`:active`/`:focus-visible`/`:disabled`, `::before`/`::after`.
- Prefer CSS-native solutions over JS workarounds for anything StyleX supports.
- Avoid manual `@layer` / `@property` inside `create` (StyleX owns layering;
`@property` compiles but emits invalid output).
- We do not use functions-in-`create` (dynamic runtime values); Mosaic styling is
fully static.
7 changes: 7 additions & 0 deletions .claude/skills/mosaic/references/styling.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Styling a component with slot recipes

> **Migration in progress:** Mosaic styling is moving off this Emotion slot-recipe
> engine onto **StyleX** (compile-time atomic CSS). New/migrated components are
> authored with StyleX — see **`references/stylex.md`**. This file documents the
> recipe system that StyleX is replacing; both coexist until the migration lands.
> The public `--cl-*` / `.cl-<slot>` / `data-<axis>` contract is identical across
> both, so it is preserved regardless of the internal engine.

A styled Mosaic component is authored with one **slot recipe**. The recipe owns
everything about how the part looks and is targeted: its slot identity
(`data-cl-slot`), base styles, variants, and the appearance cascade.
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# compiled output
dist
dist-mosaic
tmp
out-tsc
out
Expand Down
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
build
coverage
dist
dist-mosaic
/packages/nextjs/examples
node_modules
package-lock.json
Expand Down
24 changes: 24 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import pluginJsxA11y from 'eslint-plugin-jsx-a11y';
import pluginPlaywright from 'eslint-plugin-playwright';
import pluginReact from 'eslint-plugin-react';
import pluginReactHooks from 'eslint-plugin-react-hooks';
import pluginStylex from '@stylexjs/eslint-plugin';
import pluginSimpleImportSort from 'eslint-plugin-simple-import-sort';
import pluginTurbo from 'eslint-plugin-turbo';
import pluginUnusedImports from 'eslint-plugin-unused-imports';
Expand Down Expand Up @@ -539,7 +540,19 @@ export default tseslint.config([
name: 'packages/ui/mosaic',
files: ['packages/ui/src/mosaic/**/*'],
ignores: ['packages/ui/src/mosaic/utils.ts', 'packages/ui/src/mosaic/__tests__/**'],
plugins: {
'@stylexjs': pluginStylex,
},
rules: {
'@stylexjs/enforce-extension': 'error',
'@stylexjs/no-legacy-contextual-styles': 'error',
'@stylexjs/no-lookahead-selectors': 'error',
'@stylexjs/no-nonstandard-styles': 'error',
'@stylexjs/no-conflicting-props': 'error',
'@stylexjs/no-unused': 'error',
'@stylexjs/sort-keys': 'error',
'@stylexjs/valid-shorthands': 'error',
'@stylexjs/valid-styles': 'error',
// Mosaic renders elements through `render={p => <el {...p} />}`, so children and controls sit on
// the outer component. Both rules only see the empty inner element and always report.
'jsx-a11y/heading-has-content': 'off',
Expand All @@ -562,6 +575,17 @@ export default tseslint.config([
],
},
},
{
// StyleX `create()` files author conditions raw (`@media (hover: hover)`, `:hover`) — StyleX
// is compile-time and cannot inline a `hover()`/`motionSafe()` helper imported into `create`,
// so the media-query restrictions above (an Emotion-runtime convention) can't apply here. The
// `@stylexjs/*` rules from the mosaic block still cover these files.
name: 'packages/ui/mosaic - stylex styles',
files: ['packages/ui/src/mosaic/**/*.styles.ts'],
rules: {
'no-restricted-syntax': 'off',
},
},
{
name: 'packages - vitest',
files: ['packages/*/src/**/*.test.{ts,tsx}'],
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"@faker-js/faker": "^9.9.0",
"@octokit/rest": "^20.1.2",
"@playwright/test": "^1.56.1",
"@stylexjs/eslint-plugin": "0.19.0",
"@testing-library/dom": "^10.1.0",
"@testing-library/jest-dom": "^6.4.6",
"@testing-library/react": "^16.0.0",
Expand Down
17 changes: 17 additions & 0 deletions packages/swingset/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import stylexPlugin from '@stylexjs/unplugin/webpack';
import createMDX from '@next/mdx';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
Expand Down Expand Up @@ -58,6 +59,22 @@ const nextConfig = {
excludeRawQuery(config.module.rules);
config.module.rules.push({ resourceQuery: /raw/, type: 'asset/source' });

// Swingset consumes Mosaic from source, so StyleX (`defineVars`/`create`/`props`) must be
// compiled here — otherwise the calls hit the runtime and throw. The unplugin transforms the
// StyleX *JS only* (calls → static atom references), keeping SWC intact so `next/font` and the
// Emotion transform keep working. The CSS is emitted separately by `@stylexjs/postcss-plugin`
// (`@stylex` in `globals.css`), so this runs in extraction mode (no `runtimeInjection`); both
// share the same StyleX babel version/options so the atom hashes match, and the plugin's dev
// "no CSS asset" warning is expected and harmless. `useCSSLayers: true` matches the published
// build so atoms carry StyleX's `@layer priorityN` precedence.
config.plugins.push(
stylexPlugin({
dev: process.env.NODE_ENV !== 'production',
unstable_moduleResolution: { type: 'commonJS', rootDir: resolve(__dirname, '../ui') },
useCSSLayers: true,
}),
);

Comment thread
coderabbitai[bot] marked this conversation as resolved.
config.resolve.alias['@clerk/ui/mosaic'] = resolve(__dirname, '../ui/src/mosaic');
// Consume @clerk/headless primitives from source (no dist build needed), mirroring Mosaic.
// `/hooks` and `/utils` live outside `primitives/`, so alias them first (more specific wins).
Expand Down
9 changes: 8 additions & 1 deletion packages/swingset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"@clerk/headless": "workspace:*",
"@clerk/ui": "workspace:*",
"@emotion/react": "^11.11.1",
"@stylexjs/stylex": "0.19.0",
"@tailwindcss/typography": "^0.5.19",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
Expand All @@ -28,16 +29,22 @@
"tw-animate-css": "^1.4.0"
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.27.1",
"@babel/preset-typescript": "^7.28.5",
"@mdx-js/loader": "^3.1.1",
"@mdx-js/react": "^3.1.0",
"@next/mdx": "^15.0.0",
"@stylexjs/babel-plugin": "0.19.0",
"@stylexjs/postcss-plugin": "0.19.0",
"@stylexjs/unplugin": "0.19.0",
"@tailwindcss/postcss": "^4.0.0",
"@types/react": "catalog:react",
"@types/react-dom": "catalog:react",
"remark-gfm": "^4.0.0",
"shadcn": "^4.10.0",
"shiki": "^1.0.0",
"tailwindcss": "^4.0.0",
"typescript": "catalog:repo"
"typescript": "catalog:repo",
"unplugin": "^2.3.11"
}
}
33 changes: 33 additions & 0 deletions packages/swingset/postcss.config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
import { createRequire } from 'module';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';

const require = createRequire(import.meta.url);
const __dirname = dirname(fileURLToPath(import.meta.url));

// StyleX CSS extraction. The `@stylexjs/postcss-plugin` scans the Mosaic source, runs the
// StyleX babel transform itself, and replaces the `@stylex;` directive in `globals.css` with
// the generated CSS (token `:root` defaults + atoms). This is the CSS half of the setup; the
// JS half is the unplugin in `next.config.mjs`. Both must use the SAME StyleX babel version
// and options (`dev`, `rootDir`) so the atom class hashes line up.
const uiRoot = resolve(__dirname, '../ui');

export default {
plugins: {
'@stylexjs/postcss-plugin': {
useCSSLayers: true,
babelConfig: {
babelrc: false,
configFile: false,
presets: [require('@babel/preset-typescript')],
plugins: [
require('@babel/plugin-syntax-jsx'),
[
require('@stylexjs/babel-plugin'),
{
dev: process.env.NODE_ENV !== 'production',
runtimeInjection: false,
unstable_moduleResolution: { type: 'commonJS', rootDir: uiRoot },
},
],
],
},
},
'@tailwindcss/postcss': {},
},
};
4 changes: 4 additions & 0 deletions packages/swingset/src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@

@custom-variant dark (&:is(.dark *));

/* Replaced at build time by @stylexjs/postcss-plugin with the compiled Mosaic CSS
(token :root defaults + atoms). See postcss.config.mjs. */
@stylex;

body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
Expand Down
23 changes: 20 additions & 3 deletions packages/swingset/src/stories/button.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,35 @@
/** @jsxImportSource @emotion/react */
import type { ButtonProps } from '@clerk/ui/mosaic/components/button';
import { Button, buttonRecipe } from '@clerk/ui/mosaic/components/button';
import { Button } from '@clerk/ui/mosaic/components/button';

import type { StoryMeta } from '@/lib/types';

// Exposes this file's own source (via the `?raw` webpack rule) so each `<Story>` example
// renders a code footer with its function's source. See `StoryModule.__source`.
export { default as __source } from './button.stories?raw';

// StyleX has no runtime recipe to derive knobs from, so the variant surface is described
// here to drive the playground + prop table. Keys mirror `ButtonProps`.
export const meta: StoryMeta = {
group: 'Components',
title: 'Button',
source: 'packages/ui/src/mosaic/components/button.tsx',
styles: buttonRecipe,
source: 'packages/ui/src/mosaic/components/button/button.tsx',
styles: {
_variants: {
intent: { primary: {}, destructive: {} },
variant: { filled: {}, outline: {}, ghost: {} },
size: { sm: {}, md: {} },
shape: { default: {}, square: {}, circle: {} },
fullWidth: { true: {}, false: {} },
},
_defaultVariants: {
intent: 'primary',
variant: 'filled',
size: 'md',
shape: 'default',
fullWidth: false,
},
},
};

// Story functions accept Record<string,unknown> (knob values) and cast to ButtonProps.
Expand Down
Loading
Loading