Skip to content

Commit 8a36c24

Browse files
authored
Fix bug where images within code blocks are being flagged (#83)
Fix bug where fenced img is being flagged
1 parent 139cdac commit 8a36c24

File tree

2 files changed

+33
-12
lines changed

2 files changed

+33
-12
lines changed

src/rules/no-default-alt-text.js

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,38 @@ module.exports = {
2121
),
2222
tags: ["accessibility", "images"],
2323
function: function GH001(params, onError) {
24-
for (const [lineIndex, line] of params.lines.entries()) {
25-
for (const match of [
26-
...line.matchAll(markdownAltRegex),
27-
...line.matchAll(htmlAltRegex),
28-
]) {
29-
// The alt text is contained in the first capture group
30-
const altText = match[1];
31-
const [startIndex] = match.indices[1];
24+
const htmlTagsWithImages = params.parsers.markdownit.tokens.filter(
25+
(token) => {
26+
return token.type === "html_block" && token.content.includes("<img");
27+
},
28+
);
29+
const inlineImages = params.parsers.markdownit.tokens.filter(
30+
(token) =>
31+
token.type === "inline" &&
32+
token.children.some((child) => child.type === "image"),
33+
);
3234

33-
onError({
34-
lineNumber: lineIndex + 1,
35-
range: [startIndex + 1, altText.length],
36-
});
35+
for (const token of [...htmlTagsWithImages, ...inlineImages]) {
36+
const lineRange = token.map;
37+
const lineNumber = token.lineNumber;
38+
const lines = params.lines.slice(lineRange[0], lineRange[1]);
39+
40+
for (let i = 0; i < lines.length; i++) {
41+
const line = lines[i];
42+
let matches;
43+
if (token.type === "inline") {
44+
matches = line.matchAll(markdownAltRegex);
45+
} else {
46+
matches = line.matchAll(htmlAltRegex);
47+
}
48+
for (const match of matches) {
49+
const altText = match[1];
50+
const [startIndex] = match.indices[1];
51+
onError({
52+
lineNumber: lineNumber + i,
53+
range: [startIndex + 1, altText.length],
54+
});
55+
}
3756
}
3857
}
3958
},

test/no-default-alt-text.test.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ describe("GH001: No Default Alt Text", () => {
55
describe("successes", () => {
66
test("inline", async () => {
77
const strings = [
8+
"```![image](https://user-images.githubusercontent.com/abcdef.png)```",
9+
"`![Image](https://user-images.githubusercontent.com/abcdef.png)`",
810
"![Chart with a single root node reading 'Example'](https://user-images.githubusercontent.com/abcdef.png)",
911
];
1012

0 commit comments

Comments
 (0)