-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
.eleventy.ts
475 lines (416 loc) · 14.7 KB
/
.eleventy.ts
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
import "tsx/esm";
import { renderToStaticMarkup } from "react-dom/server";
import eleventyRemark from '@fec/eleventy-plugin-remark';
import { EleventyRenderPlugin } from "@11ty/eleventy";
import eleventyNavigation from '@11ty/eleventy-navigation';
import PropTypes from 'prop-types';
import argParse from 'liquid-args';
import path from 'path';
import fs from 'node:fs/promises';
import slug from 'slug';
import YAML from 'js-yaml';
import { asAttr, ifSet, IS_PRODUCTION, isolate } from './helpers';
import * as references from './references';
import { articleImage, person, license, organization } from './images';
import * as referenceSchema from './references-schema';
if (IS_PRODUCTION) {
PropTypes.resetWarningCache();
}
function _normalizeShortcodeScope(ctx) {
let obj: any = {};
if (ctx) {
obj.page = ctx.get(["page"]);
}
return obj;
}
export default function (eleventyConfig) {
eleventyConfig.addWatchTarget("src/maps");
eleventyConfig.addWatchTarget("bibliography.yaml");
eleventyConfig.addPassthroughCopy("fonts");
eleventyConfig.addPassthroughCopy("audio");
eleventyConfig.addPassthroughCopy("small-images");
eleventyConfig.addPassthroughCopy({ "site_root": "/" });
eleventyConfig.setServerPassthroughCopyBehavior("passthrough");
eleventyConfig.addPlugin(eleventyRemark, {
enableRehype: false,
plugins: [
'remark-sectionize',
{
plugin: 'remark-rehype',
options: { allowDangerousHtml: true }
},
citationPlugin,
addSlugs,
'@microflash/rehype-toc',
{
plugin: 'rehype-autolink-headings',
options: {
content: { type: 'text', value: '#' },
properties: {
ariaHidden: 'true',
tabIndex: -1,
class: 'permalink',
title: 'link to section'
}
},
},
'rehype-raw',
'rehype-stringify',
],
});
eleventyConfig.addPlugin(eleventyNavigation);
eleventyConfig.addExtension(["11ty.jsx", "11ty.ts", "11ty.tsx"], {
key: "11ty.js",
compile: function () {
return async function (data) {
let content = await this.defaultRenderer(data);
return renderToStaticMarkup(content);
};
},
});
eleventyConfig.addTemplateFormats(["11ty.ts","11ty.tsx"]);
//eleventyConfig.addDataFormats("11ty.ts,11ty.tsx");
eleventyConfig.addShortcode("person", person);
eleventyConfig.addShortcode("organization", organization);
eleventyConfig.addShortcode("license", license);
eleventyConfig.addShortcode("asAttr", asAttr);
eleventyConfig.addShortcode("isolate", isolate);
eleventyConfig.addShortcode("dice", dice);
eleventyConfig.addShortcode("cdice", chinese_dice);
eleventyConfig.addShortcode("jdice", japanese_dice);
eleventyConfig.addShortcode("cards", cards);
eleventyConfig.addLiquidTag("gameref", gameRef);
eleventyConfig.addLiquidTag("a", linkToArticle);
eleventyConfig.addShortcode("ce", () => `<abbr class="initialism">CE</abbr>`);
eleventyConfig.addShortcode("bce", () => `<abbr class="initialism">BCE</abbr>`);
eleventyConfig.addShortcode("c", () => `<abbr title="circa">c.</abbr>`);
eleventyConfig.addPairedShortcode("aside", function (content) {
return `<aside role="note" class="footnote">\n\n${content.trim()}\n\n</aside>`;
});
eleventyConfig.addPairedShortcode("fn", function (content) {
return `<span class="footnote-indicator"></span><span role="note" class="footnote">${content.trim()}</span>`;
});
eleventyConfig.addLiquidTag("pronounce", function (liquidEngine) {
return {
parse: function (tagToken) {
this.args = tagToken.args;
},
render: function* (scope) {
const args = yield Promise.all(argParse(this.args, arg => liquidEngine.evalValue(arg, scope)));
return pronunciation.call(_normalizeShortcodeScope(scope), args.find(a => a.__keywords));
}
}
});
eleventyConfig.addLiquidTag("image", function (liquidEngine) {
return {
parse: function (tagToken, remainTokens) {
this.args = tagToken.args;
this.templates = [];
var stream = liquidEngine.parser
.parseStream(remainTokens)
.on("template", tpl => this.templates.push(tpl))
.on("tag:imageEnd", () => stream.stop())
.on("end", () => { throw new Error("unclosed image tag"); });
stream.start();
},
render: function* (scope) {
const args = yield Promise.all(argParse(this.args, arg => liquidEngine.evalValue(arg, scope)));
const content = yield this.liquid.renderer.renderTemplates(this.templates, scope);
return articleImage.call(_normalizeShortcodeScope(scope), content, args.find(a => a.__keywords));
}
}
});
eleventyConfig.addPlugin(EleventyRenderPlugin);
return {
dir: {
input: "src",
output: "public",
},
};
};
// shortcode definitions:
function pronunciation(props) {
const { file, lang, word, pronouncer, noun } = props;
const klass = props['class'];
const mp3File = file ? ('/audio/' + file) : `/audio/pronunciation_${lang}_${word.replace(/\s+/g, '_')}.mp3`;
return `<audio preload="none" src="${mp3File}"></audio><span class="pronunciation${ifSet(noun, ' noun')}${ifSet(klass, ' ' + klass)}" lang="${lang}" title="Pronunciation © ‘${pronouncer}’ CC-BY-NC-SA 3.0, courtesy of Forvo.com." onclick="this.previousSibling.play()">${word}</span>`;
}
/**
* @param {string|number} content
*/
function cards(content) {
if (typeof content === 'number') {
return `<span class="playing-cards">${content}</span>`;
}
return '<span class="playing-cards">'
+ content.replace(/(1\d|.)/g, p => {
switch (p) {
case '10': return '⑩';
case '11': return '⑪';
case '12': return '⑫';
case '13': return '⑬';
case 's': return '♠';
case 'c': return '♣';
case 'h': return '<span class="red">♥</span>';
case 'd': return '<span class="red">♦</span>';
default: return p;
}
})
+ '</span>';
}
/**
* @param {string|number} content
*/
function chinese_dice(content) {
if (typeof content == 'number') {
content = content.toString(10)
}
return '<span class="dice">'
+ content.replace(/./g, c => `<img class="inline-img" alt="${c}" src="/small-images/d6_chinese/d6_${c}.svg" />`)
+ '</span>';
}
/**
* @param {string|number} content
*/
function japanese_dice(content) {
if (typeof content == 'number') {
content = content.toString(10)
}
return '<span class="dice">'
+ content.replace(/./g, c => `<img class="inline-img" alt="${c}" src="/small-images/d6_japanese/d6_${c}.svg" />`)
+ '</span>';
}
/**
* @param {string|number} content
*/
function dice(content) {
if (typeof content == 'number') {
content = content.toString(10)
}
return '<span class="dice">'
+ content.replace(/./g, c => `<img class="inline-img" alt="${c}" src="/small-images/d6/d6_${c}.svg" />`)
+ '</span>';
}
function linkToArticle() {
return {
parse: function (tagToken) {
this.args = tagToken.args.split(',');
},
render: async function(context) {
const articles = context.environments.collections.article;
const [slug, fragment] = this.args[0].split('#');
const article = articles.find(a => a.fileSlug === slug);
if (!article) {
throw new Error(`no such article found: ${slug}`);
}
const linkText = this.args.length > 1 ? this.args.slice(1).join(",") : article.data.title;
if (IS_PRODUCTION && article.data.draft) {
// don't link drafts in production
return linkText;
}
return `<a href="${article.url}${fragment ? ('#' + fragment) : ''}">${linkText}</a>`;
}
}
}
//figured out via https://github.com/11ty/eleventy/issues/813#issuecomment-1037834776
function gameRef() {
return {
parse: function (tagToken) {
this.ref = tagToken.args;
},
render: async function (context) {
const games = context.environments.collections.game;
const gameArticle = games.find(g => g.fileSlug === this.ref);
if (gameArticle) {
if (IS_PRODUCTION && gameArticle.data.draft) {
// don't link drafts in production
return `<span${asAttr('lang', gameArticle.data.titleLang)}>${gameArticle.data.title}</span>`;
}
return `<a href="${gameArticle.url}"${asAttr('lang', gameArticle.data.titleLang)}>${gameArticle.data.title}</a>`;
}
// try to find a sub-article
for (const g of games) {
if (g.data.subgames) {
for (const sg of g.data.subgames) {
const s = sg.slug || slug(sg.title);
if (s === this.ref) {
if (IS_PRODUCTION && g.data.draft) {
// don't link drafts in production
return `<span${asAttr('lang', sg.titleLang)}>${sg.title}</span>`;
}
return `<a href="${g.url}#${s}"${asAttr('lang', sg.titleLang)}>${sg.title}</a>`;
}
}
}
}
if (IS_PRODUCTION) {
throw new Error(`unknown game reference: ${this.ref}`);
} else {
console.log('Unknown game ref: ', this.ref);
return `UNKNOWN GAME REF: ${this.ref}`;
}
}
}
}
// altered from: https://github.com/rehypejs/rehype-slug/blob/main/index.js
const addSlugs = () => {
let imports: any = undefined;
return async tree => {
if (!imports) {
imports = {
hasProperty: (await import('hast-util-has-property')).hasProperty,
headingRank: (await import('hast-util-heading-rank')).headingRank,
toString: (await import('hast-util-to-string')).toString,
visit: (await import('unist-util-visit')).visit,
};
}
imports.visit(tree, 'element', node => {
if (imports.headingRank(node) && node.properties && !imports.hasProperty(node, 'id')) {
node.properties.id = slug(imports.toString(node).normalize("NFKD"));
}
})
}
}
let biblio = undefined;
let biblioLastModified = undefined;
let unist = undefined;
const citationPlugin = () => {
const indexToString = (/** @type {number} */ index) => {
let result = "";
while (index > 0) {
const num = (index - 1) % 26;
result = String.fromCodePoint('A'.charCodeAt(0) + num) + result
index = Math.floor((index - num) / 26);
}
return result;
};
const formatCitation = (
/** @type {string} */ id,
/** @type {number} */ index,
/** @type {boolean} */ inline,
/** @type {string} */ suffix) => {
const indicator = indexToString(index);
if (inline) {
const reference = biblio[id];
if (!reference) {
return `[UNKNOWN CITE: ${id}]`;
}
switch (reference.type) {
case 'book':
return `<a href="${`#ref-${id}`}">`
+ renderToStaticMarkup(references.renderLStr(reference.title, 'cite', {}))
+ `</a>`
+ ifSet(suffix, ` (${suffix})`);
case 'chapter':
case 'paper-conference':
case 'article-journal':
case 'thesis':
if (reference.author) {
return `<a href="${`#ref-${id}`}">${reference.author[0].family || reference.author[0].given}</a>`
+ ` (${referenceSchema.publicationYear(reference)}${ifSet(suffix, `, ${suffix}`)})`;
}
}
return `<span class="citation inline">[<a href="${`#ref-${id}`}" class="index">${indicator}</a>]${ifSet(suffix, ` (${suffix})`)}</span>`
} else {
return `<sup class="citation"><a class="index" href="${`#ref-${id}`}">${indicator}</a>${ifSet(suffix, `[${suffix}]`)}</sup>`;
}
};
// matches that in bibliography.11ty.js - TODO extract
const citeExtrator = /((?<!\w)@(?<id1>(_|[^\s\p{P}])+)(\s+\[(?<what1>[^\]]+)\])?)|(\[@(?<id2>(_|[^\s\p{P}])+)(,?\s+(?<what2>[^\]]+))?\])/u;
return async (tree, _file) => {
if (!unist) {
unist = await import('unist-util-visit');
}
const biblioPath = new URL('./bibliography.yaml', import.meta.url);
let stat = await fs.stat(biblioPath);
if (!biblio || stat.mtime > biblioLastModified) {
biblio = YAML.load(await fs.readFile(biblioPath, 'utf8'));
if (!referenceSchema.referenceValidator(biblio)) {
throw new Error(JSON.stringify(referenceSchema.referenceValidator.errors));
}
biblioLastModified = stat.mtime;
Object.entries(biblio).forEach(([key, value]) => {
value.id = key;
});
}
// collect all cites
const cited = [];
function handleNode(node, ix, parent) {
const text = node.value;
const match = text.match(citeExtrator);
if (!match) {
return;
}
const inline = !!match.groups.id1;
const id = match.groups.id1 || match.groups.id2;
const what = match.groups.what1 || match.groups.what2;
let index = cited.findIndex(x => x === id);
if (index < 0) {
index = cited.length;
cited.push(id);
}
const startIx = match.index;
const endIx = match.index + match[0].length;
if (node.type === 'raw') {
node.value = text.slice(0, startIx) + formatCitation(id, index + 1, inline, what) + text.slice(endIx);
return handleNode(node, ix, parent);
} else {
const children = [
{ type: 'text', value: text.slice(0, startIx) },
{ type: 'raw', value: formatCitation(id, index + 1, inline, what) },
{ type: 'text', value: text.slice(endIx) },
];
parent.children = [
...parent.children.slice(0, ix),
...children,
...parent.children.slice(ix + 1),
];
}
}
unist.visit(tree, ['text', 'raw'], handleNode);
if (cited.length > 0) {
// print the references
tree.children.push({
type: 'element',
tagName: 'section',
children: [
{
type: 'element',
tagName: 'h2',
properties: {
id: 'references',
},
children: [{ type: 'text', value: 'References' }]
},
{
type: 'element',
tagName: 'ol',
properties: {
class: "reference-list",
type: "A",
},
children: cited.map(id => {
if (!(id in biblio)) {
if (IS_PRODUCTION) {
throw new Error("unknown reference id: " + id);
} else {
console.error("unknown reference id: ", id);
return {
type: 'element',
tagName: 'li',
children: [{ type: 'text', value: `UNKNOWN REFERENCE '${id}'` }],
};
}
}
return {
type: 'element',
tagName: 'li',
children: [{ type: 'raw', value: renderToStaticMarkup(references.renderReference(biblio[id])) }],
};
}),
},
],
});
}
};
}