Fluzm/Fluzm/public/scripts/views/components/PopupForm.tsx
2023-12-18 11:38:13 +06:00

79 lines
2.3 KiB
TypeScript

// import React from "react"
interface FormFieldDefinition {
key: string
label: string
inputType: string
}
interface PopupFormProps {
name: string
submitButtonText: string
isVisible: boolean
fields: FormFieldDefinition[]
onClose: ()=>void
onSubmit: (rezult: any)=>void
}
function PopupFormRow(props: { def: FormFieldDefinition, ref: React.LegacyRef<HTMLInputElement>}){
return (
<tr>
<td>
<label>{props.def.label}:</label>
</td>
<td>
<input ref={props.ref} type={props.def.inputType} required />
</td>
</tr>
)
}
function PopupForm(props: PopupFormProps){
if(!props.isVisible)
return <div style={{display: 'none'}}></div>
var inputRefs = new Map<string, React.MutableRefObject<HTMLInputElement|null>>()
props.fields.forEach( f => {
inputRefs.set(f.key, React.useRef(null))
})
function getRezult(): any {
let rezultObj: any = {}
props.fields.forEach(f => {
const val = inputRefs.get(f.key)?.current?.value
if(val == undefined)
throw new Error(`field ${f.key} in form ${props.name} is undefined}`)
rezultObj[f.key] = val
})
return rezultObj
}
return (
<div className="popup-container">
<form className="popup-form">
<div style={{display: 'flex', justifyContent: 'space-between'}}>
<b style={{paddingTop: '10px', paddingLeft: '40px', width: '100%', fontSize: '22px'}}>
{props.name}
</b>
<a className="close-button"
onClick={()=>props.onClose()}>
X
</a>
</div>
<table style={{padding: '10px', width: '100%'}}>
<tbody>
{props.fields.map(f=> PopupFormRow({def: f, ref: inputRefs.get(f.key)!}))}
</tbody>
</table>
<div style={{display: 'flex', height: '80px'}}>
<a className="button" style={{margin: 'auto'}}
onClick={ ()=>{ props.onSubmit(getRezult()); props.onClose(); } }>
{props.submitButtonText}
</a>
</div>
</form>
</div>
)
}
export default PopupForm