9
9
// ----------------------------------------------------------------------------
10
10
11
11
import hasAttribute from '../util/hasAttribute' ;
12
+ import getAttributeValue from '../util/getAttributeValue' ;
12
13
import isHiddenFromScreenReader from '../util/isHiddenFromScreenReader' ;
13
14
import getNodeType from '../util/getNodeType' ;
14
15
@@ -21,6 +22,11 @@ const REDUNDANT_WORDS = [
21
22
const errorMessage = 'Redundant alt attribute. Screen-readers already announce `img` tags as an image. ' +
22
23
'You don\'t need to use the words `image`, `photo,` or `picture` in the alt prop.' ;
23
24
25
+ const validTypes = [
26
+ 'LITERAL' ,
27
+ 'TEMPLATELITERAL'
28
+ ] ;
29
+
24
30
module . exports = context => ( {
25
31
JSXOpeningElement : node => {
26
32
const type = getNodeType ( node ) ;
@@ -29,11 +35,26 @@ module.exports = context => ({
29
35
}
30
36
31
37
const altProp = hasAttribute ( node . attributes , 'alt' ) ;
38
+ // Return if alt prop is not present.
39
+ if ( altProp === false ) {
40
+ return ;
41
+ }
42
+
43
+ // Only check literals, as we should not enforce variable names :P
44
+ const normalizedType = altProp . value && altProp . value . type . toUpperCase ( ) === 'JSXEXPRESSIONCONTAINER' ?
45
+ altProp . value . expression . type . toUpperCase ( ) :
46
+ altProp . value . type . toUpperCase ( ) ;
47
+
48
+ if ( validTypes . indexOf ( normalizedType ) === - 1 ) {
49
+ return ;
50
+ }
51
+
52
+ const value = getAttributeValue ( altProp ) ;
32
53
const isVisible = isHiddenFromScreenReader ( node . attributes ) === false ;
33
54
34
- if ( Boolean ( altProp ) && typeof altProp === 'string' && isVisible ) {
55
+ if ( Boolean ( value ) && typeof value === 'string' && isVisible ) {
35
56
const hasRedundancy = REDUNDANT_WORDS
36
- . some ( word => Boolean ( altProp . match ( new RegExp ( `(?!{)${ word } (?!})` , 'gi' ) ) ) ) ;
57
+ . some ( word => Boolean ( value . match ( new RegExp ( `(?!{)${ word } (?!})` , 'gi' ) ) ) ) ;
37
58
38
59
if ( hasRedundancy === true ) {
39
60
context . report ( {
0 commit comments