summaryrefslogtreecommitdiffstats
path: root/lib/page/index.js
blob: f0d7f57fb2c9b3eed25c886ff5bd16e0aefe8e7b (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
var _ = require('lodash');
var path = require('path');
var direction = require('direction');
var fm = require('front-matter');

var error = require('../utils/error');
var pathUtil = require('../utils/path');
var location = require('../utils/location');
var parsers = require('../parsers');
var pluginCompatibility = require('../plugins/compatibility');
var HTMLPipeline = require('./html');

/*
A page represent a parsable file in the book (Markdown, Asciidoc, etc)
*/

function Page(book, filename) {
    if (!(this instanceof Page)) return new Page(book, filename);
    var extension;
    _.bindAll(this);

    this.book = book;
    this.log = this.book.log;

    // Map of attributes from YAML frontmatter
    // Description is also extracted by default from content
    this.attributes = {};

    // Current content
    this.content = '';

    // Relative path to the page
    this.path = location.normalize(filename);

    // Absolute path to the page
    this.rawPath = this.book.resolve(filename);

    // Last modification date
    this.mtime = 0;

    // Can we parse it?
    extension = path.extname(this.path);
    this.parser = parsers.getByExt(extension);
    if (!this.parser) throw error.ParsingError(new Error('Can\'t parse file "'+this.path+'"'));

    this.type = this.parser.name;
}

// Return the filename of the page with another extension
// "README.md" -> "README.html"
Page.prototype.withExtension = function(ext) {
    return pathUtil.setExtension(this.path, ext);
};

// Resolve a filename relative to this page
// It returns a path relative to the book root folder
Page.prototype.resolveLocal = function() {
    var dir = path.dirname(this.path);
    var file = path.join.apply(path, _.toArray(arguments));

    return location.toAbsolute(file, dir, '');
};

// Resolve a filename relative to this page
// It returns an absolute path for the FS
Page.prototype.resolve = function() {
    return this.book.resolve(this.resolveLocal.apply(this, arguments));
};

// Convert an absolute path (in the book) to a relative path from this page
Page.prototype.relative = function(name) {
    // Convert /test.png -> test.png
    name = location.toAbsolute(name, '', '');

    return location.relative(
        this.resolve('.') + '/',
        this.book.resolve(name)
    );
};

// Return a page result of a relative page from this page
Page.prototype.followPage = function(filename) {
    var absPath = this.resolveLocal(filename);
    return this.book.getPage(absPath);
};

// Update content of the page
Page.prototype.update = function(content) {
    this.content = content;
};

// Read the page as a string
Page.prototype.read = function() {
    var that = this;

    return this.book.statFile(this.path)
    .then(function(stat) {
        that.mtime = stat.mtime;
        return that.book.readFile(that.path);
    })
    .then(this.update);
};

// Return templating context for this page
// This is used both for themes and page parsing
Page.prototype.getContext = function() {
    var article = this.book.summary.getArticle(this);
    var next = article? article.next() : null;
    var prev = article? article.prev() : null;

    // Detect text direction in this page
    var dir = this.book.config.get('direction');
    if (!dir) {
        dir = direction(this.content);
        if (dir == 'neutral') dir = null;
    }

    return {
        file: {
            path: this.path,
            mtime: this.mtime,
            type: this.type
        },
        page: _.extend({}, this.attributes, {
            title: article? article.title : null,
            next: next? next.getContext() : null,
            previous: prev? prev.getContext() : null,
            level: article? article.level : null,
            depth: article? article.depth() : 0,
            content: this.content,
            dir: dir
        })
    };
};

// Return complete context for templating (page + book + summary + ...)
Page.prototype.getOutputContext = function(output) {
    return _.extend({}, this.getContext(), output.getContext());
};

// Parse the page and return its content
Page.prototype.toHTML = function(output) {
    var that = this;

    this.log.debug.ln('start parsing file', this.path);

    // Call a hook in the output
    // using an utility to "keep" compatibility with gitbook 2
    function hook(name) {
        return pluginCompatibility.pageHook(that, function(ctx) {
            return output.plugins.hook(name, ctx);
        })
        .then(function(result) {
            if(_.isString(result)) that.update(result);
        });
    }

    return this.read()

    // Parse yaml front matter
    .then(function() {
        var parsed = fm(that.content);

        // Extract attributes
        that.attributes = parsed.attributes;

        // Keep only the body
        that.update(parsed.body);
    })

    .then(function() {
        return hook('page:before');
    })

    // Pre-process page with parser
    .then(function() {
        return that.parser.page.prepare(that.content)
        .then(that.update);
    })

    // Render template
    .then(function() {
        return output.template.render(that.content, that.getOutputContext(output), {
            path: that.path
        })
        .then(that.update);
    })

    // Render markup using the parser
    .then(function() {
        return that.parser.page(that.content)
        .then(function(out) {
            that.update(out.content);
        });
    })

    // Post process templating
    .then(function() {
        return output.template.postProcess(that.content)
        .then(that.update);
    })

    // Normalize HTML output
    .then(function() {
        var pipelineOpts = {
            onRelativeLink: _.partial(output.onRelativeLink, that),
            onImage: _.partial(output.onOutputImage, that),
            onOutputSVG: _.partial(output.onOutputSVG, that),

            // Use 'code' template block
            onCodeBlock: function(source, lang) {
                return output.template.applyBlock('code', {
                    body: source,
                    kwargs: {
                        language: lang
                    }
                });
            },

            // Extract description from page's content if no frontmatter
            onDescription: function(description) {
                if (that.attributes.description) return;
                that.attributes.description = description;
            },

            // Convert glossary entries to annotations
            annotations: that.book.glossary.annotations()
        };
        var pipeline = new HTMLPipeline(that.content, pipelineOpts);

        return pipeline.output()
        .then(that.update);
    })

    .then(function() {
        return hook('page');
    })

    // Return content itself
    .then(function() {
        return that.content;
    });
};


module.exports = Page;