summaryrefslogtreecommitdiffstats
path: root/packages/gitbook-core/src/models/File.js
blob: 6f44700c982fecfebfd151fb0ecd264926358610 (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
const path = require('path');
const { Record } = require('immutable');

const DEFAULTS = {
    type:  '',
    mtime: new Date(),
    path:  ''
};

class File extends Record(DEFAULTS) {
    constructor(file = {}) {
        if (typeof file === 'string') {
            file = { path: file };
        }

        super({
            ...file,
            mtime: new Date(file.mtime)
        });
    }

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

        return path.relative(
            path.dirname(file.path),
            this.path
        );
    }

    static is(file) {
        return (file instanceof File);
    }

    static create(file) {
        return file instanceof File ?
            file : new File(file);
    }
}

module.exports = File;