build(aio): capture all the headings from a doc in the vFile.headings property

This commit is contained in:
Peter Bacon Darwin 2017-07-04 12:57:22 +01:00 committed by Pete Bacon Darwin
parent 062a7aa2cf
commit 3a0886dc12
2 changed files with 15 additions and 9 deletions

View File

@ -1,22 +1,28 @@
const visit = require('unist-util-visit'); const visit = require('unist-util-visit');
const is = require('hast-util-is-element'); const is = require('hast-util-is-element');
const source = require('unist-util-source');
const toString = require('hast-util-to-string'); const toString = require('hast-util-to-string');
const filter = require('unist-util-filter'); const filter = require('unist-util-filter');
module.exports = function h1CheckerPostProcessor() { module.exports = function h1CheckerPostProcessor() {
return (ast, file) => { return (ast, file) => {
let h1s = []; file.headings = {
h1: [],
h2: [],
h3: [],
h4: [],
h5: [],
h6: [],
hgroup: []
};
visit(ast, node => { visit(ast, node => {
if (is(node, 'h1')) { if (is(node, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup'])) {
h1s.push(node); file.headings[node.tagName].push(getText(node));
file.title = getText(node);
} }
}); });
if (h1s.length > 1) { file.title = file.headings.h1[0];
const h1Src = h1s.map(node => source(node, file)).join(', '); if (file.headings.h1.length > 1) {
file.fail(`More than one h1 found [${h1Src}]`); file.fail(`More than one h1 found in ${file}`);
} }
}; };
}; };

View File

@ -23,7 +23,7 @@ describe('h1Checker postprocessor', () => {
<h1>Heading 1a</h1> <h1>Heading 1a</h1>
` `
}; };
expect(() => processor.$process([doc])).toThrowError(createDocMessage('More than one h1 found [<h1>Heading 1, <h1>Heading 1a</h1>]', doc)); expect(() => processor.$process([doc])).toThrowError(createDocMessage('More than one h1 found in ' + doc.renderedContent, doc));
}); });
it('should not complain if there is exactly one h1 in a document', () => { it('should not complain if there is exactly one h1 in a document', () => {