@yaks/markdown 0.0.0-stage → 0.2.36

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/structural.ts ADDED
@@ -0,0 +1,713 @@
1
+ /** Markdown as structural nodes, never generated HTML or terminal escapes.
2
+ * Uses the same GFM parser/version as the older canvas markdown renderer.
3
+ */
4
+ import { Lexer, Marked, type Token, Tokenizer, type Tokens } from 'marked'
5
+ import { HUMAN, short, WRITTEN } from '@yaks/id'
6
+ import type { Child, H } from 'jsr:@yaks/render@0.2.36'
7
+ import { away, type Site } from './away.js'
8
+
9
+ export { type Token } from 'marked'
10
+
11
+ /** Where an entity id named in prose leads: an href for a reader who can open
12
+ * the entity, or nothing, and then the id stays words. The host gives it, since
13
+ * only the host knows its routes and its reader. It is asked for an id written
14
+ * bare (T-123, #a1b2c3, a 40- or 64-hex SHA), for a link written to one
15
+ * ([the plan](T-123)), and for a code span holding a hex word, the way a commit
16
+ * is quoted (`1a2b3c4`), where a bare word like "decafed" never is. An eid
17
+ * (a UUID) is asked about as it is drawn ({@link Ids}), so a link never
18
+ * carries a whole uuid. */
19
+ export type Refs = (id: string) => string | undefined
20
+
21
+ /** What an entity is called where prose holds its eid: its id (`P-1`), from
22
+ * an entity the host has already read, a series it keeps in memory, or the
23
+ * number and letter it read for the eids the prose holds ({@link eids}), or
24
+ * nothing, and then the eid is drawn as its short handle (`#a3f19c024b`). It
25
+ * is asked as the prose is drawn, so the host reads before, never during. */
26
+ export type Ids = (eid: string) => string | undefined
27
+
28
+ // An id is a word of its own: a T-123 at a boundary, whatever its letter (the
29
+ // number names the entity), a #hex short id, a UUID or a whole SHA. UTF-8 and
30
+ // SHA-256 stay words because their letters sit mid-word, and one after a slash
31
+ // is a segment of a path or an address, which drawn would lead nowhere.
32
+ let UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
33
+ let ID = `${WRITTEN}|#[0-9a-fA-F]{6,64}|${UUID}|[0-9a-f]{64}|[0-9a-f]{40}`
34
+ let START = new RegExp(`(?<![\\w#/-])(?:${ID})(?![\\w-])`)
35
+ let REF = new RegExp(`^(?:${ID})(?![\\w-])`)
36
+ let NAMED = new RegExp(
37
+ `^(?:#[0-9a-fA-F]{6,64}|${UUID}|[0-9a-f]{40}|[0-9a-f]{64})$`,
38
+ )
39
+ let HEX = /^[0-9a-f]{7,64}$/i
40
+ let EID = new RegExp(`^${UUID}$`, 'i')
41
+ let EIDS = new RegExp(UUID, 'i')
42
+
43
+ /** Whether a link's target is an entity id rather than an address. */
44
+ export let named = (href: string): boolean =>
45
+ HUMAN.test(href) || NAMED.test(href)
46
+
47
+ /** An id as prose draws it: an eid as the host calls it ({@link Ids}), or its
48
+ * short handle; any other id as written. */
49
+ export let shown = (id: string, ids?: Ids): string =>
50
+ EID.test(id) ? ids?.(id.toLowerCase()) ?? short(id) : id
51
+
52
+ // Where the next id may start. Marked asks before every run of plain text,
53
+ // about all the text left, so a search of all of it made a long text with few
54
+ // ids quadratic: a 1 MB body took 21 seconds. The search looks a window ahead
55
+ // instead, and with no id in it answers the last boundary well short of its
56
+ // end, where no id the window cut short can have begun. Marked joins adjacent
57
+ // text, and at a boundary its text either stops anyway (`\`, `<`, `!`, `[`,
58
+ // `` ` ``, `*`, `~`, `_`) or nothing else can begin: no address and no email.
59
+ // A boundary that follows a space is passed over, so the spaces of a line
60
+ // break (` \n`) are never split.
61
+ let AHEAD = 512
62
+ let REACH = 128
63
+ let BOUND = /[\s"(),;>\]\\<![`*~_]/
64
+ let next = (src: string): number | undefined => {
65
+ if (src.length <= AHEAD) return src.match(START)?.index
66
+ let head = src.slice(0, AHEAD)
67
+ let i = head.match(START)?.index
68
+ if (i != null) return i
69
+ for (let at = AHEAD - REACH; at > 0; at--) {
70
+ if (BOUND.test(head[at]) && !/\s/.test(head[at - 1])) return at
71
+ }
72
+ return src.match(START)?.index
73
+ }
74
+
75
+ // A setext heading, a run of lines underlined with `=` or `-`: marked's own
76
+ // rule, with each line's run of characters taken whole. Marked reads the run a
77
+ // character at a time, which a paragraph of megabytes runs out of stack on (a
78
+ // 12 MB JSON dump threw); a line at a time, 33 MB reads in a tenth of a second.
79
+ let setext = Lexer.rules.block.gfm.lheading
80
+ let SETEXT = new RegExp(
81
+ setext.source.replace(
82
+ '(?:.|\\n(?!',
83
+ '(?:(?=([^\\n\\r\\u2028\\u2029]+))\\2|\\n(?!',
84
+ ),
85
+ setext.flags,
86
+ )
87
+
88
+ // Emphasis and a strikethrough close within a span of text: a `*`, `_` or `~`
89
+ // whose closer stands farther off stays as typed. Marked looks for
90
+ // the closing `*`, `_` or `~` through the rest of the paragraph, once for every
91
+ // one that opens, so a paragraph of megabytes with a few hundred that never
92
+ // close took a minute. It is asked about the span ahead instead (and the run
93
+ // just behind, which says whether the opener is one), and a closer found where
94
+ // the span cuts its view short is asked about the whole text again.
95
+ let SPAN = 4096
96
+ let BEHIND = 256
97
+ let spanned = <T extends { raw: string }>(
98
+ close: (src: string, masked: string, before?: string) => T | undefined,
99
+ ) =>
100
+ function (this: Tokenizer, src: string, masked: string, before?: string) {
101
+ let at = masked.length - src.length
102
+ let found = close.call(
103
+ this,
104
+ src.slice(0, SPAN),
105
+ masked.slice(Math.max(0, at - BEHIND), at + SPAN),
106
+ before,
107
+ )
108
+ return found && src.length > SPAN && found.raw.length > SPAN - REACH
109
+ ? close.call(this, src, masked, before)
110
+ : found
111
+ }
112
+
113
+ let lexer = new Marked({
114
+ gfm: true,
115
+ tokenizer: {
116
+ emStrong: spanned(Tokenizer.prototype.emStrong),
117
+ del: spanned(Tokenizer.prototype.del),
118
+ lheading(src) {
119
+ let m = SETEXT.exec(src)
120
+ if (!m) return undefined
121
+ let text = m[1].trim()
122
+ return {
123
+ type: 'heading',
124
+ raw: m[0].replace(/\n+$/, ''),
125
+ depth: m[3][0] == '=' ? 1 : 2,
126
+ text,
127
+ tokens: this.lexer.inline(text),
128
+ }
129
+ },
130
+ },
131
+ extensions: [{
132
+ name: 'ref',
133
+ level: 'inline',
134
+ start: next,
135
+ // `start` is asked about the text after a line's first character, so it
136
+ // cannot see that character: the token before says what the id follows,
137
+ // and one glued to a word (`xT-12`) is no id. It is read only where an id
138
+ // starts: marked tries this at every step and joins adjacent text into one
139
+ // token, so reading it each time copied the paragraph so far every step.
140
+ tokenizer: (src: string, before: Token[]) => {
141
+ let m = REF.exec(src)
142
+ if (!m || /[\w#-]/.test(before.at(-1)?.raw.at(-1) ?? '')) return undefined
143
+ return { type: 'ref', raw: m[0], text: m[0], id: m[0] }
144
+ },
145
+ }],
146
+ })
147
+
148
+ /** Parse GFM. `breaks` turns a single newline into a line break, which is what
149
+ * a chat message or a terminal line wants and what a document does not: prose
150
+ * wrapped at 80 columns would keep every one of those wraps. An entity id in
151
+ * the prose is a `ref` token of its own; code keeps its ids literal. */
152
+ export let parse = (
153
+ source: string,
154
+ { breaks = true }: { breaks?: boolean } = {},
155
+ ): Token[] => lexer.lexer(source, { ...lexer.defaults, breaks })
156
+
157
+ /** Parse a line of GFM, such as a label or a title: its inline markup only,
158
+ * with no paragraph around it. */
159
+ export let parseInline = (source: string): Token[] =>
160
+ lexer.Lexer.lexInline(source, lexer.defaults)
161
+
162
+ /** Something a document points at: an entity, by the id it was written as,
163
+ * or an address. */
164
+ export type Mention =
165
+ | { kind: 'entity'; id: string }
166
+ | { kind: 'link'; href: string }
167
+
168
+ /** What a document points at, in reading order, read the way it is drawn: an
169
+ * id written bare, a link written to an id, and a hex word quoted in code
170
+ * (which the host may know as a commit) are entities; any other link or image
171
+ * is its address, unless the renderer would refuse it or it carries a quote
172
+ * or a backslash, the debris of prose around a bare URL. Code keeps its ids
173
+ * literal. */
174
+ export let mentions = (tokens: Token[]): Mention[] => {
175
+ let out: Mention[] = []
176
+ lexer.walkTokens(tokens, (t) => {
177
+ if (t.type == 'ref') {
178
+ out.push({ kind: 'entity', id: String((t as Tokens.Generic).id) })
179
+ } else if (t.type == 'codespan' && HEX.test((t as Tokens.Codespan).text)) {
180
+ out.push({ kind: 'entity', id: (t as Tokens.Codespan).text })
181
+ } else if (t.type == 'link' || t.type == 'image') {
182
+ let href = (t as Tokens.Link).href.trim()
183
+ if (named(href)) out.push({ kind: 'entity', id: href })
184
+ else if (href && !/["'\\]/.test(href) && safeHref(href) != null) {
185
+ out.push({ kind: 'link', href })
186
+ }
187
+ }
188
+ })
189
+ return out
190
+ }
191
+
192
+ // Prose rewritten id by id, still as text: each id written bare or as a link's
193
+ // target is given to `f`, and replaced by what it answers. Code keeps its ids
194
+ // literal, and a link keeps its own words. Marked keeps no offsets, but a
195
+ // token's raw text stands in the source inside its parent's, after its elder
196
+ // sibling's, so each is found there: an id is swapped where it is read, never
197
+ // where the same letters stand inside another word earlier on
198
+ // (`/tmp/T-12-proof … T-12`). A token whose raw the lexer reshaped (a list
199
+ // item's indented lines) is not found, and its children are looked for in
200
+ // what is left of its parent.
201
+ let rewritten = (
202
+ source: string,
203
+ f: (id: string) => string | undefined,
204
+ ): string => {
205
+ let edits: [number, number, string][] = []
206
+ let kids = (t: Token): Token[] =>
207
+ t.type == 'list'
208
+ ? (t as Tokens.List).items
209
+ : t.type == 'table'
210
+ ? [(t as Tokens.Table).header, ...(t as Tokens.Table).rows]
211
+ .flatMap((row) => row.flatMap((cell) => cell.tokens))
212
+ : (t as { tokens?: Token[] }).tokens ?? []
213
+ let walk = (tokens: Token[], from: number, to: number): number => {
214
+ let at = from
215
+ for (let t of tokens) {
216
+ let i = source.slice(at, to).indexOf(t.raw)
217
+ if (i < 0) {
218
+ if (t.type != 'ref') at = walk(kids(t), at, to)
219
+ continue
220
+ }
221
+ i += at
222
+ let end = i + t.raw.length
223
+ if (t.type == 'ref') {
224
+ let word = f(t.raw)
225
+ if (word != null && word != t.raw) edits.push([i, end, word])
226
+ } else if (t.type == 'link' && named((t as Tokens.Link).href)) {
227
+ let { href } = t as Tokens.Link
228
+ let j = i + t.raw.lastIndexOf(href)
229
+ let word = f(href)
230
+ if (word != null && word != href) edits.push([j, j + href.length, word])
231
+ walk(kids(t), i + 1, j)
232
+ } else if (t.type != 'code' && t.type != 'codespan') {
233
+ walk(kids(t), i, end)
234
+ }
235
+ at = end
236
+ }
237
+ return at
238
+ }
239
+ walk(parse(source, { breaks: false }), 0, source.length)
240
+ let out: string[] = []
241
+ let at = 0
242
+ for (let [from, to, word] of edits.sort((a, b) => a[0] - b[0])) {
243
+ out.push(source.slice(at, from), word)
244
+ at = to
245
+ }
246
+ out.push(source.slice(at))
247
+ return out.join('')
248
+ }
249
+
250
+ /** Prose as its reader reads it, still as text: each eid it holds, written
251
+ * bare or as a link's target, drawn as {@link shown} draws it, so a model or a
252
+ * printout never reads a whole uuid. Code keeps its ids literal, and a link
253
+ * keeps its own words. What the renderer does to the same text, for a reader
254
+ * of text rather than nodes. */
255
+ export let drawn = (source: string, ids?: Ids): string =>
256
+ EIDS.test(source)
257
+ ? rewritten(source, (id) => EID.test(id) ? shown(id, ids) : undefined)
258
+ : source
259
+
260
+ /** The eids prose holds, written bare or as a link's target, in reading
261
+ * order, once each and in lower case: what {@link drawn} and the renderer ask
262
+ * a host's {@link Ids} about. Code keeps its ids literal, so none in it is
263
+ * listed. */
264
+ export let eids = (source: string): string[] => {
265
+ if (!EIDS.test(source)) return []
266
+ let out = new Set<string>()
267
+ rewritten(source, (id) => {
268
+ if (EID.test(id)) out.add(id.toLowerCase())
269
+ return undefined
270
+ })
271
+ return [...out]
272
+ }
273
+
274
+ // An id a person types for an entity, as prose holds it before it is stored:
275
+ // a human id or a short handle. An eid is already what is stored, and a SHA
276
+ // names its content.
277
+ let TYPED = new RegExp(`^(?:${WRITTEN}|#[0-9a-fA-F]{10,64})$`)
278
+ let TYPES = new RegExp(`(?:${WRITTEN}|#[0-9a-fA-F]{10})`)
279
+
280
+ /** The ids typed in prose that a store would name an entity by: each human id
281
+ * (`T-12`) and short handle (`#a3f19c024b`) written bare or as a link's
282
+ * target, in reading order, once each. Code keeps its ids literal, so none in
283
+ * it is listed. What {@link stored} is asked to swap. */
284
+ export let typed = (source: string): string[] => {
285
+ if (!TYPES.test(source)) return []
286
+ let out = new Set<string>()
287
+ rewritten(source, (id) => {
288
+ if (TYPED.test(id)) out.add(id)
289
+ return undefined
290
+ })
291
+ return [...out]
292
+ }
293
+
294
+ /** Prose as a store keeps it: each id {@link typed} lists that `eids` names
295
+ * replaced by that eid, bare or as a link's target, so the text names the
296
+ * entity in any store and under any number. An id it does not name stays as
297
+ * typed, and so does everything in code and a link's own words.
298
+ *
299
+ * Given the text it replaces (`was`), only the ids the new text adds are
300
+ * swapped: one standing where `was` kept the same id as typed stays typed, so
301
+ * words left alone (`P-1 is very useful`) are never bound to whatever entity
302
+ * comes to hold that id later. One standing where `was` held the eid it names
303
+ * (a body written back as its reader saw it drawn) takes that eid again. */
304
+ export let stored = (
305
+ source: string,
306
+ eids: (id: string) => string | undefined,
307
+ was?: string,
308
+ ): string => {
309
+ if (!TYPES.test(source)) return source
310
+ let kept = was == null ? undefined : untouched(said(source), said(was), eids)
311
+ let n = 0
312
+ return rewritten(
313
+ source,
314
+ (id) => kept?.has(n++) || !TYPED.test(id) ? undefined : eids(id),
315
+ )
316
+ }
317
+
318
+ // Every id a text holds bare or as a link's target, in reading order: what
319
+ // `rewritten` hands its function, one per place the id stands.
320
+ let said = (source: string): string[] => {
321
+ let out: string[] = []
322
+ rewritten(source, (id) => {
323
+ out.push(id)
324
+ return undefined
325
+ })
326
+ return out
327
+ }
328
+
329
+ // Which of the new text's ids stand where the old text kept the same id as
330
+ // typed: the places of the longest run the two share in order, where an old
331
+ // id matches a new one written the same, or an old eid matches the new id
332
+ // that names it. Only a typed match is kept; the rest are the new text's own.
333
+ let untouched = (
334
+ now: string[],
335
+ was: string[],
336
+ eids: (id: string) => string | undefined,
337
+ ): Set<number> => {
338
+ let same = (a: string, b: string) =>
339
+ a == b || EID.test(b) && TYPED.test(a) && eids(a) == b
340
+ let head = 0
341
+ while (head < now.length && head < was.length && same(now[head], was[head])) {
342
+ head++
343
+ }
344
+ let tail = 0
345
+ while (
346
+ tail < now.length - head && tail < was.length - head &&
347
+ same(now[now.length - 1 - tail], was[was.length - 1 - tail])
348
+ ) tail++
349
+ let pairs: [number, number][] = []
350
+ for (let i = 0; i < head; i++) pairs.push([i, i])
351
+ for (let k = 1; k <= tail; k++) pairs.push([now.length - k, was.length - k])
352
+ let a = now.slice(head, now.length - tail)
353
+ let b = was.slice(head, was.length - tail)
354
+ if (a.length * b.length > 4e6) {
355
+ // Too many ids changed between the ends for a table: matched in order.
356
+ for (let i = 0, j = 0; i < a.length && j < b.length; i++) {
357
+ let k = b.indexOf(a[i], j)
358
+ if (k < 0) continue
359
+ pairs.push([head + i, head + k])
360
+ j = k + 1
361
+ }
362
+ } else if (a.length && b.length) {
363
+ // The longest common subsequence of what is left, table by table.
364
+ let w = b.length + 1
365
+ let t = new Uint32Array((a.length + 1) * w)
366
+ for (let i = a.length - 1; i >= 0; i--) {
367
+ for (let j = b.length - 1; j >= 0; j--) {
368
+ t[i * w + j] = same(a[i], b[j])
369
+ ? t[(i + 1) * w + j + 1] + 1
370
+ : Math.max(t[(i + 1) * w + j], t[i * w + j + 1])
371
+ }
372
+ }
373
+ for (let i = 0, j = 0; i < a.length && j < b.length;) {
374
+ if (same(a[i], b[j])) pairs.push([head + i++, head + j++])
375
+ else if (t[(i + 1) * w + j] >= t[i * w + j + 1]) i++
376
+ else j++
377
+ }
378
+ }
379
+ return new Set(
380
+ pairs.filter(([i, j]) => now[i] == was[j] && TYPED.test(was[j]))
381
+ .map(([i]) => i),
382
+ )
383
+ }
384
+
385
+ /** The words a heading is made of, with the markup dropped: a reader sees
386
+ * these words, so the anchor is named after them. */
387
+ let words = (tokens: Token[]): string =>
388
+ tokens.map((t) => {
389
+ let inner = (t as { tokens?: Token[] }).tokens
390
+ return inner ? words(inner) : (t as { text?: string }).text ?? ''
391
+ }).join('')
392
+
393
+ /** A document's anchor names, handed out in reading order: lowercase words
394
+ * joined by hyphens, everything that is not a letter or a number dropped — so
395
+ * a name can never carry a quote or an angle bracket into an attribute — and
396
+ * a number on any name the document says twice. */
397
+ export let slugs = (): (text: string) => string => {
398
+ let seen = new Map<string, number>()
399
+ return (text) => {
400
+ let base = text.toLowerCase().replace(/[^\p{L}\p{N} -]/gu, '').trim()
401
+ .replace(/\s+/g, '-') || 'section'
402
+ let n = (seen.get(base) ?? 0) + 1
403
+ seen.set(base, n)
404
+ return n > 1 ? `${base}-${n}` : base
405
+ }
406
+ }
407
+
408
+ /** Every heading of a document in reading order, each under the id `render`
409
+ * gives it — which is how a contents list links what is on the page without
410
+ * drawing the page a second time. */
411
+ export let headings = (
412
+ tokens: Token[],
413
+ ): { depth: number; text: string; id: string }[] => {
414
+ let name = slugs()
415
+ let found = (
416
+ items: Token[],
417
+ ): { depth: number; text: string; id: string }[] =>
418
+ items.flatMap((t) => {
419
+ if (t.type == 'heading') {
420
+ let text = words((t as Tokens.Heading).tokens)
421
+ return [{ depth: (t as Tokens.Heading).depth, text, id: name(text) }]
422
+ }
423
+ let inner = (t as { tokens?: Token[] }).tokens
424
+ return inner ? found(inner) : []
425
+ })
426
+ return found(tokens)
427
+ }
428
+
429
+ /** Only navigable links: no scripting, data, or control-byte URL schemes. */
430
+ export let safeHref = (href: string): string | undefined => {
431
+ if ([...href].some((c) => c.charCodeAt(0) <= 32 || c.charCodeAt(0) == 127)) {
432
+ return undefined
433
+ }
434
+ if (/^[a-z][a-z\d+.-]*:/i.test(href) && !/^(https?:|mailto:)/i.test(href)) {
435
+ return undefined
436
+ }
437
+ return href
438
+ }
439
+
440
+ let parts: Record<string, string> = {
441
+ p: 'Paragraph',
442
+ h1: 'Heading',
443
+ h2: 'Heading',
444
+ h3: 'Heading',
445
+ h4: 'Heading',
446
+ h5: 'Heading',
447
+ h6: 'Heading',
448
+ strong: 'Strong',
449
+ em: 'Emphasis',
450
+ del: 'Deleted',
451
+ code: 'Code',
452
+ pre: 'Source',
453
+ br: 'Break',
454
+ hr: 'Rule',
455
+ blockquote: 'Quote',
456
+ ol: 'Ordered',
457
+ ul: 'Unordered',
458
+ li: 'Item',
459
+ a: 'Link',
460
+ table: 'Table',
461
+ thead: 'Head',
462
+ tbody: 'Rows',
463
+ tr: 'Row',
464
+ th: 'HeadingCell',
465
+ td: 'Cell',
466
+ }
467
+
468
+ let bodyClass = (tag: string) =>
469
+ `Body_${parts[tag]}` +
470
+ (/^h[1-6]$/.test(tag) ? ` Body_Heading-${tag.slice(1)}` : '')
471
+
472
+ /** What a host gives the renderer: where an entity id leads (`Refs`), what an
473
+ * eid is called (`Ids`), how a fenced block's code is coloured, as runs of
474
+ * text each with its classes, and the page's own site, off which a link
475
+ * opens in a new tab (./away.ts; unset, the location's). */
476
+ export type Options = {
477
+ refs?: Refs
478
+ ids?: Ids
479
+ code?: (text: string, language?: string) => Run[]
480
+ site?: Site
481
+ /** Links, images and ids drawn as their words, for a line that is itself
482
+ * the thing pressed, such as a title. */
483
+ flat?: boolean
484
+ }
485
+
486
+ /** A run of code text and the classes it is coloured with. */
487
+ export type Run = { text: string; classes: string[] }
488
+
489
+ /** The parsed tree's blocks through any @yaks/render host (including
490
+ * Preact), for a caller that holds them in an element of its own, such as a
491
+ * page's `Body`. HTML tokens remain text. Images are descriptive links, never
492
+ * remote fetches.
493
+ */
494
+ export let blocks = <Node>(
495
+ tokens: Token[],
496
+ host: H<Node>,
497
+ { refs, ids, code, flat, site }: Options = {},
498
+ ): Child<Node>[] => {
499
+ let name = slugs()
500
+ // An id the host can open is an anchor carrying the id, so a host can give
501
+ // it its own click; one it cannot open is the words it was written as. An
502
+ // eid is drawn short, and leads where its short form does.
503
+ let ref = (id: string, ...words: Child<Node>[]): Child<Node>[] => {
504
+ let href = flat ? undefined : refs?.(shown(id, ids))
505
+ let link = href == null ? undefined : safeHref(href)
506
+ return link == null ? words : [
507
+ element(
508
+ 'a',
509
+ { href: link, 'data-ref': id, class: 'Body_Ref' },
510
+ ...words,
511
+ ),
512
+ ]
513
+ }
514
+ let element = (
515
+ tag: string,
516
+ props: Record<string, unknown> | null,
517
+ ...children: Child<Node>[]
518
+ ) => {
519
+ return host(tag, {
520
+ ...tag == 'a' && props ? away(props, site) : props,
521
+ class: [
522
+ bodyClass(tag),
523
+ props?.class,
524
+ ].filter(Boolean).join(' '),
525
+ }, ...children)
526
+ }
527
+ let children = (items: Token[]): Child<Node>[] => items.flatMap(token)
528
+ let token = (t: Token): Child<Node>[] => {
529
+ switch (t.type) {
530
+ case 'space':
531
+ return []
532
+ case 'paragraph':
533
+ return [element('p', null, ...children((t as Tokens.Paragraph).tokens))]
534
+ case 'heading': {
535
+ let v = t as Tokens.Heading
536
+ // The id is the anchor a contents list points at (`headings` hands
537
+ // out the same names in the same order), so every consumer of a
538
+ // document gets headings it can link to.
539
+ let at = { id: name(words(v.tokens)) }
540
+ return [element('h' + v.depth, at, ...children(v.tokens))]
541
+ }
542
+ case 'strong':
543
+ return [
544
+ element('strong', null, ...children((t as Tokens.Strong).tokens)),
545
+ ]
546
+ case 'em':
547
+ return [element('em', null, ...children((t as Tokens.Em).tokens))]
548
+ case 'del':
549
+ return [element('del', null, ...children((t as Tokens.Del).tokens))]
550
+ case 'codespan': {
551
+ let { text } = t as Tokens.Codespan
552
+ let quoted = element('code', null, text)
553
+ return HEX.test(text) ? ref(text, quoted) : [quoted]
554
+ }
555
+ case 'ref': {
556
+ let id = String((t as Tokens.Generic).id)
557
+ return ref(id, shown(id, ids))
558
+ }
559
+ case 'code': {
560
+ let v = t as Tokens.Code
561
+ let lang = v.lang?.split(/\s/)[0] || undefined
562
+ let runs = code?.(v.text, lang)
563
+ return [
564
+ element(
565
+ 'pre',
566
+ null,
567
+ element(
568
+ 'code',
569
+ { class: lang ? 'language-' + lang : undefined },
570
+ ...runs
571
+ ? runs.map((r) =>
572
+ r.classes.length
573
+ ? host('span', { class: r.classes.join(' ') }, r.text)
574
+ : r.text
575
+ )
576
+ : [v.text],
577
+ ),
578
+ ),
579
+ ]
580
+ }
581
+ case 'br':
582
+ return [element('br', null)]
583
+ case 'hr':
584
+ return [element('hr', null)]
585
+ case 'blockquote':
586
+ return [
587
+ element(
588
+ 'blockquote',
589
+ null,
590
+ ...children((t as Tokens.Blockquote).tokens),
591
+ ),
592
+ ]
593
+ case 'list': {
594
+ let v = t as Tokens.List
595
+ return [
596
+ element(
597
+ v.ordered ? 'ol' : 'ul',
598
+ { start: v.ordered ? v.start : undefined },
599
+ ...v.items.map((item, i) =>
600
+ element(
601
+ 'li',
602
+ {
603
+ 'data-marker': v.ordered
604
+ ? String(Number(v.start) + i) + '. '
605
+ : '• ',
606
+ },
607
+ item.task ? (item.checked ? '[x] ' : '[ ] ') : '',
608
+ ...children(item.tokens),
609
+ )
610
+ ),
611
+ ),
612
+ ]
613
+ }
614
+ case 'link': {
615
+ let v = t as Tokens.Link
616
+ if (named(v.href)) return ref(v.href, ...children(v.tokens))
617
+ if (flat) return children(v.tokens)
618
+ return [
619
+ element(
620
+ 'a',
621
+ { href: safeHref(v.href), title: v.title || undefined },
622
+ ...children(v.tokens),
623
+ ),
624
+ ]
625
+ }
626
+ case 'image': {
627
+ let v = t as Tokens.Image
628
+ if (flat) return [v.text]
629
+ return [
630
+ element(
631
+ 'a',
632
+ { href: safeHref(v.href), title: v.title || undefined },
633
+ v.text || '[image]',
634
+ ),
635
+ ]
636
+ }
637
+ case 'table': {
638
+ let v = t as Tokens.Table
639
+ return [
640
+ element(
641
+ 'table',
642
+ null,
643
+ element(
644
+ 'thead',
645
+ null,
646
+ element(
647
+ 'tr',
648
+ null,
649
+ ...v.header.map((cell, col) =>
650
+ element(
651
+ 'th',
652
+ { align: v.align[col] ?? undefined },
653
+ ...children(cell.tokens),
654
+ )
655
+ ),
656
+ ),
657
+ ),
658
+ element(
659
+ 'tbody',
660
+ null,
661
+ ...v.rows.map((row) =>
662
+ element(
663
+ 'tr',
664
+ null,
665
+ ...row.map((cell, col) =>
666
+ element(
667
+ 'td',
668
+ { align: v.align[col] ?? undefined },
669
+ ...children(cell.tokens),
670
+ )
671
+ ),
672
+ )
673
+ ),
674
+ ),
675
+ ),
676
+ ]
677
+ }
678
+ case 'text': {
679
+ // A soft line break, kept as a newline when `breaks` is off, is a
680
+ // space in Markdown. Left as a newline, a terminal would break the
681
+ // line there, and a renderer that joins wrapped rows would run its
682
+ // two words together.
683
+ let v = t as Tokens.Text
684
+ return v.tokens ? children(v.tokens) : [v.text.replace(/ *\n */g, ' ')]
685
+ }
686
+ case 'escape':
687
+ return [(t as Tokens.Escape).text]
688
+ case 'html': {
689
+ // Markup is text here, never markup. A comment is not even that: it
690
+ // is the author writing to whoever opens the file, which every other
691
+ // renderer drops and this one used to paint as words on the page.
692
+ let { text } = t as Tokens.HTML
693
+ return /^\s*<!--[\s\S]*-->\s*$/.test(text) ? [] : [text]
694
+ }
695
+ default:
696
+ return [t.raw]
697
+ }
698
+ }
699
+ return children(tokens)
700
+ }
701
+
702
+ /** Render the parsed tree through any @yaks/render host: its blocks, in the
703
+ * document's own element. */
704
+ export let render = <Node>(
705
+ tokens: Token[],
706
+ host: H<Node>,
707
+ options?: Options,
708
+ ): Node =>
709
+ host(
710
+ 'div',
711
+ { class: 'Markdown', wrap: '1' },
712
+ ...blocks(tokens, host, options),
713
+ )