Created
September 25, 2021 22:40
-
-
Save probablykasper/b956a3be889e2df4a2e7c320ba2c0c4d to your computer and use it in GitHub Desktop.
Svelte/SvelteKit instantly applied theme
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { onMount } from 'svelte' | |
import { writable } from 'svelte/store' | |
import type { Writable } from 'svelte/store' | |
const theme: Writable<string | null> = writable(null) | |
$: if ($theme) { | |
document.documentElement.setAttribute('data-theme', $theme) | |
} | |
onMount(() => { | |
$theme = document.documentElement.getAttribute('data-theme') || 'dark' | |
const prefersDark = matchMedia('(prefers-color-scheme: dark)') | |
prefersDark.onchange = (e) => { | |
$theme = e.matches ? 'dark' : 'light' | |
localStorage.removeItem('theme') | |
} | |
}) | |
function toggleTheme() { | |
if ($theme === 'dark') { | |
$theme = 'light' | |
} else { | |
$theme = 'dark' | |
} | |
localStorage.setItem('theme', $theme || 'dark') | |
} | |
</script> | |
<style lang="sass"> | |
:global(html) | |
--primary: #0269f7 | |
color: var(--foreground) | |
:global([data-theme='dark']) | |
--background: #0d0e12 | |
--foreground: #f7f7f7 | |
--border: #1C1E24 | |
--date-picker-background: #1b1e27 | |
--date-picker-foreground: var(--foreground) | |
--date-picker-highlight-border: rgb(2, 105, 247) | |
--date-picker-highlight-shadow: rgba(2, 105, 247, 0.5) | |
:global([data-theme='light']) | |
--background: #ffffff | |
--foreground: #0d0e12 | |
--border: #c6cddd | |
</style> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<script> | |
function detectTheme() { | |
if(localStorage.getItem('theme') == 'dark') { | |
return 'dark' | |
} else if(window.matchMedia('(prefers-color-scheme: dark)').matches) { | |
return 'light' | |
} else { | |
return 'dark' | |
} | |
} | |
document.documentElement.setAttribute('data-theme', detectTheme()) | |
</script> | |
%svelte.head% | |
</head> | |
<body> | |
%svelte.body% | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment