-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostcss-replace-attribute-selectors.cjs
More file actions
37 lines (32 loc) · 1.53 KB
/
postcss-replace-attribute-selectors.cjs
File metadata and controls
37 lines (32 loc) · 1.53 KB
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
module.exports = () => {
return {
postcssPlugin: 'postcss-replace-attribute-selectors',
Rule(rule) {
const parser = require('postcss-selector-parser');
const transformedSelectors = [];
const transformSelectors = parser((selectors) => {
selectors.walkAttributes((attr) => {
// Generate a unique class name based on the attribute selector
const attribute = attr.attribute;
const operator = attr.operator || '';
const value = attr.value || '';
const className = `attr-${attribute}${operator}${value}`.replace(/[^a-zA-Z0-9-_]/g, '');
// Replace the attribute selector with a class selector
const classSelector = parser.className({ value: className });
attr.replaceWith(classSelector);
// Store the mapping for updating HTML elements later
transformedSelectors.push({
original: `[${attribute}${operator ? operator : ''}${value ? `"${value}"` : ''}]`,
className,
});
});
});
rule.selector = transformSelectors.processSync(rule.selector);
// Attach the transformed selectors to the rule for later use
rule.walkDecls((decl) => {
decl.root().transformedSelectors = transformedSelectors;
});
},
};
};
module.exports.postcss = true;