svelte-mdast-directive Svelte Themes

Svelte Mdast Directive

Svelte Mdast Directive

Transform Mdast directive nodes into Svelte components.

Installing

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

Usage

<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 }} />

Custom Directive Component

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>

Directive Types

This library supports three directive types from the directive syntax specification:

  • Text directives: :name[content] - inline directives
  • Leaf directives: ::name[content] - block-level directives without children
  • Container directives: :::name - block-level directives that can contain other content

Pass custom components via the corresponding props:

  • textDirectives={{ name: Component }}
  • leafDirectives={{ name: Component }}
  • containerDirectives={{ name: Component }}

Test

pnpm test

License

MIT

Copyright © 2024 Matthew Gibbons

Top categories

Loading Svelte Themes