/* @flow */ import React, { useCallback, useEffect, useMemo, useState } from 'react' import classnames from 'classnames' import { buildAriaProps, buildCss, buildDataProps } from '../utilities/props' import { globalProps } from '../utilities/globalProps.js' import { zxcvbnPasswordScore } from './passwordStrength.js' import { Body, Caption, Flex, Icon, PbReactPopover, ProgressSimple, TextInput } from '../' type PassphraseProps = { aria?: object, averageThreshold?: number, common?: boolean, confirmation?: boolean, className?: string, data?: object, dark?: boolean, id?: string, inputProps?: {}, label?: string, minLength?: number, onChange: (String) => void, showTipsBelow?: 'always' | 'xs' | 'sm' | 'md' | 'lg' | 'xl', onStrengthChange?: (number) => void, strongThreshold?: number, tips?: Array, uncontrolled?: boolean, value: string, } const Passphrase = (props: PassphraseProps) => { const { aria = {}, averageThreshold = 2, className, common = false, confirmation = false, dark = false, data = {}, id, inputProps = {}, label = confirmation ? 'Confirm Passphrase' : 'Passphrase', minLength, onChange = () => {}, showTipsBelow = 'always', onStrengthChange, strongThreshold = 3, tips = [], uncontrolled = false, value = '', } = props const [uncontrolledValue, setUncontrolledValue] = useState('') const handleChange = useCallback( (e) => uncontrolled ? setUncontrolledValue(e.target.value) : onChange(e), [uncontrolled, onChange] ) const displayValue = useMemo( () => (uncontrolled ? uncontrolledValue : value), [value, uncontrolledValue, uncontrolled], ) const [showPopover, setShowPopover] = useState(false) const toggleShowPopover = () => setShowPopover(!showPopover) const [showPassphrase, setShowPassphrase] = useState(false) const toggleShowPassphrase = () => setShowPassphrase(!showPassphrase) const ariaProps = buildAriaProps(aria) const dataProps = buildDataProps(data) const classes = classnames(buildCss('pb_passphrase'), globalProps(props), className) const calculator = useMemo( () => confirmation ? { test: () => ({}) } : zxcvbnPasswordScore({ averageThreshold, strongThreshold, minLength }), [averageThreshold, confirmation, strongThreshold, minLength] ) const { percent: progressPercent, variant: progressVariant, text: strengthLabel, strength } = calculator.test(displayValue, common) useEffect(() => { if (typeof onStrengthChange === 'function') { onStrengthChange(strength) } }, [strength]) const tipClass = classnames( (dark ? 'dark' : null), (showTipsBelow === 'always' ? null : `show-below-${showTipsBelow}`), ) const popoverReference = ( ) return (
) } export default Passphrase