@mdsvex/render 1.0.0-next.0 → 1.0.0-next.1

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.
@@ -23,8 +23,8 @@ describe('ComponentRenderer', () => {
23
23
 
24
24
  expect(renderer.blocks.length).toBe(2);
25
25
  // Verify the indices point to real nodes
26
- expect(buf._kinds[renderer.blocks[0].idx]).toBe(3); // heading
27
- expect(buf._kinds[renderer.blocks[1].idx]).toBe(7); // paragraph
26
+ expect(buf.kind_at(renderer.blocks[0].idx)).toBe(3); // heading
27
+ expect(buf.kind_at(renderer.blocks[1].idx)).toBe(7); // paragraph
28
28
  });
29
29
 
30
30
  it('each block has a unique idx', () => {
@@ -49,7 +49,7 @@ describe('ComponentRenderer', () => {
49
49
  renderer.update(buf, source);
50
50
 
51
51
  for (const block of renderer.blocks) {
52
- expect(buf._kinds[block.idx]).not.toBe(6); // line_break
52
+ expect(buf.kind_at(block.idx)).not.toBe(6); // line_break
53
53
  }
54
54
  });
55
55
 
@@ -0,0 +1,90 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { PFMParser } from '@mdsvex/parse';
3
+ import { TreeBuilder } from '@mdsvex/parse/tree-builder';
4
+ import { Cursor } from '@mdsvex/parse/cursor';
5
+ import {
6
+ _escape_code,
7
+ _escape_code_text,
8
+ _escape_text_html,
9
+ escape,
10
+ escape_text,
11
+ } from '../src/html_cursor';
12
+
13
+ const DOCS = [
14
+ 'a & b < c > d "e"\n\nplain\n',
15
+ '`x < y && "z"` and `a\nb` then & more\n',
16
+ '```js\nif (a < b && c > "d") {}\n```\n\ntext " after\n',
17
+ '<div>\n\n& inside <em>html</em>\n\n</div>\n\n> quote & "q"\n',
18
+ '| a & b | "c" |\n|:-|-:|\n| <x> | y > z |\n',
19
+ 'no escapes here at all\n\n- item\n- item two\n',
20
+ '&&&<<<>>>"""\n',
21
+ 'a &lt; b &copy; & c &#123; &#x7d; &MadeUp; &copy\n\n`&lt; {x}` &amp;\n',
22
+ '<div>\n\na &mdash; b & "c"\n\n</div>\n\n&#12345678; &#; &;\n',
23
+ '```js\nconst s = "&amp;" && 1;\n```\n\n&copy; `&lt;` &copy;\n',
24
+ '{x} `{ a: "1" }` {y} and `}{`\n\n```js {1}\nconst o = { a: 1 } && "b";\n```\n\n{z} } {\n',
25
+ ];
26
+
27
+ function cursor_for(source: string): { c: Cursor } {
28
+ const tree = new TreeBuilder(source.length >> 3 || 128);
29
+ new PFMParser(tree).parse(source);
30
+ return { c: new Cursor(tree.get_buffer(), source) };
31
+ }
32
+
33
+ function indices(c: Cursor): number[] {
34
+ const out: number[] = [];
35
+ const walk = (): void => {
36
+ out.push(c.index);
37
+ if (!c.goto_first_child()) return;
38
+ do walk();
39
+ while (c.goto_next_sibling());
40
+ c.goto_parent();
41
+ };
42
+ c.reset();
43
+ walk();
44
+ return out;
45
+ }
46
+
47
+ function check(c: Cursor, order: number[]): void {
48
+ for (const idx of order) {
49
+ (c as unknown as { idx: number }).idx = idx;
50
+ expect(escape_text(c)).toBe(_escape_text_html(c.text()));
51
+ // code shares the index, so its lookups interleave with the text ones
52
+ expect(_escape_code_text(c)).toBe(_escape_code(c.text()));
53
+ }
54
+ }
55
+
56
+ describe('escape_text', () => {
57
+ for (const doc of DOCS) {
58
+ it(`matches _escape_text_html(text()) in any visit order: ${JSON.stringify(doc)}`, () => {
59
+ const { c } = cursor_for(doc);
60
+ const order = indices(c);
61
+ check(c, order);
62
+ check(c, order.slice().reverse());
63
+ // interleave front and back so the index keeps moving backwards
64
+ const mixed: number[] = [];
65
+ for (let i = 0, j = order.length - 1; i <= j; i++, j--) {
66
+ mixed.push(order[i]);
67
+ if (i !== j) mixed.push(order[j]);
68
+ }
69
+ check(c, mixed);
70
+ });
71
+ }
72
+
73
+ it('escapes an & a backslash escaped, the slice no longer shows it', () => {
74
+ const { c } = cursor_for('a \\&copy; b \\\\&copy;\n');
75
+ const out = indices(c).map((idx) => {
76
+ c.move_to(idx);
77
+ return escape_text(c);
78
+ });
79
+ expect(out).toContain('&amp;copy; b ');
80
+ expect(out).toContain('\\&copy;');
81
+ });
82
+
83
+ it('follows the cursor to a new source', () => {
84
+ const a = cursor_for(DOCS[0]);
85
+ const b = cursor_for(DOCS[2]);
86
+ check(a.c, indices(a.c));
87
+ check(b.c, indices(b.c));
88
+ check(a.c, indices(a.c));
89
+ });
90
+ });
@@ -0,0 +1,242 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { PFMParser } from '@mdsvex/parse';
3
+ import { TreeBuilder } from '@mdsvex/parse/tree-builder';
4
+ import { ComponentScope, CursorHTMLRenderer } from '../src/html_cursor';
5
+ import type {
6
+ CodeHighlighter,
7
+ HighlightedBlock,
8
+ HighlightWarningCode,
9
+ } from '../src/html_cursor';
10
+
11
+ /** a highlighter that shows what it was asked, braces as entities */
12
+ function stub(): CodeHighlighter & {
13
+ calls: string[];
14
+ warned: [HighlightWarningCode, number][];
15
+ } {
16
+ const esc = (s: string) =>
17
+ s
18
+ .replace(/&/g, '&amp;')
19
+ .replace(/</g, '&lt;')
20
+ .replace(/{/g, '&#123;')
21
+ .replace(/}/g, '&#125;');
22
+ return {
23
+ calls: [],
24
+ warned: [],
25
+ block(code, lang, meta, start): HighlightedBlock | null {
26
+ this.calls.push(`block ${lang}|${meta}|${start}`);
27
+ if (lang === 'plain') return null;
28
+ if (lang === 'wrap')
29
+ return {
30
+ before: '',
31
+ attributes: null,
32
+ body: `<div>${esc(code)}</div>`,
33
+ after: '',
34
+ props: '',
35
+ code,
36
+ code_template: null,
37
+ live: null,
38
+ dropped: null,
39
+ };
40
+ if (lang === 'live') {
41
+ // the first {...} of the code stays live
42
+ const at = code.indexOf('{');
43
+ const end = code.indexOf('}', at) + 1;
44
+ const head = '<code>' + esc(code.slice(0, at));
45
+ return {
46
+ before: '',
47
+ attributes: '',
48
+ body: head + code.slice(at, end) + esc(code.slice(end)) + '</code>',
49
+ after: '',
50
+ props: '',
51
+ code,
52
+ code_template: '`live`',
53
+ live: [head.length, at, end - at],
54
+ dropped: null,
55
+ };
56
+ }
57
+ return {
58
+ before: '<figure>',
59
+ attributes: ` class="hl ${lang}"`,
60
+ body: `<code>${esc(code)}</code>`,
61
+ after: '</figure>',
62
+ props: ' title={"t"}',
63
+ code: code.toUpperCase(),
64
+ code_template: null,
65
+ live: null,
66
+ dropped: meta.includes('drop') ? ['dropped one'] : null,
67
+ };
68
+ },
69
+ inline(code, lang, start) {
70
+ this.calls.push(`inline ${lang}|${start}`);
71
+ if (lang === 'plain') return null;
72
+ if (lang === 'wrap')
73
+ return { attributes: null, body: `<b>${esc(code)}</b>` };
74
+ return { attributes: ` class="i ${lang}"`, body: esc(code) };
75
+ },
76
+ warn(code, _message, start) {
77
+ this.warned.push([code, start]);
78
+ },
79
+ };
80
+ }
81
+
82
+ type Walk = (r: CursorHTMLRenderer, buf: any, src: string) => void;
83
+ const WALKS: [string, Walk, boolean][] = [
84
+ ['fold', (r, buf, src) => r.update(buf, src), false],
85
+ ['cached', (r, buf, src) => r.update(buf, src), true],
86
+ ['mapped', (r, buf, src) => r.update_mapped(buf, src), false],
87
+ ['trace', (r, buf, src) => r.update_trace(buf, src), false],
88
+ ['v3', (r, buf, src) => r.update_v3(buf, src, src), false],
89
+ ];
90
+
91
+ function render_all(
92
+ source: string,
93
+ highlight: CodeHighlighter,
94
+ scope?: ComponentScope
95
+ ): string {
96
+ const outs: string[] = [];
97
+ for (const [name, walk, cache] of WALKS) {
98
+ // the cached render ignores replacements
99
+ if (cache && scope) continue;
100
+ const tree = new TreeBuilder(128);
101
+ new PFMParser(tree).parse(source);
102
+ const r = new CursorHTMLRenderer({ cache });
103
+ r.highlight = highlight;
104
+ if (scope) r.scope = scope;
105
+ walk(r, tree.get_buffer(), source);
106
+ outs.push(r.html);
107
+ expect(r.highlight, name).toBe(highlight);
108
+ }
109
+ for (const out of outs) expect(out).toBe(outs[0]);
110
+ return outs[0];
111
+ }
112
+
113
+ describe('highlighting', () => {
114
+ it('a fence renders as the highlighter has it, in every walk', () => {
115
+ const h = stub();
116
+ expect(render_all('```ts a {1}\nx {y}\n```\n', h)).toBe(
117
+ '<figure><pre class="hl ts"><code>x &#123;y&#125;</code></pre></figure>'
118
+ );
119
+ expect(new Set(h.calls)).toEqual(new Set(['block ts|a {1}|0']));
120
+ });
121
+
122
+ it('a fence with no info has no language', () => {
123
+ const h = stub();
124
+ render_all('a\n\n```\nx\n```\n', h);
125
+ expect(new Set(h.calls)).toEqual(new Set(['block ||3']));
126
+ });
127
+
128
+ it('null renders plain', () => {
129
+ expect(render_all('```plain x\n{a}\n```\n\n`#!plain b`\n', stub())).toBe(
130
+ '<pre><code class="language-plain">&#123;a&#125;</code></pre><p><code>b</code></p>'
131
+ );
132
+ });
133
+
134
+ it('a block that is not one pre renders its body alone', () => {
135
+ expect(render_all('```wrap\na\n```\n', stub())).toBe('<div>a</div>');
136
+ });
137
+
138
+ it('a code span with a #! hint highlights, one without does not', () => {
139
+ const h = stub();
140
+ expect(render_all('`#!ts {a}` `{b}` `#!wrap c`\n', h)).toBe(
141
+ '<p><code class="i ts">&#123;a&#125;</code> <code>&#123;b&#125;</code> <b>c</b></p>'
142
+ );
143
+ expect(new Set(h.calls)).toEqual(
144
+ new Set(['inline ts|0', 'inline wrap|17'])
145
+ );
146
+ });
147
+
148
+ it('a code span hint keeps its newlines as spaces', () => {
149
+ expect(render_all('`#!ts a\nb`\n', stub())).toBe(
150
+ '<p><code class="i ts">a b</code></p>'
151
+ );
152
+ });
153
+
154
+ it('a pre replacement gets the props and the <pre> as children, no figure', () => {
155
+ const h = stub();
156
+ const scope = new ComponentScope(
157
+ [{ specifier: 'm', names: ['pre', 'code'] }],
158
+ 'G'
159
+ );
160
+ expect(
161
+ render_all(
162
+ '```ts title="t" drop\na\n```\n\n```wrap\nb\n```\n\n`#!ts c`\n',
163
+ h,
164
+ scope
165
+ )
166
+ ).toBe(
167
+ "<script>\nimport { pre as Pre_MDSVEX_G, code as Code_MDSVEX_G } from 'm';\n</script>" +
168
+ '<Pre_MDSVEX_G lang={"ts"} meta={"title=\\"t\\" drop"} title={"t"} code={"A"}><pre class="hl ts"><code>a</code></pre></Pre_MDSVEX_G>' +
169
+ '<Pre_MDSVEX_G lang={"wrap"} code={"b"}><div>b</div></Pre_MDSVEX_G>' +
170
+ '<p><Code_MDSVEX_G lang={"ts"} class="i ts">c</Code_MDSVEX_G></p>'
171
+ );
172
+ expect(h.warned.every(([code]) => code === 'meta_prop_ignored')).toBe(true);
173
+ expect(h.warned.length).toBeGreaterThan(0);
174
+ });
175
+
176
+ it('a code replacement warns when the span is not one <code>', () => {
177
+ const h = stub();
178
+ const scope = new ComponentScope(
179
+ [{ specifier: 'm', names: ['code'] }],
180
+ 'G'
181
+ );
182
+ expect(render_all('`#!wrap a`\n', h, scope)).toContain('<p><b>a</b></p>');
183
+ expect(new Set(h.warned.map(([c]) => c))).toEqual(
184
+ new Set(['code_replacement_skipped'])
185
+ );
186
+ });
187
+
188
+ it('the fence body maps as one code content record', () => {
189
+ const source = '```ts\nlet a\n```\n';
190
+ const tree = new TreeBuilder(128);
191
+ new PFMParser(tree).parse(source);
192
+ const r = new CursorHTMLRenderer({ cache: false });
193
+ r.highlight = stub();
194
+ const { mappings } = r.update_mapped(tree.get_buffer(), source);
195
+ const content = mappings.filter((m) => m.data.role === 'content');
196
+ expect(content).toHaveLength(1);
197
+ const [m] = content;
198
+ expect(
199
+ source.slice(m.sourceOffsets[0], m.sourceOffsets[0] + m.lengths[0])
200
+ ).toBe('let a');
201
+ expect(
202
+ r.html.slice(
203
+ m.generatedOffsets[0],
204
+ m.generatedOffsets[0] + m.generatedLengths![0]
205
+ )
206
+ ).toBe('<code>let a</code>');
207
+ });
208
+
209
+ it('a live expression maps one to one as svelte content in every walk', () => {
210
+ const source = '> ```live\n> a {b.c} d\n> ```\n';
211
+ const scope = new ComponentScope([{ specifier: 'm', names: ['pre'] }], 'G');
212
+ expect(render_all(source, stub())).toContain(
213
+ '<pre><code>a {b.c} d</code></pre>'
214
+ );
215
+ expect(render_all(source, stub(), scope)).toContain(
216
+ '<Pre_MDSVEX_G lang={"live"} code={`live`}><pre><code>a {b.c} d</code></pre></Pre_MDSVEX_G>'
217
+ );
218
+ for (const s of [null, scope]) {
219
+ const tree = new TreeBuilder(128);
220
+ new PFMParser(tree).parse(source);
221
+ const r = new CursorHTMLRenderer({ cache: false });
222
+ r.highlight = stub();
223
+ if (s) r.scope = s;
224
+ const { mappings } = r.update_mapped(tree.get_buffer(), source);
225
+ const content = mappings
226
+ .filter((m) => m.data.role === 'content')
227
+ .map((m) => [
228
+ source.slice(m.sourceOffsets[0], m.sourceOffsets[0] + m.lengths[0]),
229
+ r.html.slice(
230
+ m.generatedOffsets[0],
231
+ m.generatedOffsets[0] + (m.generatedLengths?.[0] ?? m.lengths[0])
232
+ ),
233
+ m.data.verification === true,
234
+ ]);
235
+ expect(content).toEqual([
236
+ ['> a ', '<code>a ', false],
237
+ ['{b.c}', '{b.c}', true],
238
+ [' d', ' d</code>', false],
239
+ ]);
240
+ }
241
+ });
242
+ });