|
| 1 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 2 | +module.exports = { |
| 3 | + meta: { |
| 4 | + type: 'suggestion', |
| 5 | + docs: { |
| 6 | + description: 'require self-closing on void elements', |
| 7 | + category: 'Best Practices', |
| 8 | + url: 'https://github.com/ember-cli/eslint-plugin-ember/tree/master/docs/rules/template-self-closing-void-elements.md', |
| 9 | + templateMode: 'both', |
| 10 | + }, |
| 11 | + fixable: 'code', |
| 12 | + schema: [ |
| 13 | + { |
| 14 | + oneOf: [{ type: 'boolean' }, { type: 'string', enum: ['require'] }], |
| 15 | + }, |
| 16 | + ], |
| 17 | + messages: { |
| 18 | + redundantSelfClosing: 'Self-closing a void element is redundant', |
| 19 | + requireSelfClosing: 'Self-closing a void element is required', |
| 20 | + }, |
| 21 | + originallyFrom: { |
| 22 | + name: 'ember-template-lint', |
| 23 | + rule: 'lib/rules/self-closing-void-elements.js', |
| 24 | + docs: 'docs/rule/self-closing-void-elements.md', |
| 25 | + tests: 'test/unit/rules/self-closing-void-elements-test.js', |
| 26 | + }, |
| 27 | + }, |
| 28 | + |
| 29 | + create(context) { |
| 30 | + const VOID_ELEMENTS = new Set([ |
| 31 | + 'area', |
| 32 | + 'base', |
| 33 | + 'br', |
| 34 | + 'col', |
| 35 | + 'command', |
| 36 | + 'embed', |
| 37 | + 'hr', |
| 38 | + 'img', |
| 39 | + 'input', |
| 40 | + 'keygen', |
| 41 | + 'link', |
| 42 | + 'meta', |
| 43 | + 'param', |
| 44 | + 'source', |
| 45 | + 'track', |
| 46 | + 'wbr', |
| 47 | + ]); |
| 48 | + |
| 49 | + const sourceCode = context.sourceCode; |
| 50 | + const config = context.options[0] ?? true; |
| 51 | + |
| 52 | + if (config === false) { |
| 53 | + return {}; |
| 54 | + } |
| 55 | + |
| 56 | + const requireSelfClosing = config === 'require'; |
| 57 | + |
| 58 | + return { |
| 59 | + GlimmerElementNode(node) { |
| 60 | + if (!VOID_ELEMENTS.has(node.tag)) { |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + if (requireSelfClosing) { |
| 65 | + if (!node.selfClosing) { |
| 66 | + const source = sourceCode.getText(node).trim(); |
| 67 | + |
| 68 | + context.report({ |
| 69 | + node, |
| 70 | + messageId: 'requireSelfClosing', |
| 71 | + fix(fixer) { |
| 72 | + return fixer.replaceText(node, source.replace(/>$/, '/>')); |
| 73 | + }, |
| 74 | + }); |
| 75 | + } |
| 76 | + } else { |
| 77 | + if (node.selfClosing) { |
| 78 | + const source = sourceCode.getText(node).trim(); |
| 79 | + |
| 80 | + context.report({ |
| 81 | + node, |
| 82 | + messageId: 'redundantSelfClosing', |
| 83 | + fix(fixer) { |
| 84 | + const replacement = node.blockParams?.length |
| 85 | + ? source.replace(/\/>$/, '>') |
| 86 | + : source.replace(/\s*\/>$/, '>'); |
| 87 | + |
| 88 | + return fixer.replaceText(node, replacement); |
| 89 | + }, |
| 90 | + }); |
| 91 | + } |
| 92 | + } |
| 93 | + }, |
| 94 | + }; |
| 95 | + }, |
| 96 | +}; |
0 commit comments