69 lines
2.2 KiB
TypeScript

import { ChangeEvent, EventHandler, FC, useCallback, useEffect, useRef } from 'react';
import { FieldTypes } from '../../types/schema';
import { InputBinder } from '../../types/inputBinder';
import { FieldTypeInput } from './field-type-input';
import { useInput } from '../../hooks/useInput';
interface IValueProps {
type: FieldTypes;
bind: InputBinder;
}
const DICE_SIDES = [3, 4, 6, 8, 10, 12, 20, 100];
export const ValueField: FC<IValueProps> = ({ type, bind }) => {
const { value: diceCount, bind: bindDiceCount } = useInput(1);
const { value: diceSides, bind: bindDiceSides } = useInput('');
const diceInputRef = useRef<HTMLInputElement>(null);
switch (type) {
case FieldTypes.dice: {
const onChange = (handler: (arg: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => void) => (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
handler(e)
setTimeout(() => {
if (!diceInputRef.current) return;
e.target = diceInputRef.current;
bind.onChange(e);
}, 0)
}
return (
<>
<label className="w-min">
Count:&nbsp;
<input className="w-12" type="number" {...bindDiceCount}
onChange={onChange(bindDiceCount.onChange)}
/>
</label>
<label className="w-min">
Sides:&nbsp;
<select {...bindDiceSides}
onChange={onChange(bindDiceSides.onChange)}
>
<option value=""></option>
{DICE_SIDES.map(d => (
<option value={'d' + d}>{d}</option>
))}
</select>
</label>
<input ref={diceInputRef} className="hidden" type="text" name={bind.name} value={diceCount + diceSides} readOnly />
</>
);
}
case FieldTypes.type:
return (
<FieldTypeInput bind={bind} />
)
case FieldTypes.number:
return (
<label className="w-min">Value:<input className="w-16" type="number" {...bind} /></label>
)
case FieldTypes.text:
return (
<label className="w-min">Value:<input type="number" {...bind} /></label>
)
default:
return <></>;
}
}