// Copyright 2019-2020 @polkadot/extension-ui authors & contributors // SPDX-License-Identifier: Apache-2.0 import { ThemeProps } from '../types'; import React, { useState, useEffect } from 'react'; import styled from 'styled-components'; import { Result, Validator } from '../util/validators'; interface BasicProps { isError?: boolean; value?: string; onChange?: (value: string) => void; } type Props = T & { className?: string; validator: Validator; component: React.ComponentType; onValidatedChange: (value: string | null) => void; defaultValue?: string; } function ValidatedInput> ({ className, component: Input, defaultValue, onValidatedChange, validator, ...props }: Props): React.ReactElement> { const [value, setValue] = useState(defaultValue || ''); const [wasMounted, setWasMounted] = useState(false); const [validationResult, setValidationResult] = useState>(Result.ok('')); useEffect(() => { if (!wasMounted) { setWasMounted(true); } // eslint-disable-next-line @typescript-eslint/no-floating-promises (async (): Promise => { const result = await validator(value); setValidationResult(result); onValidatedChange(Result.isOk(result) ? value : null); })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [value, validator, onValidatedChange]); return (
{Result.isError(validationResult) && {validationResult.error.errorDescription}}
); } const ErrorMessage = styled.span` display: block; margin-top: -10px; font-size: ${({ theme }: ThemeProps): string => theme.labelFontSize}; line-height: ${({ theme }: ThemeProps): string => theme.labelLineHeight}; color: ${({ theme }: ThemeProps): string => theme.errorColor}; `; ErrorMessage.displayName = 'ErrorMessage'; export default ValidatedInput;