import React, { ChangeEvent, useRef } from 'react'; export interface ICounter { className?: string; disabled?: boolean; id?: string; label?: string; name?: string; max?: string | number; min?: string | number; style?: React.CSSProperties; placeholder?: string; value: any; setValue(param: any): void; [x: string]: any; } export const Counter: React.FC = (props) => { const { className = '', disabled, id, label, name, min = 0, max = 100, placeholder, style, value, setValue, ...otherProps } = props; function isInt(n: any) { return n % 1 === 0; } function hasLeadingZero(str: any) { return str.length > 1 && str.startsWith('0'); } function isValidNumber(value: any) { return !hasLeadingZero(value) && isInt(value); } const handleCountChange = (e: ChangeEvent) => { const intValue = parseInt(e.target.value); const intMin = parseInt(e.target.min); const intMax = parseInt(e.target.max); if (isValidNumber(e.target.value)) { if (intValue > intMax) { setValue(max); } else if (intValue < intMin) { setValue(min); } else if (e.target.value === '') { setValue(''); } else { setValue(parseInt(e.target.value, 10)); } } else { return; } }; const handleDecrement = () => { if (value > min) { setValue(value - 1); } }; const handleIncrement = () => { if (value < max) { setValue(value + 1); } }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'ArrowUp') { handleIncrement(); } else if (e.key === 'ArrowDown') { handleDecrement(); } }; const handleBlur = (e: React.FocusEvent) => { if (e.target.value.trim() === '') { setValue(min); } }; return (
{label && ( )}
); };