summaryrefslogtreecommitdiffstats
path: root/packages/gitbook/src/parse/glossaryFromDocument.js
blob: 4b5bf3da142945a6a55007d5024941b004038324 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const { BLOCKS } = require('markup-it');
const Glossary = require('../models/glossary');

/**
 * Return true if a node is a entry title.
 * @param  {Node} node
 * @return {Boolean}
 */
const isTitle = node => node.type == BLOCKS.HEADING_2;

/**
 * Return true if a node is a entry description.
 * @param  {Node} node
 * @return {Boolean}
 */
const isDescription = node => node.type !== BLOCKS.HEADING_2 && node.type !== BLOCKS.CODE;

/**
 * Parse a readme from a document.
 * @param  {Document} document
 * @return {Readme} readme
 */
function glossaryFromDocument(document) {
    const { nodes } = document;
    const entries = [];

    nodes.forEach((block, i) => {
        const next = nodes.get(i);

        if (isTitle(block)) {
            entries.push({
                name:        block.text,
                description: (next && isDescription(next)) ? next.text : ''
            });
        }
    });


    return Glossary.createFromEntries(entries);
}

module.exports = glossaryFromDocument;