/* eslint-disable react/require-default-props */ import React, { ChangeEvent, JSXElementConstructor, useState } from 'react'; import { Input, styled, FormGroup as FormGroupCompoonent, } from '@jarvisnetwork/ui'; import { Toggle } from '../ToggleSwitch'; const FormGroupStyled = styled(FormGroupCompoonent)` margin-bottom: 0px; .input { margin-top: 0; } `; const LabelWrapper = styled.div` display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; `; const InputWrapper = styled.div` height: 60px; .input { &.invalid .group { border: 1px solid red; } .group { overflow: hidden; & > :first-child { padding: 0; border-radius: unset; input { background: transparent; padding-left: 10px; } } } } `; const InputLabel = styled.div``; const inputRegex = /^\d*(?:\\[.])?\d*$/; // match escaped "." characters via in a non-capturing group const escapeRegExp = (string: string): string => string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string export type RenderFunction = (props: any) => Element; export const NumericalInput = React.memo( ({ placeholder, label, value, onUserInput, suffix, LabelComponent, onToggleChange, inputDisabled, isError, }: { placeholder: string; label: string; value: string; inputDisabled?: boolean; isError?: boolean; onUserInput: (val: string) => void; onToggleChange?: () => void; suffix?: React.ReactElement | JSXElementConstructor; LabelComponent?: RenderFunction; }) => { const [toggled, setToggled] = useState(false); const enforcer = (nextUserInput: string) => { if ( nextUserInput === '' || inputRegex.test(escapeRegExp(nextUserInput)) ) { onUserInput(nextUserInput); } }; const onToggle = () => { setToggled((val) => !val); if (!onToggleChange) return; onToggleChange(); }; return ( {LabelComponent ? ( ) : ( {label} )} {!!onToggleChange && } ) => enforcer(event.target.value.replace(/,/g, '.')) } suffix={suffix} autoComplete="off" autoCorrect="off" pattern="^[0-9]*[.,]?[0-9]*$" inputMode="decimal" minLength={1} maxLength={79} spellCheck="false" type="text" disabled={inputDisabled} /> ); } );