UNPKG

@navinc/base-react-components

Version:
89 lines (81 loc) 2.42 kB
import React, { useRef, useEffect } from 'react' import styled from 'styled-components' import { Err, Errors, Field, FieldWrapper, Helper, Input, Label } from './form-elements/shared.js' import Copy from './copy' import { focusWithoutScroll } from '@navinc/utils' import { PasswordStrengthMeter } from './password-strength-meter.js' export const capitalizeString = (string = '') => string.replace(/^\w/, (c) => c.toUpperCase()) const StyledPasswordStrengthMeter = styled(PasswordStrengthMeter)` margin: 0 ${({ theme }) => theme.gu(2)}; text-align: 'left'; ` export const InputField = ({ autoFocus, children, className, label = '', hasSpaceForErrors, helperIcon, helperLinkAction, helperText, isInvalid, isStatic, value, required, type, errors = [], lede = '', touched, placeholder, passwordStrengthScore, requiredPasswordScore, ...props }) => { /* isStatic to be used to overcome auto-populated fields that do not read as values or placeholders */ const isVisited = touched || value || placeholder || isStatic const inputRef = useRef(null) useEffect(() => { if (autoFocus) { focusWithoutScroll(inputRef.current) } }, [autoFocus]) return ( <FieldWrapper className={className}> {lede && <Copy bold>{lede}</Copy>} <Field isVisited={isVisited} isInvalid={isInvalid} required={required} type={type}> <Input isInvalid={isInvalid} placeholder={placeholder} ref={inputRef} required={required} type={type} value={value} {...props} /> {children} <Label required={required} value={value}> {capitalizeString(label)} </Label> </Field> {helperText && ( <Helper iconName={helperIcon} helperLinkAction={helperLinkAction} hasSpaceForHelper={hasSpaceForErrors} helperText={helperText} /> )} {passwordStrengthScore >= 0 && ( <StyledPasswordStrengthMeter passwordStrengthScore={passwordStrengthScore} requiredPasswordScore={requiredPasswordScore} /> )} <Errors hasSpaceForErrors={hasSpaceForErrors}> {!!errors.length && errors.map((err, i) => <Err key={`err-${i}`}>{err}</Err>)} </Errors> </FieldWrapper> ) } const StyledInput = styled(InputField)`` export default StyledInput