From 74fe5f95d9542b6032fc5fc100e57ab703727ce4 Mon Sep 17 00:00:00 2001 From: Kendall Gassner Date: Wed, 11 Oct 2023 07:10:30 -0700 Subject: [PATCH] Update no-empty-alt-text to check for no alt (#88) * Update no-empty-alt-text to check for no alt * clean * Update no-empty-alt-text.js * Update no-empty-alt-text.js --- src/rules/no-empty-alt-text.js | 37 +++++++++++++++++++++++++--------- test/no-empty-alt-text.test.js | 5 ++++- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/src/rules/no-empty-alt-text.js b/src/rules/no-empty-alt-text.js index 02cab26..0ade74b 100644 --- a/src/rules/no-empty-alt-text.js +++ b/src/rules/no-empty-alt-text.js @@ -1,3 +1,4 @@ +// TODO: Clean up when https://github.com/DavidAnson/markdownlint/pull/993 is merged module.exports = { names: ["GH003", "no-empty-alt-text"], description: "Please provide an alternative text for the image.", @@ -17,22 +18,38 @@ module.exports = { }, ); - const htmlAltRegex = new RegExp(/alt=['"]['"]/, "gid"); - + const ImageRegex = new RegExp(//, "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); - for (const match of matches) { - const matchingContent = match[0]; - const startIndex = match.indices[0][0]; - onError({ - lineNumber: lineNumber + i, - range: [startIndex + 1, matchingContent.length], - }); + const imageTags = line.matchAll(ImageRegex); + + for (const imageTag of imageTags) { + const imageTagIndex = imageTag.indices[0][0]; + + const emptyAltMatches = [ + ...imageTag[0].matchAll(htmlEmptyAltRegex), + ][0]; + const noAltMatches = [...imageTag[0].matchAll(htmlAltRegex)]; + + if (emptyAltMatches) { + const matchingContent = emptyAltMatches[0]; + const startIndex = emptyAltMatches.indices[0][0]; + onError({ + lineNumber: lineNumber + i, + range: [imageTagIndex + startIndex + 1, matchingContent.length], + }); + } else if (noAltMatches.length === 0) { + onError({ + lineNumber: lineNumber + i, + range: [imageTagIndex + 1, imageTag[0].length], + }); + } } } } diff --git a/test/no-empty-alt-text.test.js b/test/no-empty-alt-text.test.js index 0b6fd43..1479bf7 100644 --- a/test/no-empty-alt-text.test.js +++ b/test/no-empty-alt-text.test.js @@ -19,6 +19,9 @@ describe("GH003: No Empty Alt Text", () => { '', "", ' ', + '', + '', + "", ]; const results = await runTest(strings, noEmptyStringAltRule); @@ -28,7 +31,7 @@ describe("GH003: No Empty Alt Text", () => { .flat() .filter((name) => !name.includes("GH")); - expect(failedRules).toHaveLength(4); + expect(failedRules).toHaveLength(8); for (const rule of failedRules) { expect(rule).toBe("no-empty-alt-text"); }