(
classStr: string,
{
env,
ignoreFirst = false,
ignoreLast = false,
removeDuplicates = true,
collapseWhitespace = { start: true, end: true },
}: SortOptions & {
env: TransformerEnv
},
)
| 9 | } |
| 10 | |
| 11 | export function sortClasses( |
| 12 | classStr: string, |
| 13 | { |
| 14 | env, |
| 15 | ignoreFirst = false, |
| 16 | ignoreLast = false, |
| 17 | removeDuplicates = true, |
| 18 | collapseWhitespace = { start: true, end: true }, |
| 19 | }: SortOptions & { |
| 20 | env: TransformerEnv |
| 21 | }, |
| 22 | ): string { |
| 23 | if (typeof classStr !== 'string' || classStr === '') { |
| 24 | return classStr |
| 25 | } |
| 26 | |
| 27 | // Ignore class attributes containing `{{`, to match Prettier behaviour: |
| 28 | // https://github.com/prettier/prettier/blob/8a88cdce6d4605f206305ebb9204a0cabf96a070/src/language-html/embed/class-names.js#L9 |
| 29 | if (classStr.includes('{{')) { |
| 30 | return classStr |
| 31 | } |
| 32 | |
| 33 | if (env.options.tailwindPreserveWhitespace) { |
| 34 | collapseWhitespace = false |
| 35 | } |
| 36 | |
| 37 | if (env.options.tailwindPreserveDuplicates) { |
| 38 | removeDuplicates = false |
| 39 | } |
| 40 | |
| 41 | // This class list is purely whitespace |
| 42 | // Collapse it to a single space if the option is enabled |
| 43 | if (collapseWhitespace && /^[\t\r\f\n ]+$/.test(classStr)) { |
| 44 | return ' ' |
| 45 | } |
| 46 | |
| 47 | let result = '' |
| 48 | let parts = classStr.split(/([\t\r\f\n ]+)/) |
| 49 | let classes = parts.filter((_, i) => i % 2 === 0) |
| 50 | let whitespace = parts.filter((_, i) => i % 2 !== 0) |
| 51 | |
| 52 | if (classes[classes.length - 1] === '') { |
| 53 | classes.pop() |
| 54 | } |
| 55 | |
| 56 | if (collapseWhitespace) { |
| 57 | whitespace = whitespace.map(() => ' ') |
| 58 | } |
| 59 | |
| 60 | let prefix = '' |
| 61 | if (ignoreFirst) { |
| 62 | prefix = `${classes.shift() ?? ''}${whitespace.shift() ?? ''}` |
| 63 | } |
| 64 | |
| 65 | let suffix = '' |
| 66 | if (ignoreLast) { |
| 67 | suffix = `${whitespace.pop() ?? ''}${classes.pop() ?? ''}` |
| 68 | } |
no test coverage detected
searching dependent graphs…