63 lines
1.6 KiB
JavaScript
Raw Normal View History

import React from 'react'
import PropTypes from 'prop-types'
2020-02-13 19:40:04 -05:00
import { length } from 'stringz'
2020-04-23 02:13:29 -04:00
/**
* Renders a character counter
* @param {string} props.text - text to use to measure
* @param {number} props.max - max text allowed
*/
class CharacterCounter extends React.PureComponent {
2019-07-02 03:10:25 -04:00
2020-04-23 23:17:27 -04:00
render() {
2020-04-16 02:00:43 -04:00
const { text, max } = this.props
2020-04-23 02:13:29 -04:00
const actualRadius = 10
const radius = 8
2020-02-13 19:40:04 -05:00
const circumference = 2 * Math.PI * radius
2020-04-16 02:00:43 -04:00
const diff = Math.min(length(text), max) / max
2020-02-13 19:40:04 -05:00
const dashoffset = circumference * (1 - diff)
const circleClass = length(text) > max ? _s.strokeError : _s.strokeBrand
2020-01-27 14:46:42 -05:00
return (
<div className={[_s.d, _s.mr10, _s.jcCenter, _s.aiCenter].join(' ')}>
2020-04-23 23:17:27 -04:00
<svg
width={actualRadius * 2}
height={actualRadius * 2}
viewBox={`0 0 ${actualRadius * 2} ${actualRadius * 2}`}
>
<circle
fill='none'
cx={actualRadius}
cy={actualRadius}
r={radius}
fill='none'
strokeWidth='2'
className={_s.strokeSecondary}
2020-04-23 23:17:27 -04:00
/>
<circle
style={{
2020-02-13 19:40:04 -05:00
strokeDashoffset: dashoffset,
strokeDasharray: circumference,
}}
fill='none'
2020-02-28 10:20:47 -05:00
cx={actualRadius}
cy={actualRadius}
r={radius}
strokeWidth='2.25'
2020-02-13 19:40:04 -05:00
strokeLinecap='round'
className={circleClass}
2020-02-13 19:40:04 -05:00
/>
</svg>
2020-01-27 14:46:42 -05:00
</div>
)
2019-07-02 03:10:25 -04:00
}
}
CharacterCounter.propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
}
export default CharacterCounter