Skip to content
Draft
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
9 changes: 9 additions & 0 deletions .changeset/static-styles-groundwork.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@skillsoft/gamut-styles': minor
---

Add groundwork for static component styles. No component uses it yet.

- `defineRecipe` describes a component's styles as data (base, variant groups, defaults, compound variants), in Chakra's and Panda's recipe shape with gamut's style objects. `recipe.styles` styles it through Emotion; `recipe.classNames` gives stable class names.
- `compileRecipe` turns a recipe into plain CSS in `@layer recipes`, and `checkRecipe` reports whether it compiles the same for every brand theme.
- `StaticStyles` puts compiled CSS on the page once, through the Emotion cache, so SSR, nonces and stylis plugins work as before.
1 change: 1 addition & 0 deletions packages/gamut-styles/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './GamutProvider';
export * from './ColorMode';
export * from './Background';
export * from './variance';
export * from './static';
export * from './cache';
export * from './variables';
export * from './styles';
Expand Down
80 changes: 80 additions & 0 deletions packages/gamut-styles/src/static/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Static styles (groundwork)

Groundwork for moving gamut's components off runtime Emotion styles. Nothing
uses it yet: no component has moved, and `GamutProvider` still delivers the
color tokens. Notes and the plan are in Base Camp, `gamut/color-tokens/how-it-works.md`
("Moving off Emotion, slowly").

Today every gamut component serializes its styles with Emotion on each render.
A component on a recipe ships CSS compiled ahead of time and only picks class
names at render.

## The pieces

| Export | What |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defineRecipe` | A component's styles as data: `className`, `base`, `variants` (named groups), `defaultVariants`, `compoundVariants`. Chakra's and Panda's recipe shape, written with the same style objects as `css()` and `variant()` |
| `recipe.styles` | The recipe as an Emotion style function, for `styled.div(recipe.styles)`. Writes what the matching `variant()` calls would |
| `recipe.classNames(props)` | `gamut-chip gamut-chip--intent_danger gamut-chip--size_sm`. Defaults filled in; `false` turns a group off |
| `compileRecipe(recipe)` | Plain CSS for those class names, in `@layer recipes` |
| `checkRecipe(recipe)` | Whether the recipe compiles the same for every brand theme. If not, it can't be static yet |
| `<StaticStyles id styles />` | Puts compiled CSS on the page once, through the Emotion cache (SSR, nonce and stylis plugins work as they do now) |

## Moving a component

1. Rewrite its `variant()` calls as one recipe and style it with
`recipe.styles`. Still Emotion; snapshots and visuals shouldn't change. This
step is safe to ship alone.
2. Add `expect(checkRecipe(recipe).pass).toBe(true)` to its tests. If it fails,
the recipe uses a per-brand value (see the rules) and stays on step 1.
3. Compile it once at module scope and render it:

```tsx
const styles = compileRecipe(chip);

export const Chip = ({ className, ...props }: ChipProps) => {
const [variants, rest] = chip.splitProps(props);
return (
<>
<StaticStyles id={chip.className} styles={styles} />
<Box className={cx(chip.classNames(variants), className)} {...rest} />
</>
);
};
```

Style props and `styled(Chip)` still work and still win: they're Emotion,
unlayered, and the recipe is in `@layer recipes`.

4. Later, a build step writes `compileRecipe` output to a generated module (or
a stylesheet), so it doesn't run in the browser at all. Components don't
change for that.

## Rules for a recipe that compiles

- **Colors are roles.** They compile to `var(--color-<role>)`, the same for
every brand and mode.
- **No per-brand values.** Fonts, font weights and elevation are still literal
values per theme, so `fontFamily: 'accent'` fails `checkRecipe`. Those move
to CSS variables in phase 2 of the plan.
- **No render-time values.** Nothing from props beyond the variant groups, no
`useTheme()`, no polished math. Those stay in Emotion next to the recipe.
- **Always logical properties.** Static CSS can't follow `useLogicalProperties`,
so `height` compiles to `block-size` and `px` to `padding-inline-*`. Same
rendering in left-to-right horizontal text; under `dir="rtl"` inline spacing
follows the text direction even if the app uses physical mode.
- **`className` is unique,** `gamut-<component>`. It's the class prefix and the
`StaticStyles` id.

## Not done

- No build step: `compileRecipe` runs once per module in the browser.
- No boolean variants yet, so `states()` (`disabled`, `active`, …) stays in
Emotion next to the recipe. Panda and Chakra take `true` / `false` keys;
that's the shape to add.
- Delivery is the Emotion cache. React 19's `<style href precedence>` or an
imported stylesheet would replace `StaticStyles`'s insides only.
- `checkRecipe` covers the brand themes. The old themes (core, admin, …) join
once they're rebuilt as brands.
- Types are as strict as `css()`: selections are checked, style values only as
far as `css()` checks them.
74 changes: 74 additions & 0 deletions packages/gamut-styles/src/static/StaticStyles.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import type { EmotionCache, SerializedStyles } from '@emotion/react';
import { withEmotionCache } from '@emotion/react';
import * as React from 'react';

/*
* Puts a compiled stylesheet on the page once, however many components render
* it. A component that has moved to a recipe renders
* `<StaticStyles id={recipe.className} styles={compiledCss} />` next to its
* element.
*
* For now it goes through the Emotion cache, the same way Emotion inserts a
* class:
* - one copy per page, deduplicated on `id` through `cache.inserted`;
* - SSR, CSP nonces, a custom container and gamut's stylis plugins all work
* the way they already do;
* - React 17, 18 and 19.
*
* Swapping the delivery later (React 19's `<style href precedence>`, or a
* stylesheet the app imports) only changes this file. See static/README.md.
*/

export interface StaticStylesProps {
/* Unique per stylesheet. A recipe's className. */
id: string;
/* compileRecipe output. Never user input: it's written into a <style>. */
styles: string;
}

const isBrowser = typeof document !== 'undefined';

/*
* React 17 has no useInsertionEffect. Emotion falls back to inserting during
* render there, and so does this. The name is split so bundlers don't warn
* about a missing export on React 17.
*/
const useInsertionEffect: (effect: () => void) => void =
(React as unknown as Record<string, typeof React.useLayoutEffect>)[
`useInsertion${'Effect'}`
] ?? ((effect: () => void) => effect());

const insert = (cache: EmotionCache, id: string, styles: string) => {
if (cache.inserted[id] !== undefined) return undefined;
const serialized: SerializedStyles = { name: id, styles, next: undefined };
return cache.insert('', serialized, cache.sheet, true) as string | undefined;
};

export const StaticStyles = withEmotionCache<StaticStylesProps>(
({ id, styles }, cache) => {
/*
* On the server, Emotion's default cache returns the rules instead of
* inserting them, and they're rendered inline. On the client, the cache
* moves those tags into its container before hydration and marks `id` as
* inserted, so nothing is inserted twice.
*/
const ssrRules = isBrowser ? undefined : insert(cache, id, styles);

useInsertionEffect(() => {
if (isBrowser) insert(cache, id, styles);
});

if (!ssrRules) return null;
return (
<style
/* How Emotion renders SSR styles, except `</style` is escaped. */
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: ssrRules.replace(/<\/style/gi, '<\\/style'),
}}
data-emotion={`${cache.key} ${id}`}
nonce={cache.sheet.nonce}
/>
);
}
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// @vitest-environment node
import { renderToString } from 'react-dom/server';
import { describe, expect, it } from 'vitest';

import { GamutProvider } from '../../GamutProvider';
import { skillsoftTheme } from '../../themes';
import { compileRecipe, defineRecipe, StaticStyles } from '..';

const box = defineRecipe({
className: 'gamut-ssr-box',
base: { bg: 'surface-default' },
});
const styles = compileRecipe(box);

const Box = () => (
<>
<StaticStyles id={box.className} styles={styles} />
<div className={box.classNames()} />
</>
);

describe('StaticStyles on the server', () => {
it('renders the stylesheet inline once, with the nonce', () => {
const html = renderToString(
<GamutProvider nonce="abc" theme={skillsoftTheme} useGlobals={false}>
<Box />
<Box />
</GamutProvider>
);
const tags = html.match(/<style[^>]*data-emotion="gamut gamut-ssr-box"/g);
expect(tags).toHaveLength(1);
expect(html).toContain('nonce="abc"');
expect(html).toContain('@layer recipes{.gamut-ssr-box{');
});
});
158 changes: 158 additions & 0 deletions packages/gamut-styles/src/static/__tests__/recipe.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { matchers } from '@emotion/jest';
import styled from '@emotion/styled';
import { render } from '@testing-library/react';
import { describe, expect, it } from 'vitest';

import { createEmotionCache } from '../../cache';
import { GamutProvider } from '../../GamutProvider';
import { skillsoftTheme } from '../../themes';
import { checkRecipe, compileRecipe, defineRecipe, StaticStyles } from '..';

expect.extend(matchers);

const chip = defineRecipe({
className: 'gamut-chip',
base: { display: 'inline-flex', borderRadius: 'md', bg: 'surface-default' },
variants: {
intent: {
primary: { bg: 'action-primary', color: 'text-inverse' },
danger: { bg: 'action-danger', color: 'text-inverse' },
},
size: {
sm: { height: '1.5rem', fontSize: 14 },
md: { height: '2rem', fontSize: 16 },
},
},
defaultVariants: { intent: 'primary', size: 'md' },
compoundVariants: [
{ intent: 'danger', size: 'sm', css: { textDecoration: 'underline' } },
],
});

describe('defineRecipe', () => {
it('names a class per selected variant, with defaults filled in', () => {
expect(chip.classNames()).toBe(
'gamut-chip gamut-chip--intent_primary gamut-chip--size_md'
);
expect(chip.classNames({ intent: 'danger', size: false })).toBe(
'gamut-chip gamut-chip--intent_danger'
);
});

it('type-checks selections', () => {
// @ts-expect-error not one of the intents
expect(chip.classNames({ intent: 'nope' })).toContain('gamut-chip');
});

it('splits variant props from the rest', () => {
const [variants, rest] = chip.splitProps({
intent: 'danger' as const,
id: 'x',
});
expect(variants).toEqual({ intent: 'danger' });
expect(rest).toEqual({ id: 'x' });
});

it('styles through Emotion the same way variant() does', () => {
const Chip = styled.div(chip.styles);
const { container } = render(
<GamutProvider theme={skillsoftTheme}>
<Chip intent="danger" size="sm" />
</GamutProvider>
);
const el = container.firstChild;
expect(el).toHaveStyleRule(
'background-color',
'var(--color-action-danger)'
);
expect(el).toHaveStyleRule('height', '1.5rem');
expect(el).toHaveStyleRule('text-decoration', 'underline');
});
});

describe('compileRecipe', () => {
const output = compileRecipe(chip);

it('writes every rule into @layer recipes', () => {
expect(output.startsWith('@layer recipes{')).toBe(true);
expect(output).toContain(
'.gamut-chip{display:inline-flex;border-radius:4px;background-color:var(--color-surface-default);}'
);
expect(output).not.toContain('label');
});

it('always writes logical properties', () => {
expect(output).toContain('block-size:1.5rem;');
expect(compileRecipe(chip, { useLogicalProperties: false })).toContain(
'height:1.5rem;'
);
});

it('keeps spaces inside values', () => {
const bordered = defineRecipe({
className: 'gamut-bordered',
base: { gridTemplateColumns: '1fr 2fr' },
});
expect(compileRecipe(bordered)).toContain('grid-template-columns:1fr 2fr;');
});

it('points colors at the role variables, not values', () => {
expect(output).toContain(
'.gamut-chip--intent_danger{color:var(--color-text-inverse);background-color:var(--color-action-danger);}'
);
});

it('gives compound variants both classes, so they win on specificity', () => {
expect(output).toContain(
'.gamut-chip--intent_danger.gamut-chip--size_sm{text-decoration:underline;}'
);
});
});

describe('checkRecipe', () => {
it('passes a recipe that only uses roles and shared scales', () => {
expect(checkRecipe(chip)).toEqual({ pass: true, differs: [] });
});

it('fails a value that changes with the brand', () => {
const titled = defineRecipe({
className: 'gamut-titled',
base: { fontFamily: 'accent' },
});
expect(checkRecipe(titled).pass).toBe(false);
});

it('names the brands that differ', () => {
const titled = defineRecipe({
className: 'gamut-titled',
base: { fontFamily: 'accent' },
});
expect(checkRecipe(titled).differs).toEqual(['originalCodecademy']);
});
});

describe('StaticStyles', () => {
const styles = compileRecipe(chip);
const Chip = () => (
<>
<StaticStyles id={chip.className} styles={styles} />
<span className={chip.classNames()} />
</>
);

it('inserts the stylesheet once, however many times it renders', () => {
const cache = createEmotionCache({ speedy: false });
render(
<GamutProvider cache={cache} theme={skillsoftTheme} useGlobals={false}>
<Chip />
<Chip />
<Chip />
</GamutProvider>
);
const sheets = Array.from(document.querySelectorAll('style')).filter((s) =>
s.textContent?.includes('.gamut-chip{')
);
expect(sheets).toHaveLength(1);
expect(cache.inserted[chip.className]).toBe(true);
});
});
Loading
Loading