@xharness/cordis-plugin-im-markdown 0.0.0-stage → 4.0.1-alpha.2
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 +21 -0
- package/lib/index.js +470 -0
- package/lib/types/convert.d.ts +59 -0
- package/lib/types/convert.d.ts.map +1 -0
- package/lib/types/index.d.ts +39 -0
- package/lib/types/index.d.ts.map +1 -0
- package/package.json +57 -3
- package/src/convert.ts +416 -0
- package/src/index.ts +84 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2019-present Shigma
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
1
|
+
import { elementInfo, h, isPhrasingContainer, isTag, tagAliases } from "@xharness/satori-element";
|
|
2
|
+
import { fromMarkdown as fromMarkdown$1 } from "mdast-util-from-markdown";
|
|
3
|
+
import { gfmFromMarkdown } from "mdast-util-gfm";
|
|
4
|
+
import { gfm } from "micromark-extension-gfm";
|
|
5
|
+
import { toHast } from "mdast-util-to-hast";
|
|
6
|
+
import { raw } from "hast-util-raw";
|
|
7
|
+
//#region lib/types/convert.js
|
|
8
|
+
/**
|
|
9
|
+
* GFM markdown → Satori elements: the one place in the IM stack that knows the markdown syntax.
|
|
10
|
+
*
|
|
11
|
+
* Adapters never see markdown source; each mode serializes its own dialect from the elements produced here (with its
|
|
12
|
+
* own escaping).
|
|
13
|
+
*
|
|
14
|
+
* Pipeline, and why it has these stages:
|
|
15
|
+
* - **mdast** (`mdast-util-from-markdown` + GFM) is where the markdown syntax lives;
|
|
16
|
+
* - **hast** (`mdast-util-to-hast`) is the HTML-shaped tree raw HTML can be spliced into — markdown has no node for
|
|
17
|
+
* `<u>x</u>`, so a syntax extension per tag is not the answer;
|
|
18
|
+
* - **hast with real elements** (`hast-util-raw`, i.e. parse5) parses the HTML that markdown carried as opaque text:
|
|
19
|
+
* it pairs tags, decodes entities and tolerates everything HTML authoring is allowed to be sloppy about;
|
|
20
|
+
* - **Satori elements** are the last step here, and they are vocabulary-driven: `elementInfo` says which tags exist,
|
|
21
|
+
* what each may contain and which attributes it requires, `tagAliases` maps HTML spellings onto them. `**x**`,
|
|
22
|
+
* `<u>x</u>`, `<spoiler>x</spoiler>` and every other registered element therefore take one path.
|
|
23
|
+
*
|
|
24
|
+
* What markdown may express is the content half of the vocabulary: an element whose category is inline, block or
|
|
25
|
+
* media. An interactive element (`button`, `input`, `select`, `form`), a renderer directive (`fallback`, `case`) or an
|
|
26
|
+
* inbound wrapper (`raw`, `forward`) cannot be authored — its children are kept as text instead, because a message
|
|
27
|
+
* must not hand a reader a control its sender never sent.
|
|
28
|
+
*
|
|
29
|
+
* Conventions kept deliberately small and lossless:
|
|
30
|
+
* - a soft line break (a single newline inside a paragraph) also becomes `<br>`: chat markdown is line-oriented, and
|
|
31
|
+
* collapsing it to a space would silently drop the author's line structure;
|
|
32
|
+
* - a paragraph that holds nothing but one image becomes a bare block-level `<img>`, so `img.inline`
|
|
33
|
+
* keeps meaning "image inside phrasing content";
|
|
34
|
+
* - an element the vocabulary gives no content (`at`, `channel`, `emoji`) holds its label in `name`, and HTML parses
|
|
35
|
+
* `<at id=ou_x />` as an *open* tag: such a tag is closed explicitly before parsing, and its text keeps becoming the
|
|
36
|
+
* label;
|
|
37
|
+
* - a block element on a line of its own becomes that block, while the same element written inside a sentence keeps
|
|
38
|
+
* its text: inline HTML is always phrasing, and the vocabulary's `normalize` refuses a whole message for one block
|
|
39
|
+
* element standing in phrasing content, so the text is what the reader keeps instead of losing the turn;
|
|
40
|
+
* - footnote markers and definitions are flattened before the HTML stage, because GFM's footnote HTML (a `<sup>`
|
|
41
|
+
* reference and an end-of-document list) is not what a chat message should show;
|
|
42
|
+
* - unsupported constructs degrade to their children (or to their literal text) instead of throwing: the input is user
|
|
43
|
+
* content, and the render engine normalizes the result anyway.
|
|
44
|
+
*/
|
|
45
|
+
/** `h` over a tag computed at run time; every tag still comes from the vocabulary. */
|
|
46
|
+
const build = h;
|
|
47
|
+
/** Element categories markdown may author: what a message says, not what a reader can operate. */
|
|
48
|
+
const CONTENT = new Set([
|
|
49
|
+
"inline",
|
|
50
|
+
"block",
|
|
51
|
+
"media"
|
|
52
|
+
]);
|
|
53
|
+
/** Tags whose empty content model takes its label from the text it wraps (`<at id=ou_x>张三</at>`). */
|
|
54
|
+
const LABELLED = new Set([
|
|
55
|
+
"at",
|
|
56
|
+
"channel",
|
|
57
|
+
"emoji"
|
|
58
|
+
]);
|
|
59
|
+
/** A Satori text element. */
|
|
60
|
+
function text(content) {
|
|
61
|
+
return h.text(content);
|
|
62
|
+
}
|
|
63
|
+
/** Line endings as the parser's offsets count them. */
|
|
64
|
+
function normalizeNewlines(source) {
|
|
65
|
+
return source.replace(/\r\n?/g, "\n");
|
|
66
|
+
}
|
|
67
|
+
/** Parse GFM markdown into an mdast tree (GFM = autolink, strikethrough, table, task list, footnote). */
|
|
68
|
+
function parse(source) {
|
|
69
|
+
return fromMarkdown$1(normalizeNewlines(source), {
|
|
70
|
+
extensions: [gfm()],
|
|
71
|
+
mdastExtensions: [gfmFromMarkdown()]
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Convert markdown source into block-level elements (never a `<message>`).
|
|
76
|
+
*
|
|
77
|
+
* @param source - GFM markdown, raw HTML included.
|
|
78
|
+
* @returns the blocks of the document.
|
|
79
|
+
*/
|
|
80
|
+
function fromMarkdown(source) {
|
|
81
|
+
const tree = parse(String(source ?? ""));
|
|
82
|
+
return convert(raw(toHast({
|
|
83
|
+
...tree,
|
|
84
|
+
children: prepare(tree.children)
|
|
85
|
+
}, { allowDangerousHtml: true })).children, void 0);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The part of a document still being written that later text cannot change: everything before its last top-level
|
|
89
|
+
* block.
|
|
90
|
+
*
|
|
91
|
+
* CommonMark parses blocks line by line, so text appended to a document can only reshape its last block (a paragraph
|
|
92
|
+
* turning into a setext heading or a table, a list continuing, an emphasis, a code span or a fence closing); every
|
|
93
|
+
* block before it is final. A link reference definition is the exception: one that arrives after the cut resolves a
|
|
94
|
+
* reference above it only in the complete document.
|
|
95
|
+
*
|
|
96
|
+
* @param source - a prefix of a markdown document.
|
|
97
|
+
* @returns the source of its settled blocks without trailing whitespace; `''` while the first block is still open.
|
|
98
|
+
*/
|
|
99
|
+
function settledMarkdown(source) {
|
|
100
|
+
const normalized = normalizeNewlines(source);
|
|
101
|
+
const end = parse(normalized).children.at(-1)?.position?.start.offset;
|
|
102
|
+
return end === void 0 ? "" : normalized.slice(0, end).trimEnd();
|
|
103
|
+
}
|
|
104
|
+
/** A self-closing tag (`<at id=ou_x />`); an attribute value may itself carry `>`. */
|
|
105
|
+
const SELF_CLOSING = /<([a-zA-Z][\w-]*)((?:[^>"']|"[^"]*"|'[^']*')*)\/>/g;
|
|
106
|
+
/**
|
|
107
|
+
* The vocabulary tag a spelled name stands for (`strong` → `b`, `ins` → `u`, `at` → `at`).
|
|
108
|
+
*
|
|
109
|
+
* @param name - the tag name as the author spelled it.
|
|
110
|
+
* @returns the tag, or undefined when the vocabulary has none for it.
|
|
111
|
+
*/
|
|
112
|
+
function resolveTag(name) {
|
|
113
|
+
const lower = name.toLowerCase();
|
|
114
|
+
if (Object.hasOwn(tagAliases, lower)) return tagAliases[lower];
|
|
115
|
+
return isTag(lower) ? lower : void 0;
|
|
116
|
+
}
|
|
117
|
+
/** Whether `tag` holds content a message may say rather than a control a reader operates. */
|
|
118
|
+
function isContent(tag) {
|
|
119
|
+
return CONTENT.has(elementInfo[tag].category);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Close every self-closing tag whose vocabulary element cannot hold children.
|
|
123
|
+
*
|
|
124
|
+
* HTML ignores the `/` of `<at id=ou_x />` and nests everything after it inside that element; the element's content
|
|
125
|
+
* model says it holds nothing, so the empty form is written as `<at id=ou_x></at>` before parsing.
|
|
126
|
+
*
|
|
127
|
+
* @param value - one raw HTML run as markdown carried it.
|
|
128
|
+
* @returns the same run with empty-content elements closed explicitly.
|
|
129
|
+
*/
|
|
130
|
+
function closeEmpty(value) {
|
|
131
|
+
return value.replace(SELF_CLOSING, (whole, name, attrs) => {
|
|
132
|
+
const tag = resolveTag(name);
|
|
133
|
+
return tag !== void 0 && elementInfo[tag].content === "empty" ? `<${name}${attrs}></${name}>` : whole;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Rewrite the mdast children a chat message must not render as GFM's own HTML: footnote markers and definitions
|
|
138
|
+
* become the literal marker plus the definition's blocks, and raw HTML runs are prepared for the HTML stage.
|
|
139
|
+
*
|
|
140
|
+
* @param nodes - mdast children.
|
|
141
|
+
* @returns the same content with those constructs flattened.
|
|
142
|
+
*/
|
|
143
|
+
function prepare(nodes) {
|
|
144
|
+
const out = [];
|
|
145
|
+
for (const node of nodes) {
|
|
146
|
+
if (node.type === "footnoteReference") {
|
|
147
|
+
out.push({
|
|
148
|
+
type: "text",
|
|
149
|
+
value: `[^${node.label ?? node.identifier}]`
|
|
150
|
+
});
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (node.type === "footnoteDefinition") {
|
|
154
|
+
out.push(...prepare(node.children));
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (node.type === "html") {
|
|
158
|
+
out.push({
|
|
159
|
+
...node,
|
|
160
|
+
value: closeEmpty(node.value)
|
|
161
|
+
});
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
const children = node.children;
|
|
165
|
+
if (Array.isArray(children) && children.length) out.push({
|
|
166
|
+
...node,
|
|
167
|
+
children: prepare(children)
|
|
168
|
+
});
|
|
169
|
+
else out.push(node);
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
}
|
|
173
|
+
/** Whether `node` is a hast element. */
|
|
174
|
+
function isElement(node) {
|
|
175
|
+
return node.type === "element";
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Attribute values of one hast element: the plain ones (parse5 keeps an unknown attribute of a raw tag verbatim),
|
|
179
|
+
* which is how `<span color="red">` reaches `span[color]`.
|
|
180
|
+
*/
|
|
181
|
+
function attrsOf(tag, properties) {
|
|
182
|
+
const attrs = {};
|
|
183
|
+
for (const [key, value] of Object.entries(properties ?? {})) {
|
|
184
|
+
if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") continue;
|
|
185
|
+
if (typeof value === "string" && !value) continue;
|
|
186
|
+
attrs[key] = value;
|
|
187
|
+
}
|
|
188
|
+
if (tag === "at") {
|
|
189
|
+
if (attrs.id === void 0 && typeof attrs.user_id === "string") attrs.id = attrs.user_id;
|
|
190
|
+
delete attrs.user_id;
|
|
191
|
+
attrs.type ??= "user";
|
|
192
|
+
if (attrs.type === "user" && (attrs.id === "all" || attrs.id === "here")) {
|
|
193
|
+
attrs.type = attrs.id;
|
|
194
|
+
delete attrs.id;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return attrs;
|
|
198
|
+
}
|
|
199
|
+
/** The language of a fence: the `language-…` class markdown put on its `<code>`. */
|
|
200
|
+
function languageOf(properties) {
|
|
201
|
+
const classes = (properties ?? {}).className;
|
|
202
|
+
if (!Array.isArray(classes)) return void 0;
|
|
203
|
+
for (const name of classes) {
|
|
204
|
+
if (typeof name !== "string") continue;
|
|
205
|
+
const match = /^language-(.+)$/.exec(name);
|
|
206
|
+
if (match) return match[1];
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Every text run of one hast subtree, in order. */
|
|
210
|
+
function hastText(node) {
|
|
211
|
+
if (node.type === "text") return node.value;
|
|
212
|
+
if (!isElement(node)) return "";
|
|
213
|
+
return node.children.map(hastText).join("");
|
|
214
|
+
}
|
|
215
|
+
/** Whether a container's content is elements only, so the whitespace between them is layout rather than content. */
|
|
216
|
+
function isStructural(tag) {
|
|
217
|
+
return tag !== void 0 && elementInfo[tag].content !== "phrasing" && elementInfo[tag].content !== "text";
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* The one element of a container whose other children are whitespace, if that is all it holds.
|
|
221
|
+
*
|
|
222
|
+
* @param children - hast children.
|
|
223
|
+
* @returns the sole element, or undefined when the container holds text or several elements.
|
|
224
|
+
*/
|
|
225
|
+
function soleElement(children) {
|
|
226
|
+
const meaningful = children.filter((child) => !(child.type === "text" && !child.value.trim()));
|
|
227
|
+
const [only] = meaningful;
|
|
228
|
+
return meaningful.length === 1 && only !== void 0 && isElement(only) ? only : void 0;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* The block-level element a paragraph is made of, when it is made of one: markdown writes inline HTML, so
|
|
232
|
+
* `<small>…</small>` on a line of its own arrives as the only child of a paragraph.
|
|
233
|
+
*
|
|
234
|
+
* @param children - the paragraph's hast children.
|
|
235
|
+
* @returns the block element, or undefined when the paragraph is anything else.
|
|
236
|
+
*/
|
|
237
|
+
function soleBlock(children) {
|
|
238
|
+
const only = soleElement(children);
|
|
239
|
+
if (only === void 0) return void 0;
|
|
240
|
+
const tag = resolveTag(only.tagName);
|
|
241
|
+
return tag !== void 0 && isContent(tag) && elementInfo[tag].position === "block" ? only : void 0;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Convert hast children into Satori elements.
|
|
245
|
+
*
|
|
246
|
+
* @param nodes - hast children.
|
|
247
|
+
* @param parent - tag of the container they stand in, when that is a vocabulary tag.
|
|
248
|
+
* @returns the elements; a tag this vocabulary has no content element for contributes its children instead.
|
|
249
|
+
*/
|
|
250
|
+
function convert(nodes, parent) {
|
|
251
|
+
const out = [];
|
|
252
|
+
for (const [index, node] of nodes.entries()) {
|
|
253
|
+
if (node.type === "text") {
|
|
254
|
+
pushText(out, parent !== void 0 && elementInfo[parent].content === "text" ? node.value : trimLineEdges(node.value, nodes[index - 1], nodes[index + 1]), parent);
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
if (!isElement(node)) continue;
|
|
258
|
+
out.push(...element(node, parent));
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
/** HTML elements that end a line by themselves, besides the vocabulary's block elements. */
|
|
263
|
+
const HTML_BLOCKS = new Set([
|
|
264
|
+
"address",
|
|
265
|
+
"article",
|
|
266
|
+
"aside",
|
|
267
|
+
"blockquote",
|
|
268
|
+
"dd",
|
|
269
|
+
"div",
|
|
270
|
+
"dl",
|
|
271
|
+
"dt",
|
|
272
|
+
"figure",
|
|
273
|
+
"footer",
|
|
274
|
+
"header",
|
|
275
|
+
"hr",
|
|
276
|
+
"li",
|
|
277
|
+
"main",
|
|
278
|
+
"nav",
|
|
279
|
+
"ol",
|
|
280
|
+
"p",
|
|
281
|
+
"pre",
|
|
282
|
+
"section",
|
|
283
|
+
"table",
|
|
284
|
+
"tbody",
|
|
285
|
+
"td",
|
|
286
|
+
"tfoot",
|
|
287
|
+
"th",
|
|
288
|
+
"thead",
|
|
289
|
+
"tr",
|
|
290
|
+
"ul"
|
|
291
|
+
]);
|
|
292
|
+
/**
|
|
293
|
+
* Whether a sibling of a text run already ends the line on its side: a `<br>`, a block element, or the edge of the
|
|
294
|
+
* container (`undefined`). The newline the source writes next to it is that same line end, not another one.
|
|
295
|
+
*/
|
|
296
|
+
function endsLine(node) {
|
|
297
|
+
if (node === void 0) return true;
|
|
298
|
+
if (!isElement(node)) return false;
|
|
299
|
+
if (node.tagName === "br" || HTML_BLOCKS.has(node.tagName)) return true;
|
|
300
|
+
const tag = resolveTag(node.tagName);
|
|
301
|
+
return tag !== void 0 && elementInfo[tag].position === "block";
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Drop the newline at either end of a text run whose neighbour already ends the line there (`a<br>\nb`, `a\n<ul>`, the
|
|
305
|
+
* first and last line of `<div>\nraw\n</div>`). A newline next to inline content stays, and becomes a break.
|
|
306
|
+
*/
|
|
307
|
+
function trimLineEdges(value, before, after) {
|
|
308
|
+
let start = 0;
|
|
309
|
+
let end = value.length;
|
|
310
|
+
if (endsLine(before) && value.startsWith("\n")) start = 1;
|
|
311
|
+
if (endsLine(after) && end > start && value.endsWith("\n")) end -= 1;
|
|
312
|
+
return value.slice(start, end);
|
|
313
|
+
}
|
|
314
|
+
/** One text run: a newline becomes `<br>`, except where the element holds text verbatim. */
|
|
315
|
+
function pushText(out, value, parent) {
|
|
316
|
+
if (parent !== void 0 && elementInfo[parent].content === "text") {
|
|
317
|
+
if (value) out.push(text(value));
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (!value.trim() && (parent === void 0 || isStructural(parent))) return;
|
|
321
|
+
value.split("\n").forEach((line, index) => {
|
|
322
|
+
if (index) out.push(h("br"));
|
|
323
|
+
if (line) out.push(text(line));
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Take a task-list checkbox off an item: the state belongs to the `<li>`, and no reader operates a disabled `<input>`.
|
|
328
|
+
*
|
|
329
|
+
* @param children - the item's hast children.
|
|
330
|
+
* @returns the state (absent when the item carries no checkbox) and the remaining children, label first.
|
|
331
|
+
*/
|
|
332
|
+
function takeCheckbox(children) {
|
|
333
|
+
const [first, ...rest] = children;
|
|
334
|
+
if (!first || !isElement(first) || first.tagName !== "input" || first.properties?.type !== "checkbox") return { children };
|
|
335
|
+
const [head, ...tail] = rest;
|
|
336
|
+
const trimmed = head?.type === "text" ? [{
|
|
337
|
+
...head,
|
|
338
|
+
value: head.value.trimStart()
|
|
339
|
+
}, ...tail] : rest;
|
|
340
|
+
return {
|
|
341
|
+
checked: first.properties.checked === true,
|
|
342
|
+
children: trimmed
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The label of an element that has no children: the text an author wrapped it around, when that is all it wrapped.
|
|
347
|
+
*
|
|
348
|
+
* @param content - the element's converted children.
|
|
349
|
+
* @returns the label, or undefined when the element carries anything but text.
|
|
350
|
+
*/
|
|
351
|
+
function labelOf(content) {
|
|
352
|
+
if (!content.length || !content.every((child) => child.type === "text")) return void 0;
|
|
353
|
+
const label = content.map((child) => String(child.attrs.content ?? "")).join("").trim();
|
|
354
|
+
return label ? label : void 0;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Convert one hast element.
|
|
358
|
+
*
|
|
359
|
+
* @param node - the element.
|
|
360
|
+
* @param parent - tag of its container, when that is a vocabulary tag.
|
|
361
|
+
* @returns the elements it stands for (more than one when children are hoisted out of it).
|
|
362
|
+
*/
|
|
363
|
+
function element(node, parent) {
|
|
364
|
+
const tag = resolveTag(node.tagName);
|
|
365
|
+
if (tag === void 0 || !isContent(tag)) return convert(node.children, parent);
|
|
366
|
+
const info = elementInfo[tag];
|
|
367
|
+
if (tag === "pre") {
|
|
368
|
+
const source = node.children.find((child) => isElement(child) && child.tagName === "code") ?? node;
|
|
369
|
+
const lang = languageOf(isElement(source) ? source.properties : void 0);
|
|
370
|
+
const body = hastText(source).replace(/\n$/, "");
|
|
371
|
+
return [build(tag, {
|
|
372
|
+
...attrsOf(tag, node.properties),
|
|
373
|
+
...lang === void 0 ? {} : { lang }
|
|
374
|
+
}, ...body ? [text(body)] : [])];
|
|
375
|
+
}
|
|
376
|
+
let children = node.children;
|
|
377
|
+
let checked;
|
|
378
|
+
if (tag === "li") ({checked, children} = takeCheckbox(children));
|
|
379
|
+
const attrs = attrsOf(tag, node.properties);
|
|
380
|
+
if (checked !== void 0) attrs.checked = checked;
|
|
381
|
+
if ((info.required ?? []).some((key) => attrs[key] === void 0 || attrs[key] === "")) return convert(node.children, parent);
|
|
382
|
+
if (tag === "p") {
|
|
383
|
+
const block = soleBlock(children);
|
|
384
|
+
if (block !== void 0) return element(block, void 0);
|
|
385
|
+
}
|
|
386
|
+
if (info.position === "block" && parent !== void 0 && !isStructural(parent)) return convert(node.children, parent);
|
|
387
|
+
if (info.parents !== void 0 && (parent === void 0 || !info.parents.includes(parent))) return convert(node.children, parent);
|
|
388
|
+
const content = convert(children, tag);
|
|
389
|
+
if (tag === "p" && content.length === 1 && content[0].type === "img") return content;
|
|
390
|
+
if (info.content !== "empty") return [build(tag, attrs, ...content)];
|
|
391
|
+
const label = LABELLED.has(tag) && attrs.name === void 0 ? labelOf(content) : void 0;
|
|
392
|
+
if (label === void 0) return [build(tag, attrs), ...content];
|
|
393
|
+
return [build(tag, {
|
|
394
|
+
...attrs,
|
|
395
|
+
name: label
|
|
396
|
+
})];
|
|
397
|
+
}
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region lib/types/index.js
|
|
400
|
+
/**
|
|
401
|
+
* `@xharness/cordis-plugin-im-markdown`: the `<markdown>` element of the IM plane.
|
|
402
|
+
*
|
|
403
|
+
* The element is a plugin contribution, not a core concept: this plugin registers its handler on the `satori` service
|
|
404
|
+
* ({@link ElementContributions}) and every mode that does not render the tag itself converts and renders it. A mode
|
|
405
|
+
* therefore only ever sees ordinary elements and keeps its own escaping.
|
|
406
|
+
*
|
|
407
|
+
* Use {@link markdown} to write one.
|
|
408
|
+
*
|
|
409
|
+
* Streaming: under the `append` strategy the platform keeps every character it was sent, while a growing markdown
|
|
410
|
+
* document re-parses as it grows — `**ab` is literal text a mode escapes, `**abc**` is bold; an open fence, a table or a
|
|
411
|
+
* setext heading change lines that were already published. An intermediate state (`ctx.stream.final === false`)
|
|
412
|
+
* therefore renders only the blocks later text cannot change ({@link settledMarkdown}) for the `<markdown>` that ends
|
|
413
|
+
* the message, the only one that can still grow. Final states and the other strategies, which can rewrite what they
|
|
414
|
+
* show, render the whole source.
|
|
415
|
+
*
|
|
416
|
+
* @module @xharness/cordis-plugin-im-markdown
|
|
417
|
+
*/
|
|
418
|
+
/** Plugin name. */
|
|
419
|
+
const name = "im-markdown";
|
|
420
|
+
/** The `satori` service owns the element contributions this plugin installs into. */
|
|
421
|
+
const inject = ["satori"];
|
|
422
|
+
/**
|
|
423
|
+
* The markdown element: GFM source that every mode renders as its own native markup.
|
|
424
|
+
*
|
|
425
|
+
* @param content - the GFM source.
|
|
426
|
+
* @returns the `<markdown>` element a message carries.
|
|
427
|
+
*/
|
|
428
|
+
function markdown(content) {
|
|
429
|
+
return h.markdown(content);
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Whether `el` ends the message: it is the last child of its parent, and so is every ancestor of it.
|
|
433
|
+
*
|
|
434
|
+
* @param el - the element.
|
|
435
|
+
* @param ancestors - its ancestors, outermost first.
|
|
436
|
+
* @returns `true` when nothing follows `el` in document order.
|
|
437
|
+
*/
|
|
438
|
+
function endsMessage(el, ancestors) {
|
|
439
|
+
let child = el;
|
|
440
|
+
for (let index = ancestors.length - 1; index >= 0; index--) {
|
|
441
|
+
const parent = ancestors[index];
|
|
442
|
+
if (parent.children[parent.children.length - 1] !== child) return false;
|
|
443
|
+
child = parent;
|
|
444
|
+
}
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Render one `<markdown>` element in its place.
|
|
449
|
+
*
|
|
450
|
+
* @param el - the element; `el.attrs.content` is the GFM source.
|
|
451
|
+
* @param ctx - render context of the element.
|
|
452
|
+
* @returns the platform nodes of the converted source.
|
|
453
|
+
*/
|
|
454
|
+
function render(el, ctx) {
|
|
455
|
+
const stream = ctx.stream;
|
|
456
|
+
const blocks = fromMarkdown(stream?.strategy === "append" && !stream.final && endsMessage(el, ctx.ancestors) ? settledMarkdown(el.attrs.content) : el.attrs.content);
|
|
457
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1];
|
|
458
|
+
const single = blocks.length === 1 && blocks[0].type === "p" ? blocks[0].children : void 0;
|
|
459
|
+
return ctx.transform(parent !== void 0 && isPhrasingContainer(parent.type) && single ? single : blocks);
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Register `<markdown>` on the `satori` service; the registration leaves with this plugin's fiber.
|
|
463
|
+
*
|
|
464
|
+
* @param ctx - plugin context, with the `satori` service injected.
|
|
465
|
+
*/
|
|
466
|
+
function apply(ctx) {
|
|
467
|
+
ctx.effect(() => ctx.satori.elements.register("markdown", render));
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
export { apply, fromMarkdown, inject, markdown, name, settledMarkdown };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GFM markdown → Satori elements: the one place in the IM stack that knows the markdown syntax.
|
|
3
|
+
*
|
|
4
|
+
* Adapters never see markdown source; each mode serializes its own dialect from the elements produced here (with its
|
|
5
|
+
* own escaping).
|
|
6
|
+
*
|
|
7
|
+
* Pipeline, and why it has these stages:
|
|
8
|
+
* - **mdast** (`mdast-util-from-markdown` + GFM) is where the markdown syntax lives;
|
|
9
|
+
* - **hast** (`mdast-util-to-hast`) is the HTML-shaped tree raw HTML can be spliced into — markdown has no node for
|
|
10
|
+
* `<u>x</u>`, so a syntax extension per tag is not the answer;
|
|
11
|
+
* - **hast with real elements** (`hast-util-raw`, i.e. parse5) parses the HTML that markdown carried as opaque text:
|
|
12
|
+
* it pairs tags, decodes entities and tolerates everything HTML authoring is allowed to be sloppy about;
|
|
13
|
+
* - **Satori elements** are the last step here, and they are vocabulary-driven: `elementInfo` says which tags exist,
|
|
14
|
+
* what each may contain and which attributes it requires, `tagAliases` maps HTML spellings onto them. `**x**`,
|
|
15
|
+
* `<u>x</u>`, `<spoiler>x</spoiler>` and every other registered element therefore take one path.
|
|
16
|
+
*
|
|
17
|
+
* What markdown may express is the content half of the vocabulary: an element whose category is inline, block or
|
|
18
|
+
* media. An interactive element (`button`, `input`, `select`, `form`), a renderer directive (`fallback`, `case`) or an
|
|
19
|
+
* inbound wrapper (`raw`, `forward`) cannot be authored — its children are kept as text instead, because a message
|
|
20
|
+
* must not hand a reader a control its sender never sent.
|
|
21
|
+
*
|
|
22
|
+
* Conventions kept deliberately small and lossless:
|
|
23
|
+
* - a soft line break (a single newline inside a paragraph) also becomes `<br>`: chat markdown is line-oriented, and
|
|
24
|
+
* collapsing it to a space would silently drop the author's line structure;
|
|
25
|
+
* - a paragraph that holds nothing but one image becomes a bare block-level `<img>`, so `img.inline`
|
|
26
|
+
* keeps meaning "image inside phrasing content";
|
|
27
|
+
* - an element the vocabulary gives no content (`at`, `channel`, `emoji`) holds its label in `name`, and HTML parses
|
|
28
|
+
* `<at id=ou_x />` as an *open* tag: such a tag is closed explicitly before parsing, and its text keeps becoming the
|
|
29
|
+
* label;
|
|
30
|
+
* - a block element on a line of its own becomes that block, while the same element written inside a sentence keeps
|
|
31
|
+
* its text: inline HTML is always phrasing, and the vocabulary's `normalize` refuses a whole message for one block
|
|
32
|
+
* element standing in phrasing content, so the text is what the reader keeps instead of losing the turn;
|
|
33
|
+
* - footnote markers and definitions are flattened before the HTML stage, because GFM's footnote HTML (a `<sup>`
|
|
34
|
+
* reference and an end-of-document list) is not what a chat message should show;
|
|
35
|
+
* - unsupported constructs degrade to their children (or to their literal text) instead of throwing: the input is user
|
|
36
|
+
* content, and the render engine normalizes the result anyway.
|
|
37
|
+
*/
|
|
38
|
+
import { type Element } from '@xharness/satori-element';
|
|
39
|
+
/**
|
|
40
|
+
* Convert markdown source into block-level elements (never a `<message>`).
|
|
41
|
+
*
|
|
42
|
+
* @param source - GFM markdown, raw HTML included.
|
|
43
|
+
* @returns the blocks of the document.
|
|
44
|
+
*/
|
|
45
|
+
export declare function fromMarkdown(source: string): Element[];
|
|
46
|
+
/**
|
|
47
|
+
* The part of a document still being written that later text cannot change: everything before its last top-level
|
|
48
|
+
* block.
|
|
49
|
+
*
|
|
50
|
+
* CommonMark parses blocks line by line, so text appended to a document can only reshape its last block (a paragraph
|
|
51
|
+
* turning into a setext heading or a table, a list continuing, an emphasis, a code span or a fence closing); every
|
|
52
|
+
* block before it is final. A link reference definition is the exception: one that arrives after the cut resolves a
|
|
53
|
+
* reference above it only in the complete document.
|
|
54
|
+
*
|
|
55
|
+
* @param source - a prefix of a markdown document.
|
|
56
|
+
* @returns the source of its settled blocks without trailing whitespace; `''` while the first block is still open.
|
|
57
|
+
*/
|
|
58
|
+
export declare function settledMarkdown(source: string): string;
|
|
59
|
+
//# sourceMappingURL=convert.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"convert.d.ts","sourceRoot":"","sources":["../../src/convert.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AASH,OAAO,EACU,KAAK,OAAO,EAC5B,MAAM,0BAA0B,CAAA;AAgCjC;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,EAAE,CAKtD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAItD"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xharness/cordis-plugin-im-markdown`: the `<markdown>` element of the IM plane.
|
|
3
|
+
*
|
|
4
|
+
* The element is a plugin contribution, not a core concept: this plugin registers its handler on the `satori` service
|
|
5
|
+
* ({@link ElementContributions}) and every mode that does not render the tag itself converts and renders it. A mode
|
|
6
|
+
* therefore only ever sees ordinary elements and keeps its own escaping.
|
|
7
|
+
*
|
|
8
|
+
* Use {@link markdown} to write one.
|
|
9
|
+
*
|
|
10
|
+
* Streaming: under the `append` strategy the platform keeps every character it was sent, while a growing markdown
|
|
11
|
+
* document re-parses as it grows — `**ab` is literal text a mode escapes, `**abc**` is bold; an open fence, a table or a
|
|
12
|
+
* setext heading change lines that were already published. An intermediate state (`ctx.stream.final === false`)
|
|
13
|
+
* therefore renders only the blocks later text cannot change ({@link settledMarkdown}) for the `<markdown>` that ends
|
|
14
|
+
* the message, the only one that can still grow. Final states and the other strategies, which can rewrite what they
|
|
15
|
+
* show, render the whole source.
|
|
16
|
+
*
|
|
17
|
+
* @module @xharness/cordis-plugin-im-markdown
|
|
18
|
+
*/
|
|
19
|
+
import type { Context } from '@xharness/cordis';
|
|
20
|
+
import { type Element } from '@xharness/satori-element';
|
|
21
|
+
export { fromMarkdown, settledMarkdown } from './convert.ts';
|
|
22
|
+
/** Plugin name. */
|
|
23
|
+
export declare const name = "im-markdown";
|
|
24
|
+
/** The `satori` service owns the element contributions this plugin installs into. */
|
|
25
|
+
export declare const inject: string[];
|
|
26
|
+
/**
|
|
27
|
+
* The markdown element: GFM source that every mode renders as its own native markup.
|
|
28
|
+
*
|
|
29
|
+
* @param content - the GFM source.
|
|
30
|
+
* @returns the `<markdown>` element a message carries.
|
|
31
|
+
*/
|
|
32
|
+
export declare function markdown(content: string): Element<'markdown'>;
|
|
33
|
+
/**
|
|
34
|
+
* Register `<markdown>` on the `satori` service; the registration leaves with this plugin's fiber.
|
|
35
|
+
*
|
|
36
|
+
* @param ctx - plugin context, with the `satori` service injected.
|
|
37
|
+
*/
|
|
38
|
+
export declare function apply(ctx: Context): void;
|
|
39
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAE/C,OAAO,EAAE,KAAK,OAAO,EAA0B,MAAM,0BAA0B,CAAA;AAG/E,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAE5D,mBAAmB;AACnB,eAAO,MAAM,IAAI,gBAAgB,CAAA;AAEjC,qFAAqF;AACrF,eAAO,MAAM,MAAM,UAAa,CAAA;AAEhC;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAE7D;AAoCD;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAExC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xharness/cordis-plugin-im-markdown",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "The <markdown> element of the Satori IM plane: a plugin contribution every mode renders as its own markup",
|
|
4
|
+
"version": "4.0.1-alpha.2",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./lib/types/index.d.ts",
|
|
9
|
+
"default": "./lib/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./src/*": "./src/*",
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"lib/index.js",
|
|
16
|
+
"lib/types/**/*.d.ts",
|
|
17
|
+
"lib/types/**/*.d.ts.map",
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"author": "Shigma <shigma10826@gmail.com>",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/Kuner/XHarness.git",
|
|
25
|
+
"directory": "vendor/im/markdown"
|
|
26
|
+
},
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/satorijs/satori/issues"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://satori.chat/",
|
|
31
|
+
"keywords": [
|
|
32
|
+
"satori",
|
|
33
|
+
"markdown",
|
|
34
|
+
"cordis"
|
|
35
|
+
],
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@xharness/cordis": "~4.2.0-alpha.2",
|
|
38
|
+
"@xharness/cordis-plugin-im-core": "~5.0.1-alpha.2",
|
|
39
|
+
"@xharness/satori-element": "~4.0.1-alpha.2"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@xharness/cordis": "~4.2.0-alpha.2",
|
|
43
|
+
"@xharness/cordis-plugin-im-core": "~5.0.1-alpha.2",
|
|
44
|
+
"@xharness/satori-element": "~4.0.1-alpha.2",
|
|
45
|
+
"@types/hast": "^3.0.5",
|
|
46
|
+
"@types/mdast": "^4.0.4"
|
|
47
|
+
},
|
|
48
|
+
"dependencies": {
|
|
49
|
+
"hast-util-raw": "~9.1.1",
|
|
50
|
+
"mdast-util-from-markdown": "^2.0.3",
|
|
51
|
+
"mdast-util-gfm": "^3.1.0",
|
|
52
|
+
"mdast-util-to-hast": "^13.2.1",
|
|
53
|
+
"micromark-extension-gfm": "^3.0.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"main": "lib/index.js",
|
|
59
|
+
"types": "lib/types/index.d.ts"
|
|
6
60
|
}
|
package/src/convert.ts
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GFM markdown → Satori elements: the one place in the IM stack that knows the markdown syntax.
|
|
3
|
+
*
|
|
4
|
+
* Adapters never see markdown source; each mode serializes its own dialect from the elements produced here (with its
|
|
5
|
+
* own escaping).
|
|
6
|
+
*
|
|
7
|
+
* Pipeline, and why it has these stages:
|
|
8
|
+
* - **mdast** (`mdast-util-from-markdown` + GFM) is where the markdown syntax lives;
|
|
9
|
+
* - **hast** (`mdast-util-to-hast`) is the HTML-shaped tree raw HTML can be spliced into — markdown has no node for
|
|
10
|
+
* `<u>x</u>`, so a syntax extension per tag is not the answer;
|
|
11
|
+
* - **hast with real elements** (`hast-util-raw`, i.e. parse5) parses the HTML that markdown carried as opaque text:
|
|
12
|
+
* it pairs tags, decodes entities and tolerates everything HTML authoring is allowed to be sloppy about;
|
|
13
|
+
* - **Satori elements** are the last step here, and they are vocabulary-driven: `elementInfo` says which tags exist,
|
|
14
|
+
* what each may contain and which attributes it requires, `tagAliases` maps HTML spellings onto them. `**x**`,
|
|
15
|
+
* `<u>x</u>`, `<spoiler>x</spoiler>` and every other registered element therefore take one path.
|
|
16
|
+
*
|
|
17
|
+
* What markdown may express is the content half of the vocabulary: an element whose category is inline, block or
|
|
18
|
+
* media. An interactive element (`button`, `input`, `select`, `form`), a renderer directive (`fallback`, `case`) or an
|
|
19
|
+
* inbound wrapper (`raw`, `forward`) cannot be authored — its children are kept as text instead, because a message
|
|
20
|
+
* must not hand a reader a control its sender never sent.
|
|
21
|
+
*
|
|
22
|
+
* Conventions kept deliberately small and lossless:
|
|
23
|
+
* - a soft line break (a single newline inside a paragraph) also becomes `<br>`: chat markdown is line-oriented, and
|
|
24
|
+
* collapsing it to a space would silently drop the author's line structure;
|
|
25
|
+
* - a paragraph that holds nothing but one image becomes a bare block-level `<img>`, so `img.inline`
|
|
26
|
+
* keeps meaning "image inside phrasing content";
|
|
27
|
+
* - an element the vocabulary gives no content (`at`, `channel`, `emoji`) holds its label in `name`, and HTML parses
|
|
28
|
+
* `<at id=ou_x />` as an *open* tag: such a tag is closed explicitly before parsing, and its text keeps becoming the
|
|
29
|
+
* label;
|
|
30
|
+
* - a block element on a line of its own becomes that block, while the same element written inside a sentence keeps
|
|
31
|
+
* its text: inline HTML is always phrasing, and the vocabulary's `normalize` refuses a whole message for one block
|
|
32
|
+
* element standing in phrasing content, so the text is what the reader keeps instead of losing the turn;
|
|
33
|
+
* - footnote markers and definitions are flattened before the HTML stage, because GFM's footnote HTML (a `<sup>`
|
|
34
|
+
* reference and an end-of-document list) is not what a chat message should show;
|
|
35
|
+
* - unsupported constructs degrade to their children (or to their literal text) instead of throwing: the input is user
|
|
36
|
+
* content, and the render engine normalizes the result anyway.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { fromMarkdown as parseMarkdown } from 'mdast-util-from-markdown'
|
|
40
|
+
import { gfmFromMarkdown } from 'mdast-util-gfm'
|
|
41
|
+
import { gfm } from 'micromark-extension-gfm'
|
|
42
|
+
import { toHast } from 'mdast-util-to-hast'
|
|
43
|
+
import { raw } from 'hast-util-raw'
|
|
44
|
+
import type { Element as HastElement, Root as HastRoot, RootContent as HastNode } from 'hast'
|
|
45
|
+
import type { RootContent } from 'mdast'
|
|
46
|
+
import {
|
|
47
|
+
type Category, type Element, elementInfo, h, isTag, tagAliases, type Tag,
|
|
48
|
+
} from '@xharness/satori-element'
|
|
49
|
+
|
|
50
|
+
/** `h` over a tag computed at run time; every tag still comes from the vocabulary. */
|
|
51
|
+
const build = h as unknown as (type: string, attrs: Record<string, unknown>, ...children: Element[]) => Element
|
|
52
|
+
|
|
53
|
+
/** Element categories markdown may author: what a message says, not what a reader can operate. */
|
|
54
|
+
const CONTENT: ReadonlySet<Category> = new Set<Category>(['inline', 'block', 'media'])
|
|
55
|
+
|
|
56
|
+
/** Tags whose empty content model takes its label from the text it wraps (`<at id=ou_x>张三</at>`). */
|
|
57
|
+
const LABELLED: ReadonlySet<Tag> = new Set<Tag>(['at', 'channel', 'emoji'])
|
|
58
|
+
|
|
59
|
+
/** A Satori text element. */
|
|
60
|
+
function text(content: string): Element {
|
|
61
|
+
return h.text(content)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
65
|
+
// Markdown source → mdast
|
|
66
|
+
|
|
67
|
+
/** Line endings as the parser's offsets count them. */
|
|
68
|
+
function normalizeNewlines(source: string): string {
|
|
69
|
+
return source.replace(/\r\n?/g, '\n')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Parse GFM markdown into an mdast tree (GFM = autolink, strikethrough, table, task list, footnote). */
|
|
73
|
+
function parse(source: string) {
|
|
74
|
+
return parseMarkdown(normalizeNewlines(source), {
|
|
75
|
+
extensions: [gfm()],
|
|
76
|
+
mdastExtensions: [gfmFromMarkdown()],
|
|
77
|
+
})
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Convert markdown source into block-level elements (never a `<message>`).
|
|
82
|
+
*
|
|
83
|
+
* @param source - GFM markdown, raw HTML included.
|
|
84
|
+
* @returns the blocks of the document.
|
|
85
|
+
*/
|
|
86
|
+
export function fromMarkdown(source: string): Element[] {
|
|
87
|
+
const tree = parse(String(source ?? ''))
|
|
88
|
+
// `raw` is typed over every hast node; a root goes in and a root comes out.
|
|
89
|
+
const hast = raw(toHast({ ...tree, children: prepare(tree.children) }, { allowDangerousHtml: true })) as HastRoot
|
|
90
|
+
return convert(hast.children, undefined)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The part of a document still being written that later text cannot change: everything before its last top-level
|
|
95
|
+
* block.
|
|
96
|
+
*
|
|
97
|
+
* CommonMark parses blocks line by line, so text appended to a document can only reshape its last block (a paragraph
|
|
98
|
+
* turning into a setext heading or a table, a list continuing, an emphasis, a code span or a fence closing); every
|
|
99
|
+
* block before it is final. A link reference definition is the exception: one that arrives after the cut resolves a
|
|
100
|
+
* reference above it only in the complete document.
|
|
101
|
+
*
|
|
102
|
+
* @param source - a prefix of a markdown document.
|
|
103
|
+
* @returns the source of its settled blocks without trailing whitespace; `''` while the first block is still open.
|
|
104
|
+
*/
|
|
105
|
+
export function settledMarkdown(source: string): string {
|
|
106
|
+
const normalized = normalizeNewlines(source)
|
|
107
|
+
const end = parse(normalized).children.at(-1)?.position?.start.offset
|
|
108
|
+
return end === undefined ? '' : normalized.slice(0, end).trimEnd()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
112
|
+
// mdast preparation: what must not reach the HTML stage
|
|
113
|
+
|
|
114
|
+
/** A self-closing tag (`<at id=ou_x />`); an attribute value may itself carry `>`. */
|
|
115
|
+
const SELF_CLOSING = /<([a-zA-Z][\w-]*)((?:[^>"']|"[^"]*"|'[^']*')*)\/>/g
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* The vocabulary tag a spelled name stands for (`strong` → `b`, `ins` → `u`, `at` → `at`).
|
|
119
|
+
*
|
|
120
|
+
* @param name - the tag name as the author spelled it.
|
|
121
|
+
* @returns the tag, or undefined when the vocabulary has none for it.
|
|
122
|
+
*/
|
|
123
|
+
function resolveTag(name: string): Tag | undefined {
|
|
124
|
+
const lower = name.toLowerCase()
|
|
125
|
+
// `tagAliases` is a plain object: `constructor` and the other inherited names are not spellings of a tag.
|
|
126
|
+
if (Object.hasOwn(tagAliases, lower)) return tagAliases[lower]
|
|
127
|
+
return isTag(lower) ? lower : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Whether `tag` holds content a message may say rather than a control a reader operates. */
|
|
131
|
+
function isContent(tag: Tag): boolean {
|
|
132
|
+
return CONTENT.has(elementInfo[tag].category)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Close every self-closing tag whose vocabulary element cannot hold children.
|
|
137
|
+
*
|
|
138
|
+
* HTML ignores the `/` of `<at id=ou_x />` and nests everything after it inside that element; the element's content
|
|
139
|
+
* model says it holds nothing, so the empty form is written as `<at id=ou_x></at>` before parsing.
|
|
140
|
+
*
|
|
141
|
+
* @param value - one raw HTML run as markdown carried it.
|
|
142
|
+
* @returns the same run with empty-content elements closed explicitly.
|
|
143
|
+
*/
|
|
144
|
+
function closeEmpty(value: string): string {
|
|
145
|
+
return value.replace(SELF_CLOSING, (whole, name: string, attrs: string) => {
|
|
146
|
+
const tag = resolveTag(name)
|
|
147
|
+
return tag !== undefined && elementInfo[tag].content === 'empty' ? `<${name}${attrs}></${name}>` : whole
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Rewrite the mdast children a chat message must not render as GFM's own HTML: footnote markers and definitions
|
|
153
|
+
* become the literal marker plus the definition's blocks, and raw HTML runs are prepared for the HTML stage.
|
|
154
|
+
*
|
|
155
|
+
* @param nodes - mdast children.
|
|
156
|
+
* @returns the same content with those constructs flattened.
|
|
157
|
+
*/
|
|
158
|
+
function prepare(nodes: readonly RootContent[]): RootContent[] {
|
|
159
|
+
const out: RootContent[] = []
|
|
160
|
+
for (const node of nodes) {
|
|
161
|
+
if (node.type === 'footnoteReference') {
|
|
162
|
+
out.push({ type: 'text', value: `[^${node.label ?? node.identifier}]` })
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
if (node.type === 'footnoteDefinition') {
|
|
166
|
+
out.push(...prepare(node.children))
|
|
167
|
+
continue
|
|
168
|
+
}
|
|
169
|
+
if (node.type === 'html') {
|
|
170
|
+
out.push({ ...node, value: closeEmpty(node.value) })
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
const children = (node as unknown as { children?: RootContent[] }).children
|
|
174
|
+
if (Array.isArray(children) && children.length) out.push({ ...node, children: prepare(children) } as RootContent)
|
|
175
|
+
else out.push(node)
|
|
176
|
+
}
|
|
177
|
+
return out
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
181
|
+
// hast → Satori elements
|
|
182
|
+
|
|
183
|
+
/** Whether `node` is a hast element. */
|
|
184
|
+
function isElement(node: HastNode): node is HastElement {
|
|
185
|
+
return node.type === 'element'
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Attribute values of one hast element: the plain ones (parse5 keeps an unknown attribute of a raw tag verbatim),
|
|
190
|
+
* which is how `<span color="red">` reaches `span[color]`.
|
|
191
|
+
*/
|
|
192
|
+
function attrsOf(tag: Tag, properties: HastElement['properties'] | undefined): Record<string, string | number | boolean> {
|
|
193
|
+
const attrs: Record<string, string | number | boolean> = {}
|
|
194
|
+
for (const [key, value] of Object.entries(properties ?? {})) {
|
|
195
|
+
if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') continue
|
|
196
|
+
if (typeof value === 'string' && !value) continue
|
|
197
|
+
attrs[key] = value
|
|
198
|
+
}
|
|
199
|
+
if (tag === 'at') {
|
|
200
|
+
// Feishu spells the id `user_id`; the vocabulary spells it `id`.
|
|
201
|
+
if (attrs.id === undefined && typeof attrs.user_id === 'string') attrs.id = attrs.user_id
|
|
202
|
+
delete attrs.user_id
|
|
203
|
+
attrs.type ??= 'user'
|
|
204
|
+
// Feishu spells "everyone" as the id `all`. Written that way it is the `all` mention, not a user whose id happens
|
|
205
|
+
// to be `all`: a mode decides whether to render a mention from its `type`, and `allowAtAll: false` only withholds
|
|
206
|
+
// the `all` variant, so a `user` carrying that id would reach the platform as @everyone.
|
|
207
|
+
if (attrs.type === 'user' && (attrs.id === 'all' || attrs.id === 'here')) {
|
|
208
|
+
attrs.type = attrs.id
|
|
209
|
+
delete attrs.id
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return attrs
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The language of a fence: the `language-…` class markdown put on its `<code>`. */
|
|
216
|
+
function languageOf(properties: HastElement['properties'] | undefined): string | undefined {
|
|
217
|
+
const classes = (properties ?? {}).className
|
|
218
|
+
if (!Array.isArray(classes)) return undefined
|
|
219
|
+
for (const name of classes) {
|
|
220
|
+
if (typeof name !== 'string') continue
|
|
221
|
+
const match = /^language-(.+)$/.exec(name)
|
|
222
|
+
if (match) return match[1]
|
|
223
|
+
}
|
|
224
|
+
return undefined
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Every text run of one hast subtree, in order. */
|
|
228
|
+
function hastText(node: HastNode): string {
|
|
229
|
+
if (node.type === 'text') return node.value
|
|
230
|
+
if (!isElement(node)) return ''
|
|
231
|
+
return node.children.map(hastText).join('')
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Whether a container's content is elements only, so the whitespace between them is layout rather than content. */
|
|
235
|
+
function isStructural(tag: Tag | undefined): boolean {
|
|
236
|
+
return tag !== undefined && elementInfo[tag].content !== 'phrasing' && elementInfo[tag].content !== 'text'
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The one element of a container whose other children are whitespace, if that is all it holds.
|
|
241
|
+
*
|
|
242
|
+
* @param children - hast children.
|
|
243
|
+
* @returns the sole element, or undefined when the container holds text or several elements.
|
|
244
|
+
*/
|
|
245
|
+
function soleElement(children: readonly HastNode[]): HastElement | undefined {
|
|
246
|
+
const meaningful = children.filter(child => !(child.type === 'text' && !child.value.trim()))
|
|
247
|
+
const [only] = meaningful
|
|
248
|
+
return meaningful.length === 1 && only !== undefined && isElement(only) ? only : undefined
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The block-level element a paragraph is made of, when it is made of one: markdown writes inline HTML, so
|
|
253
|
+
* `<small>…</small>` on a line of its own arrives as the only child of a paragraph.
|
|
254
|
+
*
|
|
255
|
+
* @param children - the paragraph's hast children.
|
|
256
|
+
* @returns the block element, or undefined when the paragraph is anything else.
|
|
257
|
+
*/
|
|
258
|
+
function soleBlock(children: readonly HastNode[]): HastElement | undefined {
|
|
259
|
+
const only = soleElement(children)
|
|
260
|
+
if (only === undefined) return undefined
|
|
261
|
+
const tag = resolveTag(only.tagName)
|
|
262
|
+
return tag !== undefined && isContent(tag) && elementInfo[tag].position === 'block' ? only : undefined
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Convert hast children into Satori elements.
|
|
267
|
+
*
|
|
268
|
+
* @param nodes - hast children.
|
|
269
|
+
* @param parent - tag of the container they stand in, when that is a vocabulary tag.
|
|
270
|
+
* @returns the elements; a tag this vocabulary has no content element for contributes its children instead.
|
|
271
|
+
*/
|
|
272
|
+
function convert(nodes: readonly HastNode[], parent: Tag | undefined): Element[] {
|
|
273
|
+
const out: Element[] = []
|
|
274
|
+
for (const [index, node] of nodes.entries()) {
|
|
275
|
+
if (node.type === 'text') {
|
|
276
|
+
const verbatim = parent !== undefined && elementInfo[parent].content === 'text'
|
|
277
|
+
pushText(out, verbatim ? node.value : trimLineEdges(node.value, nodes[index - 1], nodes[index + 1]), parent)
|
|
278
|
+
continue
|
|
279
|
+
}
|
|
280
|
+
if (!isElement(node)) continue
|
|
281
|
+
out.push(...element(node, parent))
|
|
282
|
+
}
|
|
283
|
+
return out
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** HTML elements that end a line by themselves, besides the vocabulary's block elements. */
|
|
287
|
+
const HTML_BLOCKS: ReadonlySet<string> = new Set([
|
|
288
|
+
'address', 'article', 'aside', 'blockquote', 'dd', 'div', 'dl', 'dt', 'figure', 'footer', 'header', 'hr', 'li',
|
|
289
|
+
'main', 'nav', 'ol', 'p', 'pre', 'section', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul',
|
|
290
|
+
])
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Whether a sibling of a text run already ends the line on its side: a `<br>`, a block element, or the edge of the
|
|
294
|
+
* container (`undefined`). The newline the source writes next to it is that same line end, not another one.
|
|
295
|
+
*/
|
|
296
|
+
function endsLine(node: HastNode | undefined): boolean {
|
|
297
|
+
if (node === undefined) return true
|
|
298
|
+
if (!isElement(node)) return false
|
|
299
|
+
if (node.tagName === 'br' || HTML_BLOCKS.has(node.tagName)) return true
|
|
300
|
+
const tag = resolveTag(node.tagName)
|
|
301
|
+
return tag !== undefined && elementInfo[tag].position === 'block'
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Drop the newline at either end of a text run whose neighbour already ends the line there (`a<br>\nb`, `a\n<ul>`, the
|
|
306
|
+
* first and last line of `<div>\nraw\n</div>`). A newline next to inline content stays, and becomes a break.
|
|
307
|
+
*/
|
|
308
|
+
function trimLineEdges(value: string, before: HastNode | undefined, after: HastNode | undefined): string {
|
|
309
|
+
let start = 0
|
|
310
|
+
let end = value.length
|
|
311
|
+
if (endsLine(before) && value.startsWith('\n')) start = 1
|
|
312
|
+
if (endsLine(after) && end > start && value.endsWith('\n')) end -= 1
|
|
313
|
+
return value.slice(start, end)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** One text run: a newline becomes `<br>`, except where the element holds text verbatim. */
|
|
317
|
+
function pushText(out: Element[], value: string, parent: Tag | undefined): void {
|
|
318
|
+
const verbatim = parent !== undefined && elementInfo[parent].content === 'text'
|
|
319
|
+
if (verbatim) {
|
|
320
|
+
if (value) out.push(text(value))
|
|
321
|
+
return
|
|
322
|
+
}
|
|
323
|
+
// Whitespace between blocks (at the top level, or in a container of elements) is layout, not content.
|
|
324
|
+
if (!value.trim() && (parent === undefined || isStructural(parent))) return
|
|
325
|
+
// Every newline is a break, including one at either end of the run: in `first\n**second**\nthird` the breaks are
|
|
326
|
+
// the last character of `first\n` and the first of `\nthird`, so the empty pieces a split leaves there still count.
|
|
327
|
+
value.split('\n').forEach((line, index) => {
|
|
328
|
+
if (index) out.push(h('br'))
|
|
329
|
+
if (line) out.push(text(line))
|
|
330
|
+
})
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Take a task-list checkbox off an item: the state belongs to the `<li>`, and no reader operates a disabled `<input>`.
|
|
335
|
+
*
|
|
336
|
+
* @param children - the item's hast children.
|
|
337
|
+
* @returns the state (absent when the item carries no checkbox) and the remaining children, label first.
|
|
338
|
+
*/
|
|
339
|
+
function takeCheckbox(children: HastElement['children']): { checked?: boolean; children: HastElement['children'] } {
|
|
340
|
+
const [first, ...rest] = children
|
|
341
|
+
if (!first || !isElement(first) || first.tagName !== 'input' || first.properties?.type !== 'checkbox') {
|
|
342
|
+
return { children }
|
|
343
|
+
}
|
|
344
|
+
const [head, ...tail] = rest
|
|
345
|
+
// The whitespace that separated the box from the label is markup, not text: drop it so the label starts the item.
|
|
346
|
+
const trimmed = head?.type === 'text' ? [{ ...head, value: head.value.trimStart() }, ...tail] : rest
|
|
347
|
+
return { checked: first.properties.checked === true, children: trimmed }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* The label of an element that has no children: the text an author wrapped it around, when that is all it wrapped.
|
|
352
|
+
*
|
|
353
|
+
* @param content - the element's converted children.
|
|
354
|
+
* @returns the label, or undefined when the element carries anything but text.
|
|
355
|
+
*/
|
|
356
|
+
function labelOf(content: readonly Element[]): string | undefined {
|
|
357
|
+
if (!content.length || !content.every(child => child.type === 'text')) return undefined
|
|
358
|
+
const label = content.map(child => String(child.attrs.content ?? '')).join('').trim()
|
|
359
|
+
return label ? label : undefined
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Convert one hast element.
|
|
364
|
+
*
|
|
365
|
+
* @param node - the element.
|
|
366
|
+
* @param parent - tag of its container, when that is a vocabulary tag.
|
|
367
|
+
* @returns the elements it stands for (more than one when children are hoisted out of it).
|
|
368
|
+
*/
|
|
369
|
+
function element(node: HastElement, parent: Tag | undefined): Element[] {
|
|
370
|
+
const tag = resolveTag(node.tagName)
|
|
371
|
+
if (tag === undefined || !isContent(tag)) return convert(node.children, parent)
|
|
372
|
+
const info = elementInfo[tag]
|
|
373
|
+
|
|
374
|
+
// A fence: markdown emits `<pre><code class="language-…">`, while the vocabulary holds `pre[lang]` of plain text.
|
|
375
|
+
if (tag === 'pre') {
|
|
376
|
+
const code = node.children.find(child => isElement(child) && child.tagName === 'code')
|
|
377
|
+
const source = code ?? node
|
|
378
|
+
const lang = languageOf(isElement(source) ? source.properties : undefined)
|
|
379
|
+
const body = hastText(source).replace(/\n$/, '')
|
|
380
|
+
const attrs = { ...attrsOf(tag, node.properties), ...lang === undefined ? {} : { lang } }
|
|
381
|
+
return [build(tag, attrs, ...body ? [text(body)] : [])]
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
let children = node.children
|
|
385
|
+
let checked: boolean | undefined
|
|
386
|
+
if (tag === 'li') ({ checked, children } = takeCheckbox(children))
|
|
387
|
+
const attrs = attrsOf(tag, node.properties)
|
|
388
|
+
if (checked !== undefined) attrs.checked = checked
|
|
389
|
+
// An element whose required attribute did not survive is not that element: its text is all that remains.
|
|
390
|
+
if ((info.required ?? []).some(key => attrs[key] === undefined || attrs[key] === '')) return convert(node.children, parent)
|
|
391
|
+
|
|
392
|
+
// A paragraph holding one block-level element is that block: markdown writes inline HTML, so `<small>…</small>` on a
|
|
393
|
+
// line of its own arrives as the only content of a paragraph, and the vocabulary has `small` at flow level.
|
|
394
|
+
if (tag === 'p') {
|
|
395
|
+
const block = soleBlock(children)
|
|
396
|
+
if (block !== undefined) return element(block, undefined)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// A block element inside a sentence, or a list item outside its list, is refused by `normalize` as a whole message:
|
|
400
|
+
// the text is what the reader keeps instead of losing the turn.
|
|
401
|
+
if (info.position === 'block' && parent !== undefined && !isStructural(parent)) return convert(node.children, parent)
|
|
402
|
+
if (info.parents !== undefined && (parent === undefined || !info.parents.includes(parent))) {
|
|
403
|
+
return convert(node.children, parent)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const content = convert(children, tag)
|
|
407
|
+
// A paragraph that is nothing but an image is that (block-level) picture: `img.inline` means "inside a sentence".
|
|
408
|
+
if (tag === 'p' && content.length === 1 && content[0]!.type === 'img') return content
|
|
409
|
+
|
|
410
|
+
if (info.content !== 'empty') return [build(tag, attrs, ...content)]
|
|
411
|
+
|
|
412
|
+
// The element holds no children: text wrapped around a labelled one is its label, and anything else follows it.
|
|
413
|
+
const label = LABELLED.has(tag) && attrs.name === undefined ? labelOf(content) : undefined
|
|
414
|
+
if (label === undefined) return [build(tag, attrs), ...content]
|
|
415
|
+
return [build(tag, { ...attrs, name: label })]
|
|
416
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@xharness/cordis-plugin-im-markdown`: the `<markdown>` element of the IM plane.
|
|
3
|
+
*
|
|
4
|
+
* The element is a plugin contribution, not a core concept: this plugin registers its handler on the `satori` service
|
|
5
|
+
* ({@link ElementContributions}) and every mode that does not render the tag itself converts and renders it. A mode
|
|
6
|
+
* therefore only ever sees ordinary elements and keeps its own escaping.
|
|
7
|
+
*
|
|
8
|
+
* Use {@link markdown} to write one.
|
|
9
|
+
*
|
|
10
|
+
* Streaming: under the `append` strategy the platform keeps every character it was sent, while a growing markdown
|
|
11
|
+
* document re-parses as it grows — `**ab` is literal text a mode escapes, `**abc**` is bold; an open fence, a table or a
|
|
12
|
+
* setext heading change lines that were already published. An intermediate state (`ctx.stream.final === false`)
|
|
13
|
+
* therefore renders only the blocks later text cannot change ({@link settledMarkdown}) for the `<markdown>` that ends
|
|
14
|
+
* the message, the only one that can still grow. Final states and the other strategies, which can rewrite what they
|
|
15
|
+
* show, render the whole source.
|
|
16
|
+
*
|
|
17
|
+
* @module @xharness/cordis-plugin-im-markdown
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { Context } from '@xharness/cordis'
|
|
21
|
+
import type { ModeTypes, RenderContext } from '@xharness/cordis-plugin-im-core'
|
|
22
|
+
import { type Element, h, isPhrasingContainer } from '@xharness/satori-element'
|
|
23
|
+
import { fromMarkdown, settledMarkdown } from './convert.ts'
|
|
24
|
+
|
|
25
|
+
export { fromMarkdown, settledMarkdown } from './convert.ts'
|
|
26
|
+
|
|
27
|
+
/** Plugin name. */
|
|
28
|
+
export const name = 'im-markdown'
|
|
29
|
+
|
|
30
|
+
/** The `satori` service owns the element contributions this plugin installs into. */
|
|
31
|
+
export const inject = ['satori']
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The markdown element: GFM source that every mode renders as its own native markup.
|
|
35
|
+
*
|
|
36
|
+
* @param content - the GFM source.
|
|
37
|
+
* @returns the `<markdown>` element a message carries.
|
|
38
|
+
*/
|
|
39
|
+
export function markdown(content: string): Element<'markdown'> {
|
|
40
|
+
return h.markdown(content)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Whether `el` ends the message: it is the last child of its parent, and so is every ancestor of it.
|
|
45
|
+
*
|
|
46
|
+
* @param el - the element.
|
|
47
|
+
* @param ancestors - its ancestors, outermost first.
|
|
48
|
+
* @returns `true` when nothing follows `el` in document order.
|
|
49
|
+
*/
|
|
50
|
+
function endsMessage(el: Element, ancestors: readonly Element[]): boolean {
|
|
51
|
+
let child = el
|
|
52
|
+
for (let index = ancestors.length - 1; index >= 0; index--) {
|
|
53
|
+
const parent = ancestors[index]!
|
|
54
|
+
if (parent.children[parent.children.length - 1] !== child) return false
|
|
55
|
+
child = parent
|
|
56
|
+
}
|
|
57
|
+
return true
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Render one `<markdown>` element in its place.
|
|
62
|
+
*
|
|
63
|
+
* @param el - the element; `el.attrs.content` is the GFM source.
|
|
64
|
+
* @param ctx - render context of the element.
|
|
65
|
+
* @returns the platform nodes of the converted source.
|
|
66
|
+
*/
|
|
67
|
+
function render<T extends ModeTypes>(el: Element<'markdown'>, ctx: RenderContext<T>): T['node'][] {
|
|
68
|
+
const stream = ctx.stream
|
|
69
|
+
const growing = stream?.strategy === 'append' && !stream.final && endsMessage(el, ctx.ancestors)
|
|
70
|
+
const blocks = fromMarkdown(growing ? settledMarkdown(el.attrs.content) : el.attrs.content)
|
|
71
|
+
// Inside phrasing content a one-paragraph document is that paragraph's content.
|
|
72
|
+
const parent = ctx.ancestors[ctx.ancestors.length - 1]
|
|
73
|
+
const single = blocks.length === 1 && blocks[0]!.type === 'p' ? blocks[0]!.children : undefined
|
|
74
|
+
return ctx.transform(parent !== undefined && isPhrasingContainer(parent.type) && single ? single : blocks)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Register `<markdown>` on the `satori` service; the registration leaves with this plugin's fiber.
|
|
79
|
+
*
|
|
80
|
+
* @param ctx - plugin context, with the `satori` service injected.
|
|
81
|
+
*/
|
|
82
|
+
export function apply(ctx: Context): void {
|
|
83
|
+
ctx.effect(() => ctx.satori.elements.register('markdown', render))
|
|
84
|
+
}
|
package/README.md
DELETED