forked from fbrctr/fabricator-assemble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
679 lines (519 loc) · 15 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
// modules
var _ = require('lodash');
var beautifyHtml = require('js-beautify').html;
var chalk = require('chalk');
var fs = require('fs');
var globby = require('globby');
var Handlebars = require('handlebars');
var inflect = require('i')();
var matter = require('gray-matter');
var md = require('markdown-it')({ html: true, linkify: true });
var mkdirp = require('mkdirp');
var path = require('path');
var sortObj = require('sort-object');
var yaml = require('js-yaml');
/**
* Default options
* @type {Object}
*/
var defaults = {
/**
* ID (filename) of default layout
* @type {String}
*/
layout: 'default',
/**
* Layout templates
* @type {(String|Array)}
*/
layouts: ['src/views/layouts/*'],
/**
* Layout includes (partials)
* @type {String}
*/
layoutIncludes: ['src/views/layouts/includes/*'],
/**
* Pages to be inserted into a layout
* @type {(String|Array)}
*/
views: ['src/views/**/*', '!src/views/+(layouts)/**'],
/**
* Materials - snippets turned into partials
* @type {(String|Array)}
*/
materials: ['src/materials/**/*'],
/**
* JSON or YAML data models that are piped into views
* @type {(String|Array)}
*/
data: ['src/data/**/*.{json,yml}'],
/**
* Markdown files containing toolkit-wide documentation
* @type {(String|Array)}
*/
docs: ['src/docs/**/*.md'],
/**
* Keywords used to access items in views
* @type {Object}
*/
keys: {
materials: 'materials',
views: 'views',
docs: 'docs'
},
/**
* Location to write files
* @type {String}
*/
dest: 'dist',
/**
* beautifier options
* @type {Object}
*/
beautifier: {
indent_size: 1,
indent_char: ' ',
indent_with_tabs: true
},
/**
* Function to call when an error occurs
* @type {Function}
*/
onError: null,
/**
* Whether or not to log errors to console
* @type {Boolean}
*/
logErrors: false,
/**
* Handlebars instance to use
*/
handlebars: Handlebars
};
/**
* Merged defaults and user options
* @type {Object}
*/
var options = {};
/**
* Assembly data storage
* @type {Object}
*/
var assembly = {
/**
* Contents of each layout file
* @type {Object}
*/
layouts: {},
/**
* Parsed JSON data from each data file
* @type {Object}
*/
data: {},
/**
* Meta data for materials, grouped by "collection" (sub-directory); contains name and sub-items
* @type {Object}
*/
materials: {},
/**
* Each material's front-matter data
* @type {Object}
*/
materialData: {},
/**
* Meta data for user-created views (views in views/{subdir})
* @type {Object}
*/
views: {},
/**
* Meta data (name, sub-items) for doc file
* @type {Object}
*/
docs: {}
};
/**
* Get the name of a file (minus extension) from a path
* @param {String} filePath
* @example
* './src/materials/structures/foo.html' -> 'foo'
* './src/materials/structures/02-bar.html' -> 'bar'
* @return {String}
*/
var getName = function (filePath, preserveNumbers) {
// get name; replace spaces with dashes
var name = path.basename(filePath, path.extname(filePath)).replace(/\s/g, '-');
return (preserveNumbers) ? name : name.replace(/^[0-9|\.\-]+/, '');
};
/**
* Attempt to read front matter, handle errors
* @param {String} file Path to file
* @return {Object}
*/
var getMatter = function (file) {
return matter.read(file, {
parser: require('js-yaml').safeLoad
});
};
/**
* Handle errors
* @param {Object} e Error object
*/
var handleError = function (e) {
// default to exiting process on error
var exit = true;
// construct error object by combining argument with defaults
var error = _.assign({}, {
name: 'Error',
reason: '',
message: 'An error occurred',
}, e);
// call onError
if (_.isFunction(options.onError)) {
options.onError(error);
exit = false;
}
// log errors
if (options.logErrors) {
console.error(chalk.bold.red('Error (fabricator-assemble): ' + e.message + '\n'), e.stack);
exit = false;
}
// break the build if desired
if (exit) {
console.error(chalk.bold.red('Error (fabricator-assemble): ' + e.message + '\n'), e.stack);
process.exit(1);
}
};
/**
* Build the template context by merging context-specific data with assembly data
* @param {Object} data
* @return {Object}
*/
var buildContext = function (data, hash) {
// set keys to whatever is defined
var materials = {};
materials[options.keys.materials] = assembly.materials;
var views = {};
views[options.keys.views] = assembly.views;
var docs = {};
docs[options.keys.docs] = assembly.docs;
return _.assign({}, data, assembly.data, assembly.materialData, materials, views, docs, hash);
};
/**
* Convert a file name to title case
* @param {String} str
* @return {String}
*/
var toTitleCase = function(str) {
return str.replace(/(\-|_)/g, ' ').replace(/\w\S*/g, function(word) {
return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});
};
/**
* Insert the page into a layout
* @param {String} page
* @param {String} layout
* @return {String}
*/
var wrapPage = function (page, layout) {
return layout.replace(/\{\%\s?body\s?\%\}/, page);
};
/**
* Parse each material - collect data, create partial
*/
var parseMaterials = function () {
// reset object
assembly.materials = {};
// get files and dirs
var files = globby.sync(options.materials, { nodir: true, nosort: true });
// build a glob for identifying directories
options.materials = (typeof options.materials === 'string') ? [options.materials] : options.materials;
var dirsGlob = options.materials.map(function (pattern) {
return path.dirname(pattern) + '/*/';
});
// get all directories
// do a new glob; trailing slash matches only dirs
var dirs = globby.sync(dirsGlob).map(function (dir) {
return path.normalize(dir).split(path.sep).slice(-2, -1)[0];
});
// stub out an object for each collection and subCollection
files.forEach(function (file) {
var parent = getName(path.normalize(path.dirname(file)).split(path.sep).slice(-2, -1)[0], true);
var collection = getName(path.normalize(path.dirname(file)).split(path.sep).pop(), true);
var isSubCollection = (dirs.indexOf(parent) > -1);
// get the material base dir for stubbing out the base object for each category (e.g. component, structure)
var materialBase = (isSubCollection) ? parent : collection;
// stub the base object
assembly.materials[materialBase] = assembly.materials[materialBase] || {
name: toTitleCase(getName(materialBase)),
items: {}
};
if (isSubCollection) {
assembly.materials[parent].items[collection] = assembly.materials[parent].items[collection] || {
name: toTitleCase(getName(collection)),
items: {}
};
}
});
// iterate over each file (material)
files.forEach(function (file) {
// get info
var fileMatter = getMatter(file);
var collection = getName(path.normalize(path.dirname(file)).split(path.sep).pop(), true);
var parent = path.normalize(path.dirname(file)).split(path.sep).slice(-2, -1)[0];
var isSubCollection = (dirs.indexOf(parent) > -1);
var id = (isSubCollection) ? getName(collection) + '.' + getName(file) : getName(file);
var key = (isSubCollection) ? collection + '.' + getName(file, true) : getName(file, true);
// get material front-matter, omit `notes`
var localData = _.omit(fileMatter.data, 'notes');
// trim whitespace from material content
var content = fileMatter.content.replace(/^(\s*(\r?\n|\r))+|(\s*(\r?\n|\r))+$/g, '');
// capture meta data for the material
if (!isSubCollection) {
assembly.materials[collection].items[key] = {
name: toTitleCase(id),
notes: (fileMatter.data.notes) ? md.render(fileMatter.data.notes) : '',
data: localData
};
} else {
assembly.materials[parent].items[collection].items[key] = {
name: toTitleCase(id.split('.')[1]),
notes: (fileMatter.data.notes) ? md.render(fileMatter.data.notes) : '',
data: localData
};
}
// store material-name-spaced local data in template context
assembly.materialData[id.replace(/\./g, '-')] = localData;
// replace local fields on the fly with name-spaced keys
// this allows partials to use local front-matter data
// only affects the compilation environment
if (!_.isEmpty(localData)) {
_.forEach(localData, function (val, key) {
// {{field}} => {{material-name.field}}
var regex = new RegExp('(\\{\\{[#\/]?)(\\s?' + key + '+?\\s?)(\\}\\})', 'g');
content = content.replace(regex, function (match, p1, p2, p3) {
return p1 + id.replace(/\./g, '-') + '.' + p2.replace(/\s/g, '') + p3;
});
});
}
// register the partial
Handlebars.registerPartial(id, content);
});
// sort materials object alphabetically
assembly.materials = sortObj(assembly.materials, 'order');
for (var collection in assembly.materials) {
assembly.materials[collection].items = sortObj(assembly.materials[collection].items, 'order');
}
};
/**
* Parse markdown files as "docs"
*/
var parseDocs = function () {
// reset
assembly.docs = {};
// get files
var files = globby.sync(options.docs, { nodir: true });
// iterate over each file (material)
files.forEach(function (file) {
var id = getName(file);
// save each as unique prop
assembly.docs[id] = {
name: toTitleCase(id),
content: md.render(fs.readFileSync(file, 'utf-8'))
};
});
};
/**
* Parse layout files
*/
var parseLayouts = function () {
// reset
assembly.layouts = {};
// get files
var files = globby.sync(options.layouts, { nodir: true });
// save content of each file
files.forEach(function (file) {
var id = getName(file);
var content = fs.readFileSync(file, 'utf-8');
assembly.layouts[id] = content;
});
};
/**
* Register layout includes has Handlebars partials
*/
var parseLayoutIncludes = function () {
// get files
var files = globby.sync(options.layoutIncludes, { nodir: true });
// save content of each file
files.forEach(function (file) {
var id = getName(file);
var content = fs.readFileSync(file, 'utf-8');
Handlebars.registerPartial(id, content);
});
};
/**
* Parse data files and save JSON
*/
var parseData = function () {
// reset
assembly.data = {};
// get files
var files = globby.sync(options.data, { nodir: true });
// save content of each file
files.forEach(function (file) {
var id = getName(file);
var content = yaml.safeLoad(fs.readFileSync(file, 'utf-8'));
assembly.data[id] = content;
});
};
/**
* Get meta data for views
*/
var parseViews = function () {
// reset
assembly.views = {};
// get files
var files = globby.sync(options.views, { nodir: true });
files.forEach(function (file) {
var id = getName(file, true);
// determine if view is part of a collection (subdir)
var dirname = path.normalize(path.dirname(file)).split(path.sep).pop(),
collection = (dirname !== options.keys.views) ? dirname : '';
var fileMatter = getMatter(file),
fileData = _.omit(fileMatter.data, 'notes');
// if this file is part of a collection
if (collection) {
// create collection if it doesn't exist
assembly.views[collection] = assembly.views[collection] || {
name: toTitleCase(collection),
items: {}
};
// store view data
assembly.views[collection].items[id] = {
name: toTitleCase(id),
data: fileData
};
}
});
};
/**
* Register new Handlebars helpers
*/
var registerHelpers = function () {
// get helper files
var resolveHelper = path.join.bind(null, __dirname, 'helpers');
var localHelpers = fs.readdirSync(resolveHelper());
var userHelpers = options.helpers;
// register local helpers
localHelpers.map(function (helper) {
var key = helper.match(/(^\w+?-)(.+)(\.\w+)/)[2];
var path = resolveHelper(helper);
Handlebars.registerHelper(key, require(path));
});
// register user helpers
for (var helper in userHelpers) {
if (userHelpers.hasOwnProperty(helper)) {
Handlebars.registerHelper(helper, userHelpers[helper]);
}
}
/**
* Helpers that require local functions like `buildContext()`
*/
/**
* `material`
* @description Like a normal partial include (`{{> partialName }}`),
* but with some additional templating logic to help with nested block iterations.
* The name of the helper is the singular form of whatever is defined as the `options.keys.materials`
* @example
* {{material name context}}
*/
Handlebars.registerHelper(inflect.singularize(options.keys.materials), function (name, context, opts) {
// remove leading numbers from name keyword
// partials are always registered with the leading numbers removed
var key = name.replace(/^([a-z][a-z0-9\-]*\.)?([0-9\.-]+)(.*)$/i, '$1$3');
// attempt to find pre-compiled partial
var template = Handlebars.partials[key],
fn;
// compile partial if not already compiled
if (!_.isFunction(template)) {
fn = Handlebars.compile(template);
} else {
fn = template;
}
// return beautified html with trailing whitespace removed
return beautifyHtml(fn(buildContext(context, opts.hash)).replace(/^\s+/, ''), options.beautifier);
});
};
/**
* Setup the assembly
* @param {Objet} options User options
*/
var setup = function (userOptions) {
// merge user options with defaults
options = _.merge({}, defaults, userOptions);
// set Handlebars reference used by multiple functions below
Handlebars = options.handlebars;
// setup steps
registerHelpers();
parseLayouts();
parseLayoutIncludes();
parseData();
parseMaterials();
parseViews();
parseDocs();
};
/**
* Assemble views using materials, data, and docs
*/
var assemble = function () {
// get files
var files = globby.sync(options.views, { nodir: true });
// create output directory if it doesn't already exist
mkdirp.sync(options.dest);
// iterate over each view
files.forEach(function (file) {
var id = getName(file);
// build filePath
var dirname = path.normalize(path.dirname(file)).split(path.sep).pop(),
collection = (dirname !== options.keys.views) ? dirname : '',
filePath = path.normalize(path.join(options.dest, collection, path.basename(file)));
// get page gray matter and content
var pageMatter = getMatter(file),
pageContent = pageMatter.content;
if (collection) {
pageMatter.data.baseurl = '..';
}
// template using Handlebars
var source = wrapPage(pageContent, assembly.layouts[pageMatter.data.layout || options.layout]),
context = buildContext(pageMatter.data),
template = Handlebars.compile(source);
// redefine file path if dest front-matter variable is defined
if (pageMatter.data.dest) {
filePath = path.normalize(pageMatter.data.dest);
}
// change extension to .html
filePath = filePath.replace(/\.[0-9a-z]+$/, '.html');
// write file
mkdirp.sync(path.dirname(filePath));
fs.writeFileSync(filePath, template(context));
// write a copy file if custom dest-copy front-matter variable is defined
if (pageMatter.data['dest-copy']) {
var copyPath = path.normalize(pageMatter.data['dest-copy']);
mkdirp.sync(path.dirname(copyPath));
fs.writeFileSync(copyPath, template(context));
}
});
};
/**
* Module exports
* @return {Object} Promise
*/
module.exports = function (options) {
try {
// setup assembly
setup(options);
// assemble
assemble();
} catch(e) {
handleError(e);
}
};