import type { FC } from '../../../lib/teact/teact'; import React, { useState, useEffect, useRef } from '../../../lib/teact/teact'; import type { ApiPollAnswer, ApiPollResult } from '../../../api/types'; import buildClassName from '../../../util/buildClassName'; import renderText from '../../common/helpers/renderText'; import './PollOption.scss'; type OwnProps = { answer: ApiPollAnswer; voteResults?: ApiPollResult[]; totalVoters?: number; maxVotersCount?: number; correctResults: string[]; shouldAnimate: boolean; }; const PollOption: FC = ({ answer, voteResults, totalVoters, maxVotersCount, correctResults, shouldAnimate, }) => { const result = voteResults && voteResults.find((r) => r.option === answer.option); const correctAnswer = correctResults.length === 0 || correctResults.indexOf(answer.option) !== -1; const showIcon = (correctResults.length > 0 && correctAnswer) || (result?.isChosen); const answerPercent = result ? getPercentage(result.votersCount, totalVoters || 0) : 0; const [finalPercent, setFinalPercent] = useState(shouldAnimate ? 0 : answerPercent); // eslint-disable-next-line no-null/no-null const lineRef = useRef(null); const lineWidth = result ? getPercentage(result.votersCount, maxVotersCount || 0) : 0; const isAnimationDoesNotStart = finalPercent !== answerPercent; useEffect(() => { if (shouldAnimate) { setFinalPercent(answerPercent); } }, [shouldAnimate, answerPercent]); useEffect(() => { const lineEl = lineRef.current; if (lineEl && shouldAnimate) { const svgEl = lineEl.firstElementChild; const style = isAnimationDoesNotStart ? '' : 'stroke-dasharray: 100% 200%; stroke-dashoffset: -44'; if (!svgEl) { lineEl.innerHTML = ` `; } else { svgEl.setAttribute('style', style); } } }, [isAnimationDoesNotStart, shouldAnimate]); if (!voteResults || !result) { return undefined; } const lineStyle = `width: ${lineWidth}%; transform:scaleX(${isAnimationDoesNotStart ? 0 : 1})`; return (
{answerPercent}% {showIcon && ( )}
{renderText(answer.text)}
); }; function getPercentage(value: number, total: number) { return total > 0 ? ((value / total) * 100).toFixed() : 0; } export default PollOption;