-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselector-class-interpolation.js
246 lines (200 loc) · 6.29 KB
/
selector-class-interpolation.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
const stylelint = require("stylelint");
const ruleName = "crisp/selector-class-interpolation";
const messages = stylelint.utils.ruleMessages(ruleName, {
expected: "Expected Sass interpolation in class selector"
});
const ruleFunction = (primaryOption, secondaryOptions = {}, context) => {
return (root, result) => {
// Validate options for the rule
const validOptions = stylelint.utils.validateOptions(result, ruleName, {
actual: primaryOption,
possible: [true]
}, {
actual: secondaryOptions,
possible: {
ignoreSelectors: [isStringOrRegExp]
},
optional: true
});
if (!validOptions) {
return;
}
// Skip non-Vue files
if (!root.source.input.file.endsWith(".vue")) {
return;
}
let fileScopeClass;
// First pass (identify the parent selector - via variable)
root.walkDecls(decl => {
if (decl.prop === "$c") {
// Remove leading `.` and `"`
fileScopeClass = decl.value.replace(/^["']?\./, "").replace(/["']?$/, "");
return;
}
});
if (!fileScopeClass) {
// Second pass (identify the parent selector - via first class)
root.walkRules(rule => {
if (rule.parent && rule.parent.type === "root") {
const fileScopeClassMatch = rule.selector.match(/^\.[\w-]+/);
if (fileScopeClassMatch) {
// Capture the class name without the dot
fileScopeClass = fileScopeClassMatch[0].substring(1);
return;
}
}
});
}
// Third pass (check all class selectors)
root.walkRules(rule => {
// Skip rules without selectors (e.g. @font-face, @keyframes, variables)
if (!rule.selector) {
return;
}
// Skip selector if ignored via rule options
if (isSelectorIgnoredOptions(rule, secondaryOptions.ignoreSelectors || [])) {
return;
}
// Skip selectors other than `.*`, `&__*` , `&-*` or `&.*`
if (!rule.selector.startsWith(".") &&
!rule.selector.startsWith("&__") &&
!(rule.selector.startsWith("&-") && !rule.selector.startsWith("&--")) &&
!rule.selector.startsWith("&.")
) {
return;
}
let isInterpolated = isInterpolatedClassSelector(rule);
if (!isInterpolated) {
if (isSelectorIgnored(rule, fileScopeClass)) {
return;
}
if (context.fix) {
fixSelector(rule);
} else {
reportSelector(rule, result);
}
}
});
};
};
// Helper function to resolve the actual selector name
function resolveSelector(rule, parentSelector = "") {
// Skip rules without selectors (e.g. @font-face, @keyframes)
if (!rule.selector) {
return "";
}
if (rule.selector.startsWith("&")) {
const combinedSelector = (parentSelector + " " + rule.selector.replace("&", "")).trim();
// Recurse?
if (rule.parent && rule.parent.type !== "root") {
return resolveSelector(rule.parent, combinedSelector);
}
return combinedSelector;
}
return parentSelector ? (parentSelector + " " + rule.selector).trim() : rule.selector;
}
// Helper function to check if a value is a RegExp or a string
function isStringOrRegExp(value) {
return value instanceof RegExp || typeof value === "string";
}
// Check if selector is ignored via options
function isSelectorIgnoredOptions(rule, ignoreSelectors = []) {
// Resolve the actual selector name
const resolvedSelector = resolveSelector(rule);
const isIgnored = ignoreSelectors.some(ignoreItem => {
if (typeof ignoreItem === "string") {
// Check if it's a stringified regex (e.g. "/pattern/")
if (ignoreItem.startsWith("/") && ignoreItem.endsWith("/")) {
const regexPattern = ignoreItem.slice(1, -1);
const regex = new RegExp(regexPattern);
return regex.test(resolvedSelector);
}
// It's a regular string
return ignoreItem === resolvedSelector;
}
// It's a real RegExp
return ignoreItem.test(resolvedSelector);
});
return isIgnored;
}
// Check if selector is ignored (this skip classes elements outside of current \
// file scope, for example of CSS overrides)
function isSelectorIgnored(rule, fileScopeClass) {
if (fileScopeClass) {
if (rule.selector.startsWith(".")) {
// Extract base part from BEM selector
const regex = /(\.[\w-]+?)(?=--|__|\s|:|$)/;
const match = rule.selector.match(regex);
if (match) {
const base = match[1];
if (base !== `.${fileScopeClass}`) {
return true;
}
}
}
if (rule.selector.startsWith("&.")) {
if (!rule.selector.startsWith(`&.${fileScopeClass}`)) {
return true;
}
}
}
return false;
}
// Check if the rule is a top-level class selector
function isTopLevelClassSelector(rule) {
return rule.parent && rule.parent.type === "root" && rule.selector.startsWith(".");
}
// Check if selector uses Sass interpolation
function isInterpolatedClassSelector(rule) {
return /#\{[^}]+\}/.test(rule.selector);
}
// Apply fixes for nested selector
function fixNestedSelector(rule, selector) {
let newSelector = selector;
if (selector.startsWith("&__")) {
// Transform `&__foo` to `#{$c}__foo`
selector.replace(/&__([^ ,{]+)/g, "#{$c}__$1");
}
if (selector.startsWith("&-")) {
const parentMatch = (rule.parent && rule.parent.selector)
? rule.parent.selector.match(/__([^ ,{]+)/)
: null;
if (parentMatch) {
// Transform
// ```
// &__foo {
// &-bar {
// ```
// to
// ```
// #{$c}__foo {
// #{$c}__foo-bar {
// ```
newSelector = newSelector.replace(/&-([^ ,{]+)/g, `#{$c}__${parentMatch[1]}-$1`);
}
}
return newSelector;
}
// Fix selector
function fixSelector(rule) {
let newSelector = rule.selector;
if (isTopLevelClassSelector(rule)) {
newSelector = `#{$c}`;
rule.root().prepend(`$c: "${rule.selector}";\n`);
} else {
// Auto-fix nested selector
newSelector = fixNestedSelector(rule, newSelector);
}
rule.selector = newSelector;
}
// Report selectors
function reportSelector(rule, result) {
stylelint.utils.report({
ruleName,
result,
node: rule,
message: messages.expected,
word: rule.selector
});
}
module.exports = stylelint.createPlugin(ruleName, ruleFunction);