From b8750d1058824f6a0add8245349767b69978f9bf Mon Sep 17 00:00:00 2001 From: Olivier Gagnon Date: Fri, 27 May 2022 20:41:14 -0400 Subject: [PATCH] Make a new InputComponent that can be re-used everywhere to make all text accept the same kind of input --- src/Faction/ui/DonateOption.tsx | 18 ++++++------------ src/ui/React/NumberInput.tsx | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 src/ui/React/NumberInput.tsx diff --git a/src/Faction/ui/DonateOption.tsx b/src/Faction/ui/DonateOption.tsx index bbfc4f72c..2dd997472 100644 --- a/src/Faction/ui/DonateOption.tsx +++ b/src/Faction/ui/DonateOption.tsx @@ -20,7 +20,7 @@ import { MathJaxWrapper } from "../../MathJaxWrapper"; import Typography from "@mui/material/Typography"; import Paper from "@mui/material/Paper"; import Button from "@mui/material/Button"; -import TextField from "@mui/material/TextField"; +import { NumberInput } from "../../ui/React/NumberInput"; type IProps = { faction: Faction; @@ -31,26 +31,20 @@ type IProps = { }; export function DonateOption(props: IProps): React.ReactElement { - const [donateAmt, setDonateAmt] = useState(null); + const [donateAmt, setDonateAmt] = useState(NaN); const digits = (CONSTANTS.DonateMoneyToRepDivisor + "").length - 1; function canDonate(): boolean { - if (donateAmt === null) return false; + if (isNaN(donateAmt)) return false; if (isNaN(donateAmt) || donateAmt <= 0) return false; if (props.p.money < donateAmt) return false; return true; } - function onChange(event: React.ChangeEvent): void { - const amt = numeralWrapper.parseMoney(event.target.value); - if (event.target.value === "" || isNaN(amt)) setDonateAmt(null); - else setDonateAmt(amt); - } - function donate(): void { const fac = props.faction; const amt = donateAmt; - if (amt === null) return; + if (isNaN(amt)) return; if (!canDonate()) return; props.p.loseMoney(amt, "other"); const repGain = repFromDonation(amt, props.p); @@ -85,8 +79,8 @@ export function DonateOption(props: IProps): React.ReactElement { ) : ( <> - { + onChange: (v: number) => void; +} + +export function NumberInput(props: IProps): React.ReactElement { + const textProps = { + ...props, + onChange: (event: React.ChangeEvent) => { + const amt = numeralWrapper.parseMoney(event.target.value); + if (event.target.value === "" || isNaN(amt)) props.onChange(NaN); + else props.onChange(amt); + }, + }; + return ; +}