Skip to content

Commit 6b4208c

Browse files
will svelte 5 ever work consistently?
who knows! $inspect shouldn't change behavior!!!
1 parent b370c8a commit 6b4208c

File tree

2 files changed

+16
-17
lines changed

2 files changed

+16
-17
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "svelte-theme-select",
3-
"version": "0.1.1",
3+
"version": "0.1.2",
44
"type": "module",
55
"keywords": [
66
"svelte",

src/lib/state.svelte.ts

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ export interface Config {
2727
}
2828

2929
class ThemeState {
30-
#system = new MediaQuery('(prefers-color-scheme: dark)')
31-
#override: Theme = 'system'
30+
#override = $state<Theme>('system')
31+
#system: Theme
32+
#value: Theme
3233
#subscribe: VoidFunction
3334
#update?: VoidFunction
3435

@@ -37,29 +38,33 @@ class ThemeState {
3738
labels = defaultLabels
3839

3940
constructor() {
41+
const prefersDark = new MediaQuery('(prefers-color-scheme: dark)')
42+
this.#system = $derived(prefersDark.current ? 'dark' : 'light')
43+
this.#value = $derived(this.#override === 'system' ? this.#system : this.#override)
44+
4045
this.#subscribe = createSubscriber(update => {
4146
this.#update = update
42-
4347
const saved: Theme = localStorage.theme ?? 'system'
4448
this.#override = saved
4549
update()
4650

47-
$effect(() => {
48-
document.documentElement.classList.toggle('dark', this.current === 'dark')
49-
})
50-
5151
return on(window, 'storage', (event: StorageEvent) => {
5252
if (event.key === 'theme') {
5353
this.#override = event.newValue as Theme
5454
update()
5555
}
5656
})
5757
})
58+
59+
$effect.root(() => {
60+
$effect.pre(() => {
61+
document.documentElement.classList.toggle('dark', this.#value === 'dark')
62+
})
63+
})
5864
}
5965

6066
get system() {
61-
this.#subscribe()
62-
return this.#system.current
67+
return this.#system
6368
}
6469

6570
get override() {
@@ -69,13 +74,7 @@ class ThemeState {
6974

7075
get current() {
7176
this.#subscribe()
72-
switch (this.#override) {
73-
case 'dark':
74-
case 'light':
75-
return this.#override
76-
case 'system':
77-
return this.#system.current ? 'dark' : 'light'
78-
}
77+
return this.#value
7978
}
8079

8180
set current(value: Theme) {

0 commit comments

Comments
 (0)