-
Notifications
You must be signed in to change notification settings - Fork 6
/
media.js
344 lines (301 loc) · 10.1 KB
/
media.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
338
339
340
341
342
343
344
'use strict';
const _ = require('lodash'),
path = require('path'),
files = require('nymag-fs'),
bluebird = require('bluebird'),
setup = require('./setup'),
styleguide = require('./styleguide'),
STYLE_TAG = 'style',
SCRIPT_TAG = 'scripts',
MEDIA_DIRECTORY = path.join(process.cwd(), 'public');
/**
* @param {string} str
* @returns {number}
*/
function findBottom(str) {
var index = str.lastIndexOf('</body>');
if (index === -1) {
index = str.lastIndexOf('</');
}
return index;
}
/**
* @param {string} str
* @returns {number}
*/
function findTop(str) {
var index = str.indexOf('</head>');
if (index === -1) {
index = str.indexOf('>') + 1;
}
return index;
}
/**
* Put items at index in the very large target string.
*
* @param {string} str
* @param {number} index
* @param {[string]} items
* @returns {string}
*/
function splice(str, index, items) {
return str.substr(0, index) + items + str.substr(index);
}
/**
* Get the contents of a string that come after specified characters.
*
* @param {string} str Any string to split
* @param {string} dir The directory the file is in
* @return {string}
*/
function getFileName(str, dir) {
return str.split(dir)[1];
}
/**
* Retrieve the contents of a file
*
* @param {array} fileArray An array of file names
* @param {string} targetDir The directory to retrieve files from
* @param {string} filePrefix The string that comes right before the file name
* @return {Promise}
*/
function getContentsOfFiles(fileArray, targetDir, filePrefix) {
var allPromises = [],
currentDir = process.cwd();
fileArray.forEach(file => {
allPromises.push(files.readFilePromise(path.join(currentDir, targetDir, getFileName(file, filePrefix))));
});
return Promise.all(allPromises)
.catch(err => {
throw err;
});
}
/**
* Wraps a string with HTML tags
* @param {string} string The string to wrap
* @param {string} tag The HTML tag to use
* @return {string}
*/
function wrapWithTags(string, tag) {
if (tag === SCRIPT_TAG) {
return `<script type="text/javascript">
// <![CDATA[
${string}
// ]]
</script>`;
} else {
return `<style>${string}</style>`;
}
}
/**
* Concatenates an array of files into one string.
*
* @param {array} fileArray An array of files
* @param {string} directory The directory in which `fs` will look for the file
* @param {string} filePrefix The directory path before the filename
* @param {string|null} tag The type of tag to wrap the contents in.
* @return {string}
*/
function combineFileContents(fileArray, directory, filePrefix, tag) {
if (!fileArray || !fileArray.length) {
return false;
}
// If there are files, retrieve contents
return getContentsOfFiles(fileArray, directory, filePrefix)
.then(function (fileContents) {
return wrapWithTags(fileContents.join(''), tag);
});
}
/**
* Append at the bottom of the head tag, or if no head tag, then the top of root tag.
*
* @param {array} styles
* @param {string} html
* @returns {string}
*/
function appendMediaToTop(styles, html) {
var index = findTop(html);
return splice(html, index, styles);
}
/**
* Append at the bottom of the body tag, or if no body tag, then the bottom of the root tag.
* @param {Array} scripts
* @param {string} html
* @returns {string}
*/
function appendMediaToBottom(scripts, html) {
var index = findBottom(html);
return splice(html, index, scripts);
}
function injectTags(fileArray, site, tag) {
var buster = module.exports.cacheBuster ? `?version=${module.exports.cacheBuster}` : '';
return bluebird.resolve(_.map(fileArray, function (file) {
if (tag === STYLE_TAG) {
return `<link rel="stylesheet" type="text/css" href="${file}${buster}">`;
} else {
return `<script type="text/javascript" src="${file}${buster}"></script>`;
}
}).join('\n'));
}
/**
* Gets a list of all css and js needed for the components listed.
*
* NOTE: the getStyles and getScripts are memoized using all arguments
*
* @param {Array} componentList
* @param {string} slug
* @returns {{styles: Array, scripts: Array}}
*/
function getMediaMap({ _components:componentList, locals }) {
return {
styles: flatMap(componentList, (component) => module.exports.getStyles(component, locals.site)),
scripts: flatMap(componentList, (component) => module.exports.getScripts(component, locals.site))
};
}
/**
* Get the proper scripts for the component
*
* @param {string} name
* @param {object} site
* @returns {array}
*/
function getScripts(name, site) {
const slug = site.slug,
assetDir = site && site.assetDir || MEDIA_DIRECTORY,
assetPath = site && site.assetPath || '',
assetHost = site && site.assetHost || '';
return _.map(_.filter([
path.join(assetDir, 'js', `${name}.js`),
path.join(assetDir, 'js', `${name}.${slug}.js`),
path.join(assetDir, 'js', `${name}.client.js`)
], files.fileExists), pathJoin(assetHost, assetPath, assetDir));
}
/**
* @param {Array} list
* @param {function} fn
* @returns {Array}
*/
function flatMap(list, fn) {
return _.filter(_.flattenDeep(_.map(list, fn)), _.identity);
}
/**
* Get the proper styles for the component. If a styleguide is configured, use
* that css. Defaults to the site slug
*
* @param {string} name
* @param {object} site
* @returns {array}
*/
function getStyles(name, site) {
const siteStyleguide = site && site.styleguide,
siteSlug = site && site.slug,
assetDir = site && site.assetDir || MEDIA_DIRECTORY,
assetPath = site && site.assetPath || '',
assetHost = site && site.assetHost || '';
let availableVariations, styleguidePath, cssFilePaths;
if (!siteStyleguide) {
// legacy behavior: load <component>.css and <component>.<site>.css
cssFilePaths = [
path.join(assetDir, 'css', `${name}.css`),
path.join(assetDir, 'css', `${name}.${siteSlug}.css`)
];
} else {
// styleguides: load <component>.<styleguide>.css and <component>_<variation>.<styleguide>.css
// note: this also loads default styles if the site styleguide doesn't have styles for a certain component / variation
availableVariations = styleguide.getVariations(siteStyleguide);
styleguidePath = path.join(assetDir, 'css', `${name}.${siteStyleguide}.css`);
cssFilePaths = files.fileExists(styleguidePath) ? [styleguidePath] : [path.join(assetDir, 'css', `${name}._default.css`)]; // fall back to default styleguide
// if there are variations available for the component, add them to the list
// of file paths we want
if (availableVariations[name]) {
availableVariations[name].forEach((variation) => {
let styleguideVariationPath = path.join(assetDir, 'css', `${variation}.${siteStyleguide}.css`);
cssFilePaths.push(files.fileExists(styleguideVariationPath) ? styleguideVariationPath : path.join(assetDir, 'css', `${variation}._default.css`));
});
}
}
return _.map(_.filter(cssFilePaths, files.fileExists), pathJoin(assetHost, assetPath, assetDir));
}
/**
* Trim the path on the file system bythe link of the
* asset directory and then join it with either the assetHost
* value of the site or the assetPath value (found in the
* site's config file)
*
* @param {String} assetHost
* @param {String} assetPath
* @param {String} assetDir
* @return {Function}
*/
function pathJoin(assetHost, assetPath, assetDir) {
var assetDirLen = assetDir.length;
return function (filePath) {
var pathToFile = filePath.substr(assetDirLen);
if (assetHost) return `${assetHost}${pathToFile}`;
return path.join(assetPath, pathToFile);
};
}
/**
* Set the values for inlining vs tagging edit mode styles/scripts
*
* @param {object|boolean} options
* @param {string} [cacheBuster]
*/
function configure(options, cacheBuster = '') {
if (options && _.isObject(options)) {
module.exports.editStylesTags = options.styles || false;
module.exports.editScriptsTags = options.scripts || false;
} else {
module.exports.editStylesTags = options;
module.exports.editScriptsTags = options;
}
// Assign cacheBuster
module.exports.cacheBuster = cacheBuster;
}
/**
* Given the state and html string...
*
* 1. Find all associated scripts/styles
* 2. Run `resolveMedia`
* 3. Stitch in the assets' contents
* 4. Return the HTML string
*
* @param {Object} state
* @return {Function}
*/
function injectScriptsAndStyles(state) {
const { locals } = state;
return function (html) {
var mediaMap = {};
// Check that HTML is string
if (typeof html !== 'string') {
throw new Error('Missing html parameter');
}
// We've got a string so let's actually get the map of styles
mediaMap = module.exports.getMediaMap(state);
// allow site to change the media map before applying it
if (setup.resolveMedia) mediaMap = setup.resolveMedia(mediaMap, locals) || mediaMap;
if (!locals.edit) {
mediaMap.styles = combineFileContents(mediaMap.styles, 'public/css', '/css/', STYLE_TAG);
mediaMap.scripts = combineFileContents(mediaMap.scripts, 'public/js', '/js/', SCRIPT_TAG);
} else {
mediaMap.styles = module.exports.editStylesTags ? injectTags(mediaMap.styles, locals.site, STYLE_TAG) : combineFileContents(mediaMap.styles, 'public/css', '/css/', STYLE_TAG);
mediaMap.scripts = module.exports.editScriptsTags ? injectTags(mediaMap.scripts, locals.site, SCRIPT_TAG) : combineFileContents(mediaMap.scripts, 'public/js', '/js/', SCRIPT_TAG);
}
return bluebird.props(mediaMap)
.then(combinedFiles => {
html = combinedFiles.styles ? appendMediaToTop(combinedFiles.styles, html) : html; // If there are styles, append them
html = combinedFiles.scripts ? appendMediaToBottom(combinedFiles.scripts, html) : html; // If there are scripts, append them
return html; // Return the compiled HTML
});
};
}
module.exports.injectScriptsAndStyles = injectScriptsAndStyles;
module.exports.getMediaMap = getMediaMap;
module.exports.cacheBuster = '';
module.exports.configure = configure;
module.exports.editStylesTags = false;
module.exports.editScriptsTags = false;
// For testing
module.exports.getScripts = getScripts;
module.exports.getStyles = getStyles;