24 lines
2.2 KiB
React
24 lines
2.2 KiB
React
"use client";
|
|
import {useEffect,useState} from 'react';
|
|
import {THEME_STORAGE_KEY,THEME_CHANGE_EVENT,THEME_OPTIONS,validTheme} from '../../../shared/config';
|
|
function readPreference(){try{const value=localStorage.getItem(THEME_STORAGE_KEY);return validTheme(value)?value:'system';}catch{return 'system';}}
|
|
export function ThemeControl(){
|
|
const [theme,setTheme]=useState('system');const [ready,setReady]=useState(false);
|
|
useEffect(()=>{
|
|
const sync=event=>{const value=validTheme(event?.detail)?event.detail:readPreference();setTheme(value);setReady(true);document.documentElement.dataset.theme=value;};
|
|
const onStorage=event=>{if(event.key===THEME_STORAGE_KEY||event.key===null)sync();};
|
|
sync();window.addEventListener(THEME_CHANGE_EVENT,sync);window.addEventListener('storage',onStorage);
|
|
return()=>{window.removeEventListener(THEME_CHANGE_EVENT,sync);window.removeEventListener('storage',onStorage);};
|
|
},[]);
|
|
function change(value){
|
|
if(!validTheme(value))return;
|
|
setTheme(value);setReady(true);document.documentElement.dataset.theme=value;
|
|
try{localStorage.setItem(THEME_STORAGE_KEY,value);}catch{/* Preference remains usable for this page without storage. */}
|
|
window.dispatchEvent(new CustomEvent(THEME_CHANGE_EVENT,{detail:value}));
|
|
}
|
|
const index=THEME_OPTIONS.findIndex(option=>option.value===theme);
|
|
const next=THEME_OPTIONS[(index+1)%THEME_OPTIONS.length];
|
|
const name=`Тема: ${THEME_OPTIONS[index].label}. Переключить на: ${next.label}`;
|
|
return <button type="button" className="theme-control" data-ready={ready?'true':'false'} data-theme-mode={theme} aria-label={name} title={name} onClick={()=>change(next.value)}>{THEME_OPTIONS.map(option=><svg key={option.value} className="theme-icon" data-theme-icon={option.value} viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="square" strokeLinejoin="miter" aria-hidden="true" focusable="false">{option.value==='system'?<><rect x="3" y="4" width="18" height="13"/><path d="M8 21h8M12 17v4"/></>:option.value==='light'?<><circle cx="12" cy="12" r="4"/><path d="M12 1v3M12 20v3M1 12h3M20 12h3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1"/></>:<path d="M20.6 15.1A9 9 0 0 1 8.9 3.4 9 9 0 1 0 20.6 15.1Z"/>}</svg>)}</button>;
|
|
}
|