-
Notifications
You must be signed in to change notification settings - Fork 1
/
mdsvex.config.js
387 lines (347 loc) · 10.7 KB
/
mdsvex.config.js
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/**
* Source: https://github.com/melt-ui/melt-ui/blob/develop/mdsvex.config.js
*/
import { join, resolve } from 'path';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { visit } from 'unist-util-visit';
import { toHtml } from 'hast-util-to-html';
import rehypePrettyCode from 'rehype-pretty-code';
// import { escapeSvelte } from 'mdsvex';
import { escapeSvelte } from '@huntabyte/mdsvex';
import rehypeUnwrapImages from 'rehype-unwrap-images';
import rehypeSlug from 'rehype-slug';
import math from 'remark-math';
import rehype_katex from 'rehype-katex';
import remarkGfm from 'remark-gfm';
import katex from 'katex';
import remarkToc from 'remark-toc';
import { createHighlighter } from 'shiki';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const correct_hast_tree = () => (tree) => {
visit(tree, 'text', (node) => {
if (node.value.trim().startsWith('<')) {
node.type = 'raw';
}
});
};
const katex_blocks = () => (tree) => {
visit(tree, 'code', (node) => {
if (node.lang === 'math') {
const str = katex.renderToString(node.value, {
displayMode: true,
leqno: false,
fleqn: false,
throwOnError: true,
errorColor: '#cc0000',
strict: 'warn',
output: 'htmlAndMathml',
trust: false,
macros: { '\\f': '#1f(#2)' }
});
node.type = 'raw';
node.value = '<span class="text-sm md:text-lg">{@html `' + str + '`}</span>';
}
});
};
const inlineKatexUsingInlineCode = () => (tree) => {
visit(tree, 'inlineCode', (node) => {
if (node.value.endsWith('{:eq}')) {
node.value = node.value.replace('{:eq}', '');
const str = katex.renderToString(node.value, {
displayMode: false,
leqno: false,
fleqn: false,
throwOnError: true,
errorColor: '#cc0000',
strict: 'warn',
output: 'htmlAndMathml',
trust: false,
macros: { '\\f': '#1f(#2)' }
});
node.type = 'raw';
node.value = '<span class="text-base mx-1">{@html `' + str + '`}</span>';
}
});
};
const katex_inline = () => (tree) => {
// using $$ $$ for inline math
//
visit(tree, 'text', (node, index, parent) => {
const regex = /\$\$(.*?)\$\$/g;
let replacedText = node.value;
replacedText = replacedText.replace(regex, (match, equation) => {
// Replace double backslashes with single backslashes
const cleanedEquation = equation.replace(/\\\\/g, '\\');
const str = katex.renderToString(cleanedEquation, {
throwOnError: true,
errorColor: '#cc0000',
strict: 'warn',
output: 'htmlAndMathml',
trust: false,
macros: { '\\f': '#1f(#2)' }
});
// Escape the HTML for Svelte
const escapedHTML = escapeSvelte(str);
// Wrap the rendered equation in a span
return `<span class="text-base">{@html \`${escapedHTML}\`}</span>`;
});
// Replace the original text node with the modified text
parent.children[index] = { type: 'text', value: replacedText };
});
};
const prettyCodeOptions = {
// theme: 'github-dark',
theme: {
// for dark, class name will be Moonlight II, use that class name in pre.svelte to adjust
// any changes here, you need to change in pre.svelte as well with the same class name
dark: JSON.parse(
readFileSync(resolve(__dirname, './src/lib/styles/themes/tokyo-night-storm.json'), 'utf-8')
),
light: 'min-light'
// for light, class name will be min-light, use that class name in pre.svelte to adjust
// any changes here, you need to change in pre.svelte as well with the same class name
// light: JSON.parse(
// readFileSync(resolve(__dirname, './src/lib/styles/themes/tokyo-night-light.json'), 'utf-8')
// )
},
keepBackground: false, // to use our own background color
onVisitLine(node) {
if (node.children.length === 0) {
node.children = { type: 'text', value: ' ' };
}
},
// onVisitTitle(node) {
// // console.log('title:', node);
// },
getHighlighter: (options) => {
return createHighlighter({
...options,
langs: [
'bash',
'css',
'html',
'javascript',
'json',
'markdown',
'plaintext',
'python',
'svelte',
'typescript',
'yaml'
]
});
}
};
// replaces “ and ” with " and ". useful to render {} curly braces
const replaceQuotes = () => (tree) => {
visit(tree, 'text', (node) => {
node.value = node.value
.replace(/”/g, '"') // Replace curly double quotes with straight double quotes
.replace(/“/g, '"') // Replace straight double quotes with straight double quotes
.replace(/’/g, "'") // Replace curly single quotes with straight single quotes
.replace(/‘/g, "'"); // Replace straight single quotes with straight single quotes
});
};
/** @type {import('mdsvex').MdsvexOptions} */
export const mdsvexOptions = {
extensions: ['.md', '.svx'],
layout: {
_: resolve('./src/lib/components/markdown/blueprint.svelte') // default or fallback layout
// about: resolve('./src/lib/components/markdown/about-layout.svelte') // named layout
},
// comment if not working
// highlight: {
// highlighter: highlightCode
// },
remarkPlugins: [
math,
katex_blocks,
katex_inline,
replaceQuotes,
remarkGfm,
inlineKatexUsingInlineCode,
[remarkToc, { tight: true, maxDepth: 3 }]
],
rehypePlugins: [
rehypeUnwrapImages,
rehypeCustomComponents,
rehypeComponentPreToPre,
[rehypePrettyCode, prettyCodeOptions],
rehypeHandleMetadata,
rehypeRenderCode,
rehypePreToComponentPre,
rehypeSlug,
correct_hast_tree,
rehype_katex
]
};
function rehypeCustomComponents() {
return async (tree) => {
const hTags = [
'Components.h1',
'Components.h2',
'Components.h3',
'Components.h4',
'Components.h5',
'Components.h6'
];
visit(tree, (node) => {
// Check h tags, and pass some extra parameters to the custom components.
if (node?.type === 'element' && hTags.includes(node?.tagName)) {
node.properties['id'] = node.children[0].value.split(' ').join('-').toLowerCase();
node.properties['headerTag'] = node.tagName.split('.')[1];
}
});
};
}
function rehypeComponentPreToPre() {
return async (tree) => {
// Replace `Component.pre` tags with regular `pre` tags.
// This enables us to use rehype-pretty-code with our custom `pre` component.
visit(tree, (node) => {
// if (node?.data && 'meta' in node?.data) {
// console.log('node:', node, '\n');
// console.log('data:', node?.data, '\n-------------------------');
// }
if (node?.type === 'element' && node?.tagName === 'Components.pre') {
node.tagName = 'pre';
}
});
};
}
/**
* Escapes the html string of code blocks so we can pass
* it on to our custom `Component.pre` element.
*/
// function escapeHtml(html) {
// return html
// .replaceAll('&', '&')
// .replaceAll('<', '<')
// .replaceAll('>', '>')
// .replaceAll('"', '"')
// .replaceAll("'", ''');
// }
function rehypePreToComponentPre() {
return async (tree) => {
/**
* Replace `pre` tags with our custom `Component.pre` tags.
* This enables us to use rehype-pretty-code with our custom `pre` component.
* We also add the raw html string as a parameter for the copy button.
*/
visit(tree, (node) => {
if (node?.type === 'element' && node?.tagName === 'pre') {
node.tagName = 'Components.pre';
// if (node?.children.length > 0) {
// console.log('\n\nnode:', node);
// console.log('\n\nnode.children[0]:', node?.children[0], '\n------------------------');
// }
// const value = node.children[0].value.trim();
// const rawHTMLString = value.substring(8, value.length - 2);
// node.properties['rawHTMLString'] = escapeHtml(rawHTMLString);
}
});
};
}
function rehypeHandleMetadata() {
return async (tree) => {
visit(tree, (node) => {
if (node?.type === 'element' && node?.tagName === 'figure') {
if (!('data-rehype-pretty-code-figure' in node.properties)) {
return;
}
const titleElement = node.children[0];
const preElement = node.children.at(-1);
if (
preElement.tagName !== 'pre' ||
!('data-rehype-pretty-code-title' in titleElement.properties)
) {
return;
}
// const codeElement = preElement.children.find((child) => child.tagName === 'code');
// if (codeElement) {
// processCustomCodeBlockHighlights(codeElement.children);
// }
if (titleElement.children.length > 0 && 'value' in titleElement.children[0]) {
preElement.properties['title'] = titleElement.children[0].value;
preElement.properties['language'] = node.children[0].properties['data-language'];
node.children.shift();
}
}
});
};
}
function processCustomCodeBlockHighlights(children) {
children.forEach((child) => {
if (child.type === 'element' && child.tagName === 'span' && 'data-line' in child.properties) {
let shouldAddHighlight = false;
let shouldRemoveHighlight = false;
child.children.forEach((innerChild) => {
if (innerChild.type === 'element' && innerChild.tagName === 'span') {
const textNode = innerChild.children.find((c) => c.type === 'text');
if (textNode && textNode.value) {
const addHighlightPatterns = ['# ++add', '// ++add', '#++add', '//++add'];
const removeHighlightPatterns = ['# --del', '// --del', '#--del', '//--del'];
addHighlightPatterns.forEach((pattern) => {
if (textNode.value.includes(pattern)) {
shouldAddHighlight = true;
textNode.value = textNode.value.replace(pattern, '').trim();
}
});
removeHighlightPatterns.forEach((pattern) => {
if (textNode.value.includes(pattern)) {
shouldRemoveHighlight = true;
textNode.value = textNode.value.replace(pattern, '').trim();
}
});
}
}
});
if (shouldAddHighlight) {
child.properties['data-highlighted-line-id'] = 'add';
child.properties['data-highlighted-line'] = '';
} else if (shouldRemoveHighlight) {
child.properties['data-highlighted-line-id'] = 'remove';
child.properties['data-highlighted-line'] = '';
}
}
// Recursively traverse inner children
if (child.children && child.children.length > 0) {
processCustomCodeBlockHighlights(child.children);
}
});
}
function rehypeRenderCode() {
return async (tree) => {
visit(tree, (node) => {
if (
node?.type === 'element' &&
(node?.tagName === 'Components.pre' || node?.tagName === 'pre')
) {
const codeEl = node.children[0];
if (codeEl.tagName !== 'code') {
return;
}
if (codeEl && node.properties['data-language'] !== 'md') {
processCustomCodeBlockHighlights(codeEl.children);
}
const codeString = tabsToSpaces(
toHtml(codeEl, {
allowDangerousCharacters: true,
allowDangerousHtml: true
})
);
codeEl.type = 'raw';
codeEl.value = `{@html \`${escapeSvelte(codeString)}\`}`;
}
});
};
}
/**
*
* @param {string} code
* @returns {string}
*/
function tabsToSpaces(code) {
return code.replaceAll(' ', ' ').replaceAll('\t', ' ');
}