1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | 'use strict';
|
7 |
|
8 | const Components = require('../util/Components');
|
9 | const docsUrl = require('../util/docsUrl');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | module.exports = {
|
16 | meta: {
|
17 | docs: {
|
18 | description: 'Prevent string definitions for references and prevent referencing this.refs',
|
19 | category: 'Best Practices',
|
20 | recommended: true,
|
21 | url: docsUrl('no-string-refs')
|
22 | },
|
23 | schema: [{
|
24 | type: 'object',
|
25 | properties: {
|
26 | noTemplateLiterals: {
|
27 | type: 'boolean'
|
28 | }
|
29 | },
|
30 | additionalProperties: false
|
31 | }]
|
32 | },
|
33 |
|
34 | create: Components.detect((context, components, utils) => {
|
35 | const detectTemplateLiterals = context.options[0] ? context.options[0].noTemplateLiterals : false;
|
36 | |
37 |
|
38 |
|
39 |
|
40 |
|
41 | function isRefsUsage(node) {
|
42 | return Boolean(
|
43 | (
|
44 | utils.getParentES6Component()
|
45 | || utils.getParentES5Component()
|
46 | )
|
47 | && node.object.type === 'ThisExpression'
|
48 | && node.property.name === 'refs'
|
49 | );
|
50 | }
|
51 |
|
52 | |
53 |
|
54 |
|
55 |
|
56 |
|
57 | function isRefAttribute(node) {
|
58 | return Boolean(
|
59 | node.type === 'JSXAttribute'
|
60 | && node.name
|
61 | && node.name.name === 'ref'
|
62 | );
|
63 | }
|
64 |
|
65 | |
66 |
|
67 |
|
68 |
|
69 |
|
70 | function containsStringLiteral(node) {
|
71 | return Boolean(
|
72 | node.value
|
73 | && node.value.type === 'Literal'
|
74 | && typeof node.value.value === 'string'
|
75 | );
|
76 | }
|
77 |
|
78 | |
79 |
|
80 |
|
81 |
|
82 |
|
83 | function containsStringExpressionContainer(node) {
|
84 | return Boolean(
|
85 | node.value
|
86 | && node.value.type === 'JSXExpressionContainer'
|
87 | && node.value.expression
|
88 | && ((node.value.expression.type === 'Literal' && typeof node.value.expression.value === 'string')
|
89 | || (node.value.expression.type === 'TemplateLiteral' && detectTemplateLiterals))
|
90 | );
|
91 | }
|
92 |
|
93 | return {
|
94 | MemberExpression(node) {
|
95 | if (isRefsUsage(node)) {
|
96 | context.report({
|
97 | node,
|
98 | message: 'Using this.refs is deprecated.'
|
99 | });
|
100 | }
|
101 | },
|
102 | JSXAttribute(node) {
|
103 | if (
|
104 | isRefAttribute(node)
|
105 | && (containsStringLiteral(node) || containsStringExpressionContainer(node))
|
106 | ) {
|
107 | context.report({
|
108 | node,
|
109 | message: 'Using string literals in ref attributes is deprecated.'
|
110 | });
|
111 | }
|
112 | }
|
113 | };
|
114 | })
|
115 | };
|