2019-07-20 23:13:10 +02:00
|
|
|
const { shim } = require('lib/shim.js');
|
|
|
|
const { time } = require('lib/time-utils.js');
|
|
|
|
const Mustache = require('mustache');
|
|
|
|
|
|
|
|
const TemplateUtils = {};
|
|
|
|
|
|
|
|
|
|
|
|
// Mustache escapes strings (including /) with the html code by default
|
|
|
|
// This isn't useful for markdown so it's disabled
|
2019-07-29 15:43:53 +02:00
|
|
|
Mustache.escape = text => {
|
|
|
|
return text;
|
|
|
|
};
|
2019-07-20 23:13:10 +02:00
|
|
|
|
|
|
|
TemplateUtils.render = function(input) {
|
2019-08-29 18:35:43 +02:00
|
|
|
// new template variables can be added here
|
|
|
|
// If there are too many, this should be moved to a new file
|
|
|
|
// view needs to be set in this function so that the formats reflect settings
|
|
|
|
const view = {
|
|
|
|
date: time.formatMsToLocal(new Date().getTime(), time.dateFormat()),
|
|
|
|
time: time.formatMsToLocal(new Date().getTime(), time.timeFormat()),
|
|
|
|
datetime: time.formatMsToLocal(new Date().getTime()),
|
|
|
|
custom_datetime: () => {
|
|
|
|
return (text, render) => {
|
|
|
|
return render(time.formatMsToLocal(new Date().getTime(), text));
|
|
|
|
};
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
2019-07-20 23:13:10 +02:00
|
|
|
return Mustache.render(input, view);
|
2019-07-29 15:43:53 +02:00
|
|
|
};
|
2019-07-20 23:13:10 +02:00
|
|
|
|
|
|
|
TemplateUtils.loadTemplates = async function(filePath) {
|
2019-07-29 15:43:53 +02:00
|
|
|
let templates = [];
|
|
|
|
let files = [];
|
|
|
|
|
|
|
|
if (await shim.fsDriver().exists(filePath)) {
|
|
|
|
try {
|
|
|
|
files = await shim.fsDriver().readDirStats(filePath);
|
|
|
|
} catch (error) {
|
|
|
|
let msg = error.message ? error.message : '';
|
2019-09-19 23:51:18 +02:00
|
|
|
msg = `Could not read template names from ${filePath}\n${msg}`;
|
2019-07-29 15:43:53 +02:00
|
|
|
error.message = msg;
|
|
|
|
throw error;
|
2019-07-20 23:13:10 +02:00
|
|
|
}
|
|
|
|
|
2019-08-29 18:34:54 +02:00
|
|
|
// Make sure templates are always in the same order
|
|
|
|
// sensitivity ensures that the sort will ignore case
|
|
|
|
files.sort((a, b) => { return a.path.localeCompare(b.path, undefined, {sensitivity: 'accent'}); });
|
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
files.forEach(async file => {
|
|
|
|
if (file.path.endsWith('.md')) {
|
|
|
|
try {
|
2019-09-19 23:51:18 +02:00
|
|
|
let fileString = await shim.fsDriver().readFile(`${filePath}/${file.path}`, 'utf-8');
|
2019-07-29 15:43:53 +02:00
|
|
|
templates.push({ label: file.path, value: fileString });
|
|
|
|
} catch (error) {
|
|
|
|
let msg = error.message ? error.message : '';
|
2019-09-19 23:51:18 +02:00
|
|
|
msg = `Could not load template ${file.path}\n${msg}`;
|
2019-07-29 15:43:53 +02:00
|
|
|
error.message = msg;
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2019-07-20 23:13:10 +02:00
|
|
|
}
|
|
|
|
|
2019-07-29 15:43:53 +02:00
|
|
|
return templates;
|
|
|
|
};
|
|
|
|
|
2019-07-20 23:13:10 +02:00
|
|
|
module.exports = TemplateUtils;
|