Skip to content

Commit

Permalink
Fixed Theme change on CodeBlock
Browse files Browse the repository at this point in the history
  • Loading branch information
LyonSyonII committed Nov 16, 2023
1 parent 7855755 commit 962d7b4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/components/CodeBlock.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,23 @@
import { shortcut } from "@svelte-put/shortcut";
import { clickoutside } from "@svelte-put/clickoutside";
import Icon from "@iconify/svelte";
import { writable } from "svelte/store";
import { onThemeChange } from "src/utils/onThemeChange";
import { onDestroy } from "svelte";
/** Code that will be sent to the playground, replaces __VALUE__ with the code in the editor */
export let setup = "__VALUE__";
/** Code in the editor */
export let code = "";
export let errorMsg = "";
const theme = writable(document.documentElement.dataset.theme);
const observer = onThemeChange((newtheme) => {
theme.set(newtheme);
});
onDestroy(() => {
observer.disconnect()
});
let value = code;
let running = false;
Expand Down Expand Up @@ -79,10 +90,7 @@
class="not-content"
bind:value
lang={rust()}
theme={document.documentElement.attributes.getNamedItem("data-theme")
?.value === "dark"
? githubDark
: githubLight}
theme={$theme === "dark" ? githubDark : githubLight}
basic={true}
editable={!running}
/>
Expand Down
15 changes: 15 additions & 0 deletions src/utils/onThemeChange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export function onThemeChange(callback: (theme: "dark" | "light") => void): MutationObserver {
const target = document.documentElement;
const config = { attributes: true };

const c: MutationCallback = (mutationList, _) => {
for (const mutation of mutationList) {
if (mutation.type === "attributes" && mutation.attributeName === "data-theme") {
callback(target.dataset.theme as "dark" | "light");
}
}
}
const observer = new MutationObserver(c);
observer.observe(target, config);
return observer
}

0 comments on commit 962d7b4

Please sign in to comment.