BearToCode / carta

A lightweight, fast and extensible Svelte Markdown editor and viewer.
https://beartocode.github.io/carta/
MIT License
461 stars 20 forks source link

Text is invisible after reloading with localStore on Svelte 5 #135

Closed Pasithea0 closed 2 days ago

Pasithea0 commented 2 days ago

I'm trying to migrate my code to Svelte 5, but when reloading the page the styles do not load.

Here is my relevant code:

<script lang="ts">
import { Carta, Markdown, MarkdownEditor } from "carta-md";
import { Carta as CartaType } from "carta-md";
import localStorageStore from "$lib/stores/localStorage";

let carta: CartaType = $derived(new Carta({
    sanitizer: DOMPurify.sanitize,
    theme: "dark-plus",
}));

let source = $state<string>(localStorageStore.get("markdown") || "");

$effect(() => {
    localStorageStore.set("markdown", source);
});
</script>

<MarkdownEditor
    {carta}
    bind:value={source}
    mode="tabs"
    {placeholder} 
/>
import { writable } from "svelte/store";

interface LocalStorageStore {
  get: (key: string) => string | null;
  set: (key: string, value: string) => void;
  remove: (key: string) => void;
}

const localStorageStore: LocalStorageStore = {
  get: (key: string) => {
    if (typeof window !== "undefined") {
      return localStorage.getItem(key);
    }
    return null;
  },
  set: (key: string, value: string) => {
    if (typeof window !== "undefined") {
      localStorage.setItem(key, value);
    }
  },
  remove: (key: string) => {
    if (typeof window !== "undefined") {
      localStorage.removeItem(key);
    }
  },
};

export default localStorageStore;

https://github.com/user-attachments/assets/22de92c6-5f86-4416-af6a-d0fc3273e24d

BearToCode commented 2 days ago

Hi, I'm not able to try this myself at the moment, but I would suggest to try the following:

Pasithea0 commented 2 days ago

Ah! I didn't think to do that, that did the trick though!

  let source = $state("");

  onMount(() => {
    const cached = localStorageStore.get("markdown") ;
    if (cached) source = cached;
  })

  $effect(() => {
      localStorageStore.set("markdown", source);
  });

I just added the $effect to update changes!