import client from '@api/client' import Button from '@components/Button' import haptics from '@components/haptics' import relativeTime from '@components/relativeTime' import { TimelineData } from '@components/Timelines/Timeline' import { Feather } from '@expo/vector-icons' import { ParseEmojis } from '@root/components/Parse' import { StyleConstants } from '@utils/styles/constants' import { useTheme } from '@utils/styles/ThemeManager' import { findIndex } from 'lodash' import React, { useCallback, useMemo, useState } from 'react' import { Pressable, StyleSheet, Text, View } from 'react-native' import { useMutation, useQueryClient } from 'react-query' const fireMutation = async ({ id, options }: { id: string options?: boolean[] }) => { const formData = new FormData() options && options.forEach((o, i) => { if (options[i]) { formData.append('choices[]', i.toString()) } }) const res = await client({ method: options ? 'post' : 'get', instance: 'local', url: options ? `polls/${id}/votes` : `polls/${id}`, ...(options && { body: formData }) }) if (res.body.id === id) { return Promise.resolve(res.body as Mastodon.Poll) } else { return Promise.reject() } } export interface Props { queryKey: QueryKey.Timeline poll: NonNullable reblog: boolean sameAccount: boolean } const TimelinePoll: React.FC = ({ queryKey, poll, reblog, sameAccount }) => { const { mode, theme } = useTheme() const queryClient = useQueryClient() const [allOptions, setAllOptions] = useState( new Array(poll.options.length).fill(false) ) const mutation = useMutation(fireMutation, { onSuccess: (data, { id }) => { queryClient.cancelQueries(queryKey) queryClient.setQueryData(queryKey, old => { let tootIndex = -1 const pageIndex = findIndex(old?.pages, page => { const tempIndex = findIndex(page.toots, [ reblog ? 'reblog.poll.id' : 'poll.id', id ]) if (tempIndex >= 0) { tootIndex = tempIndex return true } else { return false } }) if (pageIndex >= 0 && tootIndex >= 0) { if (reblog) { old!.pages[pageIndex].toots[tootIndex].reblog!.poll = data } else { old!.pages[pageIndex].toots[tootIndex].poll = data } } return old }) haptics('Success') }, onError: () => { haptics('Error') } }) const pollButton = useMemo(() => { if (!poll.expired) { if (!sameAccount && !poll.voted) { return (