-
Notifications
You must be signed in to change notification settings - Fork 24
/
index.js
337 lines (297 loc) · 10.8 KB
/
index.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
'use strict';
const Translator = require('./lib/translator');
const HandlebarsRenderer = require('@bigcommerce/stencil-paper-handlebars');
/**
* processor is an optional function to apply during template assembly. The
* templates parameter is a object where the keys are paths and the values are the
* raw templates. The function returns an object of the same format, possibly changing
* the values. We use this to precompile templates within the Paper module.
*
* @callback processor
* @param {Object} templates - Object that contains the gathered templates
*/
/**
* Assembler.getTemplates assembles all the templates required to render the given
* top-level template.
*
* @callback assemblerGetTemplates
* @param {string} path - The path to the templates, relative to the templates directory
* @param {processor} processor - An optional processor to apply to each template during assembly
* @return {Promise} A promise to return the (optionally processed) templates
*/
/**
* Assembler.getTranslations assembles all the translations for the theme.
*
* @callback assemblerGetTranslations
* @return {Promise} A promise to return the translations
*/
class Paper {
/**
* Paper constructor. In addition to store settings and theme settings (configuration),
* paper expects to be passed an assembler to gather all the templates required to render
* the top level template.
*
* @param {Object} siteSettings - Site settings
* @param {Object} themeSettings - Theme settings (configuration)
* @param {Object} assembler - Assembler with getTemplates and getTranslations methods.
* @param {assemblerGetTemplates} assembler.getTemplates - Method to assemble templates
* @param {assemblerGetTranslations} assembler.getTranslations - Method to assemble translations
* @param {String} rendererType - One of ['handlebars-v3', 'handlebars-v4']
* @param {Object} logger - a console-like logger object
* @param {String} logLevel - log level used by handlebars logger (debug, info, warning, error)
* @param {Object} params - Request-level parameters, part of stencil context
*/
constructor(siteSettings, themeSettings, assembler, rendererType, logger = console, logLevel = 'info', params = {}) {
this._assembler = assembler || {};
// Build renderer based on type
switch(rendererType) {
case 'handlebars-v4':
this.renderer = new HandlebarsRenderer(siteSettings, themeSettings, 'v4', logger, logLevel, params);
break;
case 'handlebars-v3':
default:
this.renderer = new HandlebarsRenderer(siteSettings, themeSettings, 'v3', logger, logLevel, params);
break;
}
this.preProcessor = this.getPreProcessor();
this.logger = logger;
}
/**
* Get the current renderer instance.
*
* @returns An instance of HandlebarsRenderer
*/
getRenderer() {
return this.renderer;
}
/**
* Get the siteSettings object containing global site settings.
*
* @return {object} settings An object containing global site settings.
*/
getSiteSettings() {
return this.renderer.getSiteSettings();
};
/**
* Set the siteSettings object containing global site settings.
*
* @param {object} settings An object containing global site settings.
*/
setSiteSettings(settings) {
this.renderer.setSiteSettings(settings);
};
/**
* Get the themeSettings object containing the theme configuration.
*
* @return {object} settings An object containing the theme configuration.
*/
getThemeSettings() {
return this.renderer.getThemeSettings();
};
/**
* Set the themeSettings object containing the theme configuration.
*
* @param {object} settings An object containing the theme configuration.
*/
setThemeSettings(settings) {
this.renderer.setThemeSettings(settings);
};
/**
* Get the requestParams object containing the request parameters
*
* @return {object} requestParams An object containing the request parameters
*/
getRequestParams() {
return this.renderer.getRequestParams();
};
/**
* Set the requestParams object containing the request parameters
*
* @param {object} params An object containing the request parameters
*/
setRequestParams(params) {
this.renderer.setRequestParams(params);
};
/**
* Reset decorator list.
*/
resetDecorators() {
this.renderer.resetDecorators();
};
/**
* Add a decorator to wrap output during render().
*
* @param {Function} decorator
*/
addDecorator(decorator) {
this.renderer.addDecorator(decorator);
};
/**
* Get page content.
*
* @return {Object} Regions with widgets
*/
getContent() {
return this.renderer.getContent();
};
/**
* Add content to be rendered in the given regions.
*
* @param {Object} Regions with widgets
*/
setContent(regions) {
this.renderer.setContent(regions);
};
/**
* Use the assembler to fetch partials/templates, and translations, then load them
* into the renderer.
*
* @param {String|Array} paths A string or array of strings - the template path(s) to load.
* @param {String} acceptLanguage The accept-language header - used to select a locale.
* @return {Promise} Promise to load the templates and translations into the renderer.
*/
loadTheme(paths, acceptLanguage) {
if (!Array.isArray(paths)) {
paths = paths ? [paths] : [];
}
const promises = [];
promises.push(this.loadTranslations(acceptLanguage));
paths.forEach(path => {
promises.push(this.loadTemplates(path));
});
return Promise.all(promises);
}
/**
* Use the assembler to fetch partials/templates, then load them
* into the renderer.
*
* @param {String} path The root template path to load. All dependencies will be loaded as well.
* @return {Promise} Promise to load the templates into the renderer.
*/
loadTemplates(path) {
return this._assembler.getTemplates(path, this.preProcessor).then(templates => {
return this.renderer.addTemplates(templates);
});
}
addTemplates(templates) {
return this.renderer.addTemplates(templates);
}
getPreProcessor() {
return this.renderer.getPreProcessor();
}
/**
* Is the given template loaded?
*
* @param {String} path The path to the template file
* @return {Boolean} is the given template loaded?
*/
isTemplateLoaded(path) {
return this.renderer.isTemplateLoaded(path);
}
/**
* Load translation files and give a translator to renderer.
*
* @param {String} acceptLanguage The accept-language header, used to select a locale
* @return {Promise} Promise to load the translations into the renderer.
*/
loadTranslations(acceptLanguage) {
return this._assembler.getTranslations().then(translations => this.addTranslations(translations, acceptLanguage));
};
addTranslations(translations, acceptLanguage) {
const translator = Translator.create(acceptLanguage, translations, this.logger);
this.renderer.setTranslator(translator);
return translations;
}
/**
* Render a string with the given context.
*
* @param {String} string
* @param {Object} context
* @return {Promise} A promise to return the rendered text
* @throws [CompileError|RenderError]
*/
renderString(string, context) {
return this.renderer.renderString(string, context);
}
/**
* Renders a template with the given context
*
* @param {String} path The path to the template
* @param {Object} context The context to provide to the template
* @return {Promise} A promise to return the rendered template
* @throws [TemplateNotFoundError|RenderError|DecoratorError]
*/
render(path, context) {
return this.renderer.render(path, context);
}
/**
* Theme rendering logic. This is used by Stencil CLI.
*
* @param {String|Array} templatePath A single template or list of templates to render.
* @param {Object} data
* @return {Promise} A promise that returns a {String|Object} depending on whether multiple templates were rendered
* @throws [TemplateNotFoundError|RenderError|DecoratorError]
*/
renderTheme(templatePath, data) {
// Simple case of a single non-ajax template
if (!data.remote && !Array.isArray(templatePath)) {
return this.render(templatePath, data.context);
}
// If no template path provided, just return the remote data
if (!templatePath) {
return Promise.resolve({ data: data.remote_data });
}
// If ajax request, merge remote_data into context
if (data.remote) {
data.context = Object.assign({}, data.context, data.remote_data);
}
const renderPromises = [];
let result;
if (Array.isArray(templatePath)) {
// If templatePath is an array (multiple templates using render_with option),
// compile all the template required files into an object
result = {};
for (let i = 0; i < templatePath.length; i++) {
const path = templatePath[i];
renderPromises.push(this.render(path, data.context).then(html => {
result[path] = html;
}));
}
} else {
renderPromises.push(this.render(templatePath, data.context).then(html => {
result = html;
}));
}
return Promise.all(renderPromises).then(() => {
// Remote requests get both the remote data & rendered html
if (data.remote) {
result = {
data: data.remote_data,
content: result
};
}
return result;
});
}
/**
* Get resource hints produced by rendering process.
* If any helper included in the theme/template/string was
* configured to produce a resource hint, then,
* AFTER A SUCCESSFUL rendering, this getter may be called.
*
* Objects in the returned array will contain following properties:
* 1. `src: String`
* 1. `state: String`
*
* and MAY contain all or some of the following optional properties:
* 1. `type: String`
* 1. `cors: String`
*
* For more details check https://github.com/bigcommerce/paper-handlebars/blob/master/helpers/lib/resourceHints.js
* @returns {Object[]}
*/
getResourceHints() {
return this.renderer.getResourceHints();
}
}
module.exports = Paper;