-
-
Notifications
You must be signed in to change notification settings - Fork 518
/
Copy pathPagination.js
executable file
·404 lines (334 loc) · 11.2 KB
/
Pagination.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
const lodashChunk = require("lodash/chunk");
const lodashGet = require("lodash/get");
const lodashSet = require("lodash/set");
const EleventyBaseError = require("../EleventyBaseError");
const { DeepCopy } = require("../Util/Merge");
const { ProxyWrap } = require("../Util/ProxyWrap");
const getPaginationDataKey = require("../Util/GetPaginationDataKey");
class PaginationConfigError extends EleventyBaseError {}
class PaginationError extends EleventyBaseError {}
class Pagination {
constructor(data, config) {
if (!config) {
throw new PaginationConfigError(
"Expected `config` argument to Pagination class."
);
}
this.config = config;
this.setData(data);
}
static hasPagination(data) {
return "pagination" in data;
}
hasPagination() {
if (!this.data) {
throw new Error("Missing `setData` call for Pagination object.");
}
return Pagination.hasPagination(this.data);
}
circularReferenceCheck() {
if (this.data.eleventyExcludeFromCollections) {
return;
}
let key = getPaginationDataKey(this.data);
let tags = this.data.tags || [];
for (let tag of tags) {
if (`collections.${tag}` === key) {
throw new PaginationError(
`Pagination circular reference${
this.template ? ` on ${this.template.inputPath}` : ""
}, data:\`${key}\` iterates over both the \`${tag}\` tag and also supplies pages to that tag.`
);
}
}
}
setData(data) {
this.data = data || {};
this.target = [];
if (!this.hasPagination()) {
return;
}
if (!data.pagination) {
throw new Error(
"Misconfigured pagination data in template front matter (YAML front matter precaution: did you use tabs and not spaces for indentation?)."
);
} else if (!("size" in data.pagination)) {
throw new Error("Missing pagination size in front matter data.");
}
this.circularReferenceCheck();
this.size = data.pagination.size;
this.alias = data.pagination.alias;
// TODO do we need the full data set for serverless?
this.fullDataSet = this._get(this.data, this._getDataKey());
// truncate pagination data to one entry for serverless render
if (
data.pagination.serverless &&
this._has(data, data.pagination.serverless)
) {
// Warn: this doesn’t run filter/before/pagination transformations
// Warn: `pagination.pages`, pageNumber, links, hrefs, etc
let serverlessPaginationKey = this._get(data, data.pagination.serverless);
if (typeof data.pagination.serverlessFilter === "function") {
this.chunkedItems = [
data.pagination.serverlessFilter(
this.fullDataSet,
serverlessPaginationKey
),
];
} else {
this.chunkedItems = [
[this._get(this.fullDataSet, serverlessPaginationKey)],
];
}
} else {
// this returns an array
this.target = this._resolveItems();
// Serverless Shortcut when key is not found in data set (probably running local build and expected a :path param in data)
// Only collections are relevant for templates that don’t have a permalink.build, they don’t have a templateContent and aren’t written to disk
if (
data.pagination.serverless &&
!data.pagination.addAllPagesToCollections
) {
// use the first page only
this.chunkedItems = [this.pagedItems[0]];
} else {
this.chunkedItems = this.pagedItems;
}
}
}
setTemplate(tmpl) {
this.template = tmpl;
}
_getDataKey() {
return this.data.pagination.data;
}
resolveDataToObjectValues() {
if ("resolve" in this.data.pagination) {
return this.data.pagination.resolve === "values";
}
return false;
}
isFiltered(value) {
if ("filter" in this.data.pagination) {
let filtered = this.data.pagination.filter;
if (Array.isArray(filtered)) {
return filtered.indexOf(value) > -1;
}
return filtered === value;
}
return false;
}
_has(target, key) {
let notFoundValue = "__NOT_FOUND_ERROR__";
let paginationDataKey = getPaginationDataKey(this.data);
let data = lodashGet(target, paginationDataKey, notFoundValue);
return data !== notFoundValue;
}
_get(target, key) {
let notFoundValue = "__NOT_FOUND_ERROR__";
let paginationDataKey = getPaginationDataKey(this.data);
let data = lodashGet(target, paginationDataKey, notFoundValue);
if (data === notFoundValue) {
throw new Error(
`Could not find pagination data, went looking for: ${paginationDataKey}`
);
}
return data;
}
_resolveItems() {
let keys;
if (Array.isArray(this.fullDataSet)) {
keys = this.fullDataSet;
} else if (this.resolveDataToObjectValues()) {
keys = Object.values(this.fullDataSet);
} else {
keys = Object.keys(this.fullDataSet);
}
// keys must be an array
let result = keys.slice();
if (
this.data.pagination.before &&
typeof this.data.pagination.before === "function"
) {
// we don’t need to make a copy of this because we .slice() above to create a new copy
result = this.data.pagination.before(result, this.data);
}
if (this.data.pagination.reverse === true) {
result = result.reverse();
}
if (this.data.pagination.filter) {
result = result.filter((value) => !this.isFiltered(value));
}
return result;
}
get pagedItems() {
if (!this.data) {
throw new Error("Missing `setData` call for Pagination object.");
}
const chunks = lodashChunk(this.target, this.size);
if (this.data.pagination && this.data.pagination.generatePageOnEmptyData) {
return chunks.length ? chunks : [[]];
} else {
return chunks;
}
}
getPageCount() {
if (!this.hasPagination()) {
return 0;
}
return this.chunkedItems.length;
}
getNormalizedItems(pageItems) {
return this.size === 1 ? pageItems[0] : pageItems;
}
getOverrideDataPages(items, pageNumber) {
return {
// See Issue #345 for more examples
page: {
previous:
pageNumber > 0
? this.getNormalizedItems(items[pageNumber - 1])
: null,
next:
pageNumber < items.length - 1
? this.getNormalizedItems(items[pageNumber + 1])
: null,
first: items.length ? this.getNormalizedItems(items[0]) : null,
last: items.length
? this.getNormalizedItems(items[items.length - 1])
: null,
},
pageNumber,
};
}
getOverrideDataLinks(pageNumber, templateCount, links) {
let obj = {};
// links are okay but hrefs are better
obj.previousPageLink = pageNumber > 0 ? links[pageNumber - 1] : null;
obj.previous = obj.previousPageLink;
obj.nextPageLink =
pageNumber < templateCount - 1 ? links[pageNumber + 1] : null;
obj.next = obj.nextPageLink;
obj.firstPageLink = links.length > 0 ? links[0] : null;
obj.lastPageLink = links.length > 0 ? links[links.length - 1] : null;
obj.links = links;
// todo deprecated, consistency with collections and use links instead
obj.pageLinks = links;
return obj;
}
getOverrideDataHrefs(pageNumber, templateCount, hrefs) {
let obj = {};
// hrefs are better than links
obj.previousPageHref = pageNumber > 0 ? hrefs[pageNumber - 1] : null;
obj.nextPageHref =
pageNumber < templateCount - 1 ? hrefs[pageNumber + 1] : null;
obj.firstPageHref = hrefs.length > 0 ? hrefs[0] : null;
obj.lastPageHref = hrefs.length > 0 ? hrefs[hrefs.length - 1] : null;
obj.hrefs = hrefs;
// better names
obj.href = {
previous: obj.previousPageHref,
next: obj.nextPageHref,
first: obj.firstPageHref,
last: obj.lastPageHref,
};
return obj;
}
async getPageTemplates() {
if (!this.data) {
throw new Error("Missing `setData` call for Pagination object.");
}
if (!this.hasPagination()) {
return [];
}
let entries = [];
let items = this.chunkedItems;
let pages = this.size === 1 ? items.map((entry) => entry[0]) : items;
let links = [];
let hrefs = [];
let hasPermalinkField = Boolean(this.data[this.config.keys.permalink]);
let hasComputedPermalinkField = Boolean(
this.data.eleventyComputed &&
this.data.eleventyComputed[this.config.keys.permalink]
);
// Do *not* pass collections through DeepCopy, we’ll re-add them back in later.
let collections = this.data.collections;
if (collections) {
delete this.data.collections;
}
let parentData = DeepCopy(
{
pagination: {
data: this.data.pagination.data,
size: this.data.pagination.size,
alias: this.alias,
pages,
},
},
this.data
);
// Restore skipped collections
if (collections) {
this.data.collections = collections;
// Keep the original reference to the collections, no deep copy!!
parentData.collections = collections;
}
// TODO future improvement dea: use a light Template wrapper for paged template clones (PagedTemplate?)
// so that we don’t have the memory cost of the full template (and can reuse the parent
// template for some things)
for (let pageNumber = 0; pageNumber < items.length; pageNumber++) {
let cloned = this.template.clone();
if (pageNumber > 0 && !hasPermalinkField && !hasComputedPermalinkField) {
cloned.setExtraOutputSubdirectory(pageNumber);
}
let paginationData = {
pagination: {
items: items[pageNumber],
},
page: {},
};
Object.assign(
paginationData.pagination,
this.getOverrideDataPages(items, pageNumber)
);
if (this.alias) {
lodashSet(
paginationData,
this.alias,
this.getNormalizedItems(items[pageNumber])
);
}
// Do *not* deep merge pagination data! See https://github.com/11ty/eleventy/issues/147#issuecomment-440802454
let clonedData = ProxyWrap(paginationData, parentData);
let { rawPath, path, href } = await cloned.getOutputLocations(clonedData);
// TO DO subdirectory to links if the site doesn’t live at /
links.push("/" + rawPath);
hrefs.push(href);
// page.url and page.outputPath are used to avoid another getOutputLocations call later, see Template->addComputedData
clonedData.page.url = href;
clonedData.page.outputPath = path;
entries.push({
template: cloned,
data: clonedData,
});
}
// we loop twice to pass in the appropriate prev/next links (already full generated now)
let numberOfEntries = entries.length;
for (let pageNumber = 0; pageNumber < numberOfEntries; pageNumber++) {
let linksObj = this.getOverrideDataLinks(
pageNumber,
numberOfEntries,
links
);
Object.assign(entries[pageNumber].data.pagination, linksObj);
let hrefsObj = this.getOverrideDataHrefs(
pageNumber,
numberOfEntries,
hrefs
);
Object.assign(entries[pageNumber].data.pagination, hrefsObj);
}
return entries;
}
}
module.exports = Pagination;