/
renderDirectoryResourceHtml.js
69 lines (61 loc) · 2.02 KB
/
renderDirectoryResourceHtml.js
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
import fs from 'fs';
import getShortDescription from './getShortDescription.js';
import createScriptManager from './createScriptManager.js';
import jstransformer from 'jstransformer';
import jstransformerMarked from 'jstransformer-marked';
import path from 'path';
import pug from 'pug';
import moment from 'moment';
const cache = {};
const marked = jstransformer(jstransformerMarked);
export default async function renderDirectoryResourceHtml(directoryResource, {resourceTree, variant}) {
let pugPaths = [
path.join(directoryResource.physicalPath, '_index.pug'),
path.join(directoryResource.physicalPath, 'index.pug')
];
let pugPath = pugPaths.find(path => fs.existsSync(path));
if (!pugPath){
throw new Error('directory has no _index.pug or index.pug');
}
let scriptManager = createScriptManager();
let opts = {
plugins: [{
read: readFile
}],
filters: {
'register-script': function (text, options) {
let {src, filename} = options;
let scriptFile = path.resolve(path.dirname(filename), src);
scriptManager.registerScript(scriptFile);
return '';
}
}
};
let renderHtml = pug.compileFile(pugPath, opts);
let locals = {
...directoryResource.data,
variant,
current: {path: [...directoryResource.id.split('/').filter(Boolean)]},
public: resourceTree,
nocms: {
renderShortDescription: function(href) {
let sitePathBacktrack = directoryResource.id.split('/').filter(Boolean).map(d => '..').join('/');
let sitePath = path.join(directoryResource.physicalPath, sitePathBacktrack);
let filePath = path.join(sitePath, href);
let file = readFile(filePath);
let shortDescription = getShortDescription(file);
return marked.render(shortDescription).body;
},
moment
}
};
let html = renderHtml(locals);
html = scriptManager.embedRegisteredScripts(html);
return html;
}
function readFile(filename) {
if (process.env.NODE_ENV === 'production') {
return cache[filename] || (cache[filename] = fs.readFileSync(filename, 'utf8'));
}
return fs.readFileSync(filename, 'utf8');
}