Skip to content

Instantly share code, notes, and snippets.

@fmal
Created August 11, 2020 09:39
Show Gist options
  • Save fmal/eeb83d562f098533ae67e18cab1fd8a5 to your computer and use it in GitHub Desktop.
Save fmal/eeb83d562f098533ae67e18cab1fd8a5 to your computer and use it in GitHub Desktop.
import PropTypes from 'prop-types';
import React from 'react';
import * as colors from '@powel/design-colors';
const uuid = () => {
let id = '';
let random;
let i;
for (i = 0; i < 32; i++) {
random = (Math.random() * 16) | 0;
id += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
}
return id;
};
const clamp = (value, min, max) => {
if (max < min) {
throw new Error('clamp: max cannot be less than min');
}
return Math.min(Math.max(value, min), max);
};
export default function PolygonIcon({ perc, ...otherProps }) {
perc = clamp(perc, 0, 100);
const maskId = `txtMask-${uuid()}`;
const fillId = `fill-${uuid()}`;
const polygonPath =
'M199.261484,0.5 L159.661484,99.5 L0.5,99.5 L0.5,0.5 L199.261484,0.5 Z';
const remainingPerc = Math.max(100 - perc, 0.001);
const textProps = {
textAnchor: 'middle',
dominantBaseline: 'central',
x: '45%',
y: '50%',
fontSize: 65,
fontWeight: 'bold'
};
return (
<svg viewBox="0 0 200 100" {...otherProps}>
<defs>
<linearGradient id={fillId} gradientTransform="rotate(90)">
<stop offset={`${remainingPerc}%`} stopColor={colors.colorGray10} />
<stop offset={`${remainingPerc}%`} stopColor={colors.colorBlue100} />
</linearGradient>
<mask id={maskId} x="0" y="0" width="100" height="100%">
<rect
width="100%"
height={`${perc}%`}
x="0"
y={`${remainingPerc}%`}
fill={colors.colorGray10}
/>
</mask>
</defs>
<path
d={polygonPath}
stroke={colors.colorGray100}
strokeWidth={4}
fill={`url(#${fillId})`}
/>
<text
className="value value--inverted"
fill={colors.colorGray125}
{...textProps}
>
{`${perc}%`}
</text>
<text mask={`url(#${maskId})`} className="value" {...textProps}>
{`${perc}%`}
</text>
</svg>
);
}
PolygonIcon.propTypes = {
perc: PropTypes.number.isRequired
};
<PolygonIcon perc={45} width="4rem" height="2rem" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment