generated from 11ty/eleventy-base-blog
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path.eleventy.js
462 lines (412 loc) · 13.4 KB
/
.eleventy.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
const { DateTime, Duration } = require("luxon");
const fs = require("fs");
const pluginRss = require("@11ty/eleventy-plugin-rss");
const pluginSyntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
const pluginNavigation = require("@11ty/eleventy-navigation");
const markdownIt = require("markdown-it");
const markdownItAnchor = require("markdown-it-anchor");
const { minify } = require("terser");
const readingTime = require("eleventy-plugin-time-to-read");
const helpers = require("./src/_data/helpers");
const siteMeta = require("./src/_data/metadata.json");
const {
fetchGithubInfo,
fetchNPMWeeklyDownloads,
} = require("./src/filters/meta");
module.exports = (eleventyConfig) => {
/* Markdown Overrides */
let markdownLibrary = markdownIt({
html: true,
breaks: true,
linkify: true,
}).use(markdownItAnchor, {
permalinkAttrs: (slug) => ({
"aria-label": slug.replace(/-/g, " "),
}),
permalink: true,
permalinkClass: "direct-link",
permalinkSymbol: '<span class="copy-link"></span>',
});
eleventyConfig.setLibrary("md", markdownLibrary);
eleventyConfig.addPlugin(pluginSyntaxHighlight);
eleventyConfig.addPlugin(require("./plugins/image-transform"));
eleventyConfig.addPlugin(require("eleventy-plugin-markdown-copy-button"), {
// live demo component handles rendering of copy component
renderer: (content) => content,
});
const {
copyComponentRenderer,
} = require("eleventy-plugin-markdown-copy-button/renderer");
// Remember old renderer, if overridden, or proxy to default renderer
const plainCodeRenderer = function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
const defaultCodeRender =
markdownLibrary.renderer.rules.fence || plainCodeRenderer;
const renderCopyComponent = (...args) =>
`<copy-to-clipboard>${defaultCodeRender(...args)}</copy-to-clipboard>`;
markdownLibrary.renderer.rules.fence = (...args) => {
const [tokens, idx, options, env, self] = args;
env.parsedDemoIds = env.parsedDemoIds || [];
const parsedDemoIds = env.parsedDemoIds;
const token = tokens[idx];
const getDataFromInfo = (token) => {
const info = token.info || "";
let lang = info.substr(0, info.indexOf(" "));
let id = info.substr(info.indexOf(" ") + 1);
if (!lang) {
lang = id;
id = "";
}
return { id, lang };
};
const wrapCode = (lang, index) => {
const renderedCode = defaultCodeRender(tokens, index, options, env, self);
const languageKey =
lang.toLowerCase() === "javascript" ? "js" : lang.toLowerCase();
return `<div contenteditable slot="${languageKey}" data-language="${languageKey}">${renderedCode}</div>`;
};
let dataObj = getDataFromInfo(token);
if (dataObj && dataObj.id) {
if (parsedDemoIds.includes(dataObj.id)) {
return "";
}
let matchingTokens = [wrapCode(dataObj.lang, idx)];
for (let i = idx + 1; i < tokens.length; i++) {
if (tokens[i].type !== "fence") {
continue;
}
const { id, lang } = getDataFromInfo(tokens[i]);
if (id && id === dataObj.id) {
matchingTokens.push(wrapCode(lang, i));
}
}
parsedDemoIds.push(dataObj.id);
return `
<live-demo id=${dataObj.id}>
${matchingTokens.join("")}</live-demo>`;
// find all code with matching id
} else {
return renderCopyComponent(...args);
}
};
markdownLibrary.renderer.rules.image = (tokens) => {
const token = tokens[0];
const attrs = token.attrs.reduce((attrs, [key, value]) => {
attrs[key] = value;
return attrs;
}, {});
return String.raw`<figure>
<div class="img-wrap" ><img src="${attrs.src}" alt="${
attrs.alt || token.content
}">
<figcaption>${attrs.alt || attrs.title || token.content}</figcaption>
</div>
</figure>`;
};
// Remember old renderer, if overridden, or proxy to default renderer
const defaultLinkRender =
markdownLibrary.renderer.rules.link_open ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
markdownLibrary.renderer.rules.link_open = function (
tokens,
idx,
options,
env,
self
) {
// If you are sure other plugins can't add `target` - drop check below
const link = tokens[idx];
var aIndex = link.attrIndex("target");
const hrefIndex = link.attrIndex("href");
if (hrefIndex > -1) {
const href = link.attrs[hrefIndex][1];
const isRelativeUrl =
href &&
(href.startsWith("/") ||
href.startsWith("#") ||
href.startsWith(siteMeta.url));
if (isRelativeUrl) {
return defaultLinkRender(tokens, idx, options, env, self);
} else {
link.attrPush(["rel", "noopener"]); // add new attribute
}
}
if (aIndex < 0) {
link.attrPush(["target", "_blank"]); // add new attribute
} else {
link.attrs[aIndex][1] = "_blank"; // replace value of existing attr
}
// pass token to default renderer.
return defaultLinkRender(tokens, idx, options, env, self);
};
// Browsersync Overrides
eleventyConfig.setBrowserSyncConfig({
callbacks: {
ready: function (err, browserSync) {
const content_404 = fs.readFileSync("dist/404.html");
browserSync.addMiddleware("*", (req, res) => {
// Provides the 404 content without redirect.
res.write(content_404);
res.end();
});
},
},
ui: false,
ghostMode: false,
open: true,
});
eleventyConfig.addPassthroughCopy("src/images");
eleventyConfig.addPassthroughCopy("src/demos/**/assets/**");
eleventyConfig.addPassthroughCopy({ "src/posts/**/images/*.*": "images" });
eleventyConfig.setUseGitIgnore(false);
eleventyConfig.addPlugin(pluginRss);
eleventyConfig.addPlugin(pluginNavigation);
eleventyConfig.addPlugin(readingTime, {
speed: "300 words a minute",
});
eleventyConfig.setDataDeepMerge(true);
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
});
// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
eleventyConfig.addFilter("htmlDateString", (dateObj) => {
return DateTime.fromJSDate(dateObj, { zone: "utc" }).toFormat("yyyy-LL-dd");
});
eleventyConfig.addFilter("readableDate", (dateObj) => {
return DateTime.fromJSDate(dateObj, { zone: "utc" }).toFormat(
"dd LLL yyyy"
);
});
eleventyConfig.addFilter("sitemapDateTimeString", (dateObj) => {
const dt = DateTime.fromJSDate(dateObj, { zone: "utc" });
if (!dt.isValid) {
return "";
}
return dt.toISO();
});
eleventyConfig.addFilter("getMins", (mins) => {
return Duration.fromISO(mins * 1000);
});
// Get the first `n` elements of a collection.
eleventyConfig.addFilter("head", (array, n) => {
if (n < 0) {
return array.slice(n);
}
return array.slice(0, n);
});
eleventyConfig.addNunjucksAsyncFilter(
"jsmin",
async function (code, callback) {
try {
if (process.env.NODE_ENV === "production") {
const minified = await minify(code);
callback(null, minified.code);
} else {
callback(null, code);
}
} catch (err) {
console.error("Terser error: ", err);
// Fail gracefully.
callback(null, code);
}
}
);
eleventyConfig.addCollection("tagList", function (collection) {
const tagSet = new Set();
collection.getAll().forEach(function (item) {
if ("tags" in item.data) {
const tags = item.data.tags.filter(helpers.filterCollectionTags);
for (const tag of tags) {
tagSet.add(tag);
}
}
});
let paginatedTaggedPosts = [];
[...tagSet].forEach((name) => {
const pageSize = 15;
const elements = collection
.getFilteredByTag(name)
.sort((a, b) => b.date - a.date);
const pages = Math.ceil(elements.length / pageSize);
for (let i = 0; i < pages; i++) {
const startFrom = i * pageSize;
const tagData = {
name,
pageNumber: i,
elements: elements.slice(startFrom, startFrom + pageSize),
index: i,
pages,
hasNext: i < pages - 1,
hasPrev: i > 0,
};
paginatedTaggedPosts.push(tagData);
}
});
return paginatedTaggedPosts;
});
eleventyConfig.addCollection("tagNames", (collection) => {
const tagSet = new Set();
collection.getAll().forEach(function (item) {
if ("tags" in item.data) {
const tags = item.data.tags.filter(helpers.filterCollectionTags);
for (const tag of tags) {
tagSet.add(tag);
}
}
});
return [...tagSet];
});
// Returns a collection of blog posts in reverse date order
eleventyConfig.addCollection("archive", (collection) => {
return [...collection.getFilteredByGlob("./src/posts/**/*.md")].reverse();
});
eleventyConfig.addCollection("series", function (collection) {
const posts = collection.getFilteredByGlob("./src/posts/**/*.md");
const seriesCollection = {};
posts.forEach((post) => {
if (!post.data.series) {
return;
}
const series = post.data.series;
if (!series.title) {
throw new Error(
`series defined but no title present in item: ${post.inputPath}`
);
}
if (!series.order) {
throw new Error(
`series defined but no order for article supplied in item: ${post.inputPath}`
);
}
if (!seriesCollection[series.title]) {
seriesCollection[series.title] = { posts: {}, description: "" };
}
seriesCollection[series.title].posts[series.order - 1] = post;
if (!seriesCollection[series.title].description && series.description) {
seriesCollection[series.title].description = series.description;
}
if (
!seriesCollection[series.title].last_modified ||
post.date > seriesCollection[series.title].last_modified
) {
seriesCollection[series.title].last_modified = post.date;
}
if (typeof series.showTotal !== "undefined") {
seriesCollection[series.title].showTotal = series.showTotal;
}
post.data.seriesEntries = seriesCollection[series.title];
});
const seriesData = Object.keys(seriesCollection)
.map((title) => {
const data = seriesCollection[title];
return {
...data,
title,
posts: Object.values(data.posts),
};
// note this mutates
})
.sort((a, b) => b.last_modified - a.last_modified);
return seriesData;
});
eleventyConfig.addFilter(
"getSeriesInfo",
function ({ series, seriesEntries }) {
if (!series || !seriesEntries) {
return null;
}
const posts = seriesEntries.posts;
const postIndex = series.order - 1;
const next = posts[postIndex + 1];
const prev = posts[postIndex - 1];
return {
order: series.order,
showTotal: seriesEntries.showTotal,
next,
prev,
hasPrev: Boolean(prev),
hasNext: Boolean(next),
total: Object.keys(posts).length,
title: series.title,
description: seriesEntries.description,
};
}
);
eleventyConfig.addFilter("debugger", (...args) => {
//tip!
console.log(...args);
debugger;
});
eleventyConfig.addNunjucksAsyncFilter(
"fetchGithubRepo",
async (github, callback) => {
try {
const data = await fetchGithubInfo(github);
callback(null, data);
} catch (e) {
callback(e, null);
}
}
);
eleventyConfig.addNunjucksAsyncFilter(
"fetchNPMWeeklyDownloads",
async (package, callback) => {
try {
const data = await fetchNPMWeeklyDownloads(package);
callback(null, data);
} catch (e) {
callback(e, null);
}
}
);
eleventyConfig.addShortcode("twitter", (id) => {
return `https://twitter.com/anyuser/status/${id}`;
});
const YouTube = require("./src/_includes/components/youtube");
eleventyConfig.addShortcode("youtube", (id) => {
return YouTube({ id });
});
eleventyConfig.addFilter("nameFromObject", (arr) => {
return arr.map((ent) => ent.name);
});
eleventyConfig.addFilter("githubIssue", (page) => {
const inputPath = encodeURIComponent(page.inputPath);
// remove leading dot
const githubData = {
branch: "main",
repo: "https://github.com/Georgegriff/griffadev",
titlePrefix: "Content+correction:",
};
const issueUrl = `${githubData.repo}/blob/${
githubData.branch
}${page.inputPath.substr(1)}`;
const body = `Hello, I've noticed an issue in:
${issueUrl} \n\n**Describe the problem**\n
A clear and concise description of what the problem is\n
**Existing content**\n
What is there at the moment?\n
**Expected content**\n
What would you expect instead? A PR is more than welcome :smiley:\n
**Screenshots**\n
If applicable, add screenshots to help explain your problem\n
**Additional context**\n
Add any other context about the problem here.
`;
return `${githubData.repo}/issues/new?title=${
githubData.titlePrefix
}+${inputPath}&body=${encodeURIComponent(body)}`;
});
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
});
return {
templateFormats: ["md", "njk", "html", "liquid"],
dir: {
input: "src",
output: "dist",
},
};
};