All files / molecule/phoneInput/src index.js

100% Statements 30/30
97.56% Branches 40/41
100% Functions 10/10
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                        1x 1x                                                   25x 25x 25x 25x 25x 25x     25x   25x                     25x 15x 5x         1x       15x 15x 15x       25x 16x       25x 13x   13x   13x               25x           4x                                                                               16x           2x 2x                                             1x   1x                                                                                            
import {useEffect, useRef, useState} from 'react'
 
import cx from 'classnames'
import PropTypes from 'prop-types'
 
import {inputSizes, inputTypes} from '@s-ui/react-atom-input'
import MoleculeDropdownList, {moleculeDropdownListDesigns} from '@s-ui/react-molecule-dropdown-list'
import MoleculeDropdownOption from '@s-ui/react-molecule-dropdown-option'
import MoleculeInputField from '@s-ui/react-molecule-input-field'
 
import {FLAG_SIZE, phoneValidationType} from './settings.js'
 
const BASE_CLASS = 'sui-MoleculePhoneInput'
const NOOP = () => {}
 
export {PREFIXES} from './settings.js'
export default function MoleculePhoneInput({
  autoHideHelpText = false,
  disabled,
  dropdownCloseIcon,
  dropdownIcon,
  hasError,
  helpText,
  id,
  label,
  name,
  onChange,
  onPrefixChange = NOOP,
  placeholder,
  prefixes = [],
  rightIcon,
  initialSelectedPrefix = prefixes[0],
  setFormattedValue,
  successText,
  type = phoneValidationType.DEFAULT,
  value = '',
  visiblePrefixes: visiblePrefixesProp = true,
  ...props
}) {
  const [showDropdown, setShowDropdown] = useState(false)
  const [selectedPrefix, setSelectedPrefix] = useState(initialSelectedPrefix)
  const [isLandLine, setIsLandLine] = useState(false)
  const modalRef = useRef(null)
  const inputPrefixRef = useRef(null)
  const inputMask = selectedPrefix && {
    mask: isLandLine ? selectedPrefix.mask.landlineMask : selectedPrefix.mask.mobileMask
  }
  const visiblePrefixes = visiblePrefixesProp && prefixes.length > 1
 
  const baseClass = cx(
    {
      disabled,
      splitted: type === phoneValidationType.SPLITTED,
      [`${BASE_CLASS}--error`]: hasError,
      withLabel: !!label
    },
    BASE_CLASS
  )
 
  // Close dropdown when click outside
  useEffect(() => {
    const handleClickOutside = event => {
      if (
        modalRef.current &&
        !modalRef.current.contains(event.target) &&
        !inputPrefixRef.current.contains(event.target)
      ) {
        setShowDropdown(false)
      }
    }
 
    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [])
 
  useEffect(() => {
    onPrefixChange(selectedPrefix)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedPrefix])
 
  const handlePhoneChange = (e, {value}) => {
    setIsLandLine(selectedPrefix.landlinePrefixs.includes(value[0]))
 
    typeof setFormattedValue === 'function' && setFormattedValue(value)
 
    typeof onChange === 'function' &&
      onChange(e, {
        name: name ?? id,
        prefix: selectedPrefix.countryCode,
        value: value.toString().replace(/\s/g, ''), // remove spaces from value
        isLandLine
      })
  }
  return (
    <div className={baseClass}>
      <div className={`${baseClass}-input`}>
        <div
          ref={inputPrefixRef}
          className={`${baseClass}-input-prefix`}
          onClick={() => !disabled && setShowDropdown(!showDropdown)}
        >
          {selectedPrefix && (
            <img
              height={FLAG_SIZE}
              width={FLAG_SIZE}
              className={`${baseClass}-input-prefix-flag`}
              src={selectedPrefix?.flag}
            />
          )}
          {visiblePrefixes && (showDropdown ? dropdownCloseIcon : dropdownIcon)}
        </div>
        <div className={`${baseClass}-input-phoneContainer`}>
          {selectedPrefix && <p className={`${baseClass}-input-prefix-code`}>{selectedPrefix.countryCode}</p>}
          <MoleculeInputField
            {...{
              ...props,
              autoHideHelpText,
              id,
              label,
              name,
              placeholder,
              successText
            }}
            {...(hasError ? {errorText: helpText} : {helpText})}
            disabled={disabled}
            mask={inputMask}
            noBorder
            onChange={handlePhoneChange}
            size={inputSizes.SMALL}
            type={inputTypes.MASK}
            value={value.toString()}
          />
          {rightIcon && <div className={`${baseClass}-input-icon`}>{rightIcon}</div>}
        </div>
      </div>
      {showDropdown && visiblePrefixes && (
        <div className={`${baseClass}-dropdown`}>
          <MoleculeDropdownList design={moleculeDropdownListDesigns.FLAT} ref={modalRef} visible={visiblePrefixes}>
            {prefixes.map(prefix => {
              return (
                <MoleculeDropdownOption
                  value={prefix.value}
                  selected={selectedPrefix.value === prefix.value}
                  key={prefix.countryCode}
                  onClick={() => {
                    setSelectedPrefix(prefix)
                    setShowDropdown(false)
                  }}
                >
                  <div className={`${baseClass}-dropdown-option`}>
                    <img
                      height={FLAG_SIZE}
                      width={FLAG_SIZE}
                      className={`${baseClass}-dropdown-option-label`}
                      src={prefix.flag}
                    />
                    <span className={`${baseClass}-dropdown-option-label`}>{prefix.label}</span>
                    <span className={`${baseClass}-dropdown-option-code`}>({prefix.countryCode})</span>
                  </div>
                </MoleculeDropdownOption>
              )
            })}
          </MoleculeDropdownList>
        </div>
      )}
    </div>
  )
}
 
MoleculePhoneInput.displayName = 'MoleculePhoneInput'
 
MoleculePhoneInput.propTypes = {
  dropdownCloseIcon: PropTypes.node,
  dropdownIcon: PropTypes.node,
  value: PropTypes.string,
  placeholder: PropTypes.string,
  prefixes: PropTypes.array,
  onChange: PropTypes.func,
  setFormattedValue: PropTypes.func,
  type: PropTypes.oneOf(Object.values(phoneValidationType)),
  initialSelectedPrefix: PropTypes.shape({
    value: PropTypes.string,
    label: PropTypes.string,
    countryCode: PropTypes.string,
    mask: PropTypes.string
  }),
 
  /** Boolean to decide if the helptext should be displayed as an error or as explanatory text */
  hasError: PropTypes.bool,
  visiblePrefixes: PropTypes.bool,
 
  /** Boolean to decide if the helptext should be auto hide */
  autoHideHelpText: PropTypes.bool,
  /** Success message to display when success state  */
  successText: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
 
  /** Help Text to display */
  helpText: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
 
  /** Name to set in the input tag */
  name: PropTypes.string,
 
  /** Id to set in the input tag */
  id: PropTypes.string,
 
  /** Label to set in the molecule field */
  label: PropTypes.string,
 
  /** Callback dispatch when selected prefix changes */
  onPrefixChange: PropTypes.func,
 
  /** Icon to display on the right of the input */
  rightIcon: PropTypes.node,
 
  /** Boolean to disable the input */
  disabled: PropTypes.bool
}