-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
Copy pathutils.mjs
53 lines (47 loc) · 1.94 KB
/
utils.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Adjusts the class names in the rule by cleaning and adding proper indentation.
*
* @param {Object} rule - The rule object containing the class names to be processed.
* @param {string} rule.params - The class names as a string to be formatted.
* @param {Object} rule.raws - The raw data of the rule.
* @param {string} rule.raws.before - The raw string before to the @apply rule.
* @returns {Object|null} The modified rule with properly formatted class names, or null if the rule is invalid.
*/
export const indentClassNames = rule => {
// Ensure that the rule contains necessary properties
if (!rule || !rule.params || !rule.raws || !rule.raws.before) {
return null;
}
const indent = ' '.repeat(rule.raws.before.length + 1);
// Clean and split the class names
const cleanedClasses = cleanClassNames(rule.params);
// Apply the indentation and join the class names back together
rule.params = applyIndentation(cleanedClasses, indent);
return rule;
};
/**
* Cleans the input string by removing unnecessary whitespace and newlines.
*
* @param {string} params - The class names string to be cleaned.
* @returns {string} The cleaned class names string.
*/
export const cleanClassNames = params => {
return params
.replace(/[\n\r]+/g, '') // Remove new lines
.replace(/\s+/g, ' ') // Replace multiple spaces with a single space
.trim(); // Trim leading/trailing spaces
};
/**
* Applies the correct indentation to each class name in the string.
*
* @param {string} classes - The cleaned class names as a string.
* @param {string} indent - The string used for indentation.
* @returns {string} The class names string with applied indentation.
*/
export const applyIndentation = (classes, indent) => {
return classes
.split(' ') // Split into an array of class names
.map(className => indent + className) // Add indentation to each class
.join('\n') // Join with new lines
.trim(); // Remove extra space at the end
};