Files
progcode/docs/design-system/kit-completeness/reference-source/fsd/features/theme-selection/ui/ThemeControl.jsx
T
huncode 12562baeb5
Build and deploy / deploy (push) Successful in 2m39s
Implement ProgCode identity and real shared reading UI kit
2026-10-27 15:19:49 +03:00

21 lines
1.5 KiB
React

"use client";
import {useEffect,useId,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 id=useId();const [theme,setTheme]=useState('system');
useEffect(()=>{
const sync=event=>{const value=validTheme(event?.detail)?event.detail:readPreference();setTheme(value);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(event){
const value=event.target.value;if(!validTheme(value))return;
setTheme(value);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}));
}
return <div className="theme-control"><label htmlFor={id}>Тема</label><select id={id} value={theme} onChange={change}>{THEME_OPTIONS.map(option=><option value={option.value} key={option.value}>{option.label}</option>)}</select></div>;
}