forked from oleeskild/digitalgarden
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.eleventy.js
455 lines (409 loc) · 13.8 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
const slugify = require("@sindresorhus/slugify");
const markdownIt = require("markdown-it");
const fs = require("fs");
const matter = require("gray-matter");
const faviconPlugin = require("eleventy-favicon");
const tocPlugin = require("eleventy-plugin-nesting-toc");
const { parse } = require("node-html-parser");
const htmlMinifier = require("html-minifier");
const pluginRss = require("@11ty/eleventy-plugin-rss");
const { headerToId, namedHeadingsFilter } = require("./src/helpers/utils");
const {
userMarkdownSetup,
userEleventySetup,
} = require("./src/helpers/userSetup");
const Image = require("@11ty/eleventy-img");
function transformImage(src, cls, alt, sizes, widths = ["500", "700", "auto"]) {
let options = {
widths: widths,
formats: ["webp", "jpeg"],
outputDir: "./dist/img/optimized",
urlPath: "/img/optimized",
};
// generate images, while this is async we don’t wait
Image(src, options);
let metadata = Image.statsSync(src, options);
return metadata;
}
const tagRegex = /(^|\s|\>)(#[^\s!@#$%^&*()=+\.,\[{\]};:'"?><]+)(?!([^<]*>))/g;
module.exports = function (eleventyConfig) {
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
});
let markdownLib = markdownIt({
breaks: true,
html: true,
})
.use(require("markdown-it-anchor"), {
slugify: headerToId,
})
.use(require("markdown-it-mark"))
.use(require("markdown-it-footnote"))
.use(function (md) {
md.renderer.rules.hashtag_open = function (tokens, idx) {
return '<a class="tag" onclick="toggleTagSearch(this)">';
};
})
.use(require("markdown-it-mathjax3"), {
tex: {
inlineMath: [["$", "$"]],
},
options: {
skipHtmlTags: { "[-]": ["pre"] },
},
})
.use(require("markdown-it-attrs"))
.use(require("markdown-it-task-checkbox"), {
disabled: true,
divWrap: false,
divClass: "checkbox",
idPrefix: "cbx_",
ulClass: "task-list",
liClass: "task-list-item",
})
.use(require("markdown-it-plantuml"), {
openMarker: "```plantuml",
closeMarker: "```",
})
.use(namedHeadingsFilter)
.use(function (md) {
//https://github.com/DCsunset/markdown-it-mermaid-plugin
const origFenceRule =
md.renderer.rules.fence ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
md.renderer.rules.fence = (tokens, idx, options, env, slf) => {
const token = tokens[idx];
if (token.info === "mermaid") {
const code = token.content.trim();
return `<pre class="mermaid">${code}</pre>`;
}
if (token.info === "transclusion") {
const code = token.content.trim();
return `<div class="transclusion">${md.render(code)}</div>`;
}
if (token.info.startsWith("ad-")) {
const code = token.content.trim();
if (code && code.toLowerCase().startsWith("title:")) {
const title = code.substring(6, code.indexOf("\n"));
const titleDiv = title
? `<div class="callout-title"><div class="callout-title-inner">${title}</div></div>`
: "";
return `<div class="callout" data-callout="${
token.info
}">${titleDiv}\n<div class="callout-content">${md.render(
code.slice(code.indexOf("\n"))
)}</div></div>`;
}
const title = `<div class="callout-title"><div class="callout-title-inner">${token.info
.charAt(3)
.toUpperCase()}${token.info
.substring(4)
.toLowerCase()}</div></div>`;
return `<div class="callout" data-callout="${
token.info
}">${title}\n<div class="callout-content">${md.render(
code
)}</div></div>`;
}
// Other languages
return origFenceRule(tokens, idx, options, env, slf);
};
const defaultImageRule =
md.renderer.rules.image ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
md.renderer.rules.image = (tokens, idx, options, env, self) => {
const imageName = tokens[idx].content;
const [fileName, width] = imageName.split("|");
if (width) {
const widthIndex = tokens[idx].attrIndex("width");
const widthAttr = `${width}px`;
if (widthIndex < 0) {
tokens[idx].attrPush(["width", widthAttr]);
} else {
tokens[idx].attrs[widthIndex][1] = widthAttr;
}
}
return defaultImageRule(tokens, idx, options, env, self);
};
const defaultLinkRule =
md.renderer.rules.link_open ||
function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options, env, self);
};
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const aIndex = tokens[idx].attrIndex("target");
const classIndex = tokens[idx].attrIndex("class");
if (aIndex < 0) {
tokens[idx].attrPush(["target", "_blank"]);
} else {
tokens[idx].attrs[aIndex][1] = "_blank";
}
if (classIndex < 0) {
tokens[idx].attrPush(["class", "external-link"]);
} else {
tokens[idx].attrs[classIndex][1] = "external-link";
}
return defaultLinkRule(tokens, idx, options, env, self);
};
})
.use(userMarkdownSetup);
eleventyConfig.setLibrary("md", markdownLib);
eleventyConfig.addFilter("link", function (str) {
return (
str &&
str.replace(/\[\[(.*?\|.*?)\]\]/g, function (match, p1) {
//Check if it is an embedded excalidraw drawing or mathjax javascript
if (p1.indexOf("],[") > -1 || p1.indexOf('"$"') > -1) {
return match;
}
const [fileLink, linkTitle] = p1.split("|");
let fileName = fileLink.replaceAll("&", "&");
let header = "";
let headerLinkPath = "";
if (fileLink.includes("#")) {
[fileName, header] = fileLink.split("#");
headerLinkPath = `#${headerToId(header)}`;
}
let permalink = `/notes/${slugify(fileName)}`;
let noteIcon = process.env.NOTE_ICON_DEFAULT;
const title = linkTitle ? linkTitle : fileName;
let deadLink = false;
try {
const startPath = "./src/site/notes/";
const fullPath = fileName.endsWith(".md")
? `${startPath}${fileName}`
: `${startPath}${fileName}.md`;
const file = fs.readFileSync(fullPath, "utf8");
const frontMatter = matter(file);
if (frontMatter.data.permalink) {
permalink = frontMatter.data.permalink;
}
if (
frontMatter.data.tags &&
frontMatter.data.tags.indexOf("gardenEntry") != -1
) {
permalink = "/";
}
if (frontMatter.data.noteIcon) {
noteIcon = frontMatter.data.noteIcon;
}
} catch {
deadLink = true;
}
return `<a class="internal-link ${
deadLink ? "is-unresolved" : ""
}" ${deadLink ? "" : 'data-note-icon="' + noteIcon + '"'} href="${permalink}${headerLinkPath}">${title}</a>`;
})
);
});
eleventyConfig.addFilter("taggify", function (str) {
return (
str &&
str.replace(tagRegex, function (match, precede, tag) {
return `${precede}<a class="tag" onclick="toggleTagSearch(this)" data-content="${tag}">${tag}</a>`;
})
);
});
eleventyConfig.addFilter("searchableTags", function (str) {
let tags;
let match = str && str.match(tagRegex);
if (match) {
tags = match
.map((m) => {
return `"${m.split("#")[1]}"`;
})
.join(", ");
}
if (tags) {
return `${tags},`;
} else {
return "";
}
});
eleventyConfig.addFilter("hideDataview", function (str) {
return (
str &&
str.replace(/\(\S+\:\:(.*)\)/g, function (_, value) {
return value.trim();
})
);
});
eleventyConfig.addTransform("callout-block", function (str) {
const parsed = parse(str);
const transformCalloutBlocks = (
blockquotes = parsed.querySelectorAll("blockquote")
) => {
for (const blockquote of blockquotes) {
transformCalloutBlocks(blockquote.querySelectorAll("blockquote"));
let content = blockquote.innerHTML;
let titleDiv = "";
let calloutType = "";
let isCollapsable;
let isCollapsed;
const calloutMeta = /\[!([\w-]*)\](\+|\-){0,1}(\s?.*)/;
if (!content.match(calloutMeta)) {
continue;
}
content = content.replace(
calloutMeta,
function (metaInfoMatch, callout, collapse, title) {
isCollapsable = Boolean(collapse);
isCollapsed = collapse === "-";
const titleText = title.replace(/(<\/{0,1}\w+>)/, "")
? title
: `${callout.charAt(0).toUpperCase()}${callout
.substring(1)
.toLowerCase()}`;
const fold = isCollapsable
? `<div class="callout-fold"><i icon-name="chevron-down"></i></div>`
: ``;
calloutType = callout;
titleDiv = `<div class="callout-title"><div class="callout-title-inner">${titleText}</div>${fold}</div>`;
return "";
}
);
blockquote.tagName = "div";
blockquote.classList.add("callout");
blockquote.classList.add(isCollapsable ? "is-collapsible" : "");
blockquote.classList.add(isCollapsed ? "is-collapsed" : "");
blockquote.setAttribute("data-callout", calloutType.toLowerCase());
blockquote.innerHTML = `${titleDiv}\n<div class="callout-content">${content}</div>`;
}
};
transformCalloutBlocks();
return str && parsed.innerHTML;
});
eleventyConfig.addTransform("picture", function (str) {
const parsed = parse(str);
for (const t of parsed.querySelectorAll(".cm-s-obsidian img")) {
const src = t.getAttribute("src");
if (src && src.startsWith("/") && !src.endsWith(".svg")) {
const cls = t.classList;
const alt = t.getAttribute("alt");
try {
const meta = transformImage(
"./src/site" + decodeURI(t.getAttribute("src")),
cls.toString(),
alt,
["(max-width: 480px)", "(max-width: 1024px)"]
);
if (meta) {
t.tagName = "picture";
t.innerHTML = `<source
media="(max-width:480px)"
srcset="${meta.webp[0].url}"
type="image/webp"
/>
<source
media="(max-width:480px)"
srcset="${meta.jpeg[0].url}"
/>
<source
media="(max-width:1920px)"
srcset="${meta.webp[1].url}"
type="image/webp"
/>
<source
media="(max-width:1920px)"
srcset="${meta.jpeg[1].url}"
/>
<img
class="${cls.toString()}"
src="${src}"
alt="${alt}"
/>`;
}
} catch {
// Make it fault tolarent.
}
}
}
return str && parsed.innerHTML;
});
eleventyConfig.addTransform("table", function (str) {
const parsed = parse(str);
for (const t of parsed.querySelectorAll(".cm-s-obsidian > table")) {
let inner = t.innerHTML;
t.tagName = "div";
t.classList.add("table-wrapper");
t.innerHTML = `<table>${inner}</table>`;
}
for (const t of parsed.querySelectorAll(
".cm-s-obsidian > .block-language-dataview > table"
)) {
t.classList.add("dataview");
t.classList.add("table-view-table");
t.querySelector("thead").classList.add("table-view-thead");
t.querySelector("tbody").classList.add("table-view-tbody");
t.querySelectorAll("thead > tr").forEach((tr) => {
tr.classList.add("table-view-tr-header");
});
t.querySelectorAll("thead > tr > th").forEach((th) => {
th.classList.add("table-view-th");
});
}
return str && parsed.innerHTML;
});
eleventyConfig.addTransform("htmlMinifier", (content, outputPath) => {
if (
process.env.NODE_ENV === "production" &&
outputPath &&
outputPath.endsWith(".html")
) {
return htmlMinifier.minify(content, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
keepClosingSlash: true,
});
}
return content;
});
eleventyConfig.addPassthroughCopy("src/site/img");
eleventyConfig.addPassthroughCopy("src/site/scripts");
eleventyConfig.addPassthroughCopy("src/site/styles/_theme.*.css");
eleventyConfig.addPlugin(faviconPlugin, { destination: "dist" });
eleventyConfig.addPlugin(tocPlugin, {
ul: true,
tags: ["h1", "h2", "h3", "h4", "h5", "h6"],
});
eleventyConfig.addFilter("dateToZulu", function (date) {
if (!date) return "";
return new Date(date).toISOString("dd-MM-yyyyTHH:mm:ssZ");
});
eleventyConfig.addFilter("jsonify", function (variable) {
return JSON.stringify(variable) || '""';
});
eleventyConfig.addFilter("validJson", function (variable) {
if (Array.isArray(variable)) {
return variable.map((x) => x.replaceAll("\\", "\\\\")).join(",");
} else if (typeof variable === "string") {
return variable.replaceAll("\\", "\\\\");
}
return variable;
});
eleventyConfig.addPlugin(pluginRss, {
posthtmlRenderOptions: {
closingSingleTag: "slash",
singleTags: ["link"],
},
});
userEleventySetup(eleventyConfig);
return {
dir: {
input: "src/site",
output: "dist",
data: `_data`,
},
templateFormats: ["njk", "md", "11ty.js"],
htmlTemplateEngine: "njk",
markdownTemplateEngine: "njk",
passthroughFileCopy: true,
};
};