-
Notifications
You must be signed in to change notification settings - Fork 0
/
mdsvex.config.js
70 lines (59 loc) · 2.1 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
import { defineMDSveXConfig as defineConfig } from 'mdsvex';
import { readFileSync } from 'fs';
import rehypeSlugPlugin from 'rehype-slug';
import rehypeExternalLinks from 'rehype-external-links';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import { lex, parse } from 'fenceparser';
import { createShikiHighlighter, runTwoSlash, renderCodeToHTML } from 'shiki-twoslash';
import { h } from 'hastscript';
const NightOwlTheme = JSON.parse(readFileSync('./src/lib/themes/Night Owl-color-theme.json'));
const escape_svelty = (str) =>
str
.replace(/[{}`]/g, (c) => ({ '{': '{', '}': '}', '`': '`' }[c]))
.replace(/\\([trn])/g, '\$1');
const highlighter = await createShikiHighlighter({ theme: NightOwlTheme });
const config = defineConfig({
extensions: ['.svx'],
rehypePlugins: [
rehypeSlugPlugin,
rehypeExternalLinks,
[
rehypeAutolinkHeadings,
{
behavior: 'prepend',
properties: {
class:
'-ml-8 pr-4 absolute no-underline text-gray-300 hover:text-red-700 opacity-0 md:opacity-100'
},
content: [h('span.sr-only', 'permalink'), h('span', { ariaHidden: true }, '#')]
}
]
],
highlight: {
highlighter(code, lang, meta) {
// Copied from https://github.com/pngwn/MDsveX/issues/212#issuecomment-937574889
// Adapted from the `remark-shiki-twoslash` repo
// See: https://github.com/shikijs/twoslash/blob/fbf061261fcda90c46e946ce1e2e9357d465c145/packages/remark-shiki-twoslash/src/index.ts#L172-L215
let fence = undefined;
try {
fence = parse(lex([lang, meta].filter(Boolean).join(' ')));
} catch (error) {
throw new Error(`Could not parse the codefence for this code sample \n${code}`);
}
let twoslash = undefined;
if (fence?.twoslash === true) {
twoslash = runTwoSlash(code, lang, {
defaultCompilerOptions: {
allowJs: true,
checkJs: true,
target: 'es2021'
}
});
code = twoslash.code;
}
const html = renderCodeToHTML(code, lang, fence ?? {}, {}, highlighter, twoslash);
return `{@html \`<div class="relative">${escape_svelty(html)}</div>\` }`;
}
}
});
export default config;