mirror of
https://github.com/theoludwig/markdownlint-rule-relative-links.git
synced 2026-02-20 03:09:05 +01:00
feat: html anchor support
This commit is contained in:
49
src/utils.js
49
src/utils.js
@@ -1,4 +1,6 @@
|
||||
const MarkdownIt = require("markdown-it")
|
||||
// @ts-ignore
|
||||
const { getHtmlAttributeRe } = require("markdownlint-rule-helpers")
|
||||
|
||||
/** @typedef {import('markdownlint').RuleParams} MarkdownLintRuleParams */
|
||||
/** @typedef {import('markdownlint').MarkdownItToken} MarkdownItToken */
|
||||
@@ -94,8 +96,55 @@ const getMarkdownHeadings = (content) => {
|
||||
return headings
|
||||
}
|
||||
|
||||
const anchorNameRe = getHtmlAttributeRe("name")
|
||||
const anchorIdRe = getHtmlAttributeRe("id")
|
||||
|
||||
/**
|
||||
* Gets the anchor HTML fragments from a Markdown string.
|
||||
* @param {string} content
|
||||
* @returns {string[]}
|
||||
*/
|
||||
const getMarkdownAnchorHTMLFragments = (content) => {
|
||||
const markdownIt = new MarkdownIt({ html: true })
|
||||
const tokens = markdownIt.parse(content, {})
|
||||
|
||||
/** @type {string[]} */
|
||||
const result = []
|
||||
|
||||
for (const token of tokens) {
|
||||
if (token.type === "inline") {
|
||||
if (!token.children) {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const child of token.children) {
|
||||
if (child.type === "html_inline") {
|
||||
const anchorMatch =
|
||||
anchorIdRe.exec(token.content) || anchorNameRe.exec(token.content)
|
||||
if (!anchorMatch || anchorMatch.length === 0) {
|
||||
continue
|
||||
}
|
||||
|
||||
const anchorIdOrName = anchorMatch[1]
|
||||
if (anchorMatch[1] === undefined) {
|
||||
continue
|
||||
}
|
||||
|
||||
const anchorHTMLFragment = "#" + anchorIdOrName
|
||||
if (!result.includes(anchorHTMLFragment)) {
|
||||
result.push(anchorHTMLFragment)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
filterTokens,
|
||||
convertHeadingToHTMLFragment,
|
||||
getMarkdownHeadings,
|
||||
getMarkdownAnchorHTMLFragments,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user