@alauda/doom
Version:
Doctor Doom making docs.
45 lines (44 loc) • 1.62 kB
JavaScript
import { toString } from 'mdast-util-to-string';
import { lintRule } from 'unified-lint-rule';
import { visitParents } from 'unist-util-visit-parents';
import { parse } from 'yaml';
export const titleRequired = lintRule('doom-lint:title-required', (root, vfile) => {
let frontmatterTitle;
let headingTitle;
visitParents(root, (node, parents) => {
if (node.type === 'yaml') {
frontmatterTitle = parse(node.value)
?.title;
}
function checkHeadingTitle(title) {
if (headingTitle) {
vfile.message('Multiple level 1 headings found, remove redundant heading or consolidate them into one.', {
ancestors: [...parents, node],
place: node.position,
});
}
else {
headingTitle = title;
}
}
if (node.type === 'heading') {
if (node.depth === 1) {
checkHeadingTitle(toString(node));
}
}
else if (node.type === 'html') {
for (const [, title] of node.value.matchAll(/<h1[^>]*>([\s\S]*?)<\/h1>/gi)) {
checkHeadingTitle(title);
}
}
else if (node.type === 'mdxJsxFlowElement' ||
node.type === 'mdxJsxTextElement') {
if (node.name === 'h1') {
checkHeadingTitle(toString(node));
}
}
});
if (!frontmatterTitle && !headingTitle) {
vfile.message('Title is required. Please add a title in the frontmatter or as a heading.', root);
}
});