-
Notifications
You must be signed in to change notification settings - Fork 0
/
.eleventy.js
553 lines (500 loc) · 17.1 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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
const slugify = require("@sindresorhus/slugify");
const markdownIt = require("markdown-it");
const fs = require("fs");
const matter = require("gray-matter");
const faviconsPlugin = require("eleventy-plugin-gen-favicons");
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;
}
function getAnchorLink(filePath, linkTitle) {
const {attributes, innerHTML} = getAnchorAttributes(filePath, linkTitle);
return `<a ${Object.keys(attributes).map(key => `${key}="${attributes[key]}"`).join(" ")}>${innerHTML}</a>`;
}
function getAnchorAttributes(filePath, linkTitle) {
let fileName = filePath.replaceAll("&", "&");
let header = "";
let headerLinkPath = "";
if (filePath.includes("#")) {
[fileName, header] = filePath.split("#");
headerLinkPath = `#${headerToId(header)}`;
}
let noteIcon = process.env.NOTE_ICON_DEFAULT;
const title = linkTitle ? linkTitle : fileName;
let permalink = `/notes/${slugify(filePath)}`;
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;
}
if (deadLink) {
return {
attributes: {
"class": "internal-link is-unresolved",
"href": "/404",
"target": "",
},
innerHTML: title,
}
}
return {
attributes: {
"class": "internal-link",
"target": "",
"data-note-icon": noteIcon,
"href": `${permalink}${headerLinkPath}`,
},
innerHTML: title,
}
}
const tagRegex = /(^|\s|\>)(#[^\s!@#$%^&*()=+\.,\[{\]};:'"?><]+)(?!([^<]*>))/g;
module.exports = function (eleventyConfig) {
eleventyConfig.setLiquidOptions({
dynamicPartials: true,
});
let markdownLib = markdownIt({
breaks: true,
html: true,
linkify: 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();
const parts = code.split("\n")
let titleLine;
let collapse;
let collapsible = false
let collapsed = true
let icon;
let color;
let nbLinesToSkip = 0
for (let i = 0; i < 4; i++) {
if (parts[i] && parts[i].trim()) {
let line = parts[i] && parts[i].trim().toLowerCase()
if (line.startsWith("title:")) {
titleLine = line.substring(6);
nbLinesToSkip++;
} else if (line.startsWith("icon:")) {
icon = line.substring(5);
nbLinesToSkip++;
} else if (line.startsWith("collapse:")) {
collapsible = true
collapse = line.substring(9);
if (collapse && collapse.trim().toLowerCase() == 'open') {
collapsed = false
}
nbLinesToSkip++;
} else if (line.startsWith("color:")) {
color = line.substring(6);
nbLinesToSkip++;
}
}
}
const foldDiv = collapsible ? `<div class="callout-fold">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon lucide-chevron-down">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</div>` : "";
const titleDiv = titleLine
? `<div class="callout-title"><div class="callout-title-inner">${titleLine}</div>${foldDiv}</div>`
: "";
let collapseClasses = titleLine && collapsible ? 'is-collapsible' : ''
if (collapsible && collapsed) {
collapseClasses += " is-collapsed"
}
let res = `<div data-callout-metadata class="callout ${collapseClasses}" data-callout="${token.info.substring(3)
}">${titleDiv}\n<div class="callout-content">${md.render(
parts.slice(nbLinesToSkip).join("\n")
)}</div></div>`;
return res
}
// 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;
//"image.png|metadata?|width"
const [fileName, ...widthAndMetaData] = imageName.split("|");
const lastValue = widthAndMetaData[widthAndMetaData.length - 1];
const lastValueIsNumber = !isNaN(lastValue);
const width = lastValueIsNumber ? lastValue : null;
let metaData = "";
if (widthAndMetaData.length > 1) {
metaData = widthAndMetaData.slice(0, widthAndMetaData.length - 1).join(" ");
}
if (!lastValueIsNumber) {
metaData += ` ${lastValue}`;
}
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("isoDate", function (date) {
return date && date.toISOString();
});
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("|");
return getAnchorLink(fileLink, linkTitle);
})
);
});
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("dataview-js-links", function (str) {
const parsed = parse(str);
for (const dataViewJsLink of parsed.querySelectorAll("a[data-href].internal-link")) {
const notePath = dataViewJsLink.getAttribute("data-href");
const title = dataViewJsLink.innerHTML;
const {attributes, innerHTML} = getAnchorAttributes(notePath, title);
for (const key in attributes) {
dataViewJsLink.setAttribute(key, attributes[key]);
}
dataViewJsLink.innerHTML = innerHTML;
}
return str && parsed.innerHTML;
});
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 calloutMetaData = "";
let isCollapsable;
let isCollapsed;
const calloutMeta = /\[!([\w-]*)\|?(\s?.*)\](\+|\-){0,1}(\s?.*)/;
if (!content.match(calloutMeta)) {
continue;
}
content = content.replace(
calloutMeta,
function (metaInfoMatch, callout, metaData, 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;
calloutMetaData = metaData;
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());
calloutMetaData && blockquote.setAttribute("data-callout-metadata", calloutMetaData);
blockquote.innerHTML = `${titleDiv}\n<div class="callout-content">${content}</div>`;
}
};
transformCalloutBlocks();
return str && parsed.innerHTML;
});
function fillPictureSourceSets(src, cls, alt, meta, width, imageTag) {
imageTag.tagName = "picture";
let html = `<source
media="(max-width:480px)"
srcset="${meta.webp[0].url}"
type="image/webp"
/>
<source
media="(max-width:480px)"
srcset="${meta.jpeg[0].url}"
/>
`
if (meta.webp && meta.webp[1] && meta.webp[1].url) {
html += `<source
media="(max-width:1920px)"
srcset="${meta.webp[1].url}"
type="image/webp"
/>`
}
if (meta.jpeg && meta.jpeg[1] && meta.jpeg[1].url) {
html += `<source
media="(max-width:1920px)"
srcset="${meta.jpeg[1].url}"
/>`
}
html += `<img
class="${cls.toString()}"
src="${src}"
alt="${alt}"
width="${width}"
/>`;
imageTag.innerHTML = html;
}
eleventyConfig.addTransform("picture", function (str) {
const parsed = parse(str);
for (const imageTag of parsed.querySelectorAll(".cm-s-obsidian img")) {
const src = imageTag.getAttribute("src");
if (src && src.startsWith("/") && !src.endsWith(".svg")) {
const cls = imageTag.classList.value;
const alt = imageTag.getAttribute("alt");
const width = imageTag.getAttribute("width") || '';
try {
const meta = transformImage(
"./src/site" + decodeURI(imageTag.getAttribute("src")),
cls.toString(),
alt,
["(max-width: 480px)", "(max-width: 1024px)"]
);
if (meta) {
fillPictureSourceSets(src, cls, alt, meta, width, imageTag);
}
} 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(faviconsPlugin, { outputDir: "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: false,
passthroughFileCopy: true,
};
};