Update MD045/no-alt-text to report instances of HTML "img" tags missing an "alt" attribute (fixes #992).

This commit is contained in:
Kate Higa 2023-10-18 23:20:19 -07:00 committed by GitHub
parent 0afedaebf4
commit 531e58ed9a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
18 changed files with 274 additions and 25 deletions

View file

@ -2,15 +2,21 @@
"use strict";
const { addError } = require("../helpers");
const { filterByTypes } = require("../helpers/micromark.cjs");
const { addError, nextLinesRe } = require("../helpers");
const { filterByTypes, getHtmlTagInfo } = require("../helpers/micromark.cjs");
// Regular expression for identifying alt attribute
const altRe = /\salt=/i;
module.exports = {
"names": [ "MD045", "no-alt-text" ],
"description": "Images should have alternate text (alt text)",
"tags": [ "accessibility", "images" ],
"function": function MD045(params, onError) {
const images = filterByTypes(params.parsers.micromark.tokens, [ "image" ]);
const { tokens } = params.parsers.micromark;
// Process Markdown images
const images = filterByTypes(tokens, [ "image" ]);
for (const image of images) {
const labelTexts = filterByTypes(image.children, [ "labelText" ]);
if (labelTexts.some((labelText) => labelText.text.length === 0)) {
@ -26,5 +32,29 @@ module.exports = {
);
}
}
// Process HTML images
const htmlTexts = filterByTypes(tokens, [ "htmlText" ]);
for (const htmlText of htmlTexts) {
const { startColumn, startLine, text } = htmlText;
const htmlTagInfo = getHtmlTagInfo(htmlText);
if (
htmlTagInfo &&
(htmlTagInfo.name.toLowerCase() === "img") &&
!altRe.test(text)
) {
const range = [
startColumn,
text.replace(nextLinesRe, "").length
];
addError(
onError,
startLine,
undefined,
undefined,
range
);
}
}
}
};