pablo-abc/svelte-markdown

Reactivity issue with Svelte 4

Opened this issue · 6 comments

I'm using this library to display markdown on my website, but also for a simple markdown editor/preview.

Because of this, the rendered HTML should be reactive with the source that is given (which is a variable bound to a textarea).

This works fine in one of my older projects where I use Svelte 3, but with my new project using Svelte 4 it seems that it only works somewhat. It works well on the first render, but when editing the source, empty paragraphs appear, empty headers appear and there are more issues with the preview. If I were to save the source and refresh the page, it would be rendered correctly again, until the source is updated. After a lot of struggle, I decided to downgrade to Svelte 3 to see if it would be resolved, which is the case.

Expected behavior: updating the source renders the markdown as HTML the same way as it would be rendered if it was rendered with the same source the first time.

Ive just spent a bit of time looking into this package as I had the same issue as you. I wasn't able to troubleshoot it because of the recursive nature of how this was built - it got very complex very quick.

Interestingly, the top level component within this package has dispatch events that are not listened to (I also dont think the onMount and setContext elements are needed, but can't confirm that).

EDIT: I have re-read my comment here and feel the tone was unfair. This was out of frustration in my own (lack of) ability to fix the issue. Apologies to the repo owner - and thank you for making this available.

Thank you @Xella37 for opening this issue, I'm seeing the same: random paragraphs missing when the source changes. When the component is first mounted and receives the source, it works just fine.

After some exploration, I believe it may be related to how Svelte creates & destroys dom elements. At the very least, it reminded me of the Keyed each blocks section of the guide. The solution I found was to wrap SvelteMarkdown in a key block like so,

    {#key source}
      <SvelteMarkdown source={source} />
    {/key}

Ideally, svelte-markdown would take care to used keyed elements where necessary. In any case, an acceptable quick win may be to move key inside SvelteMarkdown. @pablo-abc

Thank you @aryzing this just saved me some hours!

also seeing this on svelte 4.2.8 and svelte-markdown 0.4.1. i worked around it by using the {#key} {/key} solution mentioned above.

I'm seeing this as well, only it was just the first line being omitted. The {#key} workaround works great for me as well.