view-markdown.js 2.4 KB
/**
 * view-markdown
 * Created by lintry on 2018/1/9.
 */

const path = require('path'),
    fs = require('fs-extra'),
    ejs = require('ejs'),
    juice = require('juice');


class ViewMarkdown {
    /**
     * 初始化markdown
     * @param doc_path 文档所在路径
     * @param options toc: 是否显示TOC default_md: 默认markdown文件名 theme: 默认主题 relative_path: css的相对路径(便于输出html)
     */
    constructor (doc_path, options) {
        this.options = options || {};
        if (!doc_path) {
            throw new Error('document path for markdown not found')
        }

        this.doc_path = doc_path;
        this.mdviewer = new (require('./mdviewer'))({parseTokens: true, toc: this.options.toc});
    }

    /**
     * 渲染文件
     * @param filename 文件名,绝对路径
     * @param theme 主题
     * @param resource_base 资源根路径
     * @return {string}
     */
    render (filename, theme, resource_base) {
        resource_base = resource_base || '';
        const options = this.options;
        //默认md
        if (!filename || filename.match(/.+\/$/)) {
            filename = (filename || '') + (options.default_md || 'readme.md')
        }
        let file = path.resolve(this.doc_path, filename);
        if (!path.parse(file).ext) {
            //追加后缀
            file += '.md'
        }
        let result = this.mdviewer.renderFile(file);
        let tittle = result.tokens && result.tokens[1] && result.tokens[1].content || filename;
        theme = theme || options.theme || '';
        let content = result.status === 404 ? this.mdviewer.render(`
# 404
> **${filename}不存在**
`)
            : result.html;

        let inline = this.options.inline;
        const template = fs.readFileSync(path.resolve(process.cwd(), (inline) ? 'src/inline-index.ejs' : 'src/index.ejs'), 'utf8');
        let html = ejs.render(template, {
            tittle,
            theme,
            content,
            resource_base
        }, {
            root: process.cwd()
        });

        if (inline) {
            let css = [
                fs.readFileSync(path.resolve(process.cwd(), 'themes/markdown.css'), 'utf8'),
                fs.readFileSync(path.resolve(process.cwd(), 'themes', theme, theme + '.css'), 'utf8')
            ].join('\n');
            html = juice.inlineContent(html, css);
        }

        return html

    }
}

module.exports = ViewMarkdown;