-
Notifications
You must be signed in to change notification settings - Fork 422
/
template-wrapper.nunjucks.js
59 lines (53 loc) · 1.77 KB
/
template-wrapper.nunjucks.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
'use strict';
const React = require('react');
const chain = require('ramda/src/chain');
const toReactComponent = require('jsonml-to-react-component');
const exist = require('exist.js');
const NotFound = require('{{ themePath }}/template/NotFound');
const data = require('./data.js');
const NProgress = require('nprogress');
require('nprogress/nprogress.css');
const plugins = data.plugins;
const converters = chain((plugin) => plugin.converters || [], plugins);
const utils = {
get: exist.get,
toReactComponent(jsonml) {
return toReactComponent(jsonml, converters);
},
};
plugins.map((plugin) => plugin.utils || {})
.forEach((u) => Object.assign(utils, u));
function calcPropsPath(dataPath, params) {
return Object.keys(params).reduce(
(path, param) => path.replace(`:${param}`, params[param]),
dataPath
);
}
function hasParams(dataPath) {
return dataPath.split('/').some((snippet) => snippet.startsWith(':'));
}
function defaultCollect(nextProps, callback) {
callback(null, nextProps);
}
module.exports = function templateWrapper(template, dataPath = '') {
const Template = require(`{{ themePath }}/${template.replace(/^\.\//, '')}`);
return (nextState, callback) => {
const propsPath = calcPropsPath(dataPath, nextState.params);
const pageData = exist.get(data.markdown, propsPath.split('/').slice(1));
const collect = Template.collect || defaultCollect;
collect(Object.assign({}, nextState, {
data: data.markdown,
pageData,
utils,
}), (err, nextProps) => {
callback(err, (props) => {
NProgress.done();
return React.createElement(
!hasParams(dataPath) || pageData ?
Template.default || Template : NotFound,
Object.assign({}, props, nextProps)
);
});
});
};
};