Refactor to remove micromark helper matchAndGetTokensByType.

This commit is contained in:
David Anson 2024-09-18 21:02:59 -07:00
parent 2ea3f95fd1
commit 87daa5b06c
4 changed files with 66 additions and 184 deletions

View file

@ -3,15 +3,15 @@
"use strict";
const { addErrorContext, allPunctuation } = require("../helpers");
const { matchAndGetTokensByType } = require("../helpers/micromark.cjs");
const { getDescendantsByType } = require("../helpers/micromark.cjs");
const { filterByTypesCached } = require("./cache");
/** @typedef {import("../helpers/micromark.cjs").TokenType} TokenType */
/** @type {Map<TokenType, TokenType[]>} */
const emphasisAndChildrenTypes = new Map([
[ "emphasis", [ "emphasisSequence", "emphasisText", "emphasisSequence" ] ],
[ "strong", [ "strongSequence", "strongText", "strongSequence" ] ]
]);
/** @type {TokenType[][]} */
const emphasisTypes = [
[ "emphasis", "emphasisText" ],
[ "strong", "strongText" ]
];
// eslint-disable-next-line jsdoc/valid-types
/** @type import("./markdownlint").Rule */
@ -29,21 +29,15 @@ module.exports = {
.filter((token) =>
(token.parent?.type === "content") && !token.parent?.parent && (token.children.length === 1)
);
for (const paragraphToken of paragraphTokens) {
const childToken = paragraphToken.children[0];
for (const [ emphasisType, emphasisChildrenTypes ] of emphasisAndChildrenTypes) {
if (childToken.type === emphasisType) {
const matchingTokens = matchAndGetTokensByType(childToken.children, emphasisChildrenTypes);
if (matchingTokens) {
const textToken = matchingTokens[1];
if (
(textToken.children.length === 1) &&
(textToken.children[0].type === "data") &&
!punctuationRe.test(textToken.text)
) {
addErrorContext(onError, textToken.startLine, textToken.text);
}
}
for (const emphasisType of emphasisTypes) {
const textTokens = getDescendantsByType(paragraphTokens, emphasisType);
for (const textToken of textTokens) {
if (
(textToken.children.length === 1) &&
(textToken.children[0].type === "data") &&
!punctuationRe.test(textToken.text)
) {
addErrorContext(onError, textToken.startLine, textToken.text);
}
}
}