1
+ // TODO: Clean up when https://github.com/DavidAnson/markdownlint/pull/993 is merged
1
2
module . exports = {
2
3
names : [ "GH003" , "no-empty-alt-text" ] ,
3
4
description : "Please provide an alternative text for the image." ,
@@ -17,22 +18,38 @@ module.exports = {
17
18
} ,
18
19
) ;
19
20
20
- const htmlAltRegex = new RegExp ( / a l t = [ ' " ] [ ' " ] / , "gid" ) ;
21
-
21
+ const ImageRegex = new RegExp ( / < i m g ( .* ?) > / , "gid" ) ;
22
+ const htmlAltRegex = new RegExp ( / a l t = [ ' " ] / , "gid" ) ;
23
+ const htmlEmptyAltRegex = new RegExp ( / a l t = [ ' " ] [ ' " ] / , "gid" ) ;
22
24
for ( const token of htmlTagsWithImages ) {
23
25
const lineRange = token . map ;
24
26
const lineNumber = token . lineNumber ;
25
27
const lines = params . lines . slice ( lineRange [ 0 ] , lineRange [ 1 ] ) ;
26
28
27
29
for ( const [ i , line ] of lines . entries ( ) ) {
28
- const matches = line . matchAll ( htmlAltRegex ) ;
29
- for ( const match of matches ) {
30
- const matchingContent = match [ 0 ] ;
31
- const startIndex = match . indices [ 0 ] [ 0 ] ;
32
- onError ( {
33
- lineNumber : lineNumber + i ,
34
- range : [ startIndex + 1 , matchingContent . length ] ,
35
- } ) ;
30
+ const imageTags = line . matchAll ( ImageRegex ) ;
31
+
32
+ for ( const imageTag of imageTags ) {
33
+ const imageTagIndex = imageTag . indices [ 0 ] [ 0 ] ;
34
+
35
+ const emptyAltMatches = [
36
+ ...imageTag [ 0 ] . matchAll ( htmlEmptyAltRegex ) ,
37
+ ] [ 0 ] ;
38
+ const noAltMatches = [ ...imageTag [ 0 ] . matchAll ( htmlAltRegex ) ] ;
39
+
40
+ if ( emptyAltMatches ) {
41
+ const matchingContent = emptyAltMatches [ 0 ] ;
42
+ const startIndex = emptyAltMatches . indices [ 0 ] [ 0 ] ;
43
+ onError ( {
44
+ lineNumber : lineNumber + i ,
45
+ range : [ imageTagIndex + startIndex + 1 , matchingContent . length ] ,
46
+ } ) ;
47
+ } else if ( noAltMatches . length === 0 ) {
48
+ onError ( {
49
+ lineNumber : lineNumber + i ,
50
+ range : [ imageTagIndex + 1 , imageTag [ 0 ] . length ] ,
51
+ } ) ;
52
+ }
36
53
}
37
54
}
38
55
}
0 commit comments