// Light, dark or as the system (spec §10.5). The choice is stored on the server (Impostazioni, Generali) and kept in // this browser too, so the page does not flash at start (js/tema.js applies it before the first paint). // In the demo «?tema=chiaro|scuro» wins for the whole tab without changing the stored choice. import { api, carriedValue } from './api.js'; const media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null; let choice = 'sistema'; function paint() { const forced = carriedValue('tema'); const effective = forced === 'chiaro' || forced === 'scuro' ? forced : choice === 'sistema' ? (media && media.matches ? 'scuro' : 'chiaro') : choice; document.documentElement.setAttribute('data-tema', effective); document.documentElement.setAttribute('data-scelta-tema', choice); } /** The stored choice: «chiaro», «scuro» or «sistema». */ export function themeChoice() { return choice; } /** Applies a choice locally (no server call). */ export function applyTheme(value) { choice = value === 'chiaro' || value === 'scuro' ? value : 'sistema'; try { localStorage.setItem('febe.tema', choice); } catch { // storage blocked: the choice still applies to this page } paint(); } /** At start: local choice first, then the server's. */ export async function initTheme() { try { choice = localStorage.getItem('febe.tema') || 'sistema'; } catch { choice = 'sistema'; } paint(); if (media && media.addEventListener) media.addEventListener('change', paint); try { const prefs = await api('/api/preferences'); if (prefs && prefs.theme && prefs.theme !== choice) applyTheme(prefs.theme); } catch { // keep the local choice } } /** Stores a new choice on the server and applies it («Tema» in Impostazioni, Generali). */ export async function saveTheme(value) { applyTheme(value); await api('/api/preferences', { method: 'PUT', body: { theme: choice } }); }