import React, { memo, useCallback, useMemo } from 'react';
import { string, oneOf } from 'prop-types';
import styled from 'styled-components';
import measureStrength from './../measureStrength';
import './PasswordStrenghtBar.css';
const Point = styled.li`
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 = ['#F00', '#F90', '#FF0', '#9F0', '#0F0'];
function getColor(s) {
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] };
}
/**
* PasswordStrenghtBar component
*
* @param {Object} props
* @param {string} props.size
* @param {string} props.password
* @param {string} props.label
*/
export function PasswordStrenghtBar({ size, password, label }) {
const getPoints = useCallback(
(force) => {
let pts = [];
for (let i = 0; i < 5; i++) {
pts = [...pts, <Point size={size} key={i} bgColor={i < force.idx && force.col} />];
}
return pts;
},
[size]
);
const strength = useMemo(() => getColor(measureStrength(password)), [password]);
const points = useMemo(() => getPoints(strength), [getPoints, strength]);
return (
<>
<small>{label}</small>
<ul>{points}</ul>
</>
);
}
PasswordStrenghtBar.propTypes = {
password: string.isRequired,
label: string,
size: oneOf(['small', 'medium', 'large', 'huge'])
};
PasswordStrenghtBar.defaultProps = {
label: 'Sicurezza password:',
size: 'medium'
};
export default memo(PasswordStrenghtBar);