import {FormControlLabel,MenuItem,Switch,TextField} from "@mui/material";import {useEffect,useState} from "react";import type {Gallery_Control,Json_Value} from "../protocol/gallery_types";
export function Control_Field({control,on_commit}:{control:Gallery_Control;on_commit:(value:Json_Value)=>void}) {const [draft,set_draft]=useState(String(control.value??""));const [editing,set_editing]=useState(false);useEffect(()=>{if(!editing)set_draft(String(control.value??""));},[control.value,editing]);if(control.input==="boolean")return <FormControlLabel control={<Switch checked={Boolean(control.value)} onChange={(_,checked)=>on_commit(checked)}/>} label={control.label}/>;if(control.input==="select")return <TextField select fullWidth size="small" label={control.label} value={draft} onFocus={()=>set_editing(true)} onBlur={()=>set_editing(false)} onChange={event=>{set_draft(event.target.value);on_commit(event.target.value);}}>{control.options.map(option=><MenuItem key={String(option.value)} value={String(option.value)}>{option.label}</MenuItem>)}</TextField>;const commit=()=>{set_editing(false);if(control.input!=="number"){if(draft!==String(control.value??""))on_commit(draft);return;}const number=Number(draft);if(!Number.isFinite(number)||(control.minimum!==undefined&&number<control.minimum)||(control.maximum!==undefined&&number>control.maximum)){set_draft(String(control.value??""));return;}if(number!==Number(control.value))on_commit(number);};return <TextField fullWidth size="small" label={control.label} title={control.description} type={control.input==="number"?"number":"text"} value={draft} inputProps={{min:control.minimum,max:control.maximum,step:control.step??"any"}} onFocus={()=>set_editing(true)} onChange={event=>set_draft(event.target.value)} onBlur={commit} onKeyDown={event=>{if(event.key==="Enter")commit();else if(event.key==="Escape"){set_draft(String(control.value??""));set_editing(false);}}}/>;}
