TorstenDittmann / svelte-markdoc-preprocess

Bring the power of Markdoc right into your Svelte applications!
https://svelte-markdoc-preprocess.pages.dev
MIT License
65 stars 4 forks source link

I cannot pass a transformer into the default config #257

Open buhodev opened 3 weeks ago

buhodev commented 3 weeks ago

I'm trying to pass the id as an attribute to be able to use it in the Heading component like so:

<script context="module">
    /* Stores */
    import { page } from '$app/stores';
</script>

<script lang="ts">
    export let level: 1 | 2 | 3 | 4 | 5 | 6;
    export let id: string;

    $: console.log(id); // undefined
</script>

{#if level > 1}
    <svelte:element this={`h${level}`} {id}>
        <a href="{$page.url.pathname}#{id}">
            <slot />
        </a>
    </svelte:element>
{:else}
    <svelte:element this={`h${level}`}><slot /></svelte:element>
{/if}

This is my svelte.config.js:

config: {
    nodes: {
        heading: {
            children: ['inline'],
            attributes: {
                id: { type: String },
                level: { type: Number }
            },
            transform(node, config) {
                const attributes = node.transformAttributes(config);
                const children = node.transformChildren(config);

                const id = generateID(children, attributes);

                return new Markdoc.Tag(
                    `h${node.attributes['level']}`,
                    { ...attributes, id },
                    children
                );
            }
        }
    }
}

but it's not working, id isn't passed into my Heading component.

This is the official guide I followed:

https://markdoc.dev/docs/nodes#customizing-markdoc-nodes

Maybe it's because the ...nodes is overwriting the ...config?.nodes props?

https://github.com/TorstenDittmann/svelte-markdoc-preprocess/blob/5737e0cc5d88886600c730dbaa046e093004259e/packages/process/src/transformer.ts#L151

TorstenDittmann commented 2 weeks ago

I see, looks like the object merging is destructive here. Will come up with a solution 👍🏻