Transform Mdast directive nodes into Svelte components.
Add the @typematter/svelte-mdast-directive
package dependency to your Svelte / SvelteKit project:
npm install --save-dev @typematter/svelte-mdast-directive
# or
yarn add -D @typematter/svelte-mdast-directive
# or
pnpm add -D @typematter/svelte-mdast-directive
<script lang="ts">
import { components } from '@typematter/svelte-mdast-directive';
import { Unist } from '@typematter/svelte-unist';
import { u } from 'unist-builder';
import Highlight from './Highlight.svelte';
const ast: import('mdast').Root = u('root', [
u('textDirective', { name: 'highlight' }, [u('text', 'Hello, World!')])
]);
</script>
<Unist {ast} {components} textDirectives={{ highlight: Highlight }} />
Create a custom component for your directive:
<!-- Highlight.svelte -->
<script lang="ts">
import { Node } from '@typematter/svelte-unist';
let { node }: { node: import('mdast-util-directive').TextDirective } = $props();
let { children } = $derived(node);
</script>
<span style="background-color: yellow;">
{#each children as child (child)}<Node node={child} />{/each}
</span>
This library supports three directive types from the directive syntax specification:
:name[content]
- inline directives::name[content]
- block-level directives without children:::name
- block-level directives that can contain other contentPass custom components via the corresponding props:
textDirectives={{ name: Component }}
leafDirectives={{ name: Component }}
containerDirectives={{ name: Component }}
pnpm test
Copyright © 2024 Matthew Gibbons