summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/models/SummaryArticle.js
blob: 80ef5aebe78447a7a395c556033702ef5347afef (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const url = require('url');
const path = require('path');
const { Record, List } = require('immutable');
const File = require('./File');

const OUTPUT_EXTENSION = '.html';

const DEFAULTS = {
    title:    '',
    depth:    0,
    path:     '',
    ref:      '',
    level:    '',
    articles: List()
};

class SummaryArticle extends Record(DEFAULTS) {
    constructor(article) {
        super({
            ...article,
            articles: (new List(article.articles))
                .map(art => new SummaryArticle(art))
        });
    }

    /**
     * Return url for a file in a GitBook context.
     * @param {Context} context
     * @return {String} url
     */
    toURL(context) {
        const { readme } = context.getState();
        const fileReadme = readme.file;
        const parts = url.parse(this.ref);

        if (parts.protocol) {
            return this.ref;
        }

        const file = new File(parts.pathname);
        let filePath = file.toURL(context);

        // Change extension and resolve to .html
        if (
            path.basename(filePath, path.extname(filePath)) == 'README' ||
            (fileReadme && filePath == fileReadme.path)
        ) {
            filePath = path.join(path.dirname(filePath), 'index' + OUTPUT_EXTENSION);
        } else {
            filePath = path.basename(filePath, path.extname(filePath)) + OUTPUT_EXTENSION;
        }

        return filePath + (parts.hash || '');
    }

    /**
     * Return true if article is an instance of SummaryArticle
     * @param {Mixed} article
     * @return {Boolean}
     */
    static is(article) {
        return (article instanceof SummaryArticle);
    }
}

module.exports = SummaryArticle;