okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
1.5 KiB28 linesraw
1import { useEffect, useState } from 'react';
2import { parseDecimal, partialDecimal } from '../lib/decimal';
3
4/** A number field that lets the person type a decimal point: it keeps the text while it is typed and tells the page the number once it is one (#3736). */
5export function DecimalInput({ value, onChange, ariaLabel, className = 'st-input', placeholder, disabled }: {
6  value: number | null | undefined;
7  onChange: (value: number | null) => void;
8  ariaLabel: string;
9  className?: string;
10  placeholder?: string;
11  disabled?: boolean;
12}) {
13  const [text, setText] = useState(value === null || value === undefined ? '' : String(value));
14  // A change that came from elsewhere (Restore saved, another tab) replaces the text, but never while the typed text already means this number.
15  useEffect(() => {
16    const shown = text === '' ? null : parseDecimal(text);
17    if ((value ?? null) !== shown) setText(value === null || value === undefined ? '' : String(value));
18  }, [value]);
19  return <input className={className} aria-label={ariaLabel} inputMode="decimal" disabled={disabled} placeholder={placeholder} value={text}
20    onChange={e => {
21      const next = e.target.value;
22      if (!partialDecimal(next)) return;
23      setText(next);
24      if (next.trim() === '') onChange(null);
25      else { const n = parseDecimal(next); if (n !== null) onChange(n); }
26    }}
27    onBlur={() => { const n = text.trim() === '' ? null : parseDecimal(text); setText(n === null ? '' : String(n)); }}/>;
28}