MarkdownTokens.svelte 5.2 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
<script lang="ts">
Timothy J. Baek's avatar
Timothy J. Baek committed
2
	import { marked } from 'marked';
Timothy J. Baek's avatar
Timothy J. Baek committed
3
	import type { Token } from 'marked';
Timothy J. Baek's avatar
Timothy J. Baek committed
4
	import { revertSanitizedResponseContent, unescapeHtml } from '$lib/utils';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
5

Timothy J. Baek's avatar
Timothy J. Baek committed
6
	import { onMount } from 'svelte';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
7
8
9
10

	import Image from '$lib/components/common/Image.svelte';
	import CodeBlock from '$lib/components/chat/Messages/CodeBlock.svelte';

Timothy J. Baek's avatar
Timothy J. Baek committed
11
12
13
14
15
16
	import MarkdownInlineTokens from '$lib/components/chat/Messages/MarkdownInlineTokens.svelte';

	export let id: string;
	export let tokens: Token[];
	export let top = true;

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
17
18
	let containerElement;

Timothy J. Baek's avatar
Timothy J. Baek committed
19
20
21
22
	const headerComponent = (depth: number) => {
		return 'h' + depth;
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
23
24
25
26
27
28
	const renderer = new marked.Renderer();
	// For code blocks with simple backticks
	renderer.codespan = (code) => {
		return `<code class="codespan">${code.replaceAll('&amp;', '&')}</code>`;
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
29
	let codes = [];
Timothy J. Baek's avatar
Timothy J. Baek committed
30
	renderer.code = (code, lang) => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
		codes.push({
			code: code,
			lang: lang
		});
		codes = codes;
		const codeId = `${id}-${codes.length}`;

		const interval = setInterval(() => {
			if (document.getElementById(`code-${codeId}`)) {
				clearInterval(interval);

				new CodeBlock({
					target: document.getElementById(`code-${codeId}`),
					props: {
						id: `${id}-${codes.length}`,
						lang: lang,
						code: revertSanitizedResponseContent(code)
					},
					hydrate: true,
					$$inline: true
				});
			}
		}, 10);

		return `<div id="code-${id}-${codes.length}" />`;
	};

	let images = [];
	renderer.image = (href, title, text) => {
		images.push({
			href: href,
			title: title,
			text: text
		});
		images = images;

		const imageId = `${id}-${images.length}`;

		const interval = setInterval(() => {
			if (document.getElementById(`image-${imageId}`)) {
				clearInterval(interval);
				new Image({
					target: document.getElementById(`image-${imageId}`),
					props: {
						src: href,
						alt: text
					},
					hydrate: true
				});
			}
		}, 10);

		return `<div id="image-${id}-${images.length}" />`;
Timothy J. Baek's avatar
Timothy J. Baek committed
84
85
86
87
88
89
90
91
	};

	// Open all links in a new tab/window (from https://github.com/markedjs/marked/issues/655#issuecomment-383226346)
	const origLinkRenderer = renderer.link;
	renderer.link = (href, title, text) => {
		const html = origLinkRenderer.call(renderer, href, title, text);
		return html.replace(/^<a /, '<a target="_blank" rel="nofollow" ');
	};
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
92

Timothy J. Baek's avatar
Timothy J. Baek committed
93
94
95
96
	const { extensions, ...defaults } = marked.getDefaults() as marked.MarkedOptions & {
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		extensions: any;
	};
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
97
98
99
100
101

	$: if (tokens) {
		images = [];
		codes = [];
	}
Timothy J. Baek's avatar
Timothy J. Baek committed
102
103
</script>

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
104
105
106
107
108
109
110
111
112
113
114
115
116
<div bind:this={containerElement} class="flex flex-col">
	{#each tokens as token, tokenIdx (`${id}-${tokenIdx}`)}
		{#if token.type === 'code'}
			{#if token.lang === 'mermaid'}
				<pre class="mermaid">{revertSanitizedResponseContent(token.text)}</pre>
			{:else}
				<CodeBlock
					id={`${id}-${tokenIdx}`}
					lang={token?.lang ?? ''}
					code={revertSanitizedResponseContent(token?.text ?? '')}
				/>
			{/if}
			<!-- {:else if token.type === 'heading'}
Timothy J. Baek's avatar
Timothy J. Baek committed
117
118
119
		<svelte:element this={headerComponent(token.depth)}>
			<MarkdownInlineTokens id={`${id}-${tokenIdx}-h`} tokens={token.tokens} />
		</svelte:element>
Timothy J. Baek's avatar
Timothy J. Baek committed
120
121
	{:else if token.type === 'hr'}
		<hr />
Timothy J. Baek's avatar
Timothy J. Baek committed
122
123
124
125
	{:else if token.type === 'blockquote'}
		<blockquote>
			<svelte:self id={`${id}-${tokenIdx}`} tokens={token.tokens} />
		</blockquote>
Timothy J. Baek's avatar
Timothy J. Baek committed
126
127
128
129
130
131
	{:else if token.type === 'html'}
		{@html token.text}
	{:else if token.type === 'paragraph'}
		<p>
			<MarkdownInlineTokens id={`${id}-${tokenIdx}-p`} tokens={token.tokens ?? []} />
		</p>
Timothy J. Baek's avatar
Timothy J. Baek committed
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
	{:else if token.type === 'list'}
		{#if token.ordered}
			<ol start={token.start || 1}>
				{#each token.items as item, itemIdx}
					<li>
						<svelte:self
							id={`${id}-${tokenIdx}-${itemIdx}`}
							tokens={item.tokens}
							top={token.loose}
						/>
					</li>
				{/each}
			</ol>
		{:else}
			<ul>
				{#each token.items as item, itemIdx}
					<li>
						<svelte:self
							id={`${id}-${tokenIdx}-${itemIdx}`}
							tokens={item.tokens}
							top={token.loose}
						/>
					</li>
				{/each}
			</ul>
		{/if}
Timothy J. Baek's avatar
Timothy J. Baek committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
	{:else if token.type === 'table'}
		<table>
			<thead>
				<tr>
					{#each token.header as header, headerIdx}
						<th style={token.align[headerIdx] ? '' : `text-align: ${token.align[headerIdx]}`}>
							<MarkdownInlineTokens
								id={`${id}-${tokenIdx}-header-${headerIdx}`}
								tokens={header.tokens}
							/>
						</th>
					{/each}
				</tr>
			</thead>
			<tbody>
				{#each token.rows as row, rowIdx}
					<tr>
						{#each row ?? [] as cell, cellIdx}
							<td style={token.align[cellIdx] ? '' : `text-align: ${token.align[cellIdx]}`}>
								<MarkdownInlineTokens
									id={`${id}-${tokenIdx}-row-${rowIdx}-${cellIdx}`}
									tokens={cell.tokens}
								/>
							</td>
						{/each}
					</tr>
				{/each}
			</tbody>
		</table>
	{:else if token.type === 'text'} -->
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
188
			<!-- {#if top}
Timothy J. Baek's avatar
Timothy J. Baek committed
189
190
191
192
193
194
195
196
197
198
199
			<p>
				{#if token.tokens}
					<MarkdownInlineTokens id={`${id}-${tokenIdx}-t`} tokens={token.tokens} />
				{:else}
					{unescapeHtml(token.text)}
				{/if}
			</p>
		{:else if token.tokens}
			<MarkdownInlineTokens id={`${id}-${tokenIdx}-p`} tokens={token.tokens ?? []} />
		{:else}
			{unescapeHtml(token.text)}
Timothy J. Baek's avatar
Timothy J. Baek committed
200
		{/if} -->
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
201
202
203
204
205
206
207
208
209
210
		{:else}
			{@html marked.parse(token.raw, {
				...defaults,
				gfm: true,
				breaks: true,
				renderer
			})}
		{/if}
	{/each}
</div>