| 4 | import { walk, WalkAction } from '../../utils/walk' |
| 5 | |
| 6 | export async function split(stylesheets: Stylesheet[]) { |
| 7 | let stylesheetsById = new Map<StylesheetId, Stylesheet>() |
| 8 | let stylesheetsByFile = new Map<string, Stylesheet>() |
| 9 | |
| 10 | for (let sheet of stylesheets) { |
| 11 | stylesheetsById.set(sheet.id, sheet) |
| 12 | |
| 13 | if (sheet.file) { |
| 14 | stylesheetsByFile.set(sheet.file, sheet) |
| 15 | } |
| 16 | } |
| 17 | |
| 18 | // Keep track of sheets that contain `@utility` rules |
| 19 | let requiresSplit = new Set<Stylesheet>() |
| 20 | |
| 21 | for (let sheet of stylesheets) { |
| 22 | // Root files don't need to be split |
| 23 | if (sheet.isTailwindRoot) continue |
| 24 | |
| 25 | let containsUtility = false |
| 26 | let containsUnsafe = sheet.layers().size > 0 |
| 27 | |
| 28 | walk(sheet.root, (node) => { |
| 29 | if (node.type === 'atrule' && node.name === 'utility') { |
| 30 | containsUtility = true |
| 31 | } |
| 32 | |
| 33 | // Safe to keep without splitting |
| 34 | else if ( |
| 35 | // An `@import "…" layer(…)` is safe |
| 36 | (node.type === 'atrule' && node.name === 'import' && node.params.includes('layer(')) || |
| 37 | // @layer blocks are safe |
| 38 | (node.type === 'atrule' && node.name === 'layer') || |
| 39 | // Comments are safe |
| 40 | node.type === 'comment' |
| 41 | ) { |
| 42 | return WalkAction.Skip |
| 43 | } |
| 44 | |
| 45 | // Everything else is not safe, and requires a split |
| 46 | else { |
| 47 | containsUnsafe = true |
| 48 | } |
| 49 | |
| 50 | // We already know we need to split this sheet |
| 51 | if (containsUtility && containsUnsafe) { |
| 52 | return WalkAction.Stop |
| 53 | } |
| 54 | |
| 55 | return WalkAction.Skip |
| 56 | }) |
| 57 | |
| 58 | if (containsUtility && containsUnsafe) { |
| 59 | requiresSplit.add(sheet) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | // Split every imported stylesheet into two parts |