Minify arbitrary values when printing candidates (#14720)

This PR will optimize and simplify the candidates when printing the
candidate again after running codemods.

When we parse a candidate, we will add spaces around operators, for
example `p-[calc(1px+1px)]]` will internally be handled as `calc(1px +
1px)`. Before this change, we would re-print this as:
`p-[calc(1px_+_1px)]`.

This PR changes that by simplifying the candidate again so that the
output is `p-[calc(1px+1px)]`. In addition, if _you_ wrote
`p-[calc(1px_+_1px)]` then we will also simplify it to the concise form
`p-[calc(1px_+_1px)]`.


Some examples:

Input:
```html
<div class="[p]:flex"></div>
<div class="[&:is(p)]:flex"></div>
<div class="has-[p]:flex"></div>
<div class="px-[theme(spacing.4)-1px]"></div>
```

Output before:
```html
<div class="[&:is(p)]:flex"></div>
<div class="[&:is(p)]:flex"></div>
<div class="has-[&:is(p)]:flex"></div>
<div class="px-[var(--spacing-4)_-_1px]"></div>
```

Output after:
```html
<div class="[p]:flex"></div>
<div class="[p]:flex"></div>
<div class="has-[p]:flex"></div>
<div class="px-[var(--spacing-4)-1px]"></div>
```

---

This is alternative implementation to #14717 and #14718
Closes: #14717 
Closes: #14718
This commit is contained in:
Robin Malfait 2024-10-18 22:44:25 +02:00 • committed by GitHub
parent c4b97f6067
commit 2abf228124
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 137 additions and 34 deletions

View file

@ -15,6 +15,7 @@ export type ValueSeparatorNode = {
}
export type ValueAstNode = ValueWordNode | ValueFunctionNode | ValueSeparatorNode
type ValueParentNode = ValueFunctionNode | null
function word(value: string): ValueWordNode {
return {
@ -54,11 +55,11 @@ export function walk(
visit: (
node: ValueAstNode,
utils: {
parent: ValueAstNode | null
parent: ValueParentNode
replaceWith(newNode: ValueAstNode | ValueAstNode[]): void
},
) => void | ValueWalkAction,
parent: ValueAstNode | null = null,
parent: ValueParentNode = null,
) {
for (let i = 0; i < ast.length; i++) {
let node = ast[i]
@ -149,7 +150,7 @@ export function parse(input: string) {
case GREATER_THAN:
case EQUALS: {
// 1. Handle everything before the separator as a word
// Handle everything before the closing paren a word
// Handle everything before the closing paren as a word
if (buffer.length > 0) {
let node = word(buffer)
if (parent) {
@ -169,6 +170,7 @@ export function parse(input: string) {
peekChar !== COLON &&
peekChar !== COMMA &&
peekChar !== SPACE &&
peekChar !== SLASH &&
peekChar !== LESS_THAN &&
peekChar !== GREATER_THAN &&
peekChar !== EQUALS