-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathno-raw-text.js
109 lines (91 loc) · 2.74 KB
/
no-raw-text.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
/**
* @fileoverview Detects raw text outside of Text component
* @author Alex Zhukov
*/
'use strict';
const { default: traverse } = require('@babel/traverse');
const elementName = (node, scope) => {
const identifiers = [];
traverse(node, {
JSXOpeningElement({ node: element }) {
traverse(element, {
JSXIdentifier({ node: identifier }) {
if (identifier.parent.type === 'JSXOpeningElement'
|| identifier.parent.type === 'JSXMemberExpression') {
identifiers.push(identifier.name);
}
},
}, scope);
},
}, scope);
return identifiers.join('.');
};
function create(context) {
const options = context.options[0] || {};
const report = (node) => {
const errorValue = node.type === 'TemplateLiteral'
? `TemplateLiteral: ${node.expressions[0].name}`
: node.value.trim();
const formattedErrorValue = errorValue.length > 0
? `Raw text (${errorValue})`
: 'Whitespace(s)';
context.report({
node,
message: `${formattedErrorValue} cannot be used outside of a <Text> tag`,
});
};
const skippedElements = options.skip ? options.skip : [];
const allowedElements = ['Text', 'TSpan', 'StyledText', 'Animated.Text'].concat(skippedElements);
const hasOnlyLineBreak = (value) => /^[\r\n\t\f\v]+$/.test(value.replace(/ /g, ''));
const scope = context.getScope();
const getValidation = (node) => !allowedElements.some((el) => new RegExp(`^${el}$`).test(elementName(node.parent, scope)));
return {
Literal(node) {
const parentType = node.parent.type;
const onlyFor = ['JSXExpressionContainer', 'JSXElement'];
if (typeof node.value !== 'string'
|| hasOnlyLineBreak(node.value)
|| !onlyFor.includes(parentType)
|| (node.parent.parent && node.parent.parent.type === 'JSXAttribute')
) return;
const isStringLiteral = parentType === 'JSXExpressionContainer';
if (getValidation(isStringLiteral ? node.parent : node)) {
report(node);
}
},
JSXText(node) {
if (typeof node.value !== 'string' || hasOnlyLineBreak(node.value)) return;
if (getValidation(node)) {
report(node);
}
},
TemplateLiteral(node) {
if (
node.parent.type !== 'JSXExpressionContainer'
|| (node.parent.parent && node.parent.parent.type === 'JSXAttribute')
) return;
if (getValidation(node.parent)) {
report(node);
}
},
};
}
module.exports = {
meta: {
schema: [
{
type: 'object',
properties: {
skip: {
type: 'array',
items: {
type: 'string',
},
},
},
additionalProperties: false,
},
],
},
create,
};