bigbuffet-rw/app/soapbox/components/poll.tsx

260 lines
7.6 KiB
TypeScript
Raw Normal View History

import classNames from 'classnames';
import React, { useState } from 'react';
import { defineMessages, useIntl, FormattedMessage } from 'react-intl';
2022-03-26 16:11:26 -07:00
import { spring } from 'react-motion';
2022-03-26 17:53:51 -07:00
import { useDispatch } from 'react-redux';
import { openModal } from 'soapbox/actions/modals';
2022-01-10 14:01:24 -08:00
import { vote, fetchPoll } from 'soapbox/actions/polls';
import Icon from 'soapbox/components/icon';
2022-03-26 20:05:41 -07:00
import { Text, Button, Stack, HStack } from 'soapbox/components/ui';
2022-01-10 14:01:24 -08:00
import Motion from 'soapbox/features/ui/util/optional_motion';
import { useAppSelector } from 'soapbox/hooks';
2022-01-10 14:01:24 -08:00
import RelativeTimestamp from './relative_timestamp';
2020-03-27 13:59:38 -07:00
import type { Poll as PollEntity, PollOption as PollOptionEntity } from 'soapbox/types/entities';
2022-03-26 16:11:26 -07:00
2020-03-27 13:59:38 -07:00
const messages = defineMessages({
closed: { id: 'poll.closed', defaultMessage: 'Closed' },
voted: { id: 'poll.voted', defaultMessage: 'You voted for this answer' },
votes: { id: 'poll.votes', defaultMessage: '{votes, plural, one {# vote} other {# votes}}' },
2020-03-27 13:59:38 -07:00
});
2022-03-26 17:53:51 -07:00
const PollPercentageBar: React.FC<{percent: number, leading: boolean}> = ({ percent, leading }): JSX.Element => {
return (
<Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}>
{({ width }) =>(
<span
2022-03-26 20:05:41 -07:00
className={classNames('absolute inset-0 h-full inline-block rounded bg-gray-300 dark:bg-slate-900', {
'bg-primary-300 dark:bg-primary-400': leading,
})}
style={{ width: `${width}%` }}
/>
)}
</Motion>
);
};
interface IPollOptionText extends IPollOption {
percent: number,
}
2022-03-26 17:53:51 -07:00
const PollOptionText: React.FC<IPollOptionText> = ({ poll, option, index, active, percent, showResults, onToggle }) => {
const intl = useIntl();
const voted = poll.own_votes?.includes(index);
2022-03-26 20:05:41 -07:00
const message = intl.formatMessage(messages.votes, { votes: option.votes_count });
2022-03-26 20:05:41 -07:00
const handleOptionChange: React.EventHandler<React.ChangeEvent> = () => {
onToggle(index);
};
2022-03-26 20:05:41 -07:00
const handleOptionKeyPress: React.EventHandler<React.KeyboardEvent> = e => {
if (e.key === 'Enter' || e.key === ' ') {
onToggle(index);
e.stopPropagation();
e.preventDefault();
}
};
return (
2022-03-26 20:05:41 -07:00
<label
className={classNames('relative', { 'cursor-pointer': !showResults })}
title={showResults ? message : undefined}
>
<input
2022-03-26 20:05:41 -07:00
className='hidden'
name='vote-options'
type={poll.multiple ? 'checkbox' : 'radio'}
value={index}
checked={active}
onChange={handleOptionChange}
/>
<HStack alignItems='center' className='p-1 text-gray-900 dark:text-gray-300'>
2022-03-26 20:05:41 -07:00
{!showResults && (
<span
2022-04-16 19:08:18 -07:00
className={classNames('inline-block w-4 h-4 flex-none mr-2.5 border border-solid border-primary-600 rounded-full', {
2022-03-26 20:05:41 -07:00
'bg-primary-600': active,
'rounded': poll.multiple,
})}
tabIndex={0}
role={poll.multiple ? 'checkbox' : 'radio'}
onKeyPress={handleOptionKeyPress}
aria-checked={active}
aria-label={option.title}
/>
)}
2022-03-26 20:05:41 -07:00
{showResults && (
<HStack space={2} alignItems='center' className='mr-2.5'>
{voted ? (
<Icon src={require('@tabler/icons/icons/check.svg')} title={intl.formatMessage(messages.voted)} />
) : (
<div className='svg-icon' />
)}
<span className='font-bold'>{Math.round(percent)}%</span>
</HStack>
)}
2022-03-26 20:05:41 -07:00
<span dangerouslySetInnerHTML={{ __html: option.title_emojified }} />
</HStack>
</label>
);
};
interface IPollOption {
poll: PollEntity,
option: PollOptionEntity,
index: number,
showResults?: boolean,
active: boolean,
onToggle: (value: number) => void,
}
const PollOption: React.FC<IPollOption> = (props): JSX.Element | null => {
const { poll, option, showResults } = props;
if (!poll) return null;
const percent = poll.votes_count === 0 ? 0 : (option.votes_count / poll.votes_count) * 100;
const leading = poll.options.filterNot(other => other.title === option.title).every(other => option.votes_count >= other.votes_count);
return (
2022-03-26 20:05:41 -07:00
<div className='relative mb-2.5' key={option.title}>
{showResults && (
<PollPercentageBar percent={percent} leading={leading} />
)}
<PollOptionText percent={percent} {...props} />
2022-03-26 20:05:41 -07:00
</div>
);
};
2022-03-26 17:53:51 -07:00
const RefreshButton: React.FC<{poll: PollEntity}> = ({ poll }): JSX.Element => {
const dispatch = useDispatch();
2022-03-26 20:05:41 -07:00
const handleRefresh: React.EventHandler<React.MouseEvent> = (e) => {
dispatch(fetchPoll(poll.id));
e.stopPropagation();
e.preventDefault();
};
2022-03-26 17:53:51 -07:00
return (
<span>
2022-03-26 20:05:41 -07:00
<button className='underline' onClick={handleRefresh}>
2022-03-26 17:53:51 -07:00
<Text><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></Text>
</button>
</span>
);
};
const VoteButton: React.FC<{poll: PollEntity, selected: Selected}> = ({ poll, selected }): JSX.Element => {
const dispatch = useDispatch();
2022-03-26 20:05:41 -07:00
const handleVote = () => dispatch(vote(poll.id, Object.keys(selected)));
2022-03-26 17:53:51 -07:00
return (
2022-03-26 20:05:41 -07:00
<Button onClick={handleVote} theme='ghost'>
2022-03-26 17:53:51 -07:00
<FormattedMessage id='poll.vote' defaultMessage='Vote' />
2022-03-26 20:05:41 -07:00
</Button>
2022-03-26 17:53:51 -07:00
);
};
interface IPollFooter {
poll: PollEntity,
showResults: boolean,
selected: Selected,
2022-03-26 16:11:26 -07:00
}
2022-03-26 17:53:51 -07:00
const PollFooter: React.FC<IPollFooter> = ({ poll, showResults, selected }): JSX.Element => {
const intl = useIntl();
const timeRemaining = poll.expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.expires_at} futureDate />;
return (
2022-03-26 20:05:41 -07:00
<Stack space={2}>
{!showResults && <div><VoteButton poll={poll} selected={selected} /></div>}
2022-03-26 17:53:51 -07:00
<Text>
{showResults && (
<><RefreshButton poll={poll} /> · </>
)}
<FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.votes_count }} />
{poll.expires_at && <span> · {timeRemaining}</span>}
</Text>
2022-03-26 20:05:41 -07:00
</Stack>
2022-03-26 17:53:51 -07:00
);
};
type Selected = Record<number, boolean>;
interface IPoll {
id: string,
status?: string,
}
2020-03-27 13:59:38 -07:00
const Poll: React.FC<IPoll> = ({ id, status }): JSX.Element | null => {
const dispatch = useDispatch();
const me = useAppSelector((state) => state.me);
const poll = useAppSelector((state) => state.polls.get(id));
2020-03-27 13:59:38 -07:00
const [selected, setSelected] = useState({} as Selected);
const openUnauthorizedModal = () => {
dispatch(openModal('UNAUTHORIZED', {
action: 'POLL_VOTE',
ap_id: status,
}));
};
2022-03-26 16:11:26 -07:00
const toggleOption = (value: number) => {
2022-03-26 16:11:26 -07:00
if (me) {
if (poll?.multiple) {
const tmp = { ...selected };
if (tmp[value]) {
delete tmp[value];
} else {
tmp[value] = true;
}
setSelected(tmp);
2020-03-27 13:59:38 -07:00
} else {
2022-03-26 17:53:51 -07:00
const tmp: Selected = {};
2020-03-27 13:59:38 -07:00
tmp[value] = true;
setSelected(tmp);
2020-03-27 13:59:38 -07:00
}
} else {
openUnauthorizedModal();
2020-03-27 13:59:38 -07:00
}
};
if (!poll) return null;
const showResults = poll.voted || poll.expired;
return (
<div onClick={e => e.stopPropagation()}>
<Stack className={classNames('my-2', { voted: poll.voted })}>
<Stack>
{poll.options.map((option, i) => (
<PollOption
key={i}
poll={poll}
option={option}
index={i}
showResults={showResults}
active={!!selected[i]}
onToggle={toggleOption}
/>
))}
2022-03-26 20:05:41 -07:00
</Stack>
2020-03-27 13:59:38 -07:00
<PollFooter
poll={poll}
showResults={showResults}
selected={selected}
/>
</Stack>
</div>
);
};
2022-03-26 16:11:26 -07:00
export default Poll;