]> Witch of Git - web/blog/blob - eleventy.config.js
Fix a typo in p-nickname
[web/blog] / eleventy.config.js
1 import pluginRss from "@11ty/eleventy-plugin-rss";
2 import pluginSyntaxHighlight from "@11ty/eleventy-plugin-syntaxhighlight";
3 import uslug from "uslug";
4 import anchor from "markdown-it-anchor";
5 import markdownIt from "markdown-it";
6 import CleanCSS from "clean-css";
7 import htmlMinifier from "html-minifier-terser";
8 import util from "util";
9 import { DateTime } from "luxon";
10
11 const md = markdownIt({
12 html: true,
13 typographer: true,
14 }).use(anchor, {
15 slugify: s => uslug(s),
16 permalink: true,
17 permalinkBefore: true,
18 permalinkClass: "header-anchor c-sun dec-none",
19 });
20
21 export default async function (eleventyConfig) {
22 eleventyConfig.addDateParsing(parseDate);
23 // @TODO: Update to the new virtual template setup?
24 eleventyConfig.addPlugin(pluginRss);
25 eleventyConfig.addPlugin(pluginSyntaxHighlight);
26
27 eleventyConfig.setLibrary("md", md);
28
29 eleventyConfig.addTransform("html-minifier", htmlMinifierTransform);
30
31 eleventyConfig.addPassthroughCopy("img");
32 eleventyConfig.addPassthroughCopy("static");
33 eleventyConfig.addPassthroughCopy("stamps");
34 eleventyConfig.addPassthroughCopy({ "favicon": "/" });
35
36 eleventyConfig.addNunjucksShortcode("youtube", youtubeShortcode);
37 eleventyConfig.addPairedNunjucksShortcode("tweet", tweetShortcode);
38 eleventyConfig.addPairedShortcode("aside", asideShortcode);
39 eleventyConfig.addPairedShortcode("figure", figureShortcode);
40
41 eleventyConfig.addFilter("date", dateFilter);
42 eleventyConfig.addFilter("markdown", value => md.renderInline(value));
43 eleventyConfig.addFilter("groupby", groupbyFilter);
44 eleventyConfig.addFilter("cssmin", css =>
45 new CleanCSS({}).minify(css).styles);
46 eleventyConfig.addFilter("debug", util.inspect);
47 eleventyConfig.addFilter("toRfc3339", toRfc3339Filter);
48 eleventyConfig.addFilter("hasTime", hasTimeFilter);
49
50 eleventyConfig.setDataDeepMerge(true);
51
52 eleventyConfig.addCollection("years", collection => {
53 const posts = collection.getFilteredByTag("posts");
54 const items = groupby(posts, item => item.date.getFullYear());
55 return items.reduce((obj, [k, v]) => (obj[k] = v, obj), {});
56 });
57
58 return {
59 markdownTemplateEngine: "njk",
60 };
61 };
62
63 /**
64 * @param {{string | Date | DateTime}} anyDate
65 * @returns {DateTime}
66 */
67 function dateTime(anyDate) {
68 if (anyDate instanceof Date) {
69 return DateTime.fromJSDate(anyDate);
70 }
71 if (DateTime.isDateTime(anyDate)) {
72 return anyDate;
73 }
74 let date = parseDate(anyDate);
75 if (date == null) { throw Error(`failed to parse date ${anyDate}`); }
76 return date;
77 }
78
79 function dateFilter(date, format) {
80 return dateTime(date).toFormat(format);
81 }
82
83 function toRfc3339Filter(date) {
84 return dateTime(date).toISO({ suppressMilliseconds: true });
85 }
86
87 function hasTimeFilter(date) {
88 date = dateTime(date);
89 return date.hour != 0
90 || date.minute != 0
91 || date.second != 0
92 || date.millisecond != 0;
93 }
94
95 /**
96 * @param {string} dateText
97 * @returns {{DateTime | null}}
98 */
99 function parseDate(dateText) {
100 try {
101 if (!dateText) dateText = "";
102 const formats = [
103 "yyyy-MM-dd HH:mm:ss z",
104 "yyyy-MM-dd z",
105 "yyyy-MM-dd",
106 ];
107 for (const format of formats) {
108 const date = DateTime.fromFormat(dateText, format, { setZone: true });
109 if (date.isValid) { return date; }
110 }
111 } catch {
112 return null;
113 }
114 }
115
116 function access(item, path) {
117 const segments = path.split(".");
118 for (const seg of segments) {
119 if (item === undefined) { return null; }
120 if (seg.endsWith("()")) {
121 const method = item[seg.slice(0, -2)];
122 if (method === undefined) { return null; }
123 item = method.bind(item)();
124 } else {
125 item = item[seg];
126 }
127 }
128 return item;
129 }
130
131 function groupby(items, keyFn) {
132 const results = [];
133 for (const item of items) {
134 const key = keyFn(item);
135 if (results.length == 0 || key != results[results.length-1][0]) {
136 results.push([key, [item]]);
137 } else {
138 results[results.length-1][1].push(item);
139 }
140 }
141 return results;
142 }
143
144 function groupbyFilter(items, path) {
145 return groupby(items, item => access(item, path));
146 }
147
148 function youtubeShortcode(items, inWidth = 560, inHeight = 315) {
149 const width = items.width || inWidth;
150 const height = items.height || inHeight;
151 const allow = items.allow || "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
152 const border = items.border || "0";
153 const video = items.video || items;
154 if (!video) {
155 throw "Required argument 'video'.";
156 }
157 const src = "https://www.youtube.com/embed/" + video;
158 return `<div class="youtube row hcenter">
159 <iframe width="${width}" height="${height}" src="${src}"
160 frameborder="${border}" allow="${allow}" allowfullscreen></iframe>
161 </div>`;
162 }
163
164 function tweetShortcode(content, items) {
165 // @TODO: Handle parsing date
166 return `<div class="row hcenter">
167 <blockquote class="twitter-tweet">
168 <p lang="en" dir="ltr">${content}</p> &mdash; ${items.name} (@${items.at})
169 <a href="${items.link}">${items.date}</a>
170 </blockquote>
171 <script async src="https://platform.twitter.com/widgets.js" charset="utf-8">
172 </script>
173 </div>`;
174 }
175
176 function asideShortcode(content, style='') {
177 const html = md.render(content);
178 if (style) {
179 return `<aside class="${style}">${html}</aside>`;
180 } else {
181 return `<aside>${html}</aside>`;
182 }
183 }
184
185 function figureShortcode(content, { src, alt }) {
186 const captionHtml = md.render(content);
187 return `<figure class="col hcenter">
188 <img src="${src}" alt="${alt}">
189 <figcaption>${captionHtml}</figcaption>
190 </figure>`;
191 }
192
193 function htmlMinifierTransform(content, outputPath) {
194 if (outputPath.endsWith(".html")) {
195 return htmlMinifier.minify(content, {
196 useShortDoctype: true,
197 removeComments: true,
198 collapseWhitespace: true,
199 });
200 }
201 return content;
202 }