/
template.js
315 lines (252 loc) · 8.93 KB
/
template.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
Copyright 2014-2019 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/** @module lib/template */
const _ = require('lodash');
const beautify = require('js-beautify').html;
const config = require('./config');
const deepExtend = require('deep-extend');
const handlebars = require('handlebars');
const handlebarsLayouts = require('handlebars-layouts');
const loader = require('./loader');
const { lsSync } = require('@jsdoc/core').fs;
const MessageFormat = require('messageformat');
const logger = require('jsdoc/util/logger');
const path = require('path');
const { readFileSync } = require('fs');
const yaml = require('js-yaml');
// Maximum file size that we'll try to beautify.
const MAX_BEAUTIFY_SIZE = 1024 * 128;
function loadYaml(filepath) {
let parsedObject;
try {
if (filepath) {
parsedObject = yaml.load(readFileSync(filepath, 'utf8'));
}
} catch (e) {
logger.fatal('Unable to load the file %s: %s', filepath, e);
}
return parsedObject;
}
function basenameWithoutExtension(filepath) {
const basename = path.basename(filepath);
return basename.replace(path.extname(basename), '');
}
/**
* Log a message about the template. Maps JSDoc's built-in logger to Handlebars' logger.
*
* @param {string} level - The logging level. May contain one of `DEBUG`, `INFO`, `WARN`, `ERROR`,
* or `FATAL`.
* @private
*/
function log(level, message) {
let logMethod = level.toLowerCase();
if (!logger[logMethod]) {
logMethod = 'info';
}
logger[logMethod](message);
}
module.exports = class Template {
constructor(conf) {
this.config = conf;
this.cssClasses = config.readJsonSync(conf.cssClassMap);
this.encoding = this.config.encoding;
this.locale = this.config.locale;
this.ids = {};
this._l10nData = null;
this._l10nFormatter = null;
this.path = this.config.templatePath;
this.views = {};
this._handlebarsInit()
._l10nInit();
logger.debug('Initialized the template in %s with config: %j', this.path, this.config);
}
/**
* Set up Handlebars to use the appropriate views, helper functions, and translation strings.
*
* @private
* @returns {this}
*/
_handlebarsInit() {
let helpers = this.config.helpers;
const self = this;
function addInternalHelpers(modulePath) {
const helperModule = require(path.resolve(self.path, modulePath));
const instance = helperModule(self);
Object.keys(instance).forEach(key => {
handlebars.registerHelper(key, instance[key]);
});
}
if (!Array.isArray(helpers)) {
helpers = [helpers];
}
// add external helpers
handlebarsLayouts.register(handlebars);
// add Baseline helpers
helpers.forEach(addInternalHelpers, this);
handlebars.log = log;
this._loadViews();
return this;
}
/**
* Load, compile, and register the Handlebars views, including layouts and partials.
*
* @returns {this}
*/
_loadViews() {
let layouts = [];
let partials = [];
this.config.views.layouts.forEach(filepath => {
layouts = layouts.concat(lsSync(path.resolve(this.path, filepath), 0));
});
this._addLayouts(layouts);
// load the partials (handlebars-layouts requires that we also load the layouts as partials)
this.config.views.partials.forEach(filepath => {
partials = partials.concat(lsSync(path.resolve(this.path, filepath), 0));
});
this._addPartials(partials.concat(layouts));
return this;
}
/**
* Load the string resources and formatters used for localization.
*
* @private
* @returns {this}
*/
_l10nInit() {
const l10nData = [];
let l10nFiles;
try {
l10nFiles = lsSync(this.config.l10n, 0);
} catch (e) {
logger.fatal(`Unable to find the localization data file ${this.config.l10nFile}`);
return this;
}
l10nFiles.forEach(filepath => {
l10nData.push(loadYaml(filepath));
});
// Merge the objects in reverse order so that the first one loaded wins.
this._l10nData = deepExtend.apply(deepExtend, l10nData.reverse());
this._l10nFormatter = new MessageFormat(this.locale).compile(this._l10nData);
return this;
}
/**
* Add layouts to the template.
*
* @private
* @param {Array.<string>} layouts - The paths to the layouts.
* @returns {this}
*/
_addLayouts(layouts) {
layouts.forEach(layout => {
const name = basenameWithoutExtension(layout);
logger.debug('Adding the layout "%s"', name);
this._loadAndCompileLayout(name, layout);
});
return this;
}
/**
* Add partials to the template. Partials are views that can be embedded within other views.
*
* @private
* @param {(Array.<string>|Object)} partials - The paths to the partials, or an object containing
* the partials.
* @returns {this}
*/
_addPartials(partials) {
let partialsObject;
if (!Array.isArray(partials)) {
partialsObject = partials;
} else {
partialsObject = {};
partials.forEach(partial => {
const name = basenameWithoutExtension(partial);
partialsObject[name] = this._loadAndCompilePartial(name, partial);
});
}
logger.debug('Adding all partials to Handlebars');
handlebars.registerPartial(partialsObject);
}
// Load and compile the layout. We can't lazily load these, because Handlebars doesn't allow you
// to provide a custom loader.
_loadAndCompileLayout(layoutName, filepath) {
let templateString;
// skip this layout if we've already compiled a view with the same name
if (!{}.hasOwnProperty.call(this.views, layoutName)) {
templateString = loader.loadSync(filepath, 'utf8');
this.views[layoutName] = handlebars.compile(templateString);
}
}
// Load and compile the partial. We can't lazily load these, because Handlebars doesn't allow
// you to provide a custom loader.
_loadAndCompilePartial(partialName, filepath) {
let templateString;
let view;
// Skip this partial if we've already compiled a view with the same name.
if ({}.hasOwnProperty.call(this.views, partialName)) {
view = this.views[partialName];
} else {
templateString = loader.loadSync(filepath, 'utf8');
view = this.views[partialName] = handlebars.compile(templateString);
}
return view;
}
render(viewName, data, options) {
let beautifyOptions;
const i18nData = {
locales: this.config.locale
};
let rendered;
if (!{}.hasOwnProperty.call(this.views, viewName)) {
logger.fatal('The view "%s" is unknown. Cannot render output.', viewName);
return '';
}
options = options || {};
data.intl = i18nData;
rendered = this.views[viewName](data);
if (options.beautify !== false) {
/* eslint-disable camelcase */
beautifyOptions = {
indent_size: 2,
// js-beautify ignores the value 0 because it's falsy
max_preserve_newlines: 0.1
};
/* eslint-enable camelcase */
if (rendered.length < MAX_BEAUTIFY_SIZE) {
rendered = beautify(rendered, beautifyOptions);
}
}
return rendered;
}
translate(key, opts) {
const formatter = _.get(this._l10nFormatter, key);
let options;
let translation;
if (!formatter) {
logger.warn('Unable to find a localized string for the key %s', key);
return '';
}
if (typeof opts === 'number') {
options = {
items: opts
};
} else {
options = opts || {};
if (typeof options.items === 'undefined') {
options.items = 1;
}
}
translation = formatter(options);
// Remove the trailing newline, if present.
return translation.replace(/\n$/, '');
}
};