| 1 | import React, { useState } from "react"; |
| 2 | |
| 3 | interface NumberInputProps { |
| 4 | value: number; |
| 5 | onChange: (value: number) => void; |
| 6 | max: number; |
| 7 | min: number; |
| 8 | } |
| 9 | |
| 10 | const NumberInput: React.FC<NumberInputProps> = ({ |
| 11 | value, |
| 12 | onChange, |
| 13 | max, |
| 14 | min, |
| 15 | }) => { |
| 16 | const [inputValue, setInputValue] = useState(value.toString()); |
| 17 | |
| 18 | const handleIncrement = () => { |
| 19 | if (value < max) { |
| 20 | const newValue = value + 1; |
| 21 | onChange(newValue); |
| 22 | setInputValue(newValue.toString()); |
| 23 | } |
| 24 | }; |
| 25 | |
| 26 | const handleDecrement = () => { |
| 27 | if (value > min) { |
| 28 | const newValue = value - 1; |
| 29 | onChange(newValue); |
| 30 | setInputValue(newValue.toString()); |
| 31 | } |
| 32 | }; |
| 33 | |
| 34 | const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { |
| 35 | const newInputValue = e.target.value; |
| 36 | setInputValue(newInputValue); |
| 37 | |
| 38 | // Only update the actual value if it's a valid number |
| 39 | const numValue = parseInt(newInputValue, 10); |
| 40 | if (!isNaN(numValue)) { |
| 41 | // Apply min/max constraints |
| 42 | const constrainedValue = Math.min(Math.max(numValue, min), max); |
| 43 | onChange(constrainedValue); |
| 44 | } |
| 45 | }; |
| 46 | |
| 47 | const handleBlur = () => { |
| 48 | // When input loses focus, ensure the displayed value matches the actual value |
| 49 | // This handles cases where the user entered an invalid value |
| 50 | setInputValue(value.toString()); |
| 51 | }; |
| 52 | |
| 53 | return ( |
| 54 | <div className="border-vsc-input-border bg-vsc-input-background flex flex-row overflow-hidden rounded-md border border-solid"> |
| 55 | <input |
| 56 | type="text" |
| 57 | value={inputValue} |
| 58 | onChange={handleInputChange} |
| 59 | onBlur={handleBlur} |
| 60 | className="text-vsc-foreground max-w-9 border-none bg-inherit pr-1.5 text-right outline-none ring-0 focus:border-none focus:outline-none focus:ring-0" |
| 61 | style={{ |
| 62 | appearance: "none", |
| 63 | WebkitAppearance: "none", |
| 64 | MozAppearance: "none", |
| 65 | }} |
| 66 | min={min} |
| 67 | max={max} |
| 68 | /> |
| 69 | <div className="flex flex-col"> |
| 70 | <button |
| 71 | style={{ fontSize: "9px" }} |
| 72 | onClick={handleIncrement} |
| 73 | disabled={value >= max} |
| 74 | className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80" |
| 75 | > |
| 76 | ▲ |
| 77 | </button> |
| 78 | <button |
| 79 | style={{ fontSize: "9px" }} |
| 80 | className="text-vsc-foreground m-0 mb-0.5 cursor-pointer border-none bg-inherit px-1.5 py-0 hover:opacity-80" |
| 81 | onClick={handleDecrement} |
| 82 | disabled={value <= min} |
| 83 | > |
| 84 | ▼ |
| 85 | </button> |
| 86 | </div> |
| 87 | </div> |
| 88 | ); |
| 89 | }; |
| 90 | |
| 91 | export default NumberInput; |