/** * The theme, as one piece of state every toggle on the page shares. * * has already decided the theme before this runs; the store starts from * what it wrote on (data-theme-choice, data-theme, data-theme-key). `choice` is what * the visitor picked — light, dark or system — and `resolved` is what is showing. * * `value` is an accessor, so binding a control with `x-model="$store.theme.value"` goes * through the same write as `set()` and `toggle()`: the attributes, then localStorage. * * `scheme` is the colour profile on screen (, which the server chose), and * `previewScheme(name)` shows another one on this page without storing anything — the * application saves a choice itself, and the next full load draws what it saved. */ document.addEventListener('alpine:init', () => { const root = document.documentElement const media = window.matchMedia('(prefers-color-scheme: dark)') const choices = ['light', 'dark', 'system'] const resolve = (choice) => (choice === 'system' ? (media.matches ? 'dark' : 'light') : choice) window.Alpine.store('theme', { choice: choices.includes(root.dataset.themeChoice) ? root.dataset.themeChoice : 'system', resolved: root.dataset.theme === 'dark' ? 'dark' : 'light', scheme: root.dataset.scheme || null, get value() { return this.choice }, set value(choice) { this.set(choice) }, set(choice) { if (!choices.includes(choice)) { return } this.choice = choice this.resolved = resolve(choice) root.dataset.themeChoice = choice root.dataset.theme = this.resolved try { localStorage.setItem(root.dataset.themeKey || 'material-theme', choice) } catch { // Blocked storage: the page still switches, it just will not remember. } }, toggle() { this.set(this.resolved === 'dark' ? 'light' : 'dark') }, previewScheme(name) { if (typeof name !== 'string' || !/^[a-z0-9-]+$/.test(name)) { return } this.scheme = name root.dataset.scheme = name }, }) // The head script repaints on an OS change while the choice is `system`; this keeps the // store's `resolved` — which a toggle's icon reads — in step with it. media.addEventListener('change', () => { const theme = window.Alpine.store('theme') if (theme.choice === 'system') { theme.resolved = resolve('system') } }) })