Poll Card
Single-choice mobile poll with explicit submission, retry, and accessible results.
Install
First install? Set up the registry in your app.
npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add poll-cardSource files
Expand a file to read the source the installer copies into your app.
components/blocks/poll-card/PollCard.tsx
import { useRef, useState } from 'react'
import { View, type ViewProps } from 'react-native'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Button } from '@/components/ui/button'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Text } from '@/components/ui/text'
import { useAnnouncement } from '@/lib/accessibility'
import { cn } from '@/lib/utils'
const defaultLabels = {
choices: 'Poll options',
closed: 'Voting has ended',
recorded: 'Your vote was recorded.',
empty: 'No choices are available.',
yourChoice: 'Your choice',
resultsUnavailable: 'Results aren’t available yet.',
vote: 'Submit vote',
voting: 'Submitting vote…',
failed: 'Couldn’t record your vote. Your choice is still selected.',
formatResult: (label: string, share: string) => `${label}, ${share} of votes`,
formatTotal: (count: number) => `${count} ${count === 1 ? 'vote' : 'votes'}`,
}
export interface PollOption {
id: string
label: string
/** Optional caller-supplied vote count. Supply a valid count for every option to show results. */
votes?: number
}
export interface PollCardProps extends Omit<ViewProps, 'children'> {
className?: string
question: string
/** Each option needs a stable, unique ID. */
options: readonly PollOption[]
closed?: boolean
voteId?: string | null
/** Return false or reject on failure. Update voteId after a successful request. */
onVote?: (id: string) => void | boolean | Promise<void | boolean>
locale?: string
labels?: Partial<typeof defaultLabels>
}
export function PollCard({
className,
question,
options,
closed = false,
voteId = null,
onVote,
locale,
labels,
...props
}: PollCardProps) {
const copy = { ...defaultLabels, ...labels }
const [draft, setDraft] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState(false)
const request = useRef(false)
const selected = options.find(({ id }) => id === draft)
const recorded = options.find(({ id }) => id === voteId)
const canVote = !closed && voteId === null && !!onVote
const total = options.reduce((sum, { votes }) => sum + (votes ?? Number.NaN), 0)
const hasResults =
Number.isSafeInteger(total) &&
options.every(({ votes }) => votes !== undefined && Number.isSafeInteger(votes) && votes >= 0)
const formatPercent = new Intl.NumberFormat(locale, { style: 'percent' })
const submitError = error && canVote && selected ? copy.failed : undefined
useAnnouncement(voteId !== null ? copy.recorded : submitError)
async function submit() {
if (!canVote || !selected || !onVote || request.current) return
request.current = true
setBusy(true)
setError(false)
try {
if ((await onVote(selected.id)) === false) setError(true)
} catch {
setError(true)
} finally {
request.current = false
setBusy(false)
}
}
return (
<View {...props} className={cn('gap-4 rounded-xl border border-border bg-card p-4', className)}>
<View className="gap-1">
<Text size="lg" accessibilityRole="header" className="font-semibold">
{question}
</Text>
{closed || voteId !== null ? (
<Text size="sm" variant="muted">
{closed ? copy.closed : copy.recorded}
</Text>
) : null}
</View>
{options.length === 0 ? (
<Text variant="muted">{copy.empty}</Text>
) : canVote ? (
<>
<RadioGroup
accessibilityLabel={copy.choices}
value={selected?.id ?? ''}
disabled={busy}
onValueChange={(id) => {
if (request.current || !options.some((option) => option.id === id)) return
setError(false)
setDraft(id)
}}
>
{options.map(({ id, label }) => (
<RadioGroupItem key={id} value={id} label={label} />
))}
</RadioGroup>
{submitError ? (
<Alert accessibilityRole="none" variant="destructive">
<AlertDescription>{submitError}</AlertDescription>
</Alert>
) : null}
<Button
accessibilityLabel={busy ? copy.voting : copy.vote}
disabled={!selected}
loading={busy}
onPress={() => void submit()}
>
{busy ? copy.voting : copy.vote}
</Button>
</>
) : hasResults ? (
<View className="gap-3">
{options.map(({ id, label, votes }) => {
const share = total > 0 ? (votes ?? 0) / total : 0
const formatted = formatPercent.format(share)
const chosen = id === recorded?.id
return (
<View
key={id}
accessible
accessibilityLabel={copy.formatResult(label, formatted)}
accessibilityState={{ selected: chosen }}
className="gap-1.5"
>
<View className="flex-row flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
<Text className={chosen ? 'font-semibold' : undefined}>{label}</Text>
<Text variant="muted" style={{ fontVariant: ['tabular-nums'] }}>
{formatted}
</Text>
</View>
{chosen ? (
<Text size="sm" variant="muted">
{copy.yourChoice}
</Text>
) : null}
<View aria-hidden className="h-1.5 rounded-full bg-secondary">
<View className="h-full self-start rounded-full bg-primary" style={{ width: `${share * 100}%` }} />
</View>
</View>
)
})}
<Text size="sm" variant="muted">
{copy.formatTotal(total)}
</Text>
</View>
) : (
<Text variant="muted">{copy.resultsUnavailable}</Text>
)}
</View>
)
}
components/blocks/poll-card/index.ts
export { PollCard } from './PollCard'
export type { PollCardProps, PollOption } from './PollCard'