Skip to content

Commit

Permalink
register arbitrary variants
Browse files Browse the repository at this point in the history
With the new `addVariant` API, we have a beautiful way of creating new
variants.

You can use it as:
```js
addVariant('children', '& > *')
```

Now you can use the `children:` variant. The API uses a `&` as a
reference for the candidate, which means that:
```html
children:pl-4
```

Will result in:
```css
.children\:pl-4 > * { .. }
```

Notice that the `&` was replaced by `.children\:pl-4`.

We can leverage this API to implement arbitrary variants, this means
that you can write those `&>*` (Notice that we don't have spaces) inside
a variant directly. An example of this can be:
```html
<ul class="[&>*]:underline">
  <li>A</li>
  <li>B</li>
  <li>C</li>
</ul>
```
Which generates the following css:
```css
.\[\&\>\*\]\:underline > * {
  text-decoration-line: underline;
}
```

Now all the children of the `ul` will have an `underline`. The selector
itself is a bit crazy since it contains the candidate which is the
selector itself, it is just escaped.
  • Loading branch information
RobinMalfait committed May 7, 2022
1 parent cea3ccf commit dc2f8a5
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/lib/generateRules.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ function applyVariant(variant, matches, context) {
return matches
}

// Register arbitrary variants
if (isArbitraryValue(variant) && !context.variantMap.has(variant)) {
let selector = variant.slice(1, -1)
let sort = Array.from(context.variantOrder.values()).pop() << 1n
context.variantMap.set(variant, [[sort, () => normalize(selector)]])
context.variantOrder.set(variant, sort)
}

if (context.variantMap.has(variant)) {
let variantFunctionTuples = context.variantMap.get(variant)
let result = []
Expand Down

0 comments on commit dc2f8a5

Please sign in to comment.