@lvl99dotcom/edaha-editor 0.0.0-stage → 0.3.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/client/assets/index-BwcJ6yrI.js +1578 -0
- package/dist/client/assets/index-D2Y17Fm-.css +1 -0
- package/dist/client/index.html +21 -0
- package/dist/editor/index.d.ts +69 -0
- package/dist/editor/index.js +125 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- package/dist/server/app/index.d.ts +98 -0
- package/dist/server/app/index.js +390 -0
- package/dist/server/articleIndex/index.d.ts +126 -0
- package/dist/server/articleIndex/index.js +352 -0
- package/dist/server/convert/index.d.ts +38 -0
- package/dist/server/convert/index.js +180 -0
- package/dist/server/files/index.d.ts +66 -0
- package/dist/server/files/index.js +256 -0
- package/dist/server/store/index.d.ts +287 -0
- package/dist/server/store/index.js +693 -0
- package/dist/server/types/index.d.ts +251 -0
- package/dist/server/types/index.js +15 -0
- package/package.json +59 -3
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { watch } from "node:fs";
|
|
2
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { join, sep } from "node:path";
|
|
4
|
+
import { parseArticleConfig, splitArticle, splitContent, } from "@lvl99dotcom/edaha.md/generator/article";
|
|
5
|
+
import { isSlug } from "@lvl99dotcom/edaha.md/generator/slug";
|
|
6
|
+
import { DEFAULT_ORDERS } from "../types/index.js";
|
|
7
|
+
import { fileKind } from "../files/index.js";
|
|
8
|
+
/** Whether an article has problems of the kind a query looks for */
|
|
9
|
+
const hasProblems = (article, filter) => (article.problems ?? []).some(({ level }) => filter === "any" ||
|
|
10
|
+
(filter === "errors" ? level === "error" : level === "warning"));
|
|
11
|
+
/** The most articles a page of query results has */
|
|
12
|
+
export const MAX_PER_PAGE = 50;
|
|
13
|
+
/** How many of each type's most recently changed articles the editor's nav shows */
|
|
14
|
+
export const RECENT_COUNT = 5;
|
|
15
|
+
/** The names of a folder's sub-folders that can be article types or slugs (none if it doesn't exist) */
|
|
16
|
+
const slugFolders = async (dir) => {
|
|
17
|
+
try {
|
|
18
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
19
|
+
return entries
|
|
20
|
+
.filter((entry) => entry.isDirectory() && isSlug(entry.name))
|
|
21
|
+
.map((entry) => entry.name)
|
|
22
|
+
.sort();
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return [];
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Read an article's summary from its folder: its settings, title, when its article.md last changed, and (with `check`)
|
|
30
|
+
* problems with its custom metadata. Articles that can't be read are summarised with their error. Undefined if the
|
|
31
|
+
* folder has no article.md.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* await summarizeArticle("my-site/articles", "news", "hello");
|
|
35
|
+
* // { type: "news", slug: "hello", title: "Hello", status: "published", date: "2026-10-19T09:54:00.000Z", tags: [], ... }
|
|
36
|
+
*/
|
|
37
|
+
export const summarizeArticle = async (articlesDir, type, slug, check) => {
|
|
38
|
+
const file = join(articlesDir, type, slug, "article.md");
|
|
39
|
+
let source;
|
|
40
|
+
let updated;
|
|
41
|
+
try {
|
|
42
|
+
[source, updated] = await Promise.all([
|
|
43
|
+
readFile(file, "utf8"),
|
|
44
|
+
stat(file).then((info) => info.mtime.toISOString()),
|
|
45
|
+
]);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
const { header, content } = splitArticle(source);
|
|
52
|
+
const config = parseArticleConfig(header, type, `${type}/${slug}`);
|
|
53
|
+
const problems = check?.(type, header) ?? [];
|
|
54
|
+
return {
|
|
55
|
+
type,
|
|
56
|
+
slug,
|
|
57
|
+
title: config.title ?? splitContent(content).heading ?? slug,
|
|
58
|
+
status: config.status,
|
|
59
|
+
date: config.date,
|
|
60
|
+
author: config.author ? config.author.name : undefined,
|
|
61
|
+
tags: config.tags,
|
|
62
|
+
updated,
|
|
63
|
+
...(problems.length ? { problems } : {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return {
|
|
68
|
+
type,
|
|
69
|
+
slug,
|
|
70
|
+
title: slug,
|
|
71
|
+
status: "draft",
|
|
72
|
+
date: "",
|
|
73
|
+
tags: [],
|
|
74
|
+
updated,
|
|
75
|
+
error: error.message,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Text for comparing without case or accents.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* comparable("Zoë Ångström"); // "zoe angstrom"
|
|
84
|
+
*/
|
|
85
|
+
export const comparable = (text) => text
|
|
86
|
+
.normalize("NFD")
|
|
87
|
+
.replace(/\p{Diacritic}/gu, "")
|
|
88
|
+
.toLocaleLowerCase();
|
|
89
|
+
/** Sort articles newest first by a date field, then by slug */
|
|
90
|
+
const byNewest = (field) => (a, b) => b[field].localeCompare(a[field]) || a.slug.localeCompare(b.slug);
|
|
91
|
+
/** Sort articles by title (A to Z, ignoring case and accents), then by type and slug */
|
|
92
|
+
const byTitle = (a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: "base" }) ||
|
|
93
|
+
a.type.localeCompare(b.type) ||
|
|
94
|
+
a.slug.localeCompare(b.slug);
|
|
95
|
+
/** The value each sort compares (dates are ISO 8601, so they compare as text) */
|
|
96
|
+
const SORT_VALUES = {
|
|
97
|
+
title: (article) => comparable(article.title),
|
|
98
|
+
type: (article) => article.type,
|
|
99
|
+
status: (article) => article.status,
|
|
100
|
+
date: (article) => article.date,
|
|
101
|
+
updated: (article) => article.updated,
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* How to sort articles for a query: by its sort's value (default: date), in its order (default: the sort's own), then
|
|
105
|
+
* by title A to Z.
|
|
106
|
+
*/
|
|
107
|
+
const articleOrder = (query) => {
|
|
108
|
+
const sort = query.sort ?? "date";
|
|
109
|
+
const direction = (query.order ?? DEFAULT_ORDERS[sort]) === "asc" ? 1 : -1;
|
|
110
|
+
const value = SORT_VALUES[sort];
|
|
111
|
+
return (a, b) => direction * value(a).localeCompare(value(b)) || byTitle(a, b);
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Find articles: those whose title contains the search text (ignoring case and accents) and that match the type,
|
|
115
|
+
* author, tag, status and problems given, sorted by title, type, status, date or when their file last changed, ascending or
|
|
116
|
+
* descending (by default titles, types and statuses A to Z and dates newest first), one page at a time.
|
|
117
|
+
*
|
|
118
|
+
* @example
|
|
119
|
+
* queryArticles(articles, { search: "hello", type: "news", sort: "title", page: 2 });
|
|
120
|
+
* // { articles: [...], total: 73, page: 2, pages: 2, perPage: 50 }
|
|
121
|
+
*/
|
|
122
|
+
export const queryArticles = (articles, query = {}) => {
|
|
123
|
+
const search = comparable(query.search?.trim() ?? "");
|
|
124
|
+
const author = query.author && comparable(query.author);
|
|
125
|
+
const tag = query.tag && comparable(query.tag);
|
|
126
|
+
const found = articles
|
|
127
|
+
.filter((article) => (!search || comparable(article.title).includes(search)) &&
|
|
128
|
+
(!query.type || article.type === query.type) &&
|
|
129
|
+
(!author || comparable(article.author ?? "") === author) &&
|
|
130
|
+
(!tag || article.tags.some((t) => comparable(t) === tag)) &&
|
|
131
|
+
(!query.status || article.status === query.status) &&
|
|
132
|
+
(!query.problems || hasProblems(article, query.problems)))
|
|
133
|
+
.sort(articleOrder(query));
|
|
134
|
+
const perPage = Math.min(Math.max(Math.floor(query.perPage ?? MAX_PER_PAGE), 1), MAX_PER_PAGE);
|
|
135
|
+
const pages = Math.max(Math.ceil(found.length / perPage), 1);
|
|
136
|
+
const page = Math.min(Math.max(Math.floor(query.page ?? 1), 1), pages);
|
|
137
|
+
return {
|
|
138
|
+
articles: found.slice((page - 1) * perPage, page * perPage),
|
|
139
|
+
total: found.length,
|
|
140
|
+
page,
|
|
141
|
+
pages,
|
|
142
|
+
perPage,
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Each type's most recently changed articles (by when their file last changed), types in alphabetical order.
|
|
147
|
+
*
|
|
148
|
+
* @example
|
|
149
|
+
* recentArticles(articles, 5); // [{ type: "news", articles: [...5 articles], total: 120 }, ...]
|
|
150
|
+
*/
|
|
151
|
+
export const recentArticles = (articles, count = RECENT_COUNT) => [...new Set(articles.map((article) => article.type))].sort().map((type) => {
|
|
152
|
+
const ofType = articles.filter((article) => article.type === type);
|
|
153
|
+
return {
|
|
154
|
+
type,
|
|
155
|
+
articles: ofType.sort(byNewest("updated")).slice(0, count),
|
|
156
|
+
total: ofType.length,
|
|
157
|
+
};
|
|
158
|
+
});
|
|
159
|
+
/** Unique values, sorted alphabetically ignoring case and accents, keeping the first spelling of each */
|
|
160
|
+
const uniqueSorted = (values) => {
|
|
161
|
+
const unique = new Map();
|
|
162
|
+
for (const value of values)
|
|
163
|
+
if (value && !unique.has(comparable(value)))
|
|
164
|
+
unique.set(comparable(value), value);
|
|
165
|
+
return [...unique.values()].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
|
166
|
+
};
|
|
167
|
+
/**
|
|
168
|
+
* The types, authors and tags articles use, for the article browser's filters.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* articleFilters(articles); // { types: ["news", "page"], authors: ["Matt"], tags: ["News", "Releases"] }
|
|
172
|
+
*/
|
|
173
|
+
export const articleFilters = (articles) => ({
|
|
174
|
+
types: [...new Set(articles.map((article) => article.type))].sort(),
|
|
175
|
+
authors: uniqueSorted(articles.map((article) => article.author ?? "")),
|
|
176
|
+
tags: uniqueSorted(articles.flatMap((article) => article.tags)),
|
|
177
|
+
});
|
|
178
|
+
/**
|
|
179
|
+
* The files in an article's folder (not article.md or hidden files), with their kind, size and when they last changed.
|
|
180
|
+
*
|
|
181
|
+
* @example
|
|
182
|
+
* await articleFiles("my-site/articles", "news", "hello"); // [{ type: "news", slug: "hello", name: "photo.png", ... }]
|
|
183
|
+
*/
|
|
184
|
+
export const articleFiles = async (articlesDir, type, slug) => {
|
|
185
|
+
const dir = join(articlesDir, type, slug);
|
|
186
|
+
let names;
|
|
187
|
+
try {
|
|
188
|
+
names = (await readdir(dir, { withFileTypes: true }))
|
|
189
|
+
.filter((entry) => entry.isFile() &&
|
|
190
|
+
entry.name !== "article.md" &&
|
|
191
|
+
!entry.name.startsWith("."))
|
|
192
|
+
.map((entry) => entry.name)
|
|
193
|
+
.sort();
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
const files = await Promise.all(names.map(async (name) => {
|
|
199
|
+
try {
|
|
200
|
+
const info = await stat(join(dir, name));
|
|
201
|
+
return {
|
|
202
|
+
type,
|
|
203
|
+
slug,
|
|
204
|
+
name,
|
|
205
|
+
kind: fileKind(name),
|
|
206
|
+
size: info.size,
|
|
207
|
+
updated: info.mtime.toISOString(),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// Removed while being read
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
}));
|
|
215
|
+
return files.filter((file) => file !== undefined);
|
|
216
|
+
};
|
|
217
|
+
/** An article's key in the index, e.g. "news/hello" */
|
|
218
|
+
const key = (type, slug) => `${type}/${slug}`;
|
|
219
|
+
/**
|
|
220
|
+
* An in-memory index of a site's articles, so the editor can search, filter and sort them without reading every file
|
|
221
|
+
* each time. `load` reads every article; `update` and `delete` keep an entry up to date when the editor changes it;
|
|
222
|
+
* `watch` reads entries again when their files change outside the editor (e.g. a `git pull` or a text editor). The
|
|
223
|
+
* article files stay the only source of truth: nothing is written.
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* const index = new ArticleIndex("my-site/articles");
|
|
227
|
+
* await index.load();
|
|
228
|
+
* index.watch();
|
|
229
|
+
* queryArticles(index.articles(), { search: "hello" });
|
|
230
|
+
*/
|
|
231
|
+
export class ArticleIndex {
|
|
232
|
+
/** Each article's summary and the files in its folder, by "type/slug" */
|
|
233
|
+
entries = new Map();
|
|
234
|
+
articlesDir;
|
|
235
|
+
watcher;
|
|
236
|
+
/** Changed folders waiting to be read again: articles ("news/hello"), whole types ("news"), or everything ("") */
|
|
237
|
+
pending = new Set();
|
|
238
|
+
timer;
|
|
239
|
+
watchDelay;
|
|
240
|
+
onWatchUpdate;
|
|
241
|
+
check;
|
|
242
|
+
/**
|
|
243
|
+
* @param articlesDir - the site's articles folder, holding a folder per type, each holding a folder per article
|
|
244
|
+
*/
|
|
245
|
+
constructor(articlesDir, options = {}) {
|
|
246
|
+
this.articlesDir = articlesDir;
|
|
247
|
+
this.watchDelay = options.watchDelay ?? 100;
|
|
248
|
+
this.onWatchUpdate = options.onWatchUpdate;
|
|
249
|
+
this.check = options.check;
|
|
250
|
+
}
|
|
251
|
+
/** Every indexed article */
|
|
252
|
+
articles() {
|
|
253
|
+
return [...this.entries.values()].map((entry) => entry.summary);
|
|
254
|
+
}
|
|
255
|
+
/** Every file in the indexed articles' folders */
|
|
256
|
+
files() {
|
|
257
|
+
return [...this.entries.values()].flatMap((entry) => entry.files);
|
|
258
|
+
}
|
|
259
|
+
/** An article's summary and files, or undefined if it has no article.md */
|
|
260
|
+
async readEntry(type, slug) {
|
|
261
|
+
const [summary, files] = await Promise.all([
|
|
262
|
+
summarizeArticle(this.articlesDir, type, slug, this.check),
|
|
263
|
+
articleFiles(this.articlesDir, type, slug),
|
|
264
|
+
]);
|
|
265
|
+
return summary && { summary, files };
|
|
266
|
+
}
|
|
267
|
+
/** Read every article again, replacing the index */
|
|
268
|
+
async load() {
|
|
269
|
+
const entries = await Promise.all((await slugFolders(this.articlesDir)).map((type) => this.readType(type)));
|
|
270
|
+
this.entries.clear();
|
|
271
|
+
for (const entry of entries.flat())
|
|
272
|
+
this.entries.set(key(entry.summary.type, entry.summary.slug), entry);
|
|
273
|
+
}
|
|
274
|
+
/** Read every article of a type */
|
|
275
|
+
async readType(type) {
|
|
276
|
+
const slugs = await slugFolders(join(this.articlesDir, type));
|
|
277
|
+
const entries = await Promise.all(slugs.map((slug) => this.readEntry(type, slug)));
|
|
278
|
+
return entries.filter((entry) => entry !== undefined);
|
|
279
|
+
}
|
|
280
|
+
/** Read a type's articles again, dropping those that are gone */
|
|
281
|
+
async updateType(type) {
|
|
282
|
+
const entries = await this.readType(type);
|
|
283
|
+
for (const [name, entry] of this.entries)
|
|
284
|
+
if (entry.summary.type === type)
|
|
285
|
+
this.entries.delete(name);
|
|
286
|
+
for (const entry of entries)
|
|
287
|
+
this.entries.set(key(entry.summary.type, entry.summary.slug), entry);
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Read an article and its files again, e.g. after the editor saved it. It is dropped if it's gone.
|
|
291
|
+
*/
|
|
292
|
+
async update(type, slug) {
|
|
293
|
+
const entry = await this.readEntry(type, slug);
|
|
294
|
+
if (entry)
|
|
295
|
+
this.entries.set(key(type, slug), entry);
|
|
296
|
+
else
|
|
297
|
+
this.entries.delete(key(type, slug));
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Drop an article, e.g. after the editor deleted or moved it.
|
|
301
|
+
*/
|
|
302
|
+
delete(type, slug) {
|
|
303
|
+
this.entries.delete(key(type, slug));
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Read entries again when their files change, until `close` is called. Doesn't keep the process running. Does
|
|
307
|
+
* nothing if the articles folder doesn't exist or the system can't watch it.
|
|
308
|
+
*/
|
|
309
|
+
watch() {
|
|
310
|
+
if (this.watcher)
|
|
311
|
+
return;
|
|
312
|
+
try {
|
|
313
|
+
this.watcher = watch(this.articlesDir, { recursive: true, persistent: false }, (_event, file) => this.changed(file));
|
|
314
|
+
this.watcher.on("error", () => this.close());
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
// Without watching, changes made outside the editor show after it restarts
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Note a changed path (relative to the articles folder) to read again once changes pause. A path inside an article
|
|
322
|
+
* folder reads that article; a type folder reads the type; an unknown path reads everything.
|
|
323
|
+
*/
|
|
324
|
+
changed(file) {
|
|
325
|
+
const [type = "", slug = ""] = file ? file.split(sep) : [];
|
|
326
|
+
if (file && !isSlug(type))
|
|
327
|
+
return;
|
|
328
|
+
this.pending.add(slug && isSlug(slug) ? key(type, slug) : type);
|
|
329
|
+
clearTimeout(this.timer);
|
|
330
|
+
this.timer = setTimeout(() => void this.flush(), this.watchDelay);
|
|
331
|
+
}
|
|
332
|
+
/** Read the changed folders again */
|
|
333
|
+
async flush() {
|
|
334
|
+
const changes = [...this.pending];
|
|
335
|
+
this.pending.clear();
|
|
336
|
+
if (changes.includes(""))
|
|
337
|
+
await this.load();
|
|
338
|
+
else
|
|
339
|
+
await Promise.all(changes.map((change) => {
|
|
340
|
+
const [type = "", slug] = change.split("/");
|
|
341
|
+
return slug ? this.update(type, slug) : this.updateType(type);
|
|
342
|
+
}));
|
|
343
|
+
this.onWatchUpdate?.();
|
|
344
|
+
}
|
|
345
|
+
/** Stop watching for changes */
|
|
346
|
+
close() {
|
|
347
|
+
clearTimeout(this.timer);
|
|
348
|
+
this.pending.clear();
|
|
349
|
+
this.watcher?.close();
|
|
350
|
+
this.watcher = undefined;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type EmbedOptionValues } from "@lvl99dotcom/edaha.md/embeds";
|
|
2
|
+
/**
|
|
3
|
+
* The URL the editor loads an article's files from, e.g. "/files/article/hello/".
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* filesUrl("article", "hello"); // "/files/article/hello/"
|
|
7
|
+
*/
|
|
8
|
+
export declare const filesUrl: (type: string, slug: string) => string;
|
|
9
|
+
/**
|
|
10
|
+
* An embed block as editor HTML: an empty `<div class="embed">` with its key (empty for an old block without one),
|
|
11
|
+
* content and options (as JSON, if it has any) in attributes. Line breaks in the content are written as ` `, so
|
|
12
|
+
* the HTML is one line that Markdown keeps whole.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* embedHtml("mermaidjs", "graph TD;\n A-->B;"); // '<div class="embed" data-embed="mermaidjs" data-content="graph TD; A-->B;"></div>'
|
|
16
|
+
* embedHtml("bandcamp", url, { layout: "large" }); // '<div class="embed" data-embed="bandcamp" data-content="..." data-options="{"layout":"large"}"></div>'
|
|
17
|
+
*/
|
|
18
|
+
export declare const embedHtml: (key: string, content: string, options?: EmbedOptionValues) => string;
|
|
19
|
+
/**
|
|
20
|
+
* Convert article markdown to HTML for the editor: `<!-- readmore -->` becomes `<hr class="readmore">`,
|
|
21
|
+
* embed blocks become `<div class="embed" data-embed="key" data-content="...">` (except in code; see embedHtml), raw
|
|
22
|
+
* blocks become `<pre class="raw">` or
|
|
23
|
+
* `<span class="raw">` holding their content as it is, and relative URLs point at the editor's file URL.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* markdownToEditorHtml("Intro <!-- readmore -->Rest", "/files/article/hello/");
|
|
27
|
+
* // '<p>Intro</p>\n<hr class="readmore">\n<p>Rest</p>\n'
|
|
28
|
+
*/
|
|
29
|
+
export declare const markdownToEditorHtml: (source: string, baseUrl: string) => string;
|
|
30
|
+
/**
|
|
31
|
+
* Convert editor HTML back to article markdown, turning the readmore and embed blocks back into their shortcodes and
|
|
32
|
+
* the editor's file URLs back into relative URLs.
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* editorHtmlToMarkdown('<p>Hi</p><hr class="readmore"><p><img src="/files/article/a/b.png"></p>', "/files/article/a/");
|
|
36
|
+
* // "Hi\n\n<!-- readmore -->\n\n"
|
|
37
|
+
*/
|
|
38
|
+
export declare const editorHtmlToMarkdown: (html: string, baseUrl: string) => string;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import TurndownService from "turndown";
|
|
2
|
+
import { EMBED_BLOCK, embedBlock, embedContent, embedOptionsOf, splitEmbed, } from "@lvl99dotcom/edaha.md/embeds";
|
|
3
|
+
import { READMORE } from "@lvl99dotcom/edaha.md/generator/article";
|
|
4
|
+
import { escapeHtml, rawHtml, replaceOutsideCode, replaceRawBlocks, } from "@lvl99dotcom/edaha.md/generator/format";
|
|
5
|
+
import { createMarkdown, renderMarkdown, } from "@lvl99dotcom/edaha.md/generator/markdown";
|
|
6
|
+
// Without typographer, so text converts back to the same markdown
|
|
7
|
+
const markdown = createMarkdown({ typographer: false });
|
|
8
|
+
/**
|
|
9
|
+
* The URL the editor loads an article's files from, e.g. "/files/article/hello/".
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* filesUrl("article", "hello"); // "/files/article/hello/"
|
|
13
|
+
*/
|
|
14
|
+
export const filesUrl = (type, slug) => `/files/${type}/${slug}/`;
|
|
15
|
+
/**
|
|
16
|
+
* An embed block as editor HTML: an empty `<div class="embed">` with its key (empty for an old block without one),
|
|
17
|
+
* content and options (as JSON, if it has any) in attributes. Line breaks in the content are written as ` `, so
|
|
18
|
+
* the HTML is one line that Markdown keeps whole.
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* embedHtml("mermaidjs", "graph TD;\n A-->B;"); // '<div class="embed" data-embed="mermaidjs" data-content="graph TD; A-->B;"></div>'
|
|
22
|
+
* embedHtml("bandcamp", url, { layout: "large" }); // '<div class="embed" data-embed="bandcamp" data-content="..." data-options="{"layout":"large"}"></div>'
|
|
23
|
+
*/
|
|
24
|
+
export const embedHtml = (key, content, options = {}) => `<div class="embed" data-embed="${escapeHtml(key)}" data-content="${escapeHtml(content).replace(/\r?\n/g, " ")}"${Object.keys(options).length ? ` data-options="${escapeHtml(JSON.stringify(options))}"` : ""}></div>`;
|
|
25
|
+
/**
|
|
26
|
+
* An embed block's editor HTML from what is between its tags: its options and content, or (when its options can't be
|
|
27
|
+
* read) all of it as its content, so nothing is lost.
|
|
28
|
+
*/
|
|
29
|
+
const embedBlockHtml = (key, text) => {
|
|
30
|
+
const { content, options, optionsError } = splitEmbed(text);
|
|
31
|
+
return optionsError
|
|
32
|
+
? embedHtml(key, embedContent(text))
|
|
33
|
+
: embedHtml(key, content, options);
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Convert article markdown to HTML for the editor: `<!-- readmore -->` becomes `<hr class="readmore">`,
|
|
37
|
+
* embed blocks become `<div class="embed" data-embed="key" data-content="...">` (except in code; see embedHtml), raw
|
|
38
|
+
* blocks become `<pre class="raw">` or
|
|
39
|
+
* `<span class="raw">` holding their content as it is, and relative URLs point at the editor's file URL.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* markdownToEditorHtml("Intro <!-- readmore -->Rest", "/files/article/hello/");
|
|
43
|
+
* // '<p>Intro</p>\n<hr class="readmore">\n<p>Rest</p>\n'
|
|
44
|
+
*/
|
|
45
|
+
export const markdownToEditorHtml = (source, baseUrl) => renderMarkdown(markdown, replaceOutsideCode(replaceOutsideCode(
|
|
46
|
+
// Spaces in raw text are non-breaking while it is edited, so the editor keeps repeated ones
|
|
47
|
+
replaceRawBlocks(source, (raw) => rawHtml(raw.block
|
|
48
|
+
? raw
|
|
49
|
+
: { ...raw, content: raw.content.replace(/ /g, "\u00a0") })), READMORE, () => '\n\n<hr class="readmore">\n\n'), EMBED_BLOCK, ([, key, text]) => `\n\n${embedBlockHtml(key ?? "", text)}\n\n`), baseUrl);
|
|
50
|
+
/** Whether a node is an embed block (see embedHtml) */
|
|
51
|
+
const isEmbed = (node) => node.nodeName === "DIV" && node.classList.contains("embed");
|
|
52
|
+
/** An embed block's Markdown, from its editor HTML (see embedHtml) */
|
|
53
|
+
const embedMarkdown = (_, node) => {
|
|
54
|
+
const element = node;
|
|
55
|
+
const key = element.getAttribute("data-embed") ?? "";
|
|
56
|
+
const content = embedContent(element.getAttribute("data-content") ?? "");
|
|
57
|
+
const options = embedOptionsOf(element.getAttribute("data-options"));
|
|
58
|
+
// An old block without a key is kept as it was, until a kind of embed is chosen for it
|
|
59
|
+
return `\n\n${key ? embedBlock(key, content, options) : `<!-- embed -->${content}<!-- /embed -->`}\n\n`;
|
|
60
|
+
};
|
|
61
|
+
/** HTML to markdown converter with rules for the readmore and embed blocks */
|
|
62
|
+
const createTurndown = () => {
|
|
63
|
+
const turndown = new TurndownService({
|
|
64
|
+
// Other empty blocks are left out, as Turndown does by default
|
|
65
|
+
blankReplacement: (content, node) => isEmbed(node)
|
|
66
|
+
? embedMarkdown(content, node)
|
|
67
|
+
: node.isBlock
|
|
68
|
+
? "\n\n"
|
|
69
|
+
: "",
|
|
70
|
+
headingStyle: "atx",
|
|
71
|
+
codeBlockStyle: "fenced",
|
|
72
|
+
bulletListMarker: "-",
|
|
73
|
+
emDelimiter: "*",
|
|
74
|
+
hr: "---",
|
|
75
|
+
});
|
|
76
|
+
turndown.addRule("readmore", {
|
|
77
|
+
filter: (node) => node.nodeName === "HR" &&
|
|
78
|
+
node.classList.contains("readmore"),
|
|
79
|
+
replacement: () => "\n\n<!-- readmore -->\n\n",
|
|
80
|
+
});
|
|
81
|
+
// Raw blocks are written back as they are, without escaping
|
|
82
|
+
turndown.addRule("raw", {
|
|
83
|
+
filter: (node) => (node.nodeName === "PRE" || node.nodeName === "SPAN") &&
|
|
84
|
+
node.classList.contains("raw"),
|
|
85
|
+
replacement: (_, node) => node.nodeName === "PRE"
|
|
86
|
+
? `\n\n<!-- raw -->\n${String(node.textContent)}\n<!-- /raw -->\n\n`
|
|
87
|
+
: `<!-- raw -->${String(node.textContent).replace(/\u00a0/g, " ")}<!-- /raw -->`,
|
|
88
|
+
});
|
|
89
|
+
// Embed blocks are empty, which Turndown passes to `blankReplacement` rather than its rules
|
|
90
|
+
turndown.addRule("embed", { filter: isEmbed, replacement: embedMarkdown });
|
|
91
|
+
// Small and big text, and collapsible details blocks, stay HTML. A details block's summary stays HTML (Markdown
|
|
92
|
+
// isn't read inside an HTML line) and its content becomes Markdown, between blank lines so it is read as Markdown.
|
|
93
|
+
turndown.addRule("smallBig", {
|
|
94
|
+
// `big` isn't in the DOM types' list of tag names, as HTML no longer recommends it
|
|
95
|
+
filter: (node) => node.nodeName === "SMALL" || node.nodeName === "BIG",
|
|
96
|
+
replacement: (content, node) => {
|
|
97
|
+
const tag = node.nodeName.toLowerCase();
|
|
98
|
+
return `<${tag}>${content}</${tag}>`;
|
|
99
|
+
},
|
|
100
|
+
});
|
|
101
|
+
// Underlined text stays HTML (Markdown has none), and struck-through text is GFM's ~~
|
|
102
|
+
turndown.addRule("underline", {
|
|
103
|
+
filter: "u",
|
|
104
|
+
replacement: (content) => `<u>${content}</u>`,
|
|
105
|
+
});
|
|
106
|
+
turndown.addRule("strikethrough", {
|
|
107
|
+
filter: ["s", "del"],
|
|
108
|
+
replacement: (content) => `~~${content}~~`,
|
|
109
|
+
});
|
|
110
|
+
turndown.addRule("summary", { filter: "summary", replacement: () => "" });
|
|
111
|
+
turndown.addRule("details", {
|
|
112
|
+
filter: "details",
|
|
113
|
+
replacement: (content, node) => {
|
|
114
|
+
const summary = Array.from(node.childNodes).find((child) => child.nodeName === "SUMMARY");
|
|
115
|
+
return `\n\n<details>\n<summary>${summary?.innerHTML.trim() ?? ""}</summary>\n\n${content.trim()}\n\n</details>\n\n`;
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
// List items with a single space after the marker ("- item", "1. item")
|
|
119
|
+
turndown.addRule("listItem", {
|
|
120
|
+
filter: "li",
|
|
121
|
+
replacement: (content, node) => {
|
|
122
|
+
const parent = node.parentNode;
|
|
123
|
+
const index = Array.prototype.indexOf.call(parent.children, node);
|
|
124
|
+
const start = Number(parent.getAttribute("start") ?? 1);
|
|
125
|
+
const prefix = parent.nodeName === "OL" ? `${start + index}. ` : "- ";
|
|
126
|
+
const text = content
|
|
127
|
+
.replace(/^\n+/, "")
|
|
128
|
+
.replace(/\n+$/, "")
|
|
129
|
+
// Indent continuation lines under the marker, leaving blank lines empty
|
|
130
|
+
.replace(/\n(?!\n)/g, `\n${" ".repeat(prefix.length)}`);
|
|
131
|
+
return `${prefix}${text}${node.nextSibling ? "\n" : ""}`;
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
// Tables as GFM tables: the first row is the header row. Cells are kept to one line.
|
|
135
|
+
turndown.addRule("tableCell", {
|
|
136
|
+
filter: ["th", "td"],
|
|
137
|
+
replacement: (content) => `| ${content
|
|
138
|
+
.trim()
|
|
139
|
+
.replace(/\s*\n+\s*/g, " ")
|
|
140
|
+
.replace(/\|/g, "\\|")} `,
|
|
141
|
+
});
|
|
142
|
+
turndown.addRule("tableRow", {
|
|
143
|
+
filter: "tr",
|
|
144
|
+
replacement: (content, node) => {
|
|
145
|
+
const row = `${content}|\n`;
|
|
146
|
+
const table = node.closest("table");
|
|
147
|
+
if (table.rows[0] !== node)
|
|
148
|
+
return row;
|
|
149
|
+
const separator = Array.from(node.cells, () => "| --- ").join("");
|
|
150
|
+
return `${row}${separator}|\n`;
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
turndown.addRule("tableSection", {
|
|
154
|
+
filter: ["thead", "tbody", "tfoot"],
|
|
155
|
+
replacement: (content) => content,
|
|
156
|
+
});
|
|
157
|
+
turndown.addRule("table", {
|
|
158
|
+
filter: "table",
|
|
159
|
+
replacement: (content) => `\n\n${content.trim()}\n\n`,
|
|
160
|
+
});
|
|
161
|
+
// Column widths from the editor aren't kept
|
|
162
|
+
turndown.remove("colgroup");
|
|
163
|
+
return turndown;
|
|
164
|
+
};
|
|
165
|
+
const turndown = createTurndown();
|
|
166
|
+
/**
|
|
167
|
+
* Convert editor HTML back to article markdown, turning the readmore and embed blocks back into their shortcodes and
|
|
168
|
+
* the editor's file URLs back into relative URLs.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* editorHtmlToMarkdown('<p>Hi</p><hr class="readmore"><p><img src="/files/article/a/b.png"></p>', "/files/article/a/");
|
|
172
|
+
* // "Hi\n\n<!-- readmore -->\n\n"
|
|
173
|
+
*/
|
|
174
|
+
export const editorHtmlToMarkdown = (html, baseUrl) => turndown
|
|
175
|
+
.turndown(html)
|
|
176
|
+
.replaceAll(`](${baseUrl}`, "](")
|
|
177
|
+
// Turndown escapes "1." at the start of a line, which is only needed outside headings
|
|
178
|
+
.replace(/^(#+ \d+)\\\./gm, "$1.")
|
|
179
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
180
|
+
.trim();
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { type FileFilters, type FileKind, type FilePage, type FileQuery, type IndexedFile } from "../types/index.ts";
|
|
2
|
+
/** The most files a page of query results has */
|
|
3
|
+
export declare const MAX_FILES_PER_PAGE = 50;
|
|
4
|
+
/**
|
|
5
|
+
* The kind of file a name is, by its extension.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* fileKind("photo.JPG"); // "image"
|
|
9
|
+
* fileKind("notes"); // "other"
|
|
10
|
+
*/
|
|
11
|
+
export declare const fileKind: (name: string) => FileKind;
|
|
12
|
+
/**
|
|
13
|
+
* Find files: those whose name contains the search text (ignoring case) and that are of the kind and in an article of
|
|
14
|
+
* the type given, sorted by name, kind, size or location, ascending or descending (by default by location then name,
|
|
15
|
+
* A to Z), one page at a time.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* queryFiles(files, { search: "photo", kind: "image", sort: "size", order: "desc" });
|
|
19
|
+
*/
|
|
20
|
+
export declare const queryFiles: (files: IndexedFile[], query?: FileQuery) => Omit<FilePage, "files"> & {
|
|
21
|
+
files: IndexedFile[];
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* The file kinds and article types files are in, for the file browser's filters.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* fileFilters(files); // { kinds: ["document", "image"], types: ["news"] }
|
|
28
|
+
*/
|
|
29
|
+
export declare const fileFilters: (files: IndexedFile[]) => FileFilters;
|
|
30
|
+
/**
|
|
31
|
+
* The ways an article can refer to a file: its name (or `./` and its name) in the file's own article, and its path on
|
|
32
|
+
* the website (e.g. "/news/welcome/photo.png") or its full address anywhere.
|
|
33
|
+
*
|
|
34
|
+
* @param url - the file's path on the website
|
|
35
|
+
* @param siteUrl - the website's address (without a trailing slash), if it has one
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* fileReferences("photo.png", "/news/welcome/photo.png", "https://example.com", true);
|
|
39
|
+
* // ["photo.png", "./photo.png", "/news/welcome/photo.png", "https://example.com/news/welcome/photo.png"]
|
|
40
|
+
*/
|
|
41
|
+
export declare const fileReferences: (name: string, url: string, siteUrl: string | undefined, ownArticle: boolean) => string[];
|
|
42
|
+
/** What to do with references to a file: point them at another file name, or remove them */
|
|
43
|
+
export type ReferenceChange = {
|
|
44
|
+
rename: string;
|
|
45
|
+
} | {
|
|
46
|
+
remove: true;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Change references to a file in Markdown (outside code): point them at a new file name, or remove them (images are
|
|
50
|
+
* removed, links keep their text). Returns the Markdown and how many references were changed.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* changeBodyReferences(" [A](a.png)", ["a.png"], { remove: true }); // { markdown: " A", count: 2 }
|
|
54
|
+
*/
|
|
55
|
+
export declare const changeBodyReferences: (markdown: string, references: string[], change: ReferenceChange) => {
|
|
56
|
+
markdown: string;
|
|
57
|
+
count: number;
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Change references to a file in an article's source (its settings header and its body), keeping the header's format.
|
|
61
|
+
* Returns the new source, or undefined if the article doesn't refer to the file.
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* changeArticleReferences(source, ["photo.png"], { rename: "photo.jpg" });
|
|
65
|
+
*/
|
|
66
|
+
export declare const changeArticleReferences: (source: string, references: string[], change: ReferenceChange) => string | undefined;
|