Skip to content

Commit 46b3974

Browse files
authored
text-encoding-identifier-case: Enforce 'utf-8' in form[acceptCharset] and TextDecoder (#2785)
1 parent 13a37a0 commit 46b3974

File tree

5 files changed

+565
-135
lines changed

5 files changed

+565
-135
lines changed

rules/text-encoding-identifier-case.js

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {replaceStringRaw} from './fix/index.js';
2-
import {isMethodCall} from './ast/index.js';
2+
import {isMethodCall, isNewExpression} from './ast/index.js';
33

44
const MESSAGE_ID_ERROR = 'text-encoding-identifier/error';
55
const MESSAGE_ID_SUGGESTION = 'text-encoding-identifier/suggestion';
@@ -34,31 +34,31 @@ const isFsReadFileEncoding = node =>
3434
&& node.parent.arguments[1] === node
3535
&& node.parent.arguments[0].type !== 'SpreadElement';
3636

37+
const isJsxElementAttributes = (node, {element, attributes}) =>
38+
node.parent.type === 'JSXAttribute'
39+
&& node.parent.value === node
40+
&& node.parent.name.type === 'JSXIdentifier'
41+
&& attributes.includes(node.parent.name.name.toLowerCase())
42+
&& node.parent.parent.type === 'JSXOpeningElement'
43+
&& node.parent.parent.attributes.includes(node.parent)
44+
&& node.parent.parent.name.type === 'JSXIdentifier'
45+
&& node.parent.parent.name.name.toLowerCase() === element;
46+
47+
const shouldEnforceDash = node =>
48+
isJsxElementAttributes(node, {element: 'meta', attributes: ['charset']})
49+
|| isJsxElementAttributes(node, {element: 'form', attributes: ['acceptCharset', 'accept-charset'].map(attribute => attribute.toLowerCase())})
50+
|| (isNewExpression(node.parent, {name: 'TextDecoder'}) && node.parent.arguments[0] === node);
51+
3752
/** @param {import('eslint').Rule.RuleContext} context */
3853
const create = context => {
39-
const {
40-
withDash,
41-
} = context.options[0];
54+
const options = context.options[0];
4255

4356
context.on('Literal', node => {
4457
if (typeof node.value !== 'string') {
4558
return;
4659
}
4760

48-
if (
49-
// eslint-disable-next-line unicorn/text-encoding-identifier-case
50-
node.value === 'utf-8'
51-
&& node.parent.type === 'JSXAttribute'
52-
&& node.parent.value === node
53-
&& node.parent.name.type === 'JSXIdentifier'
54-
&& node.parent.name.name.toLowerCase() === 'charset'
55-
&& node.parent.parent.type === 'JSXOpeningElement'
56-
&& node.parent.parent.attributes.includes(node.parent)
57-
&& node.parent.parent.name.type === 'JSXIdentifier'
58-
&& node.parent.parent.name.name.toLowerCase() === 'meta'
59-
) {
60-
return;
61-
}
61+
const withDash = options.withDash || shouldEnforceDash(node);
6262

6363
const {raw} = node;
6464
const value = raw.slice(1, -1);

0 commit comments

Comments
 (0)