MarkdownTokens.svelte 5.37 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
		codes.push({
			code: code,
			lang: lang
		});
		codes = codes;
		const codeId = `${id}-${codes.length}`;

		const interval = setInterval(() => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
39
40
			const codeElement = document.getElementById(`code-${codeId}`);
			if (codeElement) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
41
42
43
				clearInterval(interval);

				new CodeBlock({
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
44
					target: codeElement,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
45
46
47
48
49
50
51
52
53
54
55
					props: {
						id: `${id}-${codes.length}`,
						lang: lang,
						code: revertSanitizedResponseContent(code)
					},
					hydrate: true,
					$$inline: true
				});
			}
		}, 10);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
56
		return `<div id="code-${id}-${codes.length}"></div>`;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
57
58
59
60
61
62
63
64
65
66
67
68
69
	};

	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(() => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
70
71
			const imageElement = document.getElementById(`image-${imageId}`);
			if (imageElement) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
72
				clearInterval(interval);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
73
74
75
76
77
78
79

				// If the image is already loaded, don't load it again
				if (imageElement.innerHTML) {
					return;
				}

				console.log('image', href, text);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
80
				new Image({
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
81
					target: imageElement,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
82
83
84
85
					props: {
						src: href,
						alt: text
					},
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
86
					$$inline: true
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
87
88
89
90
				});
			}
		}, 10);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
91
		return `<div id="image-${id}-${images.length}"></div>`;
Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
94
95
96
97
98
99
	};

	// 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
100

Timothy J. Baek's avatar
Timothy J. Baek committed
101
102
103
104
	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
105
106
107
108
109

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
112
113
114
115
116
117
118
119
120
121
122
123
124
<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
125
126
127
		<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
128
129
	{:else if token.type === 'hr'}
		<hr />
Timothy J. Baek's avatar
Timothy J. Baek committed
130
131
132
133
	{:else if token.type === 'blockquote'}
		<blockquote>
			<svelte:self id={`${id}-${tokenIdx}`} tokens={token.tokens} />
		</blockquote>
Timothy J. Baek's avatar
Timothy J. Baek committed
134
135
136
137
138
139
	{: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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
	{: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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
	{: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
196
			<!-- {#if top}
Timothy J. Baek's avatar
Timothy J. Baek committed
197
198
199
200
201
202
203
204
205
206
207
			<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
208
		{/if} -->
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
209
210
211
212
213
214
215
216
217
218
		{:else}
			{@html marked.parse(token.raw, {
				...defaults,
				gfm: true,
				breaks: true,
				renderer
			})}
		{/if}
	{/each}
</div>