Skip to content

Update no-empty-alt-text to check for no alt #88

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/rules/no-empty-alt-text.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,18 @@ module.exports = {
},
);

const htmlAltRegex = new RegExp(/alt=['"]['"]/, "gid");

const htmlAltRegex = new RegExp(/alt=['"]/, "gid");
const htmlEmptyAltRegex = new RegExp(/alt=['"]['"]/, "gid");
for (const token of htmlTagsWithImages) {
const lineRange = token.map;
const lineNumber = token.lineNumber;
const lines = params.lines.slice(lineRange[0], lineRange[1]);

for (const [i, line] of lines.entries()) {
const matches = line.matchAll(htmlAltRegex);
const noAlt = [...line.matchAll(htmlAltRegex)].length === 0;

const matches = line.matchAll(htmlEmptyAltRegex);

for (const match of matches) {
const matchingContent = match[0];
const startIndex = match.indices[0][0];
Expand All @@ -34,6 +37,12 @@ module.exports = {
range: [startIndex + 1, matchingContent.length],
});
}

if (noAlt) {
onError({
lineNumber: lineNumber + i,
});
}
}
}
},
Expand Down
4 changes: 3 additions & 1 deletion test/no-empty-alt-text.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ describe("GH003: No Empty Alt Text", () => {
'<img alt="" src="https://user-images.githubusercontent.com/abcdef.png">',
"<img alt='' src='https://user-images.githubusercontent.com/abcdef.png'>",
'<img src="cat.png" alt="" /> <img src="dog.png" alt="" />',
'<img src="dog.png" />',
'<img alt src="dog.png" />',
];

const results = await runTest(strings, noEmptyStringAltRule);
Expand All @@ -28,7 +30,7 @@ describe("GH003: No Empty Alt Text", () => {
.flat()
.filter((name) => !name.includes("GH"));

expect(failedRules).toHaveLength(4);
expect(failedRules).toHaveLength(6);
for (const rule of failedRules) {
expect(rule).toBe("no-empty-alt-text");
}
Expand Down