import { AtRule, type ChildNode, type Plugin, type Root } from 'postcss'
import { segment } from '../../../../tailwindcss/src/utils/segment'
export function migrateMissingLayers(): Plugin {
function migrate(root: Root) {
let lastLayer = ''
let bucket: ChildNode[] = []
let buckets: [layer: string, bucket: typeof bucket][] = []
let firstLayerName: string | null = null
root.each((node) => {
if (node.type === 'atrule') {
if (
node.name === 'config' ||
node.name === 'source' ||
node.name === 'theme' ||
node.name === 'utility' ||
node.name === 'custom-variant' ||
node.name === 'variant'
) {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
return
}
if (
(node.name === 'tailwind' && node.params === 'base') ||
(node.name === 'import' && node.params.match(/^["']tailwindcss\/base["']/))
) {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
firstLayerName ??= 'base'
lastLayer = 'base'
return
}
if (
(node.name === 'tailwind' && node.params === 'components') ||
(node.name === 'import' && node.params.match(/^["']tailwindcss\/components["']/))
) {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
firstLayerName ??= 'components'
lastLayer = 'components'
return
}
if (
(node.name === 'tailwind' && node.params === 'utilities') ||
(node.name === 'import' && node.params.match(/^["']tailwindcss\/utilities["']/))
) {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
firstLayerName ??= 'utilities'
lastLayer = 'utilities'
return
}
if (node.name === 'layer') {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
return
}
if (node.name === 'import') {
if (bucket.length > 0) {
buckets.push([lastLayer, bucket.splice(0)])
}
buckets.push([lastLayer, [node]])
return
}
}
if (
lastLayer === '' &&
(node.type === 'comment' ||
(node.type === 'atrule' && !node.nodes) ||
(node.type === 'atrule' && node.name === 'charset'))
) {
return
}
bucket.push(node)
})
for (let [layerName, nodes] of buckets) {
let targetLayerName = layerName || firstLayerName || ''
if (targetLayerName === '') {
continue
}
if (nodes.every((node) => node.type === 'comment')) {
continue
}
if (nodes.every((node) => node.type === 'atrule' && node.name === 'import')) {
for (let node of nodes) {
if (node.type !== 'atrule' || node.name !== 'import') continue
if (!node.params.includes('layer(')) {
let params = segment(node.params, ' ')
params.splice(1, 0, `layer(${targetLayerName})`)
node.params = params.join(' ')
node.raws.tailwind_injected_layer = true
}
}
continue
}
let target = nodes[0]
let layerNode = new AtRule({
name: 'layer',
params: targetLayerName,
nodes: nodes.map((node) => {
if (node === target) {
return node
}
return node.remove()
}),
raws: {
tailwind_pretty: true,
},
})
target.replaceWith(layerNode)
}
}
return {
postcssPlugin: '@tailwindcss/upgrade/migrate-missing-layers',
OnceExit: migrate,
}
}