/
no-adjacent-inline-elements.js
79 lines (72 loc) · 2.22 KB
/
no-adjacent-inline-elements.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
/**
* @fileoverview Prevent adjacent inline elements not separated by whitespace.
* @author Sean Hayes
*/
'use strict';
// ------------------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------------------
// https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements
var inlineNames = ('a b big i small tt abbr acronym cite code dfn em kbd strong' +
' samp time var bdo br img map object q script span sub sup button input' +
' label select textarea').split(' ');
var nbsp = ' ';
function isInline(node) {
if (node.type === 'Literal') {
// Regular whitespace will be removed.
var raw = node.raw.trim();
// To properly separate inline elements, each end of the literal will need
// a .
return !(raw.startsWith(nbsp) && raw.endsWith(nbsp));
}
if (node.type !== 'JSXElement') {
// Skip.
return false;
}
var name = node.openingElement.name.name;
if (inlineNames.indexOf(name) > -1) {
return true;
}
return false;
}
var ERROR = 'Child elements which render as inline HTML elements should be' +
' separated by a space or wrapped in block level elements.';
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
module.exports = {
ERROR: ERROR,
meta: {
docs: {
description: 'Prevent adjacent inline elements not separated by whitespace.',
category: 'Best Practices',
recommended: false
},
schema: []
},
create: function(context) {
function validate(node) {
var currentIsInline = false;
var previousIsInline = false;
for (var i = 0; i < node.children.length; i++) {
currentIsInline = isInline(node.children[i]);
if (previousIsInline && currentIsInline) {
context.report({
node: node,
message: ERROR
});
return;
}
previousIsInline = currentIsInline;
}
}
return {
JSXElement: function(node) {
validate(node);
},
CallExpression: function(node) {
validate(node);
}
};
}
};