@lvl99dotcom/edaha.md 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +13 -2
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +9 -0
- package/dist/cli/index.d.ts +71 -0
- package/dist/cli/index.js +149 -0
- package/dist/embeds/blocks/index.d.ts +59 -0
- package/dist/embeds/blocks/index.js +103 -0
- package/dist/embeds/index.d.ts +143 -0
- package/dist/embeds/index.js +411 -0
- package/dist/embeds/types/index.d.ts +117 -0
- package/dist/embeds/types/index.js +1 -0
- package/dist/generator/article/index.d.ts +151 -0
- package/dist/generator/article/index.js +325 -0
- package/dist/generator/build/index.d.ts +109 -0
- package/dist/generator/build/index.js +363 -0
- package/dist/generator/config/index.d.ts +96 -0
- package/dist/generator/config/index.js +298 -0
- package/dist/generator/configFile/index.d.ts +58 -0
- package/dist/generator/configFile/index.js +122 -0
- package/dist/generator/fields/index.d.ts +93 -0
- package/dist/generator/fields/index.js +186 -0
- package/dist/generator/format/index.d.ts +92 -0
- package/dist/generator/format/index.js +177 -0
- package/dist/generator/lists/index.d.ts +63 -0
- package/dist/generator/lists/index.js +133 -0
- package/dist/generator/markdown/index.d.ts +25 -0
- package/dist/generator/markdown/index.js +62 -0
- package/dist/generator/metadata/index.d.ts +150 -0
- package/dist/generator/metadata/index.js +361 -0
- package/dist/generator/metadataGroups/index.d.ts +45 -0
- package/dist/generator/metadataGroups/index.js +169 -0
- package/dist/generator/slug/index.d.ts +26 -0
- package/dist/generator/slug/index.js +57 -0
- package/dist/generator/templates/index.d.ts +88 -0
- package/dist/generator/templates/index.js +175 -0
- package/dist/generator/types/index.d.ts +186 -0
- package/dist/generator/types/index.js +1 -0
- package/dist/generator/urls/index.d.ts +50 -0
- package/dist/generator/urls/index.js +77 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +9 -0
- package/dist/theme/index.d.ts +8 -0
- package/dist/theme/index.js +9 -0
- package/package.json +64 -3
- package/theme/static/base.css +328 -0
- package/theme/templates/article/list.njk +69 -0
- package/theme/templates/article/single.njk +64 -0
- package/theme/templates/layouts/html.njk +72 -0
- package/theme/templates/layouts/rssfeed.njk +28 -0
- package/theme/templates/page/home.njk +16 -0
- package/theme/templates/page/single.njk +18 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The editor's own groups, in order, with their core settings. "slug" and "uploaded" (the files in the article's
|
|
3
|
+
* folder) aren't settings, but have their place too. Custom fields without a group go in "custom".
|
|
4
|
+
*/
|
|
5
|
+
export const BUILT_IN_GROUPS = [
|
|
6
|
+
{
|
|
7
|
+
key: "info",
|
|
8
|
+
title: "Info",
|
|
9
|
+
openedByDefault: true,
|
|
10
|
+
fields: ["type", "status", "slug", "date", "author"],
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
key: "categorise",
|
|
14
|
+
title: "Categorise",
|
|
15
|
+
openedByDefault: false,
|
|
16
|
+
fields: ["tags"],
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
key: "customise",
|
|
20
|
+
title: "Customise",
|
|
21
|
+
openedByDefault: true,
|
|
22
|
+
fields: ["excerpt", "template"],
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
key: "files",
|
|
26
|
+
title: "Files",
|
|
27
|
+
openedByDefault: true,
|
|
28
|
+
fields: ["thumbnail", "attachments", "uploaded"],
|
|
29
|
+
},
|
|
30
|
+
{ key: "custom", title: "Custom", openedByDefault: false, fields: [] },
|
|
31
|
+
];
|
|
32
|
+
/** The settings a custom group can have */
|
|
33
|
+
const GROUP_KEYS = ["title", "description", "after", "openedByDefault"];
|
|
34
|
+
/** Group keys: a letter, then letters, digits, "_" or "-" */
|
|
35
|
+
const KEY = /^[A-Za-z][\w-]*$/;
|
|
36
|
+
/** Check a value is a map (not a list), throwing an Error naming it if not */
|
|
37
|
+
const asMap = (value, what) => {
|
|
38
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
39
|
+
throw new Error(`${what} must be a map of settings`);
|
|
40
|
+
return value;
|
|
41
|
+
};
|
|
42
|
+
/** Read an optional text setting, throwing an Error naming it if it isn't text */
|
|
43
|
+
const optionalText = (value, what) => {
|
|
44
|
+
if (value === undefined || value === null)
|
|
45
|
+
return undefined;
|
|
46
|
+
if (typeof value !== "string" || !value.trim())
|
|
47
|
+
throw new Error(`${what} must be non-empty text`);
|
|
48
|
+
return value.trim();
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Read the config file's `metadataGroups` setting: groups of settings for the editor, by key. Throws an Error if a key
|
|
52
|
+
* is a built-in group's or isn't usable, or a group's settings aren't valid.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* parseMetadataGroups({ seo: { title: "SEO", after: "info", openedByDefault: true } });
|
|
56
|
+
*/
|
|
57
|
+
export const parseMetadataGroups = (value) => {
|
|
58
|
+
if (value === undefined || value === null)
|
|
59
|
+
return {};
|
|
60
|
+
const groups = asMap(value, '"metadataGroups"');
|
|
61
|
+
return Object.fromEntries(Object.entries(groups).map(([key, settings]) => {
|
|
62
|
+
const what = `"metadataGroups.${key}"`;
|
|
63
|
+
if (BUILT_IN_GROUPS.some((group) => group.key === key))
|
|
64
|
+
throw new Error(`${what} can't be used: "${key}" is a built-in group`);
|
|
65
|
+
if (!KEY.test(key))
|
|
66
|
+
throw new Error(`${what} must start with a letter and have only letters, digits, "_" and "-"`);
|
|
67
|
+
const fields = asMap(settings, what);
|
|
68
|
+
const unknown = Object.keys(fields).filter((name) => !GROUP_KEYS.includes(name));
|
|
69
|
+
if (unknown.length)
|
|
70
|
+
throw new Error(`${what} has unknown settings: ${unknown.map((name) => `"${name}"`).join(", ")}`);
|
|
71
|
+
const opened = fields.openedByDefault ?? false;
|
|
72
|
+
if (typeof opened !== "boolean")
|
|
73
|
+
throw new Error(`${what}.openedByDefault must be true or false`);
|
|
74
|
+
return [
|
|
75
|
+
key,
|
|
76
|
+
{
|
|
77
|
+
title: optionalText(fields.title, `${what}.title`) ??
|
|
78
|
+
fail(`${what}.title is required`),
|
|
79
|
+
description: optionalText(fields.description, `${what}.description`),
|
|
80
|
+
after: optionalText(fields.after, `${what}.after`),
|
|
81
|
+
openedByDefault: opened,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
84
|
+
}));
|
|
85
|
+
};
|
|
86
|
+
/** Throw an Error with a message */
|
|
87
|
+
const fail = (message) => {
|
|
88
|
+
throw new Error(message);
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Where a custom field's `$edahaField.group` puts it: a group key, or `{ key, after }`. Fields without one go in
|
|
92
|
+
* "custom". Throws an Error naming the field if it isn't valid.
|
|
93
|
+
*/
|
|
94
|
+
const fieldPlace = (name, group) => {
|
|
95
|
+
const what = `"metadata.${name}.$edahaField.group"`;
|
|
96
|
+
if (group === undefined || group === null)
|
|
97
|
+
return { key: "custom" };
|
|
98
|
+
if (typeof group === "string")
|
|
99
|
+
return { key: group };
|
|
100
|
+
const place = asMap(group, what);
|
|
101
|
+
return {
|
|
102
|
+
key: optionalText(place.key, `${what}.key`) ?? fail(`${what}.key is required`),
|
|
103
|
+
after: optionalText(place.after, `${what}.after`),
|
|
104
|
+
};
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* Put items in order: those without `after` in the order given, then each after the one it names. Throws an Error
|
|
108
|
+
* (from `missing`) for an item whose `after` names nothing in the list.
|
|
109
|
+
*/
|
|
110
|
+
const placeAfter = (start, items, missing) => {
|
|
111
|
+
const order = [...start, ...items.filter((i) => !i.after).map((i) => i.name)];
|
|
112
|
+
let waiting = items.filter((i) => i.after);
|
|
113
|
+
// Each pass places the items whose `after` is already placed, until none are left or none can be
|
|
114
|
+
while (waiting.length) {
|
|
115
|
+
const ready = waiting.filter((i) => order.includes(i.after));
|
|
116
|
+
if (!ready.length) {
|
|
117
|
+
const [first] = waiting;
|
|
118
|
+
throw new Error(missing(first.name, first.after));
|
|
119
|
+
}
|
|
120
|
+
for (const { name, after } of ready)
|
|
121
|
+
order.splice(order.indexOf(after) + 1, 0, name);
|
|
122
|
+
waiting = waiting.filter((i) => !ready.includes(i));
|
|
123
|
+
}
|
|
124
|
+
return order;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* The editor's groups of settings in order, each with its fields in order: the built-in groups (and the custom groups,
|
|
128
|
+
* placed after the group they name or at the end), with every custom field in its group (after the field it names, or
|
|
129
|
+
* at the group's end). Throws an Error if a field's group doesn't exist, or a field or group names one to follow that
|
|
130
|
+
* isn't there.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* metadataLayout({ hero: { $edahaField: { group: { key: "files", after: "thumbnail" }, file: true } } }, {});
|
|
134
|
+
* // [..., { key: "files", fields: ["thumbnail", "hero", "attachments", "uploaded"], ... }, ...]
|
|
135
|
+
*/
|
|
136
|
+
export const metadataLayout = (definitions, groups) => {
|
|
137
|
+
const all = [
|
|
138
|
+
...BUILT_IN_GROUPS.map((group) => ({
|
|
139
|
+
...group,
|
|
140
|
+
fields: [...group.fields],
|
|
141
|
+
})),
|
|
142
|
+
...Object.entries(groups).map(([key, group]) => ({
|
|
143
|
+
key,
|
|
144
|
+
title: group.title,
|
|
145
|
+
description: group.description,
|
|
146
|
+
openedByDefault: group.openedByDefault,
|
|
147
|
+
fields: [],
|
|
148
|
+
})),
|
|
149
|
+
];
|
|
150
|
+
const byKey = new Map(all.map((group) => [group.key, group]));
|
|
151
|
+
// Each group's custom fields, in the config file's order
|
|
152
|
+
const placed = new Map();
|
|
153
|
+
for (const [name, schema] of Object.entries(definitions)) {
|
|
154
|
+
const place = fieldPlace(name, schema.$edahaField?.group);
|
|
155
|
+
if (!byKey.has(place.key))
|
|
156
|
+
throw new Error(`"metadata.${name}" is in group "${place.key}", which isn't a built-in group or in "metadataGroups"`);
|
|
157
|
+
placed.set(place.key, [
|
|
158
|
+
...(placed.get(place.key) ?? []),
|
|
159
|
+
{ name, after: place.after },
|
|
160
|
+
]);
|
|
161
|
+
}
|
|
162
|
+
for (const group of all)
|
|
163
|
+
group.fields = placeAfter(group.fields, placed.get(group.key) ?? [], (name, after) => `"metadata.${name}" comes after "${after}", which isn't in group "${group.key}"`);
|
|
164
|
+
const order = placeAfter(BUILT_IN_GROUPS.map((group) => group.key), Object.entries(groups).map(([key, group]) => ({
|
|
165
|
+
name: key,
|
|
166
|
+
after: group.after,
|
|
167
|
+
})), (name, after) => `"metadataGroups.${name}" comes after "${after}", which isn't a group`);
|
|
168
|
+
return order.map((key) => byKey.get(key));
|
|
169
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convert text to a lowercase, URL-safe `kebab-case` slug. Accented letters become basic Latin, quotes and
|
|
3
|
+
* apostrophes are removed, and any other runs of characters become a single `-`.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* slugify("What?! Who Is This?!? I don't think so..."); // "what-who-is-this-i-dont-think-so"
|
|
7
|
+
* slugify("Café Naïve"); // "cafe-naive"
|
|
8
|
+
*/
|
|
9
|
+
export declare const slugify: (text: string) => string;
|
|
10
|
+
/**
|
|
11
|
+
* Whether text is already a valid slug.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* isSlug("hello-world"); // true
|
|
15
|
+
* isSlug("Hello World"); // false
|
|
16
|
+
*/
|
|
17
|
+
export declare const isSlug: (text: string) => boolean;
|
|
18
|
+
/**
|
|
19
|
+
* IDs for a document's headings, from their text (as slugs): a repeated heading gets `-2`, `-3`… added, and a heading
|
|
20
|
+
* without letters or numbers gets none (an empty string).
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* headingIds(["This?! Is an, example...", "Notes", "Notes", "!!!"]);
|
|
24
|
+
* // ["this-is-an-example", "notes", "notes-2", ""]
|
|
25
|
+
*/
|
|
26
|
+
export declare const headingIds: (texts: string[]) => string[];
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Letters that don't split into a basic Latin letter plus diacritics */
|
|
2
|
+
const LATIN_EXTRA = {
|
|
3
|
+
ß: "ss",
|
|
4
|
+
æ: "ae",
|
|
5
|
+
œ: "oe",
|
|
6
|
+
ø: "o",
|
|
7
|
+
đ: "d",
|
|
8
|
+
ð: "d",
|
|
9
|
+
ł: "l",
|
|
10
|
+
þ: "th",
|
|
11
|
+
ı: "i",
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Convert text to a lowercase, URL-safe `kebab-case` slug. Accented letters become basic Latin, quotes and
|
|
15
|
+
* apostrophes are removed, and any other runs of characters become a single `-`.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* slugify("What?! Who Is This?!? I don't think so..."); // "what-who-is-this-i-dont-think-so"
|
|
19
|
+
* slugify("Café Naïve"); // "cafe-naive"
|
|
20
|
+
*/
|
|
21
|
+
export const slugify = (text) => text
|
|
22
|
+
.normalize("NFKD")
|
|
23
|
+
.replace(/\p{Diacritic}/gu, "")
|
|
24
|
+
.toLowerCase()
|
|
25
|
+
.replace(/[ßæœøđðłþı]/g, (letter) => LATIN_EXTRA[letter])
|
|
26
|
+
.replace(/['"‘’“”`´]/g, "")
|
|
27
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
28
|
+
.replace(/^-+|-+$/g, "");
|
|
29
|
+
/**
|
|
30
|
+
* Whether text is already a valid slug.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* isSlug("hello-world"); // true
|
|
34
|
+
* isSlug("Hello World"); // false
|
|
35
|
+
*/
|
|
36
|
+
export const isSlug = (text) => text !== "" && slugify(text) === text;
|
|
37
|
+
/**
|
|
38
|
+
* IDs for a document's headings, from their text (as slugs): a repeated heading gets `-2`, `-3`… added, and a heading
|
|
39
|
+
* without letters or numbers gets none (an empty string).
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* headingIds(["This?! Is an, example...", "Notes", "Notes", "!!!"]);
|
|
43
|
+
* // ["this-is-an-example", "notes", "notes-2", ""]
|
|
44
|
+
*/
|
|
45
|
+
export const headingIds = (texts) => {
|
|
46
|
+
const used = new Set();
|
|
47
|
+
return texts.map((text) => {
|
|
48
|
+
const base = slugify(text);
|
|
49
|
+
if (!base)
|
|
50
|
+
return "";
|
|
51
|
+
let id = base;
|
|
52
|
+
for (let n = 2; used.has(id); n++)
|
|
53
|
+
id = `${base}-${n}`;
|
|
54
|
+
used.add(id);
|
|
55
|
+
return id;
|
|
56
|
+
});
|
|
57
|
+
};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import nunjucks from "nunjucks";
|
|
2
|
+
import type { Logger, TemplateData } from "../types/index.ts";
|
|
3
|
+
/** Templates that must exist for the build to run */
|
|
4
|
+
export declare const REQUIRED_TEMPLATES: string[];
|
|
5
|
+
/**
|
|
6
|
+
* Template names starting with this always load from the last template folder (the default theme's), e.g.
|
|
7
|
+
* `{% extends "@theme/article/single.njk" %}` in a site's own `article/single.njk`, to build on the theme's version.
|
|
8
|
+
*/
|
|
9
|
+
export declare const THEME_PREFIX = "@theme/";
|
|
10
|
+
/**
|
|
11
|
+
* A Nunjucks loader for template names starting with THEME_PREFIX, from one folder. Other names are left to the next
|
|
12
|
+
* loader.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* themeLoader("/theme/templates").getSource("@theme/article/single.njk"); // the theme's article/single.njk
|
|
16
|
+
*/
|
|
17
|
+
export declare const themeLoader: (dir: string) => nunjucks.ILoader;
|
|
18
|
+
/**
|
|
19
|
+
* Make a root-relative URL absolute on the website's domain, e.g. for RSS feeds read outside the website. Template
|
|
20
|
+
* data URLs already start with the website's base URL, so only its origin is added.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* absoluteUrl("/news/", "https://example.com"); // "https://example.com/news/"
|
|
24
|
+
* absoluteUrl("/edaha.md/news/", "https://lvl99.github.io/edaha.md"); // "https://lvl99.github.io/edaha.md/news/"
|
|
25
|
+
*/
|
|
26
|
+
export declare const absoluteUrl: (url: string, siteUrl: string) => string;
|
|
27
|
+
/**
|
|
28
|
+
* Make root-relative `href` and `src` URLs in HTML absolute (see absoluteUrl), e.g. for RSS feeds read outside the
|
|
29
|
+
* website.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* absoluteUrls('<a href="/news/">', "https://example.com"); // '<a href="https://example.com/news/">'
|
|
33
|
+
*/
|
|
34
|
+
export declare const absoluteUrls: (html: string, siteUrl: string) => string;
|
|
35
|
+
/** Template tags that output the page's embed HTML (`TemplateData.embeds`), by where it goes */
|
|
36
|
+
export declare const EMBED_TAGS: {
|
|
37
|
+
readonly embedHead: "head";
|
|
38
|
+
readonly embedFoot: "foot";
|
|
39
|
+
readonly embedRenderHead: "head";
|
|
40
|
+
readonly embedRenderFoot: "foot";
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Loads and renders the site's Nunjucks templates from one or more folders. A file in an earlier folder overrides the
|
|
44
|
+
* same file in later ones (e.g. a site's templates over the default theme's). Falls back to the `article` templates
|
|
45
|
+
* (with a warning) when an article type has none of its own. Names starting with THEME_PREFIX (`@theme/`) load from
|
|
46
|
+
* the last folder only.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* const templates = new Templates(["site/templates", join(THEME_DIR, "templates")], console);
|
|
50
|
+
* templates.render(templates.resolve("article", "single"), data);
|
|
51
|
+
*/
|
|
52
|
+
export declare class Templates {
|
|
53
|
+
private readonly dirs;
|
|
54
|
+
private readonly logger;
|
|
55
|
+
private readonly env;
|
|
56
|
+
private readonly warned;
|
|
57
|
+
/**
|
|
58
|
+
* Throws if any of the required templates are missing.
|
|
59
|
+
*/
|
|
60
|
+
constructor(dirs: string | string[], logger: Logger);
|
|
61
|
+
/**
|
|
62
|
+
* Whether a template file or folder exists in any of the template folders.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* templates.exists("page/home.njk"); // true
|
|
66
|
+
*/
|
|
67
|
+
private exists;
|
|
68
|
+
/**
|
|
69
|
+
* The template file for an article type's template name (e.g. "single", "list" or "home"). Types without their own
|
|
70
|
+
* templates folder use `templates/article/`; a type folder without the template falls back to `templates/article/`
|
|
71
|
+
* with a warning (once per file). Throws if the template exists in neither.
|
|
72
|
+
*
|
|
73
|
+
* @example
|
|
74
|
+
* templates.resolve("page", "home"); // "page/home.njk" if it exists, otherwise "article/home.njk"
|
|
75
|
+
*/
|
|
76
|
+
resolve(type: string, name: string): string;
|
|
77
|
+
/**
|
|
78
|
+
* The template names an article of a type can use (its own and the default ones, except "list"), sorted.
|
|
79
|
+
*
|
|
80
|
+
* @example
|
|
81
|
+
* templates.names("page"); // ["home", "single"]
|
|
82
|
+
*/
|
|
83
|
+
names(type: string): string[];
|
|
84
|
+
/**
|
|
85
|
+
* Render a template with the given data.
|
|
86
|
+
*/
|
|
87
|
+
render(file: string, data: TemplateData): string;
|
|
88
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import nunjucks from "nunjucks";
|
|
4
|
+
import { formatDate, formatRfc822 } from "../format/index.js";
|
|
5
|
+
/** Templates that must exist for the build to run */
|
|
6
|
+
export const REQUIRED_TEMPLATES = [
|
|
7
|
+
"layouts/html.njk",
|
|
8
|
+
"layouts/rssfeed.njk",
|
|
9
|
+
"article/single.njk",
|
|
10
|
+
"article/list.njk",
|
|
11
|
+
];
|
|
12
|
+
/**
|
|
13
|
+
* Template names starting with this always load from the last template folder (the default theme's), e.g.
|
|
14
|
+
* `{% extends "@theme/article/single.njk" %}` in a site's own `article/single.njk`, to build on the theme's version.
|
|
15
|
+
*/
|
|
16
|
+
export const THEME_PREFIX = "@theme/";
|
|
17
|
+
/**
|
|
18
|
+
* A Nunjucks loader for template names starting with THEME_PREFIX, from one folder. Other names are left to the next
|
|
19
|
+
* loader.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* themeLoader("/theme/templates").getSource("@theme/article/single.njk"); // the theme's article/single.njk
|
|
23
|
+
*/
|
|
24
|
+
export const themeLoader = (dir) => {
|
|
25
|
+
const files = new nunjucks.FileSystemLoader(dir);
|
|
26
|
+
return {
|
|
27
|
+
getSource: (name) => name.startsWith(THEME_PREFIX)
|
|
28
|
+
? files.getSource(name.slice(THEME_PREFIX.length))
|
|
29
|
+
: // Nunjucks' loaders answer null for templates they don't have
|
|
30
|
+
null,
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Make a root-relative URL absolute on the website's domain, e.g. for RSS feeds read outside the website. Template
|
|
35
|
+
* data URLs already start with the website's base URL, so only its origin is added.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* absoluteUrl("/news/", "https://example.com"); // "https://example.com/news/"
|
|
39
|
+
* absoluteUrl("/edaha.md/news/", "https://lvl99.github.io/edaha.md"); // "https://lvl99.github.io/edaha.md/news/"
|
|
40
|
+
*/
|
|
41
|
+
export const absoluteUrl = (url, siteUrl) => new URL(url, siteUrl).href;
|
|
42
|
+
/**
|
|
43
|
+
* Make root-relative `href` and `src` URLs in HTML absolute (see absoluteUrl), e.g. for RSS feeds read outside the
|
|
44
|
+
* website.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* absoluteUrls('<a href="/news/">', "https://example.com"); // '<a href="https://example.com/news/">'
|
|
48
|
+
*/
|
|
49
|
+
export const absoluteUrls = (html, siteUrl) => html.replace(/(\s(?:href|src)=")\/(?!\/)/g, `$1${new URL(siteUrl).origin}/`);
|
|
50
|
+
/** Template tags that output the page's embed HTML (`TemplateData.embeds`), by where it goes */
|
|
51
|
+
export const EMBED_TAGS = {
|
|
52
|
+
embedHead: "head",
|
|
53
|
+
embedFoot: "foot",
|
|
54
|
+
// The names the brief's first draft used
|
|
55
|
+
embedRenderHead: "head",
|
|
56
|
+
embedRenderFoot: "foot",
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* The `{% embedHead %}` and `{% embedFoot %}` tags (also `{% embedRenderHead() %}` and `{% embedRenderFoot() %}`): output
|
|
60
|
+
* the HTML that the page's embeds need once in its `<head>`, or before `</body>`. They output nothing on pages without
|
|
61
|
+
* embeds.
|
|
62
|
+
*/
|
|
63
|
+
class EmbedTags {
|
|
64
|
+
tags = Object.keys(EMBED_TAGS);
|
|
65
|
+
/** Read the tag (with or without empty brackets) */
|
|
66
|
+
parse(parser, nodes) {
|
|
67
|
+
const token = parser.nextToken();
|
|
68
|
+
// Brackets are optional, and the tags take no arguments
|
|
69
|
+
const args = parser.parseSignature(true, false) ??
|
|
70
|
+
new nodes.NodeList(token.lineno, token.colno);
|
|
71
|
+
parser.advanceAfterBlockEnd(token.value);
|
|
72
|
+
return new nodes.CallExtension(this, token.value, args, []);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const [tag, part] of Object.entries(EMBED_TAGS))
|
|
76
|
+
Object.defineProperty(EmbedTags.prototype, tag, {
|
|
77
|
+
value: (context) => new nunjucks.runtime.SafeString(context.ctx.embeds?.[part] ?? ""),
|
|
78
|
+
});
|
|
79
|
+
/**
|
|
80
|
+
* Loads and renders the site's Nunjucks templates from one or more folders. A file in an earlier folder overrides the
|
|
81
|
+
* same file in later ones (e.g. a site's templates over the default theme's). Falls back to the `article` templates
|
|
82
|
+
* (with a warning) when an article type has none of its own. Names starting with THEME_PREFIX (`@theme/`) load from
|
|
83
|
+
* the last folder only.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* const templates = new Templates(["site/templates", join(THEME_DIR, "templates")], console);
|
|
87
|
+
* templates.render(templates.resolve("article", "single"), data);
|
|
88
|
+
*/
|
|
89
|
+
export class Templates {
|
|
90
|
+
dirs;
|
|
91
|
+
logger;
|
|
92
|
+
env;
|
|
93
|
+
warned = new Set();
|
|
94
|
+
/**
|
|
95
|
+
* Throws if any of the required templates are missing.
|
|
96
|
+
*/
|
|
97
|
+
constructor(dirs, logger) {
|
|
98
|
+
this.dirs = typeof dirs === "string" ? [dirs] : dirs;
|
|
99
|
+
const missing = REQUIRED_TEMPLATES.filter((file) => !this.exists(file));
|
|
100
|
+
if (missing.length)
|
|
101
|
+
throw new Error(`Missing required templates in ${this.dirs.join(", ")}: ${missing.join(", ")}`);
|
|
102
|
+
this.logger = logger;
|
|
103
|
+
this.env = new nunjucks.Environment([
|
|
104
|
+
themeLoader(this.dirs.at(-1)),
|
|
105
|
+
new nunjucks.FileSystemLoader(this.dirs),
|
|
106
|
+
], {
|
|
107
|
+
autoescape: true,
|
|
108
|
+
// Keep the generated HTML free of blank lines left by template tags
|
|
109
|
+
trimBlocks: true,
|
|
110
|
+
lstripBlocks: true,
|
|
111
|
+
});
|
|
112
|
+
this.env.addFilter("date", formatDate);
|
|
113
|
+
this.env.addFilter("rfc822", formatRfc822);
|
|
114
|
+
this.env.addFilter("absoluteUrl", absoluteUrl);
|
|
115
|
+
this.env.addFilter("absoluteUrls", absoluteUrls);
|
|
116
|
+
this.env.addExtension("embeds", new EmbedTags());
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Whether a template file or folder exists in any of the template folders.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* templates.exists("page/home.njk"); // true
|
|
123
|
+
*/
|
|
124
|
+
exists(file) {
|
|
125
|
+
return this.dirs.some((dir) => existsSync(join(dir, file)));
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The template file for an article type's template name (e.g. "single", "list" or "home"). Types without their own
|
|
129
|
+
* templates folder use `templates/article/`; a type folder without the template falls back to `templates/article/`
|
|
130
|
+
* with a warning (once per file). Throws if the template exists in neither.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* templates.resolve("page", "home"); // "page/home.njk" if it exists, otherwise "article/home.njk"
|
|
134
|
+
*/
|
|
135
|
+
resolve(type, name) {
|
|
136
|
+
const file = `${type}/${name}.njk`;
|
|
137
|
+
if (this.exists(file))
|
|
138
|
+
return file;
|
|
139
|
+
const fallback = `article/${name}.njk`;
|
|
140
|
+
if (!this.exists(fallback))
|
|
141
|
+
throw new Error(`Template "${name}" not found: looked for ${file} and ${fallback} in ${this.dirs.join(" and ")}`);
|
|
142
|
+
if (this.exists(type) && !this.warned.has(file)) {
|
|
143
|
+
this.warned.add(file);
|
|
144
|
+
this.logger.warn(`Template ${file} not found; using ${fallback}`);
|
|
145
|
+
}
|
|
146
|
+
return fallback;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The template names an article of a type can use (its own and the default ones, except "list"), sorted.
|
|
150
|
+
*
|
|
151
|
+
* @example
|
|
152
|
+
* templates.names("page"); // ["home", "single"]
|
|
153
|
+
*/
|
|
154
|
+
names(type) {
|
|
155
|
+
const names = new Set();
|
|
156
|
+
for (const dir of this.dirs)
|
|
157
|
+
for (const folder of ["article", type]) {
|
|
158
|
+
try {
|
|
159
|
+
for (const file of readdirSync(join(dir, folder)))
|
|
160
|
+
if (file.endsWith(".njk") && file !== "list.njk")
|
|
161
|
+
names.add(file.slice(0, -4));
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// A type without its own templates folder
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return [...names].sort();
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Render a template with the given data.
|
|
171
|
+
*/
|
|
172
|
+
render(file, data) {
|
|
173
|
+
return this.env.render(file, data);
|
|
174
|
+
}
|
|
175
|
+
}
|