2023-12-18 13:12:25 +08:00
|
|
|
module.exports = function postcssPrefixSelector(options) {
|
|
|
|
const prefix = options.prefix;
|
|
|
|
const prefixWithSpace = /\s+$/.test(prefix) ? prefix : `${prefix} `;
|
2024-01-16 21:26:16 +08:00
|
|
|
const ignoreFiles = options.ignoreFiles ? [].concat(options.ignoreFiles) : [];
|
|
|
|
const includeFiles = options.includeFiles
|
|
|
|
? [].concat(options.includeFiles)
|
|
|
|
: [];
|
2023-12-18 13:12:25 +08:00
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
return function (root) {
|
|
|
|
if (
|
|
|
|
ignoreFiles.length &&
|
|
|
|
root.source.input.file &&
|
|
|
|
isFileInArray(root.source.input.file, ignoreFiles)
|
|
|
|
) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (
|
|
|
|
includeFiles.length &&
|
|
|
|
root.source.input.file &&
|
|
|
|
!isFileInArray(root.source.input.file, includeFiles)
|
|
|
|
) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
root.walkRules((rule) => {
|
2023-12-18 13:12:25 +08:00
|
|
|
const keyframeRules = [
|
|
|
|
'keyframes',
|
|
|
|
'-webkit-keyframes',
|
|
|
|
'-moz-keyframes',
|
2024-01-16 21:26:16 +08:00
|
|
|
'-o-keyframes',
|
2023-12-18 13:12:25 +08:00
|
|
|
];
|
|
|
|
|
|
|
|
if (rule.parent && keyframeRules.includes(rule.parent.name)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
rule.selectors = rule.selectors.map((selector) => {
|
2023-12-18 13:12:25 +08:00
|
|
|
if (options.exclude && excludeSelector(selector, options.exclude)) {
|
|
|
|
return selector;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (options.transform) {
|
|
|
|
return options.transform(
|
|
|
|
prefix,
|
|
|
|
selector,
|
2024-01-16 21:26:16 +08:00
|
|
|
prefixWithSpace + selector,
|
|
|
|
root.source.input.file,
|
|
|
|
rule
|
2023-12-18 13:12:25 +08:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return prefixWithSpace + selector;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
function isFileInArray(file, arr) {
|
|
|
|
return arr.some((ruleOrString) => {
|
|
|
|
if (ruleOrString instanceof RegExp) {
|
|
|
|
return ruleOrString.test(file);
|
|
|
|
}
|
|
|
|
|
|
|
|
return file.includes(ruleOrString);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-12-18 13:12:25 +08:00
|
|
|
function excludeSelector(selector, excludeArr) {
|
2024-01-16 21:26:16 +08:00
|
|
|
return excludeArr.some((excludeRule) => {
|
2023-12-18 13:12:25 +08:00
|
|
|
if (excludeRule instanceof RegExp) {
|
|
|
|
return excludeRule.test(selector);
|
|
|
|
}
|
|
|
|
|
|
|
|
return selector === excludeRule;
|
|
|
|
});
|
|
|
|
}
|