-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathprefer-class-directive.ts
367 lines (347 loc) · 9.13 KB
/
prefer-class-directive.ts
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import type { AST } from 'svelte-eslint-parser';
import type { TSESTree } from '@typescript-eslint/types';
import { createRule } from '../utils';
import { getStringIfConstant, isHTMLElementLike, needParentheses } from '../utils/ast-utils';
import type { Rule } from 'eslint';
import { getSourceCode } from '../utils/compat';
export default createRule('prefer-class-directive', {
meta: {
docs: {
description: 'require class directives instead of ternary expressions',
category: 'Stylistic Issues',
recommended: false,
conflictWithPrettier: false
},
fixable: 'code',
schema: [
{
type: 'object',
properties: {
prefer: { enum: ['always', 'empty'] }
},
additionalProperties: false
}
],
messages: {
unexpected: 'Unexpected class using the ternary operator.'
},
type: 'suggestion'
},
create(context) {
const sourceCode = getSourceCode(context);
const preferEmpty = context.options[0]?.prefer !== 'always';
type Expr = {
not?: true;
node: TSESTree.Expression;
chains?: Expr;
};
/**
* Returns a map of expressions and strings from ConditionalExpression.
* Returns null if it has an unknown string.
*/
function parseConditionalExpression(
node: TSESTree.ConditionalExpression
): Map<Expr, string> | null {
const result = new Map<Expr, string>();
if (
!processItems(
{
node: node.test
},
node.consequent
)
) {
return null;
}
if (
!processItems(
{
not: true,
node: node.test
},
node.alternate
)
) {
return null;
}
return result;
/** Process items */
function processItems(key: Expr, e: TSESTree.Expression) {
if (e.type === 'ConditionalExpression') {
const sub = parseConditionalExpression(e);
if (sub == null) {
return false;
}
for (const [expr, str] of sub) {
result.set(
{
...key,
chains: expr
},
str
);
}
} else {
const str = getStringIfConstant(e);
if (str == null) {
return false;
}
result.set(key, str);
}
return true;
}
}
/**
* Expr to string
*/
function exprToString({ node, not }: Expr): string {
let text = sourceCode.text.slice(...node.range);
// *Currently not supported.
// if (chains) {
// if (needParentheses(node, "logical")) {
// text = `(${text})`
// }
// let chainsText = exprToString(chains)
// const needParenForChains =
// !/^[!(]/u.test(chainsText) && needParentheses(chains.node, "logical")
// if (needParenForChains) {
// chainsText = `(${chainsText})`
// }
// text = `${text} && ${chainsText}`
// if (not) {
// text = `!(${text})`
// }
// return text
// }
if (not) {
if (node.type === 'BinaryExpression') {
if (
node.operator === '===' ||
node.operator === '==' ||
node.operator === '!==' ||
node.operator === '!='
) {
const left = sourceCode.text.slice(...node.left.range);
const op = sourceCode.text.slice(node.left.range[1], node.right.range[0]);
const right = sourceCode.text.slice(...node.right.range);
return `${left}${
node.operator === '===' || node.operator === '=='
? op.replace(/[=](={1,2})/g, '!$1')
: op.replace(/!(={1,2})/g, '=$1')
}${right}`;
}
} else if (node.type === 'UnaryExpression') {
if (node.operator === '!' && node.prefix) {
return sourceCode.text.slice(...node.argument.range);
}
}
if (needParentheses(node, 'not')) {
text = `(${text})`;
}
text = `!${text}`;
}
return text;
}
/**
* Returns all possible strings.
*/
function getStrings(node: AST.SvelteAttribute['value'][number]) {
if (node.type === 'SvelteLiteral') {
return [node.value];
}
if (node.expression.type === 'ConditionalExpression') {
const values = parseConditionalExpression(node.expression);
if (values == null) {
// unknown
return null;
}
return [...values.values()];
}
const str = getStringIfConstant(node.expression);
if (str == null) {
// unknown
return null;
}
return [str];
}
/**
* Checks if the last character is a non word.
*/
function endsWithNonWord(node: AST.SvelteAttribute, index: number): boolean {
for (let i = index; i >= 0; i--) {
const valueNode = node.value[i];
const strings = getStrings(valueNode);
if (strings == null) {
// unknown
return false;
}
for (const str of strings) {
if (str) {
return !str[str.length - 1].trim();
}
}
// If the string is empty, check the previous string.
}
return true;
}
/**
* Checks if the first character is a non word.
*/
function startsWithNonWord(node: AST.SvelteAttribute, index: number): boolean {
for (let i = index; i < node.value.length; i++) {
const valueNode = node.value[i];
const strings = getStrings(valueNode);
if (strings == null) {
// unknown
return false;
}
for (const str of strings) {
if (str) {
return !str[0].trim();
}
}
// If the string is empty, check the previous string.
}
return true;
}
/** Report */
function report(
node: AST.SvelteMustacheTagText,
map: Map<Expr, string>,
attr: AST.SvelteAttribute
) {
context.report({
node,
messageId: 'unexpected',
*fix(fixer) {
const classDirectives: string[] = [];
let space = ' ';
for (const [expr, className] of map) {
const trimmedClassName = className.trim();
if (trimmedClassName) {
classDirectives.push(`class:${trimmedClassName}={${exprToString(expr)}}`);
} else {
space = className;
}
}
const fixesBuffer: Rule.Fix[] = [];
const index = attr.value.indexOf(node);
const beforeAttrValues = attr.value.slice(0, index);
const afterAttrValues = attr.value.slice(index + 1);
let valueNode;
while ((valueNode = beforeAttrValues[beforeAttrValues.length - 1])) {
if (valueNode.type === 'SvelteLiteral') {
if (!valueNode.value.trim()) {
// Before spaces
beforeAttrValues.pop();
fixesBuffer.push(fixer.remove(valueNode));
continue;
}
if (valueNode.value.trimEnd() !== valueNode.value) {
// Before spaces
fixesBuffer.push(fixer.replaceText(valueNode, valueNode.value.trimEnd()));
}
}
break;
}
while ((valueNode = afterAttrValues[0])) {
if (valueNode.type === 'SvelteLiteral') {
if (!valueNode.value.trim()) {
// After spaces
afterAttrValues.shift();
fixesBuffer.push(fixer.remove(valueNode));
continue;
}
if (valueNode.value.trimStart() !== valueNode.value) {
// After spaces
fixesBuffer.push(fixer.replaceText(valueNode, valueNode.value.trimStart()));
}
}
break;
}
if (!beforeAttrValues.length && !afterAttrValues.length) {
yield fixer.replaceText(attr, classDirectives.join(' '));
} else {
yield* fixesBuffer;
if (beforeAttrValues.length && afterAttrValues.length) {
yield fixer.replaceText(node, space || ' ');
} else {
yield fixer.remove(node);
}
yield fixer.insertTextAfterRange(
[attr.range[1], attr.range[1]],
` ${classDirectives.join(' ')}`
);
}
}
});
}
/** verify */
function verify(node: AST.SvelteMustacheTagText, index: number, attr: AST.SvelteAttribute) {
if (node.expression.type !== 'ConditionalExpression') {
return;
}
const map = parseConditionalExpression(node.expression);
if (map == null) {
// has unknown
return;
}
if (map.size > 2) {
// It's too complicated.
return;
}
if (preferEmpty && [...map.values()].every((x) => x.trim())) {
// We prefer directives when there's an empty string, but they're all not empty
return;
}
const prevIsWord = !startsWithNonWord(attr, index + 1);
const nextIsWord = !endsWithNonWord(attr, index - 1);
let canTransform = true;
for (const className of map.values()) {
if (className) {
if (!/^[\w-]*$/u.test(className.trim())) {
// Cannot be transformed to an attribute.
canTransform = false;
break;
}
if (
(className[0].trim() && prevIsWord) ||
(className[className.length - 1].trim() && nextIsWord)
) {
// The previous or next may be connected to this element.
canTransform = false;
break;
}
} else {
if (prevIsWord && nextIsWord) {
// The previous and next may be connected.
canTransform = false;
break;
}
}
}
if (!canTransform) {
return;
}
report(node, map, attr);
}
return {
'SvelteStartTag > SvelteAttribute'(
node: AST.SvelteAttribute & {
parent: AST.SvelteStartTag;
}
) {
if (!isHTMLElementLike(node.parent.parent) || node.key.name !== 'class') {
return;
}
for (let index = 0; index < node.value.length; index++) {
const valueElement = node.value[index];
if (valueElement.type !== 'SvelteMustacheTag') {
continue;
}
verify(valueElement, index, node);
}
}
};
}
});