Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
87 changes: 87 additions & 0 deletions packages/tailwindcss/src/ast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,93 @@ it('should not emit empty rules once optimized', () => {
`)
})

it('should not emit exact duplicate declarations in the same rule', () => {
let ast = CSS.parse(css`
.foo {
color: red;
.bar {
color: green;
color: blue;
color: green;
}
color: red;
}
.foo {
color: red;
& {
color: green;
& {
color: red;
color: green;
color: blue;
}
color: red;
}
background: blue;
.bar {
color: green;
color: blue;
color: green;
}
caret-color: orange;
}
`)

expect(toCss(ast)).toMatchInlineSnapshot(`
".foo {
color: red;
.bar {
color: green;
color: blue;
color: green;
}
color: red;
}
.foo {
color: red;
& {
color: green;
& {
color: red;
color: green;
color: blue;
}
color: red;
}
background: blue;
.bar {
color: green;
color: blue;
color: green;
}
caret-color: orange;
}
"
`)

expect(toCss(optimizeAst(ast, defaultDesignSystem))).toMatchInlineSnapshot(`
".foo {
.bar {
color: blue;
color: green;
}
color: red;
}
.foo {
color: green;
color: blue;
color: red;
background: blue;
.bar {
color: blue;
color: green;
}
caret-color: orange;
}
"
`)
})

it('should only visit children once when calling `replaceWith` with single element array', () => {
let visited = new Set()

Expand Down
25 changes: 25 additions & 0 deletions packages/tailwindcss/src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,31 @@ export function optimizeAst(
transform(child, nodes, context, depth + 1)
}

// Keep the last decl when there are exact duplicates. Keeping the *first* one might
// not be correct when given nested rules where a rule sits between declarations.
let seen: Record<string, AstNode[]> = {}
let toRemove = new Set<AstNode>()

// Keep track of all nodes that produce a given declaration
for (let child of nodes) {
if (child.kind !== 'declaration') continue

let key = `${child.property}:${child.value}:${child.important}`
seen[key] ??= []
seen[key].push(child)
Comment on lines +370 to +371
Copy link
Member

Choose a reason for hiding this comment

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

jk 😂

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I mean basically lol

}

// And remove all but the last of each
for (let key in seen) {
for (let i = 0; i < seen[key].length - 1; ++i) {
toRemove.add(seen[key][i])
}
}

if (toRemove.size > 0) {
nodes = nodes.filter((node) => !toRemove.has(node))
}

if (nodes.length === 0) return

// Rules with `&` as the selector should be flattened
Expand Down