-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheleventy.config.mjs
More file actions
316 lines (277 loc) · 12.7 KB
/
Copy patheleventy.config.mjs
File metadata and controls
316 lines (277 loc) · 12.7 KB
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
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import matter from "gray-matter";
import { execSync } from 'child_process';
import { RenderPlugin } from "@11ty/eleventy";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Load allowed tags from JSON file
const allowedTagsPath = path.join(__dirname, "_data", "labels.json");
const allowedTagsData = JSON.parse(fs.readFileSync(allowedTagsPath, "utf-8"));
export default function (eleventyConfig) {
eleventyConfig.addPlugin(RenderPlugin);
eleventyConfig.ignores.add("a11y.md");
eleventyConfig.ignores.add("privacy.md");
eleventyConfig.ignores.add("README.md");
eleventyConfig.ignores.add("SECURITY.md");
eleventyConfig.ignores.add("CONTRIBUTING.md");
eleventyConfig.ignores.add("CODE_OF_CONDUCT.md");
eleventyConfig.ignores.add("LICENSE");
eleventyConfig.ignores.add("_includes/");
eleventyConfig.ignores.add("_templates/");
eleventyConfig.setWatchThrottleWaitTime(100);
eleventyConfig.addPassthroughCopy("LICENSE");
eleventyConfig.addPassthroughCopy("assets/css/*.css");
eleventyConfig.addPassthroughCopy("assets/favicons/*");
eleventyConfig.addPassthroughCopy("assets/img");
eleventyConfig.addPassthroughCopy("assets/fonts/*");
eleventyConfig.addPassthroughCopy("assets/js/**/*.js");
eleventyConfig.addPassthroughCopy("assets/js/**/*.mjs");
eleventyConfig.addTemplateFormats("md");
eleventyConfig.addGlobalData("layout", "md.liquid");
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
strict_filters: true,
});
eleventyConfig.addShortcode("year", () => `2013 — ${new Date().getFullYear()}`);
eleventyConfig.addFilter("readFile", (filePath) => {
const fullPath = path.join(process.cwd(), filePath);
return fs.readFileSync(fullPath, "utf-8");
});
eleventyConfig.addFilter("fileExists", (filePath, joinPath = "_includes") => {
const fullPath = path.join(joinPath, filePath);
return fs.existsSync(fullPath);
});
eleventyConfig.addFilter("safe", (content) => {
return content; // Return the content as-is
});
eleventyConfig.addFilter('dateISO', (date) =>{
return new Date(date).toISOString();
});
// Only allow certain tags within changelogs
const allowedTags = allowedTagsData.labels;
const allowedTagKeys = allowedTags.map((tag) => tag.key);
eleventyConfig.on("beforeBuild", () => {
const outputDir = path.join(process.cwd(), "_site");
// Check if the _site directory exists
if (fs.existsSync(outputDir)) {
// Read all files and subdirectories inside _site
const files = fs.readdirSync(outputDir);
// Iterate over each file/subdirectory and remove it
files.forEach((file) => {
const filePath = path.join(outputDir, file);
if (fs.lstatSync(filePath).isDirectory()) {
// Remove subdirectory recursively
fs.rmSync(filePath, { recursive: true, force: true });
// Recreate the subdirectory
fs.mkdirSync(filePath);
} else {
// Remove file
fs.unlinkSync(filePath);
}
});
console.log("Cleaned and recreated contents of _site directory.");
}
const changelogDir = path.join(__dirname, "changelog");
const files = fs.readdirSync(changelogDir).filter((file) => file.endsWith(".md"));
files.forEach((file) => {
const filePath = path.join(changelogDir, file);
const content = fs.readFileSync(filePath, "utf-8");
// Extract front matter using gray-matter
const frontMatter = matter(content).data;
if (frontMatter.tags) {
const invalidTags = frontMatter.tags.filter((tag) => !allowedTagKeys.includes(tag));
if (invalidTags.length > 0) {
throw new Error(`Invalid tags found in "${file}": ${invalidTags.join(", ")}`);
}
}
});
});
eleventyConfig.addCollection("groupPages", (collectionApi) => {
const pagesDir = path.join(process.cwd(), "pages");
const folders = fs.readdirSync(pagesDir).filter((file) => {
return fs.lstatSync(path.join(pagesDir, file)).isDirectory();
});
return folders.map((folder) => {
const folderItems = collectionApi.getFilteredByGlob(`./pages/${folder}/**/*.*`);
return {
folderName: folder,
folderItems: folderItems,
permalink: `/${folder}/`,
};
});
});
const pagesDir = path.join(process.cwd(), "pages");
const folders = fs.readdirSync(pagesDir).filter((file) => {
return fs.lstatSync(path.join(pagesDir, file)).isDirectory();
});
folders.forEach((folder) => {
eleventyConfig.addCollection(folder, (collectionApi) => {
return collectionApi.getFilteredByGlob(`./pages/${folder}/*.liquid`);
});
});
eleventyConfig.addCollection("versions", (collectionApi) => {
return collectionApi.getFilteredByGlob("./changelog/**/*.md").sort((a, b) => {
const parseVersion = (version) => version.split('.').map(Number);
const [aMajor, aMinor, aPatch] = parseVersion(a.data.title);
const [bMajor, bMinor, bPatch] = parseVersion(b.data.title);
// Compare major, then minor, then patch
if (aMajor !== bMajor) {
return bMajor - aMajor; // Sort by major version (descending)
}
if (aMinor !== bMinor) {
return bMinor - aMinor; // Sort by minor version (descending)
}
return bPatch - aPatch; // Sort by patch version (descending)
});
});
// Automatically set permalink for changelog items
eleventyConfig.addGlobalData("eleventyComputed", {
permalink: (data) => {
if (data.customPermalink) {
return data.customPermalink; // Use custom permalink if provided
}
if (data.page.inputPath.includes("pages/")) {
// Remove 'pages/' from the input path and construct the permalink
const relativePath = data.page.inputPath.replace(/^.*\/pages\//, "");
const permalinkPath = relativePath.replace(/\.[^/.]+$/, ""); // Remove file extension
return `/${permalinkPath}/`; // Ensure it ends with a trailing slash
}
if (data.page.inputPath.includes("changelog/")) {
const versionSlug = data.page.fileSlug; // Use the file name (e.g., "2.0.0")
return `/changelog/${versionSlug}/`; // Set the desired permalink
}
return data.permalink; // Keep existing permalink for other files
},
description: (data) => {
if (data.page.inputPath.includes("changelog/")) {
const date = new Date(data.date);
return `Released on ${date.toLocaleDateString("en-US", {
year: "numeric",
month: "long",
day: "numeric",
})}`;
}
return data.description; // Keep existing description for other pages
},
folderName: (data) => {
if (data.page.inputPath.includes("pages/")) {
const folderPath = data.page.inputPath.split("/").slice(-2, -1)[0];
return folderPath;
}
if (data.page.fileSlug && data.collections && data.collections.groupPages) {
const groupPage = data.collections.groupPages.find(
(group) => group.folderName === data.page.fileSlug
);
return groupPage ? groupPage.folderName : null;
}
return data.folderName;
},
folderItems: (data) => {
if (data.folderName && data.collections && data.collections.groupPages) {
const groupPage = data.collections.groupPages.find(
(group) => group.folderName === data.folderName
);
return groupPage ? groupPage.folderItems : [];
}
return [];
},
"page-id": (data) => {
if (data.page && data.page.fileSlug) {
return data.page.fileSlug;
}
return null;
},
"lastmod": (data) => {
if (data.page && data.page.inputPath) {
const filePath = path.join(process.cwd(), data.page.inputPath);
const stats = fs.statSync(filePath);
return stats.mtime; // Return the last modified time of the file
}
},
});
eleventyConfig.addFilter("removeHiddenClass", (content, isLandingPage) => {
if (isLandingPage) {
// Remove the "hidden" class from section-toggle links and <hr> tags
return content
.replace(/class="([^"]*d-none[^"]*)"/g, (match, classes) => {
// Remove "hidden" from the class list
return `class="${classes.replace(/\bd-none\b/g, "").trim()}"`;
});
}
return content; // Return content unchanged if not part of the landing page
});
eleventyConfig.addCollection("filteredTags", (collectionApi) => {
// Get all items and extract their tags
const allTags = collectionApi.getAll().flatMap((item) => item.data.tags || []);
// Filter tags to include only those in allowedTagKeys and remove duplicates
const uniqueFilteredTags = [...new Set(allTags.filter((tag) => allowedTagKeys.includes(tag)))];
return uniqueFilteredTags;
});
eleventyConfig.addCollection("filteredTagPages", (collectionApi) => {
const tagPageSize = 20;
const parseVersion = (version) => version.split('.').map(Number);
const versions = collectionApi.getFilteredByGlob("./changelog/**/*.md").sort((a, b) => {
const [aMajor, aMinor, aPatch] = parseVersion(a.data.title);
const [bMajor, bMinor, bPatch] = parseVersion(b.data.title);
if (aMajor !== bMajor) {
return bMajor - aMajor;
}
if (aMinor !== bMinor) {
return bMinor - aMinor;
}
return bPatch - aPatch;
});
const tagMap = new Map();
versions.forEach((item) => {
(item.data.tags || [])
.filter((tag) => allowedTagKeys.includes(tag))
.forEach((tag) => {
if (!tagMap.has(tag)) {
tagMap.set(tag, []);
}
tagMap.get(tag).push(item);
});
});
return Array.from(tagMap.entries())
.sort(([a], [b]) => a.localeCompare(b))
.flatMap(([tag, items]) => {
const encodedTag = encodeURIComponent(tag);
const totalPages = Math.ceil(items.length / tagPageSize);
const hrefs = Array.from({ length: totalPages }, (_, index) => {
if (index === 0) {
return `/changelog/tag/${encodedTag}/`;
}
return `/changelog/tag/${encodedTag}/${index + 1}/`;
});
return Array.from({ length: totalPages }, (_, pageIndex) => {
const start = pageIndex * tagPageSize;
const end = start + tagPageSize;
return {
tag,
permalink: hrefs[pageIndex],
items: items.slice(start, end),
pagination: {
label: `Pagination for ${tag} changelog pages`,
pageNumber: pageIndex,
pages: hrefs.map((_, i) => i + 1),
hrefs,
href: {
first: hrefs[0],
last: hrefs[hrefs.length - 1],
},
previousPageHref: pageIndex > 0 ? hrefs[pageIndex - 1] : null,
nextPageHref: pageIndex < totalPages - 1 ? hrefs[pageIndex + 1] : null,
},
};
});
});
});
eleventyConfig.on("eleventy.after", () => {
try {
execSync('npx pagefind --site _site --glob "**/*.html"', { stdio: 'inherit', encoding: 'utf-8' });
} catch (err) {
console.error('Pagefind generation failed:', err);
}
});
}