Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs][pigment] Add example and guide section #41249

Merged
merged 10 commits into from Mar 8, 2024
167 changes: 163 additions & 4 deletions packages/pigment-react/README.md
@@ -1,6 +1,6 @@
# Pigment CSS

A zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build-time.
A Pigment CSS CSS-in-JS library that extracts the colocated styles to their own CSS files at build-time.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
A Pigment CSS CSS-in-JS library that extracts the colocated styles to their own CSS files at build-time.
Pigment CSS is a zero-runtime CSS-in-JS library that extracts the colocated styles to their own CSS files at build time.


- [Getting started](#getting-started)
- [Next.js](#nextjs)
Expand All @@ -18,13 +18,26 @@ A zero-runtime CSS-in-JS library that extracts the colocated styles to their own
- [Color schemes](#color-schemes)
- [Switching color schemes](#switching-color-schemes)
- [TypeScript](#typescript)
- [How-to guides](#how-to-guides)
- [Coming from Emotion or styled-components](#coming-from-emotion-or-styled-components)

## Getting started

Pigment CSS supports Next.js and Vite with support for more bundlers in future. You must install the corresponding plugin, as shown below.

### Next.js

#### Starter template

Use the following commands to create a new Next.js project with Zero Runtime setup:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Use the following commands to create a new Next.js project with Zero Runtime setup:
Use the following commands to create a new Next.js project with Pigment CSS set up:


```bash
curl https://codeload.github.com/mui/material-ui/tar.gz/master | tar -xz --strip=2 material-ui-master/examples/pigmentcss-nextjs
cd pigmentcss-nextjs
```

#### Manual installation

```bash
npm install @pigmentcss/react
npm install --save-dev @pigmentcss/nextjs-plugin
Expand All @@ -42,6 +55,17 @@ module.exports = withPigment({

### Vite

#### Starter template

Use the following commands to create a new Vite project with Zero Runtime setup:
siriwatknp marked this conversation as resolved.
Show resolved Hide resolved

```bash
curl https://codeload.github.com/mui/material-ui/tar.gz/master | tar -xz --strip=2 material-ui-master/examples/pigmentcss-vite
cd pigmentcss-vite
```

#### Manual installation

```bash
npm install @pigmentcss/react
npm install --save-dev @pigmentcss/vite-plugin
Expand Down Expand Up @@ -132,7 +156,7 @@ Use the `variants` key to define styles for a combination of the component's pro

Each variant is an object with `props` and `style` keys. The styles are applied when the component's props match the `props` object.

**Example 1**: A button component with `small` and `large` sizes:
**Example 1** A button component with `small` and `large` sizes:

```jsx
const Button = styled('button')({
Expand All @@ -156,7 +180,7 @@ const Button = styled('button')({
<Button size="small">Small button</Button>; // padding: 0.5rem
```

**Example 2**: A button component with variants and colors:
**Example 2** A button component with variants and colors:

```jsx
const Button = styled('button')({
Expand All @@ -177,7 +201,7 @@ const Button = styled('button')({
</Button>;
```

**Example 3**: Apply styles based on a condition:
**Example 3** Apply styles based on a condition:

The value of the `props` can be a function that returns a boolean. If the function returns `true`, the styles are applied.

Expand All @@ -195,6 +219,37 @@ const Button = styled('button')({
});
```

Note that the `props` function will not work if it is inside another closure, for example, inside an `array.map`:

```jsx
const Button = styled('button')({
border: 'none',
padding: '0.75rem',
// ...other base styles
variants: ['red', 'blue', 'green'].map((item) => ({
props: (props) => {
// ❌ Cannot access `item` in this closure
return props.color === item && !props.disabled;
},
style: { backgroundColor: 'tomato' },
})),
});
```

Instead, use plain objects to define the variants:

```jsx
const Button = styled('button')({
border: 'none',
padding: '0.75rem',
// ...other base styles
variants: ['red', 'blue', 'green'].map((item) => ({
props: { color: item, disabled: false },
style: { backgroundColor: 'tomato' },
})),
});
```

#### Styling based on runtime values

> 💡 This approach is recommended when the value of a prop is **unknown** ahead of time or possibly unlimited values, e.g. styling based on the user's input.
Expand Down Expand Up @@ -451,3 +506,107 @@ declare module '@pigmentcss/react/theme' {
}
}
```

## How-to guides

### Coming from Emotion or styled-components

Emotion and styled-components are runtime CSS-in-JS libraries. What you write in your styles is what you get in the final bundle which means that the styles can be as dynamic as you want with the trade-offs of bundle size and performance overhead.
siriwatknp marked this conversation as resolved.
Show resolved Hide resolved

On the other hand, Pigment CSS extracts CSS at build time and replaces the JS code with hashed class names and some CSS variables. This means that it has to know all of the styles to be extracted ahead of time, so there are rules and limitations that you need to be aware of when using JavaScript callbacks or variables in Pigment CSS APIs.
siriwatknp marked this conversation as resolved.
Show resolved Hide resolved

Here are some common patterns and how to achieve them with Pigment CSS:

1. **Fixed set of styles**

In Emotion or styled-components, you can use props to create styles conditionally:

```js
const Flex = styled('div')((props) => ({
display: 'flex',
...(props.vertical // ❌ Zero Runtime will throw an error
? {
flexDirection: 'column',
paddingBlock: '1rem',
}
: {
paddingInline: '1rem',
}),
}));
```

But in Pigment CSS, you need to define all of the styles ahead of time using the `variants` key:

```js
const Flex = styled('div')((props) => ({
display: 'flex',
variants: [
{
props: { vertical: true },
style: {
flexDirection: 'column',
paddingBlock: '1rem',
},
},
{
props: { vertical: false },
style: {
paddingInline: '1rem',
},
},
],
}));
```

> 💡 Keep in mind that the `variants` key is for fixed values of props, for example, a component's colors, sizes, and states.

2. **Programatically generated styles**

For Emotion and styled-components, the styles will be different on each render and instance because the styles are generated at runtime:

```js
function randomBetween(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function generateBubbleVars() {
return `
--x: ${randomBetween(10, 90)}%;
--y: ${randomBetween(15, 85)}%;
`;
}

function App() {
return (
<div>
{[...Array(10)].map((_, index) => (
<div key={index} className={css`${generateBubbleVars()}`} />
))}
</div>
)
}
```

However, in Pigment CSS, all instances will have the same styles and won't change between renders because the styles are extracted at build time.

To achieve the same result, you need to move the dynamic logic to props and pass the value to CSS variables instead:

```js
function randomBetween(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}

const Bubble = styled('div')({
'--x': props => props.x,
'--y': props => props.y,
});

function App() {
return (
<div>
{[...Array(10)].map((_, index) => (
<Bubble key={index} x={`${randomBetween(10, 90)}%`} y={`${randomBetween(15, 85)}%`} />
))}
</div>
)
}
```