/
index.js
88 lines (77 loc) · 2.42 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
/*!
* assemble-indexer <https://github.com/doowb/assemble-indexer>
*
* Copyright (c) 2015, Brian Woodward.
* Licensed under the MIT License.
*/
'use strict';
var merge = require('mixin-deep');
/**
* Add `addIndices` to a [templates][] collection that will
* add index views to the collection when given an array of pages.
*
* ```
* var archives = app.create('archives')
* .use(indexer())
* .addIndices(pages);
* ```
*
* @param {Object} `options`
* @param {Object} `options.index` Optional instance of `View` to use as the basis for the index views being added. Required if `createView` is not passed on plugin or method options.
* @param {Function} `options.createView` Function to create a view instance for the index view being added. Required if `index` is not passed on plugin or method options.
* @return {Function} Function to use as a plugin for [templates][]
* @api public
* @name indexer
*/
module.exports = function indexer (options) {
options = options || {};
/**
* Plugin passed to [templates][] `.use` method.
*
* @param {Object} `collection` collection instance the plugin is added to.
*/
return function plugin (collection) {
collection.define('addIndices', function (pages, opts) {
opts = merge({}, options, opts);
var createView = opts.createView;
if (typeof createView !== 'function') {
var index = opts.index;
createView = createViewFn(index);
delete opts.index;
}
pages.forEach(function (pagination) {
var locals = merge({}, opts);
locals.pages = pages;
locals.pagination = pagination;
var view = createView(locals);
view.key = view.url || view.path;
collection.addView(view);
});
return collection;
});
};
};
/**
* Default method for creating a new index view.
*
* ```js
* var view = createViewFn(locals);
* ```
*
* @param {Object} `locals` Combined locals for this index view.
* @return {Object} New View instance to be used as the index view
*/
function createViewFn (index) {
if (typeof index !== 'object' || !index.isView) {
throw new Error('expected index to be an instance of View');
}
return function (locals) {
var view = index.clone({deep: true});
view.locals = merge({}, view.locals, locals);
if (typeof view.permalink === 'function') {
view.permalink(view.data.permalink, locals);
return view;
}
return view;
};
}