@mdsvex/render 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Node.svelte CHANGED
@@ -1,14 +1,273 @@
1
+ <script lang="ts" module>
2
+ import type { NodeBuffer } from '@mdsvex/parse/utils';
3
+ import type { Highlight, MathRenderer } from './component.js';
4
+
5
+ // each chunk replaces every token of an open fence, about 1ms for 1000 characters, a longer one waits until it closes
6
+ const OPEN_FENCE_LIMIT = 4096;
7
+
8
+ const HIGHLIGHT_CONTEXT = {
9
+ filename: undefined,
10
+ unknown_language() {},
11
+ warn() {},
12
+ };
13
+ const OPEN_HIGHLIGHT_CONTEXT = { ...HIGHLIGHT_CONTEXT, open: true };
14
+
15
+ // the text selector keeps the arrow from being drawn as an emoji
16
+ const BACK_ARROW = String.fromCharCode(0x21a9, 0xfe0e);
17
+
18
+ /** the href of an id, a label with half a surrogate pair has no encoding and goes as it is */
19
+ function fragment(id: string): string {
20
+ try {
21
+ return '#' + encodeURIComponent(id);
22
+ } catch {
23
+ return '#' + id;
24
+ }
25
+ }
26
+
27
+ function attribute_text(attrs: Record<string, any>): string {
28
+ let out = '';
29
+ for (const key in attrs) {
30
+ const value = attrs[key];
31
+ out +=
32
+ value === true
33
+ ? ' ' + key
34
+ : ' ' +
35
+ key +
36
+ '="' +
37
+ String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;') +
38
+ '"';
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /** html with attrs at the end of the open tag it starts with, unchanged when that is no tag */
44
+ function with_attributes(html: string, tag: string, attrs: string): string {
45
+ const at = tag.length + 1;
46
+ const after = html.charCodeAt(at);
47
+ if (
48
+ attrs === '' ||
49
+ !html.startsWith('<' + tag) ||
50
+ (after !== 62 && after !== 32 && after !== 9 && after !== 10)
51
+ )
52
+ return html;
53
+ let quote = 0;
54
+ for (let i = at; i < html.length; i++) {
55
+ const ch = html.charCodeAt(i);
56
+ if (quote !== 0) {
57
+ if (ch === quote) quote = 0;
58
+ } else if (ch === 34 || ch === 39) quote = ch;
59
+ else if (ch === 62) return html.slice(0, i) + attrs + html.slice(i);
60
+ }
61
+ return html;
62
+ }
63
+
64
+ /** the props of a typed element with those compile adds for its kind, the level of a heading and the start of an ordered list */
65
+ function typed_props(
66
+ tag: string,
67
+ props: Record<string, any>
68
+ ): Record<string, any> {
69
+ if (tag.length === 2 && tag.charCodeAt(0) === 104) {
70
+ const level = tag.charCodeAt(1) - 48;
71
+ if (level >= 1 && level <= 6 && !('level' in props))
72
+ return { ...props, level };
73
+ } else if (tag === 'ol' && !('start' in props))
74
+ return { ...props, start: 1 };
75
+ return props;
76
+ }
77
+
78
+ const ATTRIBUTE = /([^\s"'=]+)(?:="([^"]*)"|='([^']*)')?/g;
79
+ const ENTITIES: Record<string, string> = {
80
+ '&quot;': '"',
81
+ '&#39;': "'",
82
+ '&lt;': '<',
83
+ '&gt;': '>',
84
+ '&amp;': '&',
85
+ };
86
+
87
+ /** the attributes and the content of html that is one code element, null for any other html */
88
+ function code_parts(
89
+ html: string
90
+ ): { props: Record<string, any>; body: string } | null {
91
+ const after = html.charCodeAt(5);
92
+ if (
93
+ !html.startsWith('<code') ||
94
+ !html.endsWith('</code>') ||
95
+ (after !== 62 && after !== 32 && after !== 9 && after !== 10)
96
+ )
97
+ return null;
98
+ let quote = 0;
99
+ for (let i = 5; i < html.length - 7; i++) {
100
+ const ch = html.charCodeAt(i);
101
+ if (quote !== 0) {
102
+ if (ch === quote) quote = 0;
103
+ } else if (ch === 34 || ch === 39) quote = ch;
104
+ else if (ch === 62) {
105
+ const props: Record<string, any> = {};
106
+ for (const found of html.slice(5, i).matchAll(ATTRIBUTE)) {
107
+ const value = found[2] ?? found[3];
108
+ props[found[1]] =
109
+ value === undefined
110
+ ? true
111
+ : value.replace(
112
+ /&(?:quot|#39|lt|gt|amp);/g,
113
+ (entity) => ENTITIES[entity]
114
+ );
115
+ }
116
+ return { props, body: html.slice(i + 1, -7) };
117
+ }
118
+ }
119
+ return null;
120
+ }
121
+
122
+ /** the language of an info string and what follows it */
123
+ function info_parts(info: string | undefined): [string, string] {
124
+ const lang = info ?? '';
125
+ const space = lang.search(/[ \t]/);
126
+ return space === -1
127
+ ? [lang, '']
128
+ : [lang.slice(0, space), lang.slice(space).trim()];
129
+ }
130
+
131
+ /**
132
+ * the html of a fence from the highlighter, null draws it plain, bare is
133
+ * the pre alone, as its replacement draws what goes around it
134
+ */
135
+ function fence_html(
136
+ highlight: Highlight,
137
+ code: string,
138
+ info: string | undefined,
139
+ attrs: Record<string, any>,
140
+ open: boolean,
141
+ bare: boolean
142
+ ): string | null {
143
+ const [lang, meta] = info_parts(info);
144
+ try {
145
+ if (typeof highlight === 'function') {
146
+ const out = highlight(code, { lang, meta, inline: false, open });
147
+ return typeof out === 'string'
148
+ ? with_attributes(out, 'pre', attribute_text(attrs))
149
+ : null;
150
+ }
151
+ const block = highlight.block(
152
+ code,
153
+ lang,
154
+ meta,
155
+ open ? OPEN_HIGHLIGHT_CONTEXT : HIGHLIGHT_CONTEXT
156
+ );
157
+ if (block === null) return null;
158
+ if (block.attributes === null)
159
+ return bare ? block.body : block.before + block.body + block.after;
160
+ const pre =
161
+ '<pre' +
162
+ block.attributes +
163
+ attribute_text(attrs) +
164
+ '>' +
165
+ block.body +
166
+ '</pre>';
167
+ return bare ? pre : block.before + pre + block.after;
168
+ } catch {
169
+ // an open fence can be code the highlighter can not read yet
170
+ return null;
171
+ }
172
+ }
173
+
174
+ /** the html of a code span with a #! hint from the highlighter, null draws it plain */
175
+ function span_html(
176
+ highlight: Highlight,
177
+ code: string,
178
+ lang: string,
179
+ attrs: Record<string, any>,
180
+ open: boolean
181
+ ): string | null {
182
+ if (code.indexOf('\n') !== -1) code = code.replace(/\n/g, ' ');
183
+ try {
184
+ if (typeof highlight === 'function') {
185
+ const out = highlight(code, { lang, meta: '', inline: true, open });
186
+ return typeof out === 'string'
187
+ ? with_attributes(out, 'code', attribute_text(attrs))
188
+ : null;
189
+ }
190
+ if (highlight.inline === undefined) return null;
191
+ const span = highlight.inline(
192
+ code,
193
+ lang,
194
+ open ? OPEN_HIGHLIGHT_CONTEXT : HIGHLIGHT_CONTEXT
195
+ );
196
+ if (span === null) return null;
197
+ if (span.attributes === null) return span.body;
198
+ return (
199
+ '<code' +
200
+ span.attributes +
201
+ attribute_text(attrs) +
202
+ '>' +
203
+ span.body +
204
+ '</code>'
205
+ );
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+
211
+ // the markup compile writes around math
212
+ const MATH_OPEN = '<div class="math math-display" translate="no">';
213
+ const MATH_INLINE_OPEN = '<span class="math math-inline" translate="no">';
214
+
215
+ /** the html of a math fence or of inline math from the renderer, null draws it plain */
216
+ function math_html(
217
+ math: MathRenderer,
218
+ latex: string,
219
+ display: boolean,
220
+ meta: string
221
+ ): string | null {
222
+ try {
223
+ const out = math(latex, { display, meta, filename: undefined });
224
+ if (typeof out !== 'string') return null;
225
+ return display
226
+ ? MATH_OPEN + out + '</div>'
227
+ : MATH_INLINE_OPEN + out + '</span>';
228
+ } catch {
229
+ // a stream has no build to fail, latex the renderer can not read shows as written
230
+ return null;
231
+ }
232
+ }
233
+
234
+ // the last html of each open math fence by its node, an open block is a new component on every chunk
235
+ const open_math = new WeakMap<NodeBuffer, Map<number, string>>();
236
+
237
+ /** the html of a math fence that is still open, what it last rendered as when its latex can not be read yet */
238
+ function open_math_html(
239
+ math: MathRenderer,
240
+ buf: NodeBuffer,
241
+ idx: number,
242
+ latex: string,
243
+ meta: string
244
+ ): string | null {
245
+ let last = open_math.get(buf);
246
+ if (latex.length <= OPEN_FENCE_LIMIT && latex.trim() !== '') {
247
+ const html = math_html(math, latex, true, meta);
248
+ if (html !== null) {
249
+ if (last === undefined) open_math.set(buf, (last = new Map()));
250
+ last.set(idx, html);
251
+ return html;
252
+ }
253
+ }
254
+ return last?.get(idx) ?? null;
255
+ }
256
+ </script>
257
+
1
258
  <script lang="ts">
2
259
  import { is_raw_text_tag } from '@mdsvex/parse/utils';
3
- import type { NodeBuffer } from '@mdsvex/parse/utils';
4
260
  import {
5
261
  buf_children,
6
262
  buf_code,
7
263
  buf_text,
8
264
  buf_text_content,
265
+ footnote_id,
266
+ footnote_ref_id,
9
267
  } from '@mdsvex/parse/buf-utils';
268
+ import type { FootnoteIndex } from '@mdsvex/parse/buf-utils';
10
269
  import { setContext } from 'svelte';
11
- import type { Component } from 'svelte';
270
+ import type { Component, Snippet } from 'svelte';
12
271
  import Node from './Node.svelte';
13
272
 
14
273
  type ComponentMap = Record<string, Component<any>>;
@@ -18,18 +277,30 @@
18
277
  idx,
19
278
  source,
20
279
  components,
280
+ component_mode = 'all',
21
281
  directives,
22
282
  plugin_data,
283
+ highlight,
284
+ math,
285
+ footnotes,
23
286
  }: {
24
287
  buf: NodeBuffer;
25
288
  idx: number;
26
289
  source: string;
27
- /** a component for an element by its tag */
290
+ /** a component for an element by its tag, with the props a replacement gets in a compiled document */
28
291
  components?: ComponentMap;
292
+ /** markdown keeps the lowercase html in the source as elements, as the component_mode option of compile does */
293
+ component_mode?: 'markdown' | 'all';
29
294
  /** a component for a directive by its name, args are its props, label and children snippets */
30
295
  directives?: ComponentMap;
31
296
  /** what plugins wrote, a component reads it from the context, see PluginStream */
32
297
  plugin_data?: { readonly current: unknown };
298
+ /** highlights code fences, takes what the highlight option of compile takes, its html is not escaped */
299
+ highlight?: Highlight | false | null;
300
+ /** renders math fences and inline math, takes what the math option of compile takes, its html is not escaped */
301
+ math?: MathRenderer | false | null;
302
+ /** the footnotes of a ComponentRenderer, without it a reference is its label and a definition is drawn in place */
303
+ footnotes?: FootnoteIndex | null;
33
304
  } = $props();
34
305
 
35
306
  // the key of @mdsvex/render/stream and of a compiled document, Symbol.for so every copy agrees
@@ -74,6 +345,19 @@
74
345
  const K_FOOTNOTE_REFERENCE = 36;
75
346
  const K_FOOTNOTE_DEFINITION = 37;
76
347
  const K_DEFINITION = 38;
348
+ /** no kind, a node drawn as its replacement matches no branch above the last ones */
349
+ const K_REPLACED = -1;
350
+
351
+ const HEADINGS = ['', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
352
+ /** lowercase elements only, a capitalised tag is a component by its name */
353
+ const ELEMENT_NAME = /^[a-z][a-z0-9-]*$/;
354
+ /** what a component can not take, an element that has one stays an element */
355
+ const ELEMENT_DIRECTIVE =
356
+ /^(?:bind|on|use|class|style|transition|in|out|animate|let):/;
357
+ const TABLE_PARTS = ['thead', 'tbody', 'tr', 'th', 'td'];
358
+ // the block a ComponentRenderer adds for the footnotes section, which is no node
359
+ const FOOTNOTES_BLOCK = -1;
360
+ const K_FOOTNOTES = -2;
77
361
 
78
362
  const NEWLINE = '\n';
79
363
 
@@ -118,7 +402,9 @@
118
402
  return result;
119
403
  }
120
404
 
121
- let kind = $derived(buf.kind_at(idx));
405
+ let node_kind = $derived(
406
+ idx === FOOTNOTES_BLOCK ? K_FOOTNOTES : (buf.kind_at(idx) as number)
407
+ );
122
408
  let extra = $derived(buf.extra_at(idx));
123
409
  let meta = $derived(buf.metadata_at(idx));
124
410
 
@@ -127,7 +413,7 @@
127
413
  // so the tight-list default matches the common case and avoids a
128
414
  // <p> flash before the list closes.
129
415
  let skip_list_item_paragraph_wrapper = $derived(
130
- kind === K_PARAGRAPH &&
416
+ node_kind === K_PARAGRAPH &&
131
417
  buf.pending_at(idx) === 1 &&
132
418
  buf.kind_at(buf.parent_at(idx)) === K_LIST_ITEM
133
419
  );
@@ -144,10 +430,10 @@
144
430
 
145
431
  // the checkbox state this node renders, undefined for no checkbox
146
432
  let checked = $derived.by(() => {
147
- if (kind === K_LIST_ITEM) {
433
+ if (node_kind === K_LIST_ITEM) {
148
434
  return box_in_paragraph(idx) ? undefined : meta?.checked;
149
435
  }
150
- if (kind !== K_PARAGRAPH || skip_list_item_paragraph_wrapper) {
436
+ if (node_kind !== K_PARAGRAPH || skip_list_item_paragraph_wrapper) {
151
437
  return undefined;
152
438
  }
153
439
  const parent = buf.parent_at(idx);
@@ -158,12 +444,14 @@
158
444
  ) {
159
445
  return undefined;
160
446
  }
447
+ // a replaced item is given checked and draws its own checkbox
448
+ if (components?.li !== undefined) return undefined;
161
449
  return buf.metadata_at(parent)?.checked;
162
450
  });
163
451
 
164
452
  /** the directive_label of a leaf or container, its first child, or NONE */
165
453
  function label_of(node: number): number {
166
- if (kind === K_DIRECTIVE_INLINE) return NONE;
454
+ if (node_kind === K_DIRECTIVE_INLINE) return NONE;
167
455
  const first = buf.first_child_at(node);
168
456
  return first !== NONE &&
169
457
  buf.parent_at(first) === node &&
@@ -182,12 +470,277 @@
182
470
  }
183
471
 
184
472
  let directive = $derived(
185
- kind === K_DIRECTIVE_INLINE ||
186
- kind === K_DIRECTIVE_LEAF ||
187
- kind === K_DIRECTIVE_CONTAINER
473
+ node_kind === K_DIRECTIVE_INLINE ||
474
+ node_kind === K_DIRECTIVE_LEAF ||
475
+ node_kind === K_DIRECTIVE_CONTAINER
188
476
  ? directives?.[meta?.name as string]
189
477
  : undefined
190
478
  );
479
+
480
+ /** the props compile gives a footnote replacement, null for a reference in a note that is not drawn */
481
+ let reference = $derived.by(() => {
482
+ if (node_kind !== K_FOOTNOTE_REFERENCE || !footnotes) return undefined;
483
+ const at = footnotes.references.get(idx);
484
+ if (at === undefined) return null;
485
+ const number = Math.floor(at / 65536);
486
+ const label = footnotes.labels[number - 1];
487
+ return {
488
+ label,
489
+ number,
490
+ href: fragment(footnote_id(label)),
491
+ id: footnote_ref_id(number, at % 65536),
492
+ };
493
+ });
494
+
495
+ interface Note {
496
+ node: number;
497
+ number: number;
498
+ id: string;
499
+ /** set when a footnote before it has no definition, so the list skips a number */
500
+ value: number | undefined;
501
+ count: number;
502
+ /** its last block when that is a paragraph no component replaces, which then holds the links back */
503
+ paragraph: number;
504
+ }
505
+
506
+ /** every footnote a reference reached that has a definition, in number order */
507
+ function notes_of(index: FootnoteIndex): Note[] {
508
+ const notes: Note[] = [];
509
+ let next = 1;
510
+ for (let i = 0; i < index.definitions.length; i++) {
511
+ const node = index.definitions[i];
512
+ if (node === NONE) continue;
513
+ let last = NONE;
514
+ for (const child of buf_children(buf, node)) {
515
+ if (buf.kind_at(child) !== K_LINE_BREAK) last = child;
516
+ }
517
+ notes.push({
518
+ node,
519
+ number: i + 1,
520
+ id: footnote_id(index.labels[i]),
521
+ value: i + 1 !== next ? i + 1 : undefined,
522
+ count: index.counts[i],
523
+ paragraph:
524
+ last !== NONE &&
525
+ buf.kind_at(last) === K_PARAGRAPH &&
526
+ components?.p === undefined
527
+ ? last
528
+ : NONE,
529
+ });
530
+ next = i + 2;
531
+ }
532
+ return notes;
533
+ }
534
+
535
+ // the info string of a fence, the #! hint of a code span
536
+ let fence_info = $derived(
537
+ node_kind === K_CODE_FENCE || node_kind === K_CODE_SPAN
538
+ ? ((meta?.info as string | undefined) ??
539
+ (meta?.info_start != null
540
+ ? source.slice(meta.info_start as number, meta.info_end as number)
541
+ : undefined))
542
+ : undefined
543
+ );
544
+
545
+ // the meta of a math fence, undefined for any other node and with no renderer
546
+ let math_meta = $derived.by(() => {
547
+ if (!math || node_kind !== K_CODE_FENCE || !fence_info) return undefined;
548
+ const space = fence_info.search(/[ \t]/);
549
+ if (space === -1) return fence_info === 'math' ? '' : undefined;
550
+ return fence_info.slice(0, space) === 'math'
551
+ ? fence_info.slice(space).trim()
552
+ : undefined;
553
+ });
554
+
555
+ let rendered_math = $derived.by(() => {
556
+ if (!math) return null;
557
+ const open = buf.end_at(idx) === NONE;
558
+ if (node_kind === K_CODE_SPAN)
559
+ return extra === 1 && !open
560
+ ? math_html(math, buf_code(buf, idx, source), false, '')
561
+ : null;
562
+ if (math_meta === undefined) return null;
563
+ const latex = buf_code(buf, idx, source);
564
+ if (open) return open_math_html(math, buf, idx, latex, math_meta);
565
+ open_math.get(buf)?.delete(idx);
566
+ return math_html(math, latex, true, math_meta);
567
+ });
568
+
569
+ // a highlighter that reads state runs again for a closed fence when that state changes
570
+ let highlighted = $derived.by(() => {
571
+ if (rendered_math !== null) return rendered_math;
572
+ if (!highlight) return null;
573
+ if (node_kind === K_CODE_SPAN) {
574
+ // inline math is a code span too, it has no hint, and a math hint is not a language
575
+ if (!fence_info || (math && fence_info === 'math')) return null;
576
+ return span_html(
577
+ highlight,
578
+ buf_code(buf, idx, source),
579
+ fence_info,
580
+ get_attrs(meta),
581
+ buf.end_at(idx) === NONE
582
+ );
583
+ }
584
+ // a math fence the renderer left plain is no code to highlight
585
+ if (node_kind !== K_CODE_FENCE || math_meta !== undefined) return null;
586
+ const code = buf_code(buf, idx, source);
587
+ const open = buf.end_at(idx) === NONE;
588
+ if (open && code.length > OPEN_FENCE_LIMIT) return null;
589
+ const bare = components?.pre !== undefined;
590
+ return fence_html(
591
+ highlight,
592
+ code,
593
+ fence_info,
594
+ bare ? {} : get_attrs(meta),
595
+ open,
596
+ bare
597
+ );
598
+ });
599
+
600
+ /** the element a markdown node is drawn as, empty for one that is never replaced */
601
+ function element_name(): string {
602
+ switch (node_kind) {
603
+ case K_PARAGRAPH:
604
+ return skip_list_item_paragraph_wrapper ? '' : 'p';
605
+ case K_HEADING:
606
+ return HEADINGS[extra] ?? '';
607
+ case K_EMPHASIS:
608
+ return 'em';
609
+ case K_STRONG:
610
+ return 'strong';
611
+ case K_STRIKETHROUGH:
612
+ return 'del';
613
+ case K_SUPERSCRIPT:
614
+ return 'sup';
615
+ case K_SUBSCRIPT:
616
+ return 'sub';
617
+ case K_BLOCK_QUOTE:
618
+ return 'blockquote';
619
+ case K_LIST:
620
+ return meta?.ordered ? 'ol' : 'ul';
621
+ case K_LIST_ITEM:
622
+ return 'li';
623
+ case K_CODE_SPAN:
624
+ return math && extra === 1 ? 'math' : 'code';
625
+ case K_CODE_FENCE:
626
+ return math_meta !== undefined ? 'math' : 'pre';
627
+ case K_LINK:
628
+ return 'a';
629
+ case K_IMAGE:
630
+ return 'img';
631
+ case K_THEMATIC_BREAK:
632
+ return 'hr';
633
+ case K_HARD_BREAK:
634
+ return 'br';
635
+ case K_TABLE:
636
+ return 'table';
637
+ default:
638
+ return '';
639
+ }
640
+ }
641
+
642
+ // the highlighted html of a code span as its replacement takes it
643
+ let code_span = $derived(
644
+ node_kind === K_CODE_SPAN && highlighted !== null
645
+ ? code_parts(highlighted)
646
+ : null
647
+ );
648
+
649
+ // the component a markdown node is drawn as, a typed element finds its own
650
+ let replacement = $derived.by(() => {
651
+ if (components === undefined) return undefined;
652
+ const name = element_name();
653
+ if (name === '') return undefined;
654
+ // math that has not rendered is the code it is drawn as, no math replacement takes that
655
+ if (name === 'math')
656
+ return rendered_math === null ? undefined : components.math;
657
+ // highlighted html that is not one code element is drawn as it is
658
+ if (highlighted !== null && node_kind === K_CODE_SPAN && code_span === null)
659
+ return undefined;
660
+ return components[name];
661
+ });
662
+
663
+ // a table with a replaced part is drawn part by part
664
+ let replaced_parts = $derived(
665
+ node_kind === K_TABLE &&
666
+ components !== undefined &&
667
+ TABLE_PARTS.some((part) => components[part] !== undefined)
668
+ );
669
+
670
+ let kind = $derived(
671
+ replacement !== undefined || replaced_parts ? K_REPLACED : node_kind
672
+ );
673
+
674
+ // what compile gives the replacement of each kind
675
+ let replaced_props = $derived.by((): Record<string, any> => {
676
+ switch (node_kind) {
677
+ case K_HEADING:
678
+ return { ...get_attrs(meta), level: extra };
679
+ case K_LINK:
680
+ return {
681
+ href: meta?.href,
682
+ title: meta?.title || undefined,
683
+ ...get_attrs(meta, LINK_SKIP),
684
+ };
685
+ case K_IMAGE:
686
+ return {
687
+ src: meta?.src,
688
+ alt: buf_text_content(buf, idx, source),
689
+ title: meta?.title || undefined,
690
+ ...get_attrs(meta, IMAGE_SKIP),
691
+ };
692
+ case K_LIST:
693
+ return meta?.ordered
694
+ ? {
695
+ ...get_attrs(meta),
696
+ start: typeof meta.start === 'number' ? meta.start : 1,
697
+ }
698
+ : get_attrs(meta);
699
+ case K_LIST_ITEM:
700
+ return typeof meta?.checked === 'boolean'
701
+ ? { ...get_attrs(meta), checked: meta.checked }
702
+ : get_attrs(meta);
703
+ case K_CODE_SPAN:
704
+ if (rendered_math !== null)
705
+ return { code: buf_code(buf, idx, source), ...get_attrs(meta) };
706
+ return code_span === null
707
+ ? get_attrs(meta)
708
+ : { lang: fence_info, ...code_span.props };
709
+ case K_CODE_FENCE: {
710
+ if (rendered_math !== null)
711
+ return {
712
+ display: true,
713
+ code: buf_code(buf, idx, source),
714
+ meta: math_meta || undefined,
715
+ ...get_attrs(meta),
716
+ };
717
+ const [lang, rest] = info_parts(fence_info);
718
+ return {
719
+ ...get_attrs(meta),
720
+ lang: lang || undefined,
721
+ meta: rest || undefined,
722
+ code: buf_code(buf, idx, source),
723
+ };
724
+ }
725
+ default:
726
+ return get_attrs(meta);
727
+ }
728
+ });
729
+
730
+ /** the component a typed or plugin made element is drawn as */
731
+ function element_component(
732
+ tag: string,
733
+ attrs: Record<string, unknown> | undefined
734
+ ): Component<any> | undefined {
735
+ const found = components?.[tag];
736
+ if (found === undefined || !ELEMENT_NAME.test(tag)) return found;
737
+ // the author typed every element no plugin made
738
+ if (component_mode !== 'all' && !buf.synthetic_at(idx)) return undefined;
739
+ if (tag === 'script' || tag === 'style') return undefined;
740
+ if (attrs !== undefined)
741
+ for (const key in attrs) if (ELEMENT_DIRECTIVE.test(key)) return undefined;
742
+ return found;
743
+ }
191
744
  </script>
192
745
 
193
746
  {#snippet task_box()}
@@ -209,13 +762,29 @@
209
762
  idx={child_idx}
210
763
  {source}
211
764
  {components}
765
+ {component_mode}
212
766
  {directives}
213
767
  {plugin_data}
768
+ {highlight}
769
+ {math}
770
+ {footnotes}
214
771
  />
215
772
  {/if}
216
773
  {/each}
217
774
  {/snippet}
218
775
 
776
+ {#snippet back_links(note: Note)}
777
+ {#each { length: note.count } as _, i (i)}
778
+ {@const name = i === 0 ? '' + note.number : note.number + '-' + (i + 1)}
779
+ {' '}<a
780
+ href={fragment(footnote_ref_id(note.number, i + 1))}
781
+ role="doc-backlink"
782
+ aria-label={'Back to reference ' + name}
783
+ >{BACK_ARROW}{#if i !== 0}<sup>{i + 1}</sup>{/if}</a
784
+ >
785
+ {/each}
786
+ {/snippet}
787
+
219
788
  {#snippet directive_label()}
220
789
  {@render child_nodes(label_of(idx))}
221
790
  {/snippet}
@@ -287,6 +856,94 @@
287
856
  </table>
288
857
  {/snippet}
289
858
 
859
+ {#snippet part(tag: string, props: Record<string, any>, body: Snippet)}
860
+ {@const Part = components?.[tag]}
861
+ {#if Part}
862
+ <Part {...props} children={body} />
863
+ {:else}
864
+ <svelte:element this={tag} {...props}>{@render body()}</svelte:element>
865
+ {/if}
866
+ {/snippet}
867
+
868
+ {#snippet table_parts(table_idx: number)}
869
+ {@const meta = buf.metadata_at(table_idx)}
870
+ {@const alignments = (meta?.alignments as string[]) ?? []}
871
+ {@const header_columns = meta?.header_columns as number[] | undefined}
872
+ {@const spans = meta?.spans === true}
873
+ {@const col_count = (meta?.col_count as number | undefined) ?? alignments.length}
874
+ {@const row_l = header_columns ? header_columns[0] : 0}
875
+ {@const row_r = header_columns ? col_count - header_columns[1] : col_count}
876
+ {@const rows = buf_children(buf, table_idx)}
877
+ {#snippet row(row_idx: number, head: boolean)}
878
+ {#snippet cells()}
879
+ {#each buf_children(buf, row_idx).filter((c) => buf.kind_at(c) === K_TABLE_CELL) as cell_idx (cell_idx)}
880
+ {@const col = buf.extra_at(cell_idx)}
881
+ {@const align = alignments[col]}
882
+ {@const cell_meta = spans ? buf.metadata_at(cell_idx) : undefined}
883
+ {@const row_head = !head && (col < row_l || col >= row_r)}
884
+ {#snippet content()}{@render child_nodes(cell_idx)}{/snippet}
885
+ {@render part(
886
+ head || row_head ? 'th' : 'td',
887
+ {
888
+ scope: row_head ? 'row' : undefined,
889
+ align: align && align !== 'none' ? align : undefined,
890
+ colspan: cell_meta?.colspan,
891
+ rowspan: cell_meta?.rowspan,
892
+ },
893
+ content
894
+ )}
895
+ {/each}
896
+ {/snippet}
897
+ {@render part('tr', {}, cells)}
898
+ {/snippet}
899
+ {#snippet head_rows()}
900
+ {#each rows as row_idx (row_idx)}
901
+ {#if buf.kind_at(row_idx) === K_TABLE_HEADER}
902
+ {@render row(row_idx, true)}
903
+ {/if}
904
+ {/each}
905
+ {/snippet}
906
+ {#snippet body_rows()}
907
+ {#each rows as row_idx (row_idx)}
908
+ {#if buf.kind_at(row_idx) === K_TABLE_ROW}
909
+ {@render row(row_idx, false)}
910
+ {/if}
911
+ {/each}
912
+ {/snippet}
913
+ <!-- no space between the two, it would be text in the table -->
914
+ {#if rows.some((r) => buf.kind_at(r) === K_TABLE_HEADER)}
915
+ {@render part('thead', {}, head_rows)}
916
+ {/if}{#if rows.some((r) => buf.kind_at(r) === K_TABLE_ROW)}
917
+ {@render part('tbody', {}, body_rows)}
918
+ {/if}
919
+ {/snippet}
920
+
921
+ <!-- the children of a replacement, a void element has none -->
922
+ {#snippet replaced_children()}
923
+ {#if node_kind === K_PARAGRAPH}
924
+ {@render task_box()}{@render child_nodes(idx)}
925
+ {:else if node_kind === K_CODE_SPAN}
926
+ {#if code_span !== null}{@html code_span.body}{:else if rendered_math !== null}{@html rendered_math}{:else}{buf_code(
927
+ buf,
928
+ idx,
929
+ source
930
+ ).replace(/\n/g, ' ')}{/if}
931
+ {:else if node_kind === K_CODE_FENCE}
932
+ {#if highlighted !== null}
933
+ {@html highlighted}
934
+ {:else}
935
+ {@const lang = info_parts(fence_info)[0]}
936
+ <pre><code class={lang ? 'language-' + lang : undefined}
937
+ >{buf_code(buf, idx, source)}</code
938
+ ></pre>
939
+ {/if}
940
+ {:else if node_kind === K_TABLE}
941
+ {@render table_parts(idx)}
942
+ {:else}
943
+ {@render child_nodes(idx)}
944
+ {/if}
945
+ {/snippet}
946
+
290
947
  {#if directive}
291
948
  {@const Directive = directive}
292
949
  <Directive
@@ -310,16 +967,12 @@
310
967
  <em {...get_attrs(meta)}>{@render child_nodes(idx)}</em>
311
968
  {:else if kind === K_STRONG}
312
969
  <strong {...get_attrs(meta)}>{@render child_nodes(idx)}</strong>
313
- {:else if kind === K_CODE_SPAN}
970
+ {:else if kind === K_CODE_SPAN && highlighted === null}
314
971
  <code {...get_attrs(meta)}
315
972
  >{buf_code(buf, idx, source).replace(/\n/g, ' ')}</code
316
973
  >
317
- {:else if kind === K_CODE_FENCE}
318
- {@const info =
319
- (meta?.info as string | undefined) ??
320
- (meta?.info_start != null
321
- ? source.slice(meta.info_start as number, meta.info_end as number)
322
- : undefined)}
974
+ {:else if kind === K_CODE_FENCE && highlighted === null}
975
+ {@const info = fence_info}
323
976
  <pre><code class={info ? 'language-' + info : undefined} {...get_attrs(meta)}
324
977
  >{buf_code(buf, idx, source)}</code
325
978
  ></pre>
@@ -381,10 +1034,10 @@
381
1034
  ])
382
1035
  )
383
1036
  : {}}
384
- {@const CustomComponent = components?.[tag]}
1037
+ {@const CustomComponent = element_component(tag, attrs)}
385
1038
  {@const is_raw_text = is_raw_text_tag(tag)}
386
1039
  {#if CustomComponent}
387
- <CustomComponent {...spread}>
1040
+ <CustomComponent {...typed_props(tag, spread)}>
388
1041
  {#if !meta?.self_closing}
389
1042
  {@render child_nodes(idx)}
390
1043
  {/if}
@@ -407,15 +1060,77 @@
407
1060
  {:else if kind === K_DIRECTIVE_LABEL}
408
1061
  <!-- a directive renders as its children, its label is not one of them -->
409
1062
  {:else if kind === K_FOOTNOTE_REFERENCE}
410
- <!-- a stream has no number for it yet, so the label stands in -->
411
- <sup class="footnote-reference">{meta?.label}</sup>
412
- {:else if kind === K_FOOTNOTE_DEFINITION}
413
- <div class="footnote">
1063
+ {#if reference === undefined}
414
1064
  <sup class="footnote-reference">{meta?.label}</sup>
415
- {@render child_nodes(idx)}
416
- </div>
1065
+ {:else if reference !== null}
1066
+ <sup
1067
+ ><a href={reference.href} id={reference.id} role="doc-noteref"
1068
+ >{reference.number}</a
1069
+ ></sup
1070
+ >
1071
+ {/if}
1072
+ {:else if kind === K_FOOTNOTE_DEFINITION}
1073
+ {#if !footnotes}
1074
+ <div class="footnote">
1075
+ <sup class="footnote-reference">{meta?.label}</sup>
1076
+ {@render child_nodes(idx)}
1077
+ </div>
1078
+ {/if}
417
1079
  {:else if kind === K_DEFINITION}
418
1080
  <!-- a link reference definition renders nothing, the links that use it carry its url -->
1081
+ {:else if highlighted !== null && replacement === undefined}
1082
+ <!-- last so the branch index svelte writes for every other node stays the same -->
1083
+ {@html highlighted}
1084
+ {:else if replacement !== undefined}
1085
+ {@const Replacement = replacement}
1086
+ <Replacement
1087
+ {...replaced_props}
1088
+ children={node_kind === K_IMAGE ||
1089
+ node_kind === K_THEMATIC_BREAK ||
1090
+ node_kind === K_HARD_BREAK
1091
+ ? undefined
1092
+ : replaced_children}
1093
+ />
1094
+ {:else if replaced_parts}
1095
+ <table>{@render table_parts(idx)}</table>
1096
+ {:else if kind === K_FOOTNOTES}
1097
+ {@const notes = footnotes ? notes_of(footnotes) : []}
1098
+ {#if notes.length !== 0}
1099
+ <section class="footnotes" role="doc-endnotes" aria-label="Footnotes">
1100
+ <ol>
1101
+ {#each notes as note (note.node)}
1102
+ <li id={note.id} value={note.value}>
1103
+ {#each buf_children(buf, note.node) as child_idx (child_idx)}
1104
+ {@const kind = buf.kind_at(child_idx)}
1105
+ {#if kind === K_TEXT}
1106
+ {buf_text(buf, child_idx, source)}
1107
+ {:else if kind === K_LINE_BREAK}
1108
+ <!-- skip -->
1109
+ {:else if child_idx === note.paragraph}
1110
+ <p {...get_attrs(buf.metadata_at(child_idx))}>
1111
+ {@render child_nodes(child_idx)}{@render back_links(note)}
1112
+ </p>
1113
+ {:else}
1114
+ <Node
1115
+ {buf}
1116
+ idx={child_idx}
1117
+ {source}
1118
+ {components}
1119
+ {component_mode}
1120
+ {directives}
1121
+ {plugin_data}
1122
+ {highlight}
1123
+ {math}
1124
+ {footnotes}
1125
+ />
1126
+ {/if}
1127
+ {/each}
1128
+ {#if note.paragraph === NONE}{@render back_links(note)}{/if}
1129
+ </li>
1130
+ {/each}
1131
+ </ol>
1132
+ </section>
1133
+ {/if}
419
1134
  {:else}
420
1135
  {@render child_nodes(idx)}
421
1136
  {/if}