|
| 1 | +import { useEffect, useState } from "react" |
1 | 2 | import { isNumber } from "./isNumber" |
2 | 3 |
|
3 | 4 | import "./Stepper.css" |
@@ -36,23 +37,51 @@ function clamp(value: number, min: number, max: number) { |
36 | 37 | } |
37 | 38 |
|
38 | 39 | export function Stepper({ value = 0, min = 0, step: stepAmount = 1, onChange }: Props) { |
| 40 | + const [inputValue, setInputValue] = useState<string>(() => String(value)) |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + setInputValue(String(value)) |
| 44 | + }, [value]) |
| 45 | + |
39 | 46 | const step = (direction: -1 | 1) => { |
40 | | - onChange(clamp(value + stepAmount * direction, 0, Infinity)) |
| 47 | + onChange(clamp(value + stepAmount * direction, min, Infinity)) |
| 48 | + } |
| 49 | + |
| 50 | + const commitInput = () => { |
| 51 | + const trimmed = inputValue.trim() |
| 52 | + if (trimmed === "") { |
| 53 | + setInputValue(String(value)) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + const parsed = Number(trimmed) |
| 58 | + if (!isNumber(parsed)) { |
| 59 | + setInputValue(String(value)) |
| 60 | + return |
| 61 | + } |
| 62 | + |
| 63 | + const snapped = Math.round(clamp(parsed, min, Infinity)) |
| 64 | + |
| 65 | + setInputValue(String(snapped)) |
| 66 | + onChange(snapped) |
41 | 67 | } |
42 | 68 |
|
43 | 69 | return ( |
44 | 70 | <div className="stepper"> |
45 | 71 | <input |
46 | 72 | className="stepper-input" |
47 | 73 | type="number" |
48 | | - value={value} |
| 74 | + value={inputValue} |
49 | 75 | min={min} |
50 | 76 | step={stepAmount} |
51 | 77 | onChange={event => { |
52 | | - const numberValue = event.currentTarget.valueAsNumber |
53 | | - const value = isNumber(numberValue) ? numberValue : 0 |
54 | | - |
55 | | - onChange(value) |
| 78 | + setInputValue(event.currentTarget.value) |
| 79 | + }} |
| 80 | + onBlur={commitInput} |
| 81 | + onKeyDown={event => { |
| 82 | + if (event.key === "Enter") { |
| 83 | + commitInput() |
| 84 | + } |
56 | 85 | }} |
57 | 86 | /> |
58 | 87 |
|
|
0 commit comments