Svelte exposes a readable function to create readable stores.
Pass an initial value and a start function. The start function runs when the first subscriber arrives.
Access browser APIs inside the start function, not at module scope. The guard also makes the store safe to subscribe to on the server.
Set the current theme, then listen for changes.
Return a cleanup function. It runs when the last subscriber leaves.
import { readable } from 'svelte/store';
export const theme = readable('light', (set) => {
if (typeof window === 'undefined') return;
const query = window.matchMedia(
'(prefers-color-scheme: dark)',
);
function update() {
set(query.matches ? 'dark' : 'light');
}
update();
query.addEventListener('change', update);
return () => query.removeEventListener('change', update);
});