Skip to content

Commit

Permalink
feat(web): detect theme based on preferred color scheme
Browse files Browse the repository at this point in the history
Signed-off-by: Jordan Shatford <[email protected]>
  • Loading branch information
jordanshatford committed Sep 13, 2023
1 parent 789e32a commit ac83502
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions apps/web/src/lib/stores/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,31 @@ import { browser } from '$app/environment';
import { writable } from 'svelte/store';

const THEME_KEY = 'theme';
const DEFAULT_THEME = 'light';

export function getInferredDefaultTheme(): 'dark' | 'light' {
if (!window.matchMedia) {
return DEFAULT_THEME;
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
} else {
return 'light';
}
}

function createThemeStore() {
const { subscribe, set, update } = writable<'light' | 'dark'>('light');
const { subscribe, set, update } = writable<'light' | 'dark'>(DEFAULT_THEME);

if (browser) {
const data = localStorage?.getItem(THEME_KEY) as 'light' | 'dark';
let data = localStorage?.getItem(THEME_KEY) as 'light' | 'dark';

if (data) {
set(data);
if (data === 'dark') {
document.querySelector('html')?.classList.add('dark');
}
if (!data) {
data = getInferredDefaultTheme();
}
set(data);
if (data === 'dark') {
document.querySelector('html')?.classList.add('dark');
}
}

Expand Down

0 comments on commit ac83502

Please sign in to comment.