import React, { forwardRef } from 'react'; import cuid from 'cuid'; import isChromatic from 'chromatic/isChromatic'; import Call from '../../assets/icons/Call'; import PhoneAndroid from '../../assets/icons/PhoneAndroid'; import { Spacer } from '../../foundations/Layout'; import { filterGlobalProps } from '@lendi-ui/commons/utils'; import { ErrorText, HelpText, FieldLabel, ClearActionButton, useClearAction } from '../TextField'; import type { InputFieldBaseProps, InputProps } from '../TextField'; import { Input, PhoneIconWrapper, MobileIconWrapper, Wrapper } from './PhoneField.style'; import { getPattern } from './utils'; import { useTheme } from '../../foundations/Theme'; interface PhoneFieldProps extends Omit { variant?: 'mobile'; } export type PhoneFieldComponentProps = InputProps; const filterAlphabet = (value: string) => value.replace(/\D*/g, ''); const handleFormatting = (value?: string) => { // because we handle uncontrolled, this function could receive undefined. if (value) { return filterAlphabet(value); } return value; }; const PhoneFieldComponent = ( { inputId, name, variant, helpText, errorText, validationState, placeholder, ariaLabel, ariaLabelledBy, label, labelSuffix, inlineAction, isRequired, isDisabled, value, defaultValue, onChange, width = '100%', maxCharCount, minCharCount, minWidth, maxWidth, ...props }: PhoneFieldComponentProps, ref: React.Ref ) => { const globalProps = filterGlobalProps(props); const inputElId = isChromatic() ? '1' : inputId ?? cuid(); const helpTextId = isChromatic() ? '2' : cuid(); const errorTextId = isChromatic() ? '3' : cuid(); const hasError = errorText && validationState === 'invalid'; const theme = useTheme(); const handleValueChange = (e: React.ChangeEvent) => { if (e.target.value !== '') { e.target.value = handleFormatting(e.target.value) ?? ''; } if (onChange) { onChange(e); } }; const { isCleared, handleChange, clearValue } = useClearAction(handleValueChange, ref, value); const ariaDescribedBy = []; if (helpText) { ariaDescribedBy.push(helpTextId); } if (hasError) { ariaDescribedBy.push(errorTextId); } return ( {label && } {variant === 'mobile' ? ( ) : ( )} 0 ? ariaDescribedBy.join(' ') : undefined} required={isRequired} disabled={isDisabled} maxLength={maxCharCount} minLength={minCharCount} value={value && isCleared ? '' : handleFormatting(value)} defaultValue={handleFormatting(defaultValue)} onChange={handleChange} ref={ref} hasRightItem={!!inlineAction} variant={variant} /> {inlineAction === 'clear' && } {helpText && } {hasError && errorText && } ); }; export const PhoneField = forwardRef(PhoneFieldComponent);