import { gql, useMutation } from '@apollo/client' import Button from 'react-bootstrap/Button' import { fixedDecimal, numWithUnits } from '@/lib/format' import { timeLeft } from '@/lib/time' import { useMe } from './me' import styles from './poll.module.css' import Check from '@/svgs/checkbox-circle-fill.svg' import { signIn } from 'next-auth/react' import ActionTooltip from './action-tooltip' import { POLL_COST } from '@/lib/constants' import { payOrLoginError, useInvoiceModal } from './invoice' export default function Poll ({ item }) { const me = useMe() const [pollVote] = useMutation( gql` mutation pollVote($id: ID!, $hash: String, $hmac: String) { pollVote(id: $id, hash: $hash, hmac: $hmac) }`, { update (cache, { data: { pollVote } }) { cache.modify({ id: `Item:${item.id}`, fields: { poll (existingPoll) { const poll = { ...existingPoll } poll.meVoted = true poll.count += 1 return poll } } }) cache.modify({ id: `PollOption:${pollVote}`, fields: { count (existingCount) { return existingCount + 1 }, meVoted () { return true } } }) } } ) const PollButton = ({ v }) => { const showInvoiceModal = useInvoiceModal(async ({ hash, hmac }, { variables }) => { await pollVote({ variables: { ...variables, hash, hmac } }) }, [pollVote]) const variables = { id: v.id } return ( ) } const hasExpiration = !!item.pollExpiresAt const timeRemaining = timeLeft(new Date(item.pollExpiresAt)) const mine = item.user.id === me?.id const showPollButton = (!hasExpiration || timeRemaining) && !item.poll.meVoted && !mine return (
{item.poll.options.map(v => showPollButton ? : )}
{numWithUnits(item.poll.count, { unitSingular: 'vote', unitPlural: 'votes' })} {hasExpiration && ` \\ ${timeRemaining ? `${timeRemaining} left` : 'poll ended'}`}
) } function PollResult ({ v, progress }) { return (
{v.option}{v.meVoted && } {progress}%
) }