refactor preview logic out of component

This commit is contained in:
Nicola Clark 2024-10-17 11:09:38 -05:00
parent aa5f8e15dd
commit 9abf179d65
Signed by: nicola
GPG Key ID: 3E1710E7FF08956C
2 changed files with 30 additions and 26 deletions

View File

@ -1,12 +1,6 @@
<script lang="ts"> <script lang="ts">
import rehypeDocument from 'rehype-document';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import rehypeStringify from 'rehype-stringify';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import { unified } from 'unified';
import { pane } from '$lib/stores/nav.js'; import { pane } from '$lib/stores/nav.js';
import renderPreview from '$lib/render-preview';
interface Props { interface Props {
mobile?: boolean; mobile?: boolean;
@ -18,25 +12,7 @@
let hidden: boolean = $derived(mobile ? $pane !== 'preview' : true); let hidden: boolean = $derived(mobile ? $pane !== 'preview' : true);
let output: Promise<string> = $derived.by(async () => { let output: Promise<string> = $derived.by(() => renderPreview(markdown, stylesheet));
let allowedTags: string[] = ['body', 'head', 'html', 'style'];
if (defaultSchema.tagNames) {
allowedTags = [...defaultSchema.tagNames, ...allowedTags];
}
return String(
await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, { style: stylesheet })
.use(rehypeSanitize, {
...defaultSchema,
allowDoctypes: true,
tagNames: allowedTags,
})
.use(rehypeStringify)
.process(markdown),
);
});
</script> </script>
<main class:hidden class:mobile data-testid="preview-pane"> <main class:hidden class:mobile data-testid="preview-pane">

28
src/lib/render-preview.ts Normal file
View File

@ -0,0 +1,28 @@
import rehypeDocument from 'rehype-document';
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
import rehypeStringify from 'rehype-stringify';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import { unified } from 'unified';
const renderPreview = async (markdown: string, stylesheet: string): Promise<string> => {
let allowedTags: string[] = ['body', 'head', 'html', 'style'];
if (defaultSchema.tagNames) {
allowedTags = [...defaultSchema.tagNames, ...allowedTags];
}
return String(
await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, { style: stylesheet })
.use(rehypeSanitize, {
...defaultSchema,
allowDoctypes: true,
tagNames: allowedTags,
})
.use(rehypeStringify)
.process(markdown),
);
};
export default renderPreview;