Skip to content

Commit

Permalink
[Fix] img-redundant-alt: fixed multibyte character support
Browse files Browse the repository at this point in the history
Fixes #969
  • Loading branch information
makotot authored and ljharb committed Jan 8, 2024
1 parent 540cb7a commit ef90c1f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 4 additions & 0 deletions __tests__/src/rules/img-redundant-alt-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ ruleTester.run('img-redundant-alt', rule, {
{ code: '<img alt="ImageMagick" />;' },
{ code: '<Image alt="Photo of a friend" />' },
{ code: '<Image alt="Foo" />', settings: componentsSettings },
{ code: '<img alt="画像" />', options: [{ words: ['イメージ'] }] },
)).map(parserOptionsMapper),
invalid: parsers.all([].concat(
{ code: '<img alt="Photo of friend." />;', errors: [expectedError] },
Expand Down Expand Up @@ -129,5 +130,8 @@ ruleTester.run('img-redundant-alt', rule, {
{ code: '<img alt="Word2" />;', options: array, errors: [expectedError] },
{ code: '<Image alt="Word1" />;', options: array, errors: [expectedError] },
{ code: '<Image alt="Word2" />;', options: array, errors: [expectedError] },

{ code: '<img alt="イメージ" />', options: [{ words: ['イメージ'] }], errors: [expectedError] },
{ code: '<img alt="イメージです" />', options: [{ words: ['イメージ'] }], errors: [expectedError] },
)).map(parserOptionsMapper),
});
13 changes: 12 additions & 1 deletion src/rules/img-redundant-alt.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
// ----------------------------------------------------------------------------

import { getProp, getLiteralPropValue } from 'jsx-ast-utils';
import includes from 'array-includes';
import { generateObjSchema, arraySchema } from '../util/schemas';
import getElementType from '../util/getElementType';
import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader';
Expand All @@ -25,6 +26,16 @@ const schema = generateObjSchema({
words: arraySchema,
});

function containsRedundantWord(value, redundantWords) {
const lowercaseRedundantWords = redundantWords.map((redundantWord) => redundantWord.toLowerCase());
const isASCII = /[\x20-\x7F]+/.test(value);

if (isASCII) {
return value.split(/\s+/).some((valueWord) => includes(lowercaseRedundantWords, valueWord.toLowerCase()));
}
return lowercaseRedundantWords.some((redundantWord) => value.toLowerCase().includes(redundantWord));
}

export default {
meta: {
docs: {
Expand Down Expand Up @@ -63,7 +74,7 @@ export default {
const redundantWords = REDUNDANT_WORDS.concat(words);

if (typeof value === 'string' && isVisible) {
const hasRedundancy = new RegExp(`(?!{)\\b(${redundantWords.join('|')})\\b(?!})`, 'i').test(value);
const hasRedundancy = containsRedundantWord(value, redundantWords);

if (hasRedundancy === true) {
context.report({
Expand Down

0 comments on commit ef90c1f

Please sign in to comment.