import React, { memo, useCallback, useMemo } from 'react'; import styled from 'styled-components'; import measureStrength from '../measureStrength'; import './PasswordStrenghtBar.css'; type SIZES = 'small' | 'medium' | 'large' | 'huge'; const Point = styled.li<{ size?: SIZES; bgColor?: string }>` background: #ddd; border-radius: 2px; display: inline-block; height: 5px; margin-right: 1px; width: 20px; &:last-child { margin: 0 !important; } ${({ size }) => size === 'small' && 'height: 2px;'} ${({ size }) => size === 'large' && 'height: 10px;'} ${({ size }) => size === 'huge' && 'height: 15px;'} ${({ bgColor }) => bgColor && `background-color: ${bgColor};`} `; const colors: string[] = ['#F00', '#F90', '#FF0', '#9F0', '#0F0']; function getColor(s: number) { let idx = 0; if (s <= 10) { idx = 0; } else if (s <= 20) { idx = 1; } else if (s <= 30) { idx = 2; } else if (s <= 40) { idx = 3; } else { idx = 4; } return { idx: idx + 1, col: colors[idx] }; } interface IProps { password: string; label?: string; size?: SIZES; } export function PasswordStrenghtBar({ size, password, label }: IProps) { const getPoints = useCallback( (force) => { let pts: any = []; for (let i = 0; i < 5; i += 1) { pts = [ ...pts, ]; } return pts; }, [size] ); const strength = useMemo(() => getColor(measureStrength(password)), [ password ]); const points = useMemo(() => getPoints(strength), [getPoints, strength]); return ( <> {label ?? 'Sicurezza password:'} ); } export default memo(PasswordStrenghtBar);