<script lang="ts">
let theme: "light" | "dark" : "auto";
const isPageDark = () => document.body.getAttribute("dark") !== null;
let themeCurrent: "light" | "dark" = isPageDark() ? "dark" : "light";
$: if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
new MutationObserver(() => {
if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
}).observe(document.body, { attribtes: true, attributeFilter: ["dark"] })
</script>
<button on:click={() => theme = "light"}Light theme</button>
<button on:click={() => theme = "dark"}>Dark theme</button>
<button on:click={() => theme = "auto"}>Auto</button>
<main data-theme={themeCurrent}>
</main>
<style lang="scss">
[data-theme="light"] {
--bg: some-color;
}
[data-theme="dark"] {
--bg: some-other-color;
}
main {
background-color: var(--bg);
}
</style>
<script lang="ts">
let theme: "light" | "dark" : "auto";
const isPageDark = () => document.body.getAttribute("dark") !== null;
let themeCurrent: "light" | "dark" = isPageDark() ? "dark" : "light";
$: if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
new MutationObserver(() => {
if (theme === "auto") {
themeCurrent = isPageDark() ? "dark" : "light";
}
}).observe(document.body, { attribtes: true, attributeFilter: ["dark"] })
</script>
<button on:click={() => theme = "light"}Light theme</button>
<button on:click={() => theme = "dark"}>Dark theme</button>
<button on:click={() => theme = "auto"}>Auto</button>
<main data-theme={themeCurrent}>
</main>
<style lang="scss">
[data-theme="light"] {
--bg: some-color;
}
[data-theme="dark"] {
--bg: some-other-color;
}
main {
background-color: var(--bg);
}
</style>