import React, { memo } from 'react';
import { string, oneOf } from 'prop-types';
import styled from 'styled-components';
import measureStrength from '../measureStrength';
import './index.css';
/**
* @constant
*/
const Point = styled.li`
background: #ddd;
border-radius: 2px;
display: inline-block;
height: 5px;
margin-right: 1px;
width: 20px;
&:last-child {
margin: 0 !important;
}
${props => props.size === 'small' && `height: 2px;`}
${props => props.size === 'large' && `height: 10px;`}
${props => props.size === 'huge' && `height: 15px;`}
${props => props.bgColor && `background-color: ${props.bgColor};`}
`;
/**
* List of colors
* @constant {string[]}
*/
const colors = ['#F00', '#F90', '#FF0', '#9F0', '#0F0'];
/**
* Get color and idx by an argument
* @param {number} s
*/
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
*/
function PasswordStrenghtBar({ size, password, label }) {
const getPoints = force => {
const pts = [];
for (let i = 0; i < 5; i++) {
pts.push(
<Point size={size} key={i} bgColor={i < force.idx && force.col} />
);
}
return pts;
};
const strength = getColor(measureStrength(password));
const points = 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);