summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/TemplateCollection.js
blob: 6e99a32a66e3c9f3be459f4d86e8b617aa21c6b8 (plain)
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
import { TemplatePath } from "@11ty/eleventy-utils";

import TemplateData from "./Data/TemplateData.js";
import Sortable from "./Util/Objects/Sortable.js";
import { isGlobMatch } from "./Util/GlobMatcher.js";

class TemplateCollection extends Sortable {
	constructor() {
		super();

		this._filteredByGlobsCache = new Map();
	}

	getAll() {
		return this.items.slice();
	}

	getAllSorted() {
		return this.sort(Sortable.sortFunctionDateInputPath);
	}

	getSortedByDate() {
		return this.sort(Sortable.sortFunctionDate);
	}

	getGlobs(globs) {
		if (typeof globs === "string") {
			globs = [globs];
		}

		globs = globs.map((glob) => TemplatePath.addLeadingDotSlash(glob));

		return globs;
	}

	getFilteredByGlob(globs) {
		globs = this.getGlobs(globs);

		let key = globs.join("::");
		if (!this._dirty) {
			// Try to find a pre-sorted list and clone it.
			if (this._filteredByGlobsCache.has(key)) {
				return [...this._filteredByGlobsCache.get(key)];
			}
		} else if (this._filteredByGlobsCache.size) {
			// Blow away cache
			this._filteredByGlobsCache = new Map();
		}

		let filtered = this.getAllSorted().filter((item) => {
			return isGlobMatch(item.inputPath, globs);
		});
		this._dirty = false;
		this._filteredByGlobsCache.set(key, [...filtered]);
		return filtered;
	}

	getFilteredByTag(tagName) {
		return this.getAllSorted().filter((item) => {
			if (!tagName || TemplateData.getIncludedTagNames(item.data).includes(tagName)) {
				return true;
			}
			return false;
		});
	}

	getFilteredByTags(...tags) {
		return this.getAllSorted().filter((item) => {
			let itemTags = new Set(TemplateData.getIncludedTagNames(item.data));
			return tags.every((requiredTag) => {
				return itemTags.has(requiredTag);
			});
		});
	}
}

export default TemplateCollection;