File size: 4,733 Bytes
1bcd186
 
 
cbd723d
1bcd186
6f93b29
cbd723d
1bcd186
 
a1a6daf
 
 
 
 
 
1bcd186
cbd723d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1a6daf
cbd723d
 
 
1bcd186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f93b29
 
3ad7680
6f93b29
cbd723d
6f93b29
 
 
0f674e1
6f93b29
 
 
 
1bcd186
 
 
 
 
 
 
 
6f7beab
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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
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
188
189
190
191
192
193
194
195
196
197
198
199
<script lang="ts">
	import type { WebSearchSource } from "$lib/types/WebSearch";
	import katex from "katex";
	import "katex/dist/contrib/mhchem.mjs";
	import DOMPurify from "isomorphic-dompurify";
	import { Marked } from "marked";
	import type { Tokens, TokenizerExtension, RendererExtension } from "marked";
	import CodeBlock from "../CodeBlock.svelte";

	interface Props {
		content: string;
		sources?: WebSearchSource[];
	}

	let { content, sources = [] }: Props = $props();

	interface katexBlockToken extends Tokens.Generic {
		type: "katexBlock";
		raw: string;
		text: string;
		displayMode: true;
	}

	interface katexInlineToken extends Tokens.Generic {
		type: "katexInline";
		raw: string;
		text: string;
		displayMode: false;
	}

	export const katexBlockExtension: TokenizerExtension & RendererExtension = {
		name: "katexBlock",
		level: "block",

		start(src: string): number | undefined {
			const match = src.match(/(\${2}|\\\[)/);
			return match ? match.index : -1;
		},

		tokenizer(src: string): katexBlockToken | undefined {
			// 1) $$ ... $$
			const rule1 = /^\${2}([\s\S]+?)\${2}/;
			const match1 = rule1.exec(src);
			if (match1) {
				const token: katexBlockToken = {
					type: "katexBlock",
					raw: match1[0],
					text: match1[1].trim(),
					displayMode: true,
				};
				return token;
			}

			// 2) \[ ... \]
			const rule2 = /^\\\[([\s\S]+?)\\\]/;
			const match2 = rule2.exec(src);
			if (match2) {
				const token: katexBlockToken = {
					type: "katexBlock",
					raw: match2[0],
					text: match2[1].trim(),
					displayMode: true,
				};
				return token;
			}

			return undefined;
		},

		renderer(token) {
			if (token.type === "katexBlock") {
				return katex.renderToString(token.text, {
					throwOnError: false,
					displayMode: token.displayMode,
				});
			}

			return undefined;
		},
	};

	const katexInlineExtension: TokenizerExtension & RendererExtension = {
		name: "katexInline",
		level: "inline",

		start(src: string): number | undefined {
			const match = src.match(/(\$|\\\()/);
			return match ? match.index : -1;
		},

		tokenizer(src: string): katexInlineToken | undefined {
			// 1) $...$
			const rule1 = /^\$([^$]+?)\$/;
			const match1 = rule1.exec(src);
			if (match1) {
				const token: katexInlineToken = {
					type: "katexInline",
					raw: match1[0],
					text: match1[1].trim(),
					displayMode: false,
				};
				return token;
			}

			// 2) \(...\)
			const rule2 = /^\\\(([\s\S]+?)\\\)/;
			const match2 = rule2.exec(src);
			if (match2) {
				const token: katexInlineToken = {
					type: "katexInline",
					raw: match2[0],
					text: match2[1].trim(),
					displayMode: false,
				};
				return token;
			}

			return undefined;
		},

		renderer(token) {
			if (token.type === "katexInline") {
				return katex.renderToString(token.text, {
					throwOnError: false,
					displayMode: token.displayMode,
				});
			}
			return undefined;
		},
	};

	function escapeHTML(content: string) {
		return content.replace(
			/[<>&"']/g,
			(x) =>
				({
					"<": "&lt;",
					">": "&gt;",
					"&": "&amp;",
					"'": "&#39;",
					'"': "&quot;",
				})[x] || x
		);
	}

	function addInlineCitations(md: string, webSearchSources: WebSearchSource[] = []): string {
		const linkStyle =
			"color: rgb(59, 130, 246); text-decoration: none; hover:text-decoration: underline;";

		return md.replace(/\[(\d+)\]/g, (match: string) => {
			const indices: number[] = (match.match(/\d+/g) || []).map(Number);
			const links: string = indices
				.map((index: number) => {
					if (index === 0) return false;
					const source = webSearchSources[index - 1];
					if (source) {
						return `<a href="${source.link}" target="_blank" rel="noreferrer" style="${linkStyle}">${index}</a>`;
					}
					return "";
				})
				.filter(Boolean)
				.join(", ");

			return links ? ` <sup>${links}</sup>` : match;
		});
	}

	const marked = new Marked({
		hooks: {
			postprocess: (html) => DOMPurify.sanitize(addInlineCitations(html, sources)),
		},
		extensions: [katexBlockExtension, katexInlineExtension],
		renderer: {
			link: (href, title, text) =>
				`<a href="${href?.replace(/>$/, "")}" target="_blank" rel="noreferrer">${text}</a>`,
			html: (html) => escapeHTML(html),
		},
		gfm: true,
	});

	DOMPurify.addHook("afterSanitizeAttributes", (node) => {
		if (node.tagName === "A") {
			node.setAttribute("rel", "noreferrer");
			node.setAttribute("target", "_blank");
		}
	});
</script>

{#each marked.lexer(content) as token}
	{#if token.type === "code"}
		<CodeBlock lang={token.lang} code={token.text} />
	{:else}
		{#await marked.parse(token.raw) then parsed}
			<!-- eslint-disable-next-line svelte/no-at-html-tags -->
			{@html parsed}
		{/await}
	{/if}
{/each}